@punica/editor 1.50.1 → 1.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- var e;!function(e){e.CREATED="created",e.BOOTSTRAPPING="bootstrapping",e.BOOTSTRAPPED="bootstrapped",e.BOOTSTRAP_FAILED="bootstrap_failed",e.STARTING="starting",e.STARTED="started",e.START_FAILED="start_failed",e.READY="ready"}(e||(e={}));async function t(){try{const e=punica.runtime?.workspace;if(!e)return;const t=await e.getCurrent();return t?.id}catch(e){return void console.warn("[hostAccess] Failed to get current workspace id:",e)}}function n(){return!!punica.runtime?.workspace}function r(){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>=12&&(t=t.split(n).join("[REDACTED]"))}}}catch{}return t}function s(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 o=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function a(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||o.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function c(e){const t=new WeakSet;return function e(n){if(null===n||"object"!=typeof n)return n;if(t.has(n))return"[Circular]";if(t.add(n),Array.isArray(n))return n.map(e);const r={};for(const[t,i]of Object.entries(n))a(t)?r[t]=null==i?i:"[REDACTED]":r[t]=e(i);return r}(e)}function l(e,t=2){const n=c(e);return s(JSON.stringify(n,null,t))}function u(e){return d(e,"sensitive")}function d(e,t){return p(e,t).filter(e=>!0===e.value).map(e=>e.path)}function p(e,t){const n=[],r=new Set;function i(e,i){if(!e||"object"!=typeof e)return;const o=e;if(t in o){const e=i.join(" ");r.has(e)||(r.add(e),n.push({path:i,value:o[t]}))}s(o,i)}function s(e,t){if(!e||"object"!=typeof e)return;const n=e,r=n.properties;if(r&&"object"==typeof r)for(const[e,n]of Object.entries(r))i(n,[...t,e]);const o=n.items;if(o&&"object"==typeof o)if(Array.isArray(o))for(const e of o)i(e,[...t,"*"]);else i(o,[...t,"*"]);for(const e of["anyOf","oneOf","allOf"]){const r=n[e];if(Array.isArray(r))for(const e of r)s(e,t)}}return s(e,[]),n}function f(e,t){if(0===t.length)return e;return function e(t,n){if(null===t||"object"!=typeof t)return t;if(0===n.length)return t;if(Array.isArray(t)){const r=[];let i=!1;for(const e of n)"*"===e[0]&&(1===e.length?i=!0:r.push(e.slice(1)));return i&&0===r.length?t.map(e=>null==e?e:"[REDACTED]"):t.map(t=>e(t,r))}const r={};for(const[i,s]of Object.entries(t)){const t=[];let o=!1;for(const e of n)e[0]===i&&(1===e.length?o=!0:t.push(e.slice(1)));o?r[i]=null==s?s:"[REDACTED]":t.length>0?r[i]=e(s,t):r[i]=s}return r}(e,t)}const h=/^(?:secrets|secret-manager)\./,m=new Set(["value"]);const g={manager:new class{#e=new Map;#t=new Map;registerCommand(e,t){const n={dispose:()=>{this.#e.delete(e),this.#t.delete(e)}};t.disposable=n,this.#t.set(e,n),this.#e.set(e,t)}executeCommand(e,...t){const n=this.#e.get(e);if(!n){const n=punica.extensions?.manager;if(!n)return void console.error(`[Commands] Command ${e} not found (extension manager unavailable)`);const r=n.getExtensionsForCommand(e);if(0===r.length)return void console.error(`[Commands] Command ${e} not found`);const i=r[0];return n.activate(i,{reason:"command",trigger:e}).then(()=>{const n=this.#e.get(e);return n?(console.log("[Commands] execute after activate",e,"via extension",i),n.execute(...t)):void console.error(`Command ${e} not found after activating extension "${i}"`)}).catch(t=>{console.error(`Error activating extension "${i}" for command ${e}:`,t)})}console.log("[Commands] execute",e,"with args",function(e,t){const n=h.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]=m.has(n)?"[REDACTED]":r;return c(t)}return c(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 y=new class{async write(e){try{const t=r();if(!t)return;const n=".punica/audit";await t.createFolder(n).catch(()=>{});const i=new Date(e.timestamp).toISOString().split("T")[0],s=`${n}/${`${i}_${e.invocationId}.json`}`;await t.createFileWithContent(s,JSON.stringify(e,null,2))}catch(e){console.warn("[AuditWriter] Failed to write audit record:",e)}}async read(e){try{const t=r();if(!t)return[];const n=".punica/audit",i=await t.getFileTree(),s=(e,t)=>{const n=[];for(const r of e)(r.path.startsWith(t+"/")||r.path===t)&&(r.isDirectory||n.push(r),r.isDirectory&&r.children&&n.push(...s(r.children,t)));return n},o=s(i,n),a=[];for(const n of o)if(n.name.endsWith(".json"))try{const r=await t.readFile(n.path),i=JSON.parse(r);if(e?.since&&i.timestamp<e.since)continue;if(e?.until&&i.timestamp>e.until)continue;if(e?.capability&&i.capability!==e.capability)continue;if(e?.workspaceId&&i.workspace!==e.workspaceId)continue;a.push(i)}catch(e){console.warn(`[AuditWriter] Failed to read audit file ${n.name}:`,e)}return a.sort((e,t)=>t.timestamp-e.timestamp),a}catch(e){return console.warn("[AuditWriter] Failed to read audit records:",e),[]}}};const w={manager:new class{#n=new Map;#r=[];#i=[];registerCommand(e){this.#n.set(e.id,e)}executeCommand(e){const t=this.#n.get(e);t?(t.execute(),this.#r.push(t),this.#i=[]):console.error(`Command with ID ${e} not found.`)}undo(){const e=this.#r.pop();e?(e.undo(),this.#i.push(e)):console.error("No command to undo.")}redo(){const e=this.#i.pop();e?(e.execute(),this.#r.push(e)):console.error("No command to redo.")}},auditWriter:y};const v={manager:new class{#s=[];#o=null;#a(){null===this.#o&&(this.#o=window.setInterval(()=>{const e=new Date;this.#s.forEach(t=>t.update(e))},1e3))}#c(){null!==this.#o&&(window.clearInterval(this.#o),this.#o=null)}subscribe(e){this.#s.push(e),1==this.#s.length&&this.#a()}unsubscribe(e){this.#s=this.#s.filter(t=>t!==e),0==this.#s.length&&this.#c()}}};function b(){return(new Date).toISOString()}function I(e,t){const n=new Map,r=new Map,i=new Set;function s(e){for(const t of i)try{t(e)}catch{}try{const t=window,n=t.punica?.Commands?.manager,r=t.punica?.runtime,i="failed"===e.status?"error":"cancelled"===e.status?"warning":"info";let s=`[${e.label}] ${e.status}`;null!=e.exitCode&&(s+=` (exitCode=${e.exitCode})`),n&&n.executeCommand("output.append",{channel:"Tasks",text:s,level:i}),r?.events?.publish("tasks.runChanged",{run:e}),!r?.notifications||"failed"!==e.status&&"success"!==e.status||r.notifications.push({id:"",level:"failed"===e.status?"error":"success",title:e.label,message:s,timestamp:"",source:"tasks",actionCommandId:"tasks.open"})}catch{}}const o={listDefinitions:async()=>Array.from(n.values()),registerDefinition(e){n.set(e.id,e)},unregisterDefinition(e){n.delete(e)},async run(i,a){const c=n.get(i);if(!c)throw new Error(`[Runtime.tasks] Task definition not found: ${i}`);const l=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`task_${Date.now()}_${Math.floor(1e6*Math.random())}`}(),u=b(),{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 i=n??r.currentEnvironmentId,s=r.environments.find(e=>e.id===i),o={...s?.variables??{},...e??{}};return{env:Object.keys(o).length?o:void 0,workspaceId:r.id,resolvedEnvironmentId:s?.id}}catch{return{env:e}}}(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),s(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:b(),exitCode:e??null};r.set(l,n),s(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 i={...n,status:"cancelled",finishedAt:b()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const k=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=I(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 E={manager:k},S=Object.freeze({__proto__:null,createTasksApi:I,default:E,manager:k});const A=7776e6,x={rules:[],defaultTtlMs:A};function C(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 T(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(C(e,i.pattern)){const e=i.pattern.length;e>r&&(n=i,r=e)}return n}(e,t.rules??[]);return n-(r?.ttlMs??t.defaultTtlMs??A)}function P(e){return new Date(e).toISOString().slice(0,10)}function N(e,t,n){const r=function(e){const t=e.slice(e.lastIndexOf("/")+1),n=/^(\d{4}-\d{2}-\d{2})_/.exec(t);return n?n[1]:null}(e);return r?r>P(n-t.shortestTtlMs)?"keep":r<P(n-t.longestTtlMs)?"expire":"unknown":"unknown"}const M=".punica/.gitignore",R="# 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# Governance, and the whole reason it is a file. A policy that lives in the\n# commit is one that shows up in a diff and gets argued about in review — the\n# claim the argument-level policy engine and the policy export are both built\n# on. It was ignored here, so in a fresh workspace it was reviewable by nobody.\n# serve.yaml is its pair: what this project exposes to a remote caller.\n!/policy.yaml\n!/serve.yaml\n\n# Authored process definitions. The same case as mlops.yaml below — a person\n# writes them, presses Save, and a teammate cloning the project needs them or\n# gets no process at all.\n!/llmops.yaml\n!/evals.yaml\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 $(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.startsWith("!"))}async function _(){const e=r();if(e&&(!n()||await t()))try{if(!!e.exists&&await e.exists(M)){const t=function(e){if(!e.includes("# Punica editor — workspace internal state."))return null;const t=new Set($(e)),n=$(R).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(M)??"");return void(t&&e.updateFileContent&&await e.updateFileContent(M,t))}try{await e.createFolder(".punica")}catch{}await e.createFileWithContent(M,R)}catch{}}const O=".punica/events";let L={};function j(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(O)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function D(e){const t=e.split("/").pop()??"";return t.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]}function F(e){return new Date(e).toISOString().split("T")[0]}function q(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.traceId&&n?.traceId!==t.traceId)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 B=new class{#d;#p=!1;#f=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const i=r();if(!i)return;if(n()&&!await t())return;const s=Date.now();try{await i.createFolder(O)}catch{}if(!this.#p){this.#p=!0;try{await i.createFileWithContent(`${O}/.gitignore`,"*\n!.gitignore\n")}catch{}}this.#f||(this.#f=!0,await _());for(const t of e)try{const e=t.envelope?.timestampMs??Date.now(),n=new Date(e).toISOString().split("T")[0],r=t.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,s=`${O}/${n}_${r}.json`,o=l(t);await i.createFileWithContent(s,o)}catch{}try{L.onWrite?.(Date.now()-s,e.length)}catch{}}async query(e){const t=r();if(!t)return[];let n;try{n=await t.getFileTree()}catch{return[]}if(!Array.isArray(n))return[];const i=void 0!==e?.since?F(e.since):void 0,s=void 0!==e?.until?F(e.until):void 0,o=new Map;for(const e of j(n)){const t=D(e);if(t){if(void 0!==i&&t<i)continue;if(void 0!==s&&t>s)continue}const n=t??"",r=o.get(n);r?r.push(e):o.set(n,[e])}const a=[...o.keys()].sort((e,t)=>t.localeCompare(e)),c=e?.limit&&e.limit>0?e.limit:void 0,l=[];for(const n of a){for(const r of o.get(n))try{const n=await t.readFile(r),i=JSON.parse(n);q(i,e)&&l.push(i)}catch{}if(void 0!==c&&l.length>=c)break}return l.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),void 0!==c?l.slice(-c):l}async delete(e){const t=r();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const i=j(n);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(q(JSON.parse(r),e))await t.deleteFile(n),s++;else{const e=n.split("/").pop()??"",t=e.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]??"";o.push({path:n,dateKey:t})}}catch{}if(o.length>this.#d){o.sort((e,t)=>e.dateKey.localeCompare(t.dateKey));const e=o.length-this.#d;for(const n of o.slice(0,e))try{await t.deleteFile(n.path),s++}catch{}}return s}async#h(e,t){const n=[];for(const e of t){const t=D(e);t&&n.push({path:e,day:t})}if(n.length<=this.#d)return 0;n.sort((e,t)=>e.day.localeCompare(t.day));let r=0;for(const t of n.slice(0,n.length-this.#d))try{await e.deleteFile(t.path),r++}catch{}return r}async applyRetention(e,t=Date.now()){const n=r();if(!n)return 0;let i;try{i=await n.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=j(i),o=function(e){const t=e.defaultTtlMs??A;let n=t,r=t;for(const t of e.rules??[])Number.isFinite(t.ttlMs)&&(t.ttlMs<n&&(n=t.ttlMs),t.ttlMs>r&&(r=t.ttlMs));return{shortestTtlMs:n,longestTtlMs:r}}(e);let a=0;for(const r of s)try{const i=N(r,o,t);if("keep"===i)continue;if("expire"===i){await n.deleteFile(r),a++;continue}const s=await n.readFile(r),c=JSON.parse(s),l=c.envelope?.timestampMs??0;l<T(c.name,e,t)&&(await n.deleteFile(r),a++)}catch{}return a+=await this.#h(n,s),a}};let U=B;function V(){return U}const W=new class{#m=void 0;get(){return this.#m}runWith(e,t){const n=this.#m;let r;this.#m=e;try{r=t()}catch(e){throw this.#m=n,e}return r&&"function"==typeof r.then?r.then(e=>(this.#m=n,e),e=>{throw this.#m=n,e}):(this.#m=n,r)}};let K=W;function G(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=K.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function Y(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(C(e.name,t)){r=!0;break}if(!r)return!1}return!0}class z extends Error{constructor(e){super(e),this.name="EventReplayError"}}const J={exportSpan:()=>{}};let H=J;function Q(){return H}function Z(e){const t=e;return t&&void 0===t.name&&void 0!==t.names?{...t,name:t.names}:e}function X(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function ee(){return Date.now()}let te=!0;function ne(e){te=e}function re(){return te}function ie(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;let o=0;function a(){try{L.onQueueDepthChange?.(i.length)}catch{}}async function c(){if(0===i.length)return;const e=[...i];i=[],a(),s&&(clearTimeout(s),s=null);try{await V().write(e),ee()-o>=6e4&&(o=ee(),le())}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function u(e){te&&function(e){if("audit"===e.envelope?.kind)return!0;const t=e.name;return r.some(e=>e.test(t))}(e)&&(i.push(e),a(),i.length>=10?c():s||(s=setTimeout(()=>{c()},5e3)))}function d(n,r){if("string"==typeof n){const t=n;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(r),()=>{i?.delete(r),i&&0===i.size&&e.delete(t)}}const i={filter:n,listener:r};return t.push(i),()=>{const e=t.indexOf(i);e>=0&&t.splice(e,1)}}function p(r,i){const s=i,o=s&&"object"==typeof s&&s.name===r?s:{name:r,envelope:{id:X(),timestampMs:ee()},payload:i};try{n.push(o),n.length>200&&n.splice(0,n.length-200),u(o)}catch{}const a=e.get(r);if(a&&a.size>0)for(const e of a)try{e(i)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(Y(o,t.filter))try{t.listener(o)}catch{}}}async function f(e){try{return await V().query(Z(e))}catch{return[]}}function h(e){let t=[...n];if(e=Z(e),e?.correlationId){const n=e.correlationId;t=t.filter(e=>e.envelope?.correlationId===n||e.envelope?.id===n)}if(e?.traceId){const n=e.traceId;t=t.filter(e=>e.envelope?.traceId===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:p,subscribe:d,subscribeMany(e,t){const n=e.map(e=>d(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:X,publishEvent:function(e){const t=G({id:e.envelope?.id??X(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??ee(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{Q().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=l(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 p(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:h,getTrace:function(e){return h({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?h(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??"",l(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 l({exportedAt:ee(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:f,replay:async function(e){"dispatch"===e.mode&&function(){throw new z('events.replay({ mode: "dispatch" }) is disabled. Host must call setReplayDispatchAllowed(true) during bootstrap (test/dev only — side-effectful listeners will fire again).')}();const t=!1!==e.includePersisted,r=[...n];let i=[];if(t)try{i=await f({name:e.name,traceId:e.traceId,since:e.since,until:e.until})}catch{i=[]}const s=function(e,t,n){const r=new Set,i=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}i.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}i.push(e)}const s={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=i.filter(e=>{if(!Y(e,s))return!1;const t=e.envelope?.timestampMs??0;return!(void 0!==n.since&&t<n.since||void 0!==n.until&&t>n.until)});return o.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),void 0!==n.limit&&n.limit>0&&(o=o.slice(-n.limit)),o}(r,i,{name:e.name,correlationId:e.correlationId,traceId:e.traceId,kind:e.kind,source:e.source,since:e.since,until:e.until,limit:e.limit});if("log"===e.mode)for(const e of s)console.log("[Punica Replay]",e.name,e);else for(const e of s)p(e.name,e);return{count:s.length,events:s}},async flush(){await c()}}}const se=ie();var oe={manager:se};let ae=x;function ce(){return ae}async function le(){try{const e=V(),t=ce();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??A;return await e.delete({until:ee()-n})??0}catch{return 0}}var ue=Object.freeze({__proto__:null,createCorrelationId:X,createEventsApi:ie,default:oe,getRetentionConfig:ce,isEventPersistenceEnabled:re,manager:se,runEventRetentionCleanup:le,setEventPersistence:ne,setRetentionConfig:function(e){ae=e??x}});function de(){let e=[];const t=new Set;function n(){for(const e of t)try{e()}catch{}}const r={list:async()=>e.slice(),push(t){const r=t.id||`notif_${Date.now()}_${Math.random().toString(36).slice(2)}`,i=t.timestamp||(new Date).toISOString(),s={...t,id:r,timestamp:i};e=[s,...e],n()},markRead(t){e=e.map(e=>e.id===t?{...e,read:!0}:e),n()},clear(t){e=t?e.filter(e=>e.source!==t):[],n()},onDidChange:e=>(t.add(e),()=>{t.delete(e)})};return r}const pe=de();var fe={manager:pe},he=Object.freeze({__proto__:null,createNotificationsApi:de,default:fe,manager:pe});let me;function ge(){return me}function ye(){return me?.email}function we(){const e=me?.roles;return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}const ve=/^[a-z0-9][a-z0-9-]{0,31}$/,be=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Ie(e){if("string"!=typeof e)return;const t=e.trim();if("owner"===t)return{kind:"owner"};if(t.startsWith("role:")){const e=t.slice(5).trim().toLowerCase();return ve.test(e)?{kind:"role",role:e}:void 0}if(t.startsWith("user:")){const e=t.slice(5).trim().toLowerCase();return be.test(e)?{kind:"user",email:e}:void 0}}function ke(e){const t=Ie(e);if(t)switch(t.kind){case"owner":return"owner";case"role":return`role:${t.role}`;case"user":return`user:${t.email}`}}function Ee(e,t,n){if(!t||0===t.length)return;const r=e?.email?.trim().toLowerCase(),i=function(e,t){const n=e=>String(e).trim().toLowerCase();return t&&Array.isArray(e?.orgs)?new Set(e.orgs.filter(e=>function(e,t){const n=t.trim().toLowerCase();return""!==n&&(e.id.trim().toLowerCase()===n||e.name.trim().toLowerCase()===n)}(e,t)).map(e=>n(e.role))):new Set((e?.roles??[]).map(n))}(e,n);for(const e of t){const t=Ie(e);if(t){if("owner"===t.kind&&i.has("owner"))return"owner";if("role"===t.kind&&i.has(t.role))return`role:${t.role}`;if("user"===t.kind&&r&&r===t.email)return`user:${t.email}`}}}const Se="punica.kernel.policy.v2";function Ae(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function xe(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class Ce{#g=new Map;constructor(){this.#y()}set(e,t,n){let r=this.#g.get(e);r||(r=new Map,this.#g.set(e,r)),r.set(t,n),this.#w()}get(e,t){return this.#g.get(e)?.get(t)}has(e,t){return this.#g.get(e)?.has(t)??!1}delete(e,t){const n=this.#g.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#g.delete(e),r&&this.#w(),r}list(){const e=[];for(const t of this.#g.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#g.size&&(this.#g.clear(),this.#w())}restoreAll(e){this.#g.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=xe(n);if(!e)continue;let r=this.#g.get(n.key);r||(r=new Map,this.#g.set(n.key,r)),r.set(e,n),t++}return this.#w(),t}#y(){const e=Ae();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=xe(e);if(!t)continue;let n=this.#g.get(e.key);n||(n=new Map,this.#g.set(e.key,n)),n.set(t,e)}}catch{}}#w(){const e=Ae();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 Te=new Ce;const Pe="any",Ne=2048;function Me(e){if(void 0===e)return"null";if(null===e||"object"!=typeof e)return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(e=>Me(e)).join(",")}]`;return`{${Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Me(t)}`).join(",")}}`}function Re(e,t){if(0===t.length)return;if(t.some(e=>0===e.length))return e;if(Array.isArray(e)){const n=t.filter(e=>"*"===e[0]).map(e=>e.slice(1));if(0===n.length)return;return e.map(e=>Re(e,n))}if(!e||"object"!=typeof e)return;const n={},r=e;for(const e of Object.keys(r)){const i=t.filter(t=>t[0]===e).map(e=>e.slice(1));if(0===i.length)continue;const s=Re(r[e],i);void 0!==s&&(n[e]=s)}return Object.keys(n).length>0?n:void 0}function $e(e){const t=Me(e);return t.length<=Ne?e:{truncated:!0,droppedChars:t.length-Ne,head:`${t.slice(0,Ne)}…`}}async function _e(e,t={}){const n=t.policyKeyPaths??[],r=n.length>0?Re(e,n):e;return{binding:await Oe(r),preview:$e(r)}}async function Oe(e){const t=(new TextEncoder).encode(Me(e)),n=await function(){const e=globalThis.crypto?.subtle;if(!e)throw new Error("[ArgsBinding] crypto.subtle is unavailable, so an approval cannot be bound to its arguments. Run in an environment with Web Crypto (browser, Node 18+).");return e}().digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("").slice(0,32)}const Le=["file.read","file.write","file.list","file.stat","secret.read","secret.write","process.exec","net.request","model.invoke","memory.read","memory.write","vcs.read","vcs.write","flow.run","ui.reveal"],je=new Set(Le);function De(e){return"string"==typeof e&&je.has(e)}function Fe(e){const t=e?.action;if(!Array.isArray(t))return;const n=t.filter(De);return n.length>0?n:void 0}const qe=new Set(["kind","id","action","egress","sensitive","effect","when","approval","scope","approvers","signatures","reason"]),Be=["eq","neq","in","notIn","startsWith","endsWith","glob","exists","absent","lt","lte","gt","gte"],Ue=["allow","deny","require"],Ve={deny:0,require:1,allow:2};function We(e,t){const n=e.split(".").filter(e=>e.length>0);for(const e of t){const t=Math.min(n.length,e.length);let r=!0;for(let i=0;i<t;i++)if(n[i]!==e[i]&&"*"!==e[i]){r=!1;break}if(r)return!0}return!1}function Ke(e){return"string"==typeof e?e:"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e?String(e):null}function Ge(e,t){return Me(e)===Me(t)}function Ye(e,t){const{op:n,value:r}=t;switch(n){case"eq":return Ge(e,r);case"neq":return!Ge(e,r);case"in":return Array.isArray(r)&&r.some(t=>Ge(e,t));case"notIn":return Array.isArray(r)&&!r.some(t=>Ge(e,t));case"startsWith":{const t=Ke(e),n=Ke(r);return null!==t&&null!==n&&t.startsWith(n)}case"endsWith":{const t=Ke(e),n=Ke(r);return null!==t&&null!==n&&t.endsWith(n)}case"glob":{const t=Ke(e),n=Ke(r);return null!==t&&null!==n&&function(e,t){const n=t.split("*").map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`).test(e)}(t,n)}case"exists":return void 0!==e;case"absent":return void 0===e;case"lt":case"lte":case"gt":case"gte":return function(e,t,n){if("number"!=typeof e||!Number.isFinite(e))return!1;if("number"!=typeof t||!Number.isFinite(t))return!1;switch(n){case"lt":return e<t;case"lte":return e<=t;case"gt":return e>t;case"gte":return e>=t}}(e,r,n);default:return!1}}function ze(e,t,n){const r=function(e,t){const n=t.split(".").filter(e=>e.length>0);let r=[e];for(const e of n){const t=[];for(const n of r){if(null==n)continue;if("*"===e){Array.isArray(n)&&t.push(...n);continue}if(Array.isArray(n)||"object"!=typeof n)continue;const r=n[e];void 0!==r&&t.push(r)}if(r=t,0===r.length)return[]}return r}(e,t.path);if(0===r.length)return"absent"===t.op;return"allow"===n?r.every(e=>Ye(e,t)):r.some(e=>Ye(e,t))}function Je(e,t){return void 0===e||""===e||"*"===e||(e.endsWith("*")?t.startsWith(e.slice(0,-1)):e===t)}function He(e,t,n){if(void 0===e||0===e.length)return!0;if(void 0===t||0===t.length)return!1;const r=new Set(e);return"allow"===n?t.every(e=>r.has(e)):t.some(e=>r.has(e))}function Qe(e,t,n,r={}){const i=r.sensitivePaths??[];let s=null,o=Number.POSITIVE_INFINITY;for(const a of e){const e=Array.isArray(a?.rules)?a.rules:[];for(let c=0;c<e.length;c++){const l=e[c];if(!l||l.kind!==t.kind)continue;if(!Je(l.id,t.id))continue;if(!He(l.action,t.action,l.effect))continue;if(l.egress&&"remote"!==t.egress)continue;if(l.sensitive&&!t.sensitive)continue;const u=Ve[l.effect];if(void 0===u)continue;if(u>=o)continue;const d=Array.isArray(l.when)?l.when:[];let p=!0;for(const e of d){if(!0===r.argsWhollyRedacted||We(e.path,i)){r.onRedactedCondition?.(a.name,c,e.path),p=!1;break}if(!ze(n,e,l.effect)){p=!1;break}}if(p&&(s={ref:{template:a.name,ruleIndex:c,effect:l.effect,reason:l.reason,...l.scope?{scope:l.scope}:{},...l.approvers?{approvers:l.approvers}:{},...a.org?{org:a.org}:{},...l.signatures?{signatures:l.signatures}:{},...l.sensitive?{sensitive:!0}:{},digest:a.digest,matchedBy:l.action&&l.action.length>0&&!l.id?"action":l.egress&&!l.id?"egress":l.sensitive&&!l.id?"sensitive":"id"},rule:l},o=u,0===u))return s}}return s}function Ze(e,t){return{path:e,message:t}}function Xe(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return n.push(Ze(t,"a condition must be a mapping")),null;const r=e,i=r.path;if("string"!=typeof i||""===i.trim())return n.push(Ze(`${t}.path`,"a condition needs a path")),null;const s=r.op;if("string"!=typeof s||!Be.includes(s))return n.push(Ze(`${t}.op`,`unknown operator ${JSON.stringify(s)} — one of ${Be.join(", ")}`)),null;return"exists"!==s&&"absent"!==s&&void 0===r.value?(n.push(Ze(`${t}.value`,`operator "${s}" needs a value`)),null):"in"!==s&&"notIn"!==s||Array.isArray(r.value)?{path:i,op:s,value:r.value}:(n.push(Ze(`${t}.value`,`operator "${s}" needs a list of values`)),null)}function et(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return n.push(Ze(t,"a rule must be a mapping")),null;const r=e,i=r.kind;if("string"!=typeof i||""===i.trim())return n.push(Ze(`${t}.kind`,'a rule needs a kind, e.g. "capability"')),null;const s=r.effect;if("string"!=typeof s||!Ue.includes(s))return n.push(Ze(`${t}.effect`,`effect must be one of ${Ue.join(", ")} — got ${JSON.stringify(s)}`)),null;const o={kind:i,effect:s};if(void 0!==r.id){if("string"!=typeof r.id)return n.push(Ze(`${t}.id`,"id must be a string")),null;o.id=r.id}if(void 0!==r.action){if(!Array.isArray(r.action)||0===r.action.length)return n.push(Ze(`${t}.action`,"action must be a non-empty list of actions")),null;const e=[];for(let i=0;i<r.action.length;i++){const s=r.action[i];if(!De(s))return n.push(Ze(`${t}.action.${i}`,`unknown action ${JSON.stringify(s)} — see docs/capability-actions.md`)),null;e.push(s)}o.action=e}if(void 0!==r.egress){if("remote"!==r.egress)return n.push(Ze(`${t}.egress`,`egress must be "remote", got ${JSON.stringify(r.egress)}`)),null;o.egress="remote"}if(void 0!==r.reason){if("string"!=typeof r.reason)return n.push(Ze(`${t}.reason`,"reason must be a string")),null;o.reason=r.reason}if(void 0!==r.approval){if("plan"!==r.approval&&"step"!==r.approval)return n.push(Ze(`${t}.approval`,"approval must be plan or step — for silent execution write effect: allow")),null;if("require"!==o.effect)return n.push(Ze(`${t}.approval`,`approval only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;o.approval=r.approval}if(void 0!==r.scope){if("once"!==r.scope&&"workspace"!==r.scope&&"always"!==r.scope)return n.push(Ze(`${t}.scope`,"scope must be once, workspace or always")),null;if("require"!==o.effect)return n.push(Ze(`${t}.scope`,`scope only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;o.scope=r.scope}if(void 0!==r.approvers){if(!Array.isArray(r.approvers)||0===r.approvers.length)return n.push(Ze(`${t}.approvers`,"approvers must be a non-empty list of owner, role:<name> or user:<email>")),null;if("require"!==o.effect)return n.push(Ze(`${t}.approvers`,`approvers only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;const e=[];for(let i=0;i<r.approvers.length;i++){const s=ke(r.approvers[i]);if(!s)return n.push(Ze(`${t}.approvers.${i}`,`unknown approver ${JSON.stringify(r.approvers[i])} — write owner, role:<name> or user:<email>`)),null;e.includes(s)||e.push(s)}o.approvers=e}if(void 0!==r.signatures){if("number"!=typeof r.signatures||!Number.isInteger(r.signatures)||r.signatures<1)return n.push(Ze(`${t}.signatures`,"signatures must be a whole number of signatures, at least 1")),null;if("require"!==o.effect)return n.push(Ze(`${t}.signatures`,`signatures only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;if(!o.approvers)return n.push(Ze(`${t}.signatures`,"signatures needs approvers — name who may sign (owner, role:<name> or user:<email>)")),null;r.signatures>1&&(o.signatures=r.signatures)}for(const e of Object.keys(r))if(!qe.has(e))return n.push(Ze(`${t}.${e}`,`unknown key "${e}" — this substrate does not read it, and a rule it cannot read whole is not applied`)),null;if(void 0!==r.sensitive){if(!0!==r.sensitive)return n.push(Ze(`${t}.sensitive`,`sensitive must be true, got ${JSON.stringify(r.sensitive)}`)),null;o.sensitive=!0}if(void 0!==r.when){if(!Array.isArray(r.when))return n.push(Ze(`${t}.when`,"when must be a list")),null;const e=[];for(let i=0;i<r.when.length;i++){const s=Xe(r.when[i],`${t}.when.${i}`,n);if(!s)return null;e.push(s)}o.when=e}return o}function tt(e){const t=[],n=[];if(null==e)return{templates:n,problems:t};if("object"!=typeof e||Array.isArray(e))return t.push(Ze("","the policy file must be a mapping")),{templates:n,problems:t};const r=e;if(void 0!==r.version&&1!==r.version)return t.push(Ze("version",`unsupported policy file version ${JSON.stringify(r.version)} — this build reads version 1`)),{templates:n,problems:t};let i;void 0!==r.org&&("string"==typeof r.org&&""!==r.org.trim()?i=r.org.trim():t.push(Ze("org","org must be the name or id of an organisation")));const s=r.templates;if(void 0===s)return{templates:n,problems:t,...i?{org:i}:{}};if(!Array.isArray(s))return t.push(Ze("templates","templates must be a list")),{templates:n,problems:t,...i?{org:i}:{}};const o=new Set;for(let e=0;e<s.length;e++){const r=`templates.${e}`,a=s[e];if(!a||"object"!=typeof a){t.push(Ze(r,"a template must be a mapping"));continue}const c=a,l=c.name;if("string"!=typeof l||""===l.trim()){t.push(Ze(`${r}.name`,"a template needs a name"));continue}if(o.has(l)){t.push(Ze(`${r}.name`,`duplicate template name "${l}" — the later one is ignored`));continue}o.add(l);const u=c.rules,d=[];if(void 0!==u)if(Array.isArray(u))for(let e=0;e<u.length;e++){const n=et(u[e],`${r}.rules.${e}`,t);n&&d.push(n)}else t.push(Ze(`${r}.rules`,"rules must be a list"));const p={name:l,rules:d};"string"==typeof c.description&&(p.description=c.description),i&&(p.org=i),n.push(p)}return{templates:n,problems:t,...i?{org:i}:{}}}class nt extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalChainError"}}function rt(e){switch(e.type){case"single":return[e.approver];case"sequential":case"parallel":return e.approvers;case"signatures":return[]}}function it(e,t){return function(e){if("sequential"===e.type||"parallel"===e.type){if(!e.approvers||0===e.approvers.length)throw new nt("INVALID_SPEC",`${e.type} chain must have at least one approver`);const t=new Set;for(const n of e.approvers){if(t.has(n.id))throw new nt("INVALID_SPEC",`Duplicate approver id "${n.id}" in chain spec`);t.add(n.id)}if("parallel"===e.type&&void 0!==e.quorum&&(e.quorum<1||e.quorum>e.approvers.length||!Number.isInteger(e.quorum)))throw new nt("INVALID_SPEC",`parallel quorum must be an integer in [1, ${e.approvers.length}]; got ${e.quorum}`)}else if("single"===e.type){if(!e.approver?.id)throw new nt("INVALID_SPEC","single chain must declare an approver with an id")}else{if("signatures"!==e.type)throw new nt("INVALID_SPEC",`Unknown chain type: ${e.type}`);if(!Number.isInteger(e.required)||e.required<1)throw new nt("INVALID_SPEC",`signatures chain must require a whole number of signatures, at least 1; got ${e.required}`);if(!Array.isArray(e.approvers)||0===e.approvers.length)throw new nt("INVALID_SPEC","signatures chain must name who may sign (the rule's approvers)")}}(t),{chainId:e,spec:t,decisions:[],status:"pending"}}function st(e,t){if("pending"!==e.status)throw new nt("CHAIN_NOT_PENDING",`Chain ${e.chainId} is already ${e.status}; cannot accept more decisions`);const n=rt(e.spec);if(!("signatures"===e.spec.type?""!==t.approverId.trim():n.some(e=>e.id===t.approverId)))throw new nt("UNKNOWN_APPROVER","signatures"===e.spec.type?"A signature needs a name; sign in to sign this call.":`Approver "${t.approverId}" is not in chain ${e.chainId}`);if("sequential"===e.spec.type){const n=e.spec.approvers[e.decisions.length];if(n?.id!==t.approverId)throw new nt("UNKNOWN_APPROVER",`Sequential chain ${e.chainId} expects approver "${n?.id??"(end)"}" next; got "${t.approverId}"`)}if("parallel"===e.spec.type||"single"===e.spec.type||"signatures"===e.spec.type){const n=(t,n)=>"signatures"===e.spec.type?t.trim().toLowerCase()===n.trim().toLowerCase():t===n;if(e.decisions.some(e=>n(e.approverId,t.approverId)))throw new nt("DUPLICATE_DECISION","signatures"===e.spec.type?`${t.approverId} already signed this call; the next signature must come from someone else.`:`Approver "${t.approverId}" already decided on chain ${e.chainId}`)}const r=[...e.decisions,t];return{...e,decisions:r,status:ot(e.spec,r)}}function ot(e,t){const n=rt(e),r=function(e){switch(e.type){case"sequential":return e.approvers.length;case"parallel":return e.quorum??e.approvers.length;case"single":return 1;case"signatures":return e.required}}(e);let i=0,s=0;for(const e of t)"approve"===e.decision?i++:s++;switch(e.type){case"sequential":return s>0?"denied":i===n.length?"granted":"pending";case"parallel":if(i>=r)return"granted";return i+(n.length-t.length)<r?"denied":"pending";case"single":return 1===i?"granted":1===s?"denied":"pending";case"signatures":return s>0?"denied":i>=r?"granted":"pending"}}function at(){return Date.now()}function ct(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function lt(e){const t=`${e.kind}:${e.id}`;return e.argsBinding?`${t}|args=${e.argsBinding}`:t}class ut extends Error{approvers;code="APPROVER_NOT_ALLOWED";constructor(e,t,n){super(`${t?`${t} is`:"This host is"} not among the approvers this rule names (${function(e){const t=e.map(e=>{const t=Ie(e);return t?"owner"===t.kind?"the owner":"role"===t.kind?`a ${t.role}`:t.email:String(e)}).filter((e,t,n)=>n.indexOf(e)===t);return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}(e)}${n?` in ${n}`:""}); ask one of them.`),this.approvers=e,this.name="ApproverNotAllowedError"}}function dt(e,t){if(!t||0===t.length)return!0;const n=new Set(t.map(e=>ke(e)).filter(e=>!!e)),r=ke(e.decidedRole);if(r&&n.has(r))return!0;const i=e.decidedBy?.trim().toLowerCase();return!!i&&n.has(`user:${i}`)}function pt(e,t){const n=t&&t>1?t:1;return(e.signatures?e.signatures.by.length:1)>=n}function ft(e){return"once"===e?["once"]:"workspace"===e?["once","workspace"]:["once","workspace","always"]}function ht(e,t){return"workspace"===e?`workspace:${t??""}`:e}function mt(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const gt="punica.kernel.policy.v1",yt="punica.kernel.policy.v2";class wt{#v="execute";#b;#I=new Set;#k=new Map;#E=[];#S=1e3;constructor(e){this.#b=e??new Ce,this.#A()}#A(){const e=mt();if(e)try{const t=e.getItem(yt);if(t){const e=JSON.parse(t);if(e&&2===e.v)return"suggest"!==e.mode&&"execute"!==e.mode||(this.#v=e.mode),void this.#x(e.templates)}const n=e.getItem(gt);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#v=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#b.restoreAll(n),this.#w();try{e.removeItem(gt)}catch{}return}}}catch{}}#C(){const e=[];for(const[t,n]of this.#k)for(const r of n.values())e.push({scope:t,template:r});return e}#x(e){if(Array.isArray(e))for(const t of e){const e=t?.scope,n=t?.template;if("string"!=typeof e||!e)continue;if(!n||"string"!=typeof n.name)continue;let r=this.#k.get(e);r||(r=new Map,this.#k.set(e,r)),r.set(n.name,n)}}#T(e){const t=[];if(e){const n=this.#k.get(e);n&&t.push(...n.values())}const n=this.#k.get("global");return n&&t.push(...n.values()),t}#w(){const e=mt();if(e)try{let t={};try{const n=e.getItem(yt);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#v,exportedAt:at(),templates:this.#C()};e.setItem(yt,JSON.stringify(n))}catch{}}setMode(e){this.#v=e,this.#w()}getMode(){return this.#v}clearApprovals(){this.#b.clear(),this.#I.clear()}#P(e,t,n="audit",r){try{se.publishEvent({name:e,envelope:{id:se.createCorrelationId(),timestampMs:at(),source:"kernel:policy",kind:n,...r?.traceId?{traceId:r.traceId}:{},...r?.parentSpanId?{parentSpanId:r.parentSpanId}:{}},payload:r?.conversationId?{...t,conversationId:r.conversationId}:t})}catch{}}#N(e,t){return`${e}|${t}`}revokeApproval(e){const t=lt({kind:e.kind,id:e.id,argsBinding:e.argsBinding}),n="workspace"===e.scope?ht("workspace",e.workspaceId):ht(e.scope),r=this.#b.delete(t,n);return r&&(this.#M("revocation",{kind:e.kind,id:e.id,risk:"low",approval:"none"},void 0,e.scope,e.workspaceId),this.#P("approval.revoked",{kind:e.kind,id:e.id,scope:e.scope,workspaceId:e.workspaceId}),this.#I.delete(this.#N(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#b.list();if(t)return n;const r=at();return n.filter(e=>!ct(e,r))}#R(e,t){const n=[lt(e)];e.argsBinding&&e.argsBinding!==Pe&&n.push(lt({...e,argsBinding:Pe}));const r=[],i=at();for(const s of n){const n=this.#b.get(s,t);if(n&&(dt(n,e.approvers)&&pt(n,e.signatures))){if(!ct(n,i))return{rec:n,key:s};r.push({rec:n,key:s})}}return r[0]??null}hasApproval(e,t,n){const r="workspace"===t?n?.workspaceId?ht("workspace",n.workspaceId):null:ht(t);if(null===r)return!1;const i=this.#R(e,r);if(!i)return!1;const{rec:s,key:o}=i;if(ct(s,at())){const e=this.#N(o,r);return this.#I.has(e)||(this.#I.add(e),this.#P("approval.expired",{kind:s.kind,id:s.id,scope:s.scope,workspaceId:s.workspaceId,expiresAt:s.expiresAt,decidedBy:s.decidedBy},"warn")),!1}return!0}recordApproval(e,t,n){if("workspace"===t&&!n?.workspaceId)throw new Error("[Policy] Workspace scope requires workspaceId in context");const r=lt(e),i="workspace"===t?ht("workspace",n?.workspaceId):ht(t),s=function(e){const t=e?.decidedBy??ye(),n=Ie(e?.decidedRole);if("owner"===n?.kind)return{email:t,roles:["owner"]};if("role"===n?.kind)return{email:t,roles:[n.role]};if("user"===n?.kind)return{email:n.email,roles:[]};if(e?.decidedBy)return{email:t,roles:[]};const r=ge()?.orgs;return{email:t,roles:we(),...Array.isArray(r)?{orgs:r}:{}}}(n);let o;if(e.approvers&&e.approvers.length>0){if(o=Ee(s,e.approvers,e.org),!o)throw new ut(e.approvers,s.email,e.org)}else o=ke(n?.decidedRole);const a=e.signatures&&e.signatures>1?e.signatures:1;let c,l=n?.chainRef;if(a>1){const t=this.#N(r,i),n=this.#b.get(r,i),u=st(function(e,t,n,r){let i=it(e,{type:"signatures",required:n,approvers:r});if(t?.signatures&&t.signatures.need===n)for(const e of t.signatures.by)i=st(i,{approverId:e.by,decision:"approve",timestampMs:e.atMs,...e.role?{role:e.role}:{}});return i}(t,n?.signatures&&n.signatures.need===a&&n.signatures.by.length<a&&!ct(n,at())?n:void 0,a,e.approvers??[]),{approverId:s.email??"",decision:"approve",timestampMs:at(),...o?{role:o}:{}});c={need:a,by:u.decisions.map(e=>({by:e.approverId,...e.role?{role:e.role}:{},atMs:e.timestampMs}))},l=t}const u={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:s.email,...o?{decidedRole:o}:{},timestampMs:at(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,argsBinding:e.argsBinding,argsPreview:e.argsPreview,chainRef:l,...c?{signatures:c}:{}};return this.#b.set(r,i,u),c&&c.by.length<c.need?(this.#M("signature",e,void 0,t,n?.workspaceId),this.#P("approval.signed",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:u.decidedBy,...u.decidedRole?{decidedRole:u.decidedRole}:{},signatures:{need:c.need,have:c.by.length,by:c.by}},"audit",{traceId:n?.traceId,parentSpanId:n?.parentSpanId,conversationId:n?.conversationId}),u):(this.#M("approval",e,void 0,t,n?.workspaceId),this.#I.delete(this.#N(r,i)),this.#P("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:u.decidedBy,...u.decidedRole?{decidedRole:u.decidedRole}:{},...c?{signatures:{need:c.need,have:c.by.length,by:c.by}}:{},expiresAt:n?.expiresAt},"audit",{traceId:n?.traceId,parentSpanId:n?.parentSpanId,conversationId:n?.conversationId}),u)}declineApproval(e,t){this.#M("decline",e,void 0,void 0,t?.workspaceId),this.#P("approval.declined",{request:e,workspaceId:t?.workspaceId,decidedBy:t?.decidedBy??ye(),...ke(t?.decidedRole)?{decidedRole:ke(t?.decidedRole)}:{},reason:t?.reason},"audit",{traceId:t?.traceId,parentSpanId:t?.parentSpanId,conversationId:t?.conversationId})}#M(e,t,n,r,i){this.#E.push({timestampMs:at(),type:e,request:t,decision:n,scope:r,workspaceId:i}),this.#E.length>this.#S&&this.#E.splice(0,this.#E.length-this.#S)}evaluate(e,t){const n=n=>{const r=t,i=r?.correlationId,s=r?.traceId??i,o=r?.parentSpanId;se.publishEvent({name:"policy.evaluated",envelope:{id:se.createCorrelationId(),correlationId:i,traceId:s,...o?{parentSpanId:o}:{},timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})},r=Qe(this.#T(t?.workspaceId),{kind:e.kind,id:e.id,action:e.action,...e.egress?{egress:e.egress}:{},...e.sensitive?{sensitive:e.sensitive}:{}},t?.args,{sensitivePaths:t?.redactedPaths,argsWhollyRedacted:t?.argsWhollyRedacted,onRedactedCondition:(e,t,n)=>{console.warn(`[Policy] Rule ${e}#${t} tests "${n}", which the redactor has already replaced — the condition cannot match and the rule does not apply.`)}}),i=r?.ref;if(r&&"deny"===r.ref.effect){const s={allowed:!1,mode:"execute",requiresApproval:!1,reason:r.ref.reason??`Denied by policy rule ${r.ref.template}#${r.ref.ruleIndex}.`,policyRule:i};return this.#M("decision",e,s,void 0,t?.workspaceId),n(s),s}if(r&&"allow"===r.ref.effect){const s={allowed:!0,mode:"execute",requiresApproval:!1,reason:r.ref.reason??`Allowed by policy rule ${r.ref.template}#${r.ref.ruleIndex}.`,policyRule:i};return this.#M("decision",e,s,void 0,t?.workspaceId),n(s),s}const s=r&&"require"===r.ref.effect?r.rule.approval??"step":e.approval,o=r&&"require"===r.ref.effect?r.rule.scope:void 0,a=r&&"require"===r.ref.effect&&r.rule.approvers?.length?r.rule.approvers:void 0,c=a&&r?.ref.org?r.ref.org:void 0,l=a&&r?.ref.signatures&&r.ref.signatures>1?r.ref.signatures:void 0,u=a?{...e,approvers:a,...c?{org:c}:{},...l?{signatures:l}:{}}:e;if("suggest"===this.#v&&s===e.approval){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#M("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===s){const r={allowed:!0,mode:"execute",requiresApproval:!1,policyRule:i};return this.#M("decision",e,r,void 0,t?.workspaceId),n(r),r}if("plan"===s){const s=ft(o).some(e=>this.hasApproval(u,e,t))?{allowed:!0,mode:"execute",requiresApproval:!1,policyRule:i}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:r?.ref.reason??"Approval required (plan).",policyRule:i};return o&&(s.maxScope=o),a&&(s.approvers=a),c&&(s.org=c),l&&(s.signatures=l),this.#M("decision",e,s,void 0,t?.workspaceId),n(s),s}const d=ft(o).some(e=>this.hasApproval(u,e,t))?{allowed:!0,mode:"execute",requiresApproval:!1,policyRule:i}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:r?.ref.reason??"Approval required (step).",policyRule:i};return o&&(d.maxScope=o),a&&(d.approvers=a),c&&(d.org=c),l&&(d.signatures=l),this.#M("decision",e,d,void 0,t?.workspaceId),n(d),d}requestApproval(e,t){se.publishEvent({name:"policy.approvalRequested",envelope:{id:se.createCorrelationId(),correlationId:t?.correlationId,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,context:{workspaceId:t?.workspaceId,traceId:t?.traceId,...t?.reason?{reason:t.reason}:{}}}})}exportState(){return{version:3,exportedAt:at(),mode:this.#v,approvals:this.listApprovals({includeExpired:!0}),templates:this.#C().map(e=>({...e.template,workspaceId:e.template.workspaceId??("global"===e.scope?void 0:e.scope)}))}}importState(e,t){if(!e||"object"!=typeof e)throw new Error("[Policy] Invalid export data");if(2!==e.version&&3!==e.version)throw new Error(`[Policy] Unsupported export version: ${e.version}. Expected 2 or 3.`);const n=t?.merge??!1,r=Array.isArray(e.approvals)?e.approvals:[];"suggest"!==e.mode&&"execute"!==e.mode||(this.#v=e.mode);const i=Array.isArray(e.templates)?e.templates:[];n||this.#k.clear();for(const e of i){if(!e||"string"!=typeof e.name)continue;const t=e.workspaceId??"global",r=this.#k.get(t);if(n&&r?.has(e.name))continue;let i=r;i||(i=new Map,this.#k.set(t,i)),i.set(e.name,e)}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?ht("workspace",r):ht(n);"string"==typeof i&&i&&(this.#b.has(t,i)||(this.#b.set(t,i,e),s++))}else s=this.#b.restoreAll(r),this.#I.clear();return this.#w(),se.publishEvent({name:"policy.stateImported",envelope:{id:se.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:s,merged:n}}),s}saveTemplate(e,t,n){const r=n??"global";let i=this.#k.get(r);i||(i=new Map,this.#k.set(r,i));const s={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??at(),updatedAtMs:at()};i.set(e,s),this.#w()}getTemplate(e,t){const n=t??"global",r=this.#k.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#k.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#k.get(n);if(!r)return!1;const i=r.delete(e);return i&&this.#w(),i}exportAuditLog(e){const t=e?.format??"json";let n=[...this.#E];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:at(),version:1,count:n.length,entries:n},null,2)}}const vt=new wt(Te);var bt={manager:vt},It=Object.freeze({__proto__:null,ARGS_BINDING_ANY:Pe,ApproverNotAllowedError:ut,PolicyManager:wt,canonicalDigest:Oe,computeArgsBinding:_e,default:bt,manager:vt,matchRules:Qe,scopesWithin:ft,validatePolicyTemplates:tt});async function kt(e,n,r){if(r())e.status="cancelled";else if("success"!==e.status&&"cancelled"!==e.status){e.status="running",e.startedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runStepStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=n,s=await t(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:n,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:"kernel.planExecution"},trace:{traceId:i,parentSpanId:void 0},policy:{mode:"execute"}});e.status="success",e.finishedAtMs=Date.now(),e.correlationId=r,e.resultPayload=o,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:n,step:e}})}catch(t){const r=String(t?.message??t);if(r.includes("Approval required")||r.includes("CAPABILITY_APPROVAL_REQUIRED"))throw e.status="blocked",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}}),new Error("blocked");throw e.status="failed",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:n,step:e}}),t}}}async function Et(e,t,n,r){let i=e;if(i||(i=function(){try{const e=punica.kernel.Events.manager.getRecent(200);for(let t=e.length-1;t>=0;t--){const n=e[t],r=n?.name??n?.event?.name,i=n?.payload??n?.event?.payload;if("ai.planGenerated"===r&&i?.plan?.planId)return i.plan}}catch{}return null}(),i&&r(i)),!i)throw new Error("[AI] No plan to run");return await async function(e,t,n){const r=t&&t.planId===e.planId&&!t.finishedAtMs?t:{runId:punica.kernel.Events.manager.createCorrelationId(),planId:e.planId,startedAtMs:Date.now(),steps:e.steps.map(e=>({...e,status:"pending"}))};punica.kernel.Events.manager.publishEvent({name:"ai.runStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}});for(const e of r.steps)try{await kt(e,r.runId,n)}catch(e){if("blocked"===e?.message)break;break}return r.finishedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}}),r}(i,t,n)}const St={once:0,workspace:1,always:2};function At(e,t,n,r){const i=n.get(e);if(!i)return!1;const s=i.signedScope??(o=t,(a=i.maxScope)&&St[o]>St[a]?a:o);var o,a;const c=punica.kernel.Policy.manager.recordApproval({kind:i.kind,id:i.id,risk:i.risk,approval:i.approval,reason:i.reason,argsBinding:i.argsBinding,argsPreview:i.argsPreview,...i.approvers?{approvers:i.approvers}:{},...i.org?{org:i.org}:{},...i.signatures&&i.signatures>1?{signatures:i.signatures}:{}},s,{workspaceId:i.workspaceId,...r?.decidedBy?{decidedBy:r.decidedBy}:{},...r?.decidedRole?{decidedRole:r.decidedRole}:{},...i.traceId?{traceId:i.traceId}:{},...i.correlationId?{parentSpanId:i.correlationId}:{}}),l=c?.signatures;if(l&&l.by.length<l.need){const t={...i,signed:l.by,signedScope:s};return n.set(e,t),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalSigned",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:t,scope:s,signatures:{need:l.need,have:l.by.length}}}),!0}return n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.approvalRecorded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:i,scope:s}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"approved"}}),!0}function xt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ct(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Tt(e,t,n){if(!xt(t)||!0===t.truncated)return{...n};const r={};for(const n of Object.keys(e))n in t||(r[n]=e[n]);for(const i of Object.keys(n)){const s=i in t&&i in e&&Ct(n[i],t[i]);r[i]=s?e[i]:n[i]}return r}const Pt=[];function Nt(e){Pt.push(e)}function Mt(){const e={};for(const t of Pt)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function Rt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $t(e){return"string"==typeof e}function _t(e){return"string"==typeof e&&e.trim().length>0}function Ot(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const Lt=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"]),jt=new Set(["light","dark","auto"]),Dt=new Set(["compact","comfortable"]),Ft=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const qt=new class{validate(e){const t=[];if(!Rt(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)}`),Rt(e.identity)?(_t(e.identity.id)||t.push("identity.id must be a non-empty string"),_t(e.identity.name)||t.push("identity.name must be a non-empty string"),_t(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),Rt(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys(Mt()),r=new Set([...Lt,...n]);e.shell.activeModules.forEach((e,n)=>{$t(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&&(Rt(e.shell.layout)?(_t(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),Rt(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(Rt(e.theme)?(jt.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||Dt.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"),Rt(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||Ot(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||Ot(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)=>{$t(e)&&Ft.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 Bt;function Ut(e){Bt=e}function Vt(){return Bt??qt}function Wt(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 Kt{#$=new Map;#_;register(e){if(this.#$.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#$.set(e.identity.id,e),void 0===this.#_&&(this.#_=e.identity.id)}replace(e){this.#$.set(e.identity.id,e),void 0===this.#_&&(this.#_=e.identity.id)}get(e){return this.#$.get(e)}getActive(){if(void 0===this.#_||!this.#$.has(this.#_))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#$.get(this.#_)}setActive(e){if(!this.#$.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#_=e}switchProfile(e){if(!this.#$.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#_=e,Wt({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#$.has(e)}list(){return Array.from(this.#$.values())}}const Gt={manager:new class{registry=new Kt;get validator(){return Vt()}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.#O(t)}this.#O(e)}#O(e){const t=this.validator.validate(e);if(!t.valid)throw Wt({name:"shell.profile.load_failed",payload:{errors:t.errors}}),new Error(`ApplicationProfile validation failed:\n ${t.errors.join("\n ")}`);this.registry.replace(t.profile),this.registry.setActive(t.profile.identity.id),Wt({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}};function Yt(e){return!(!e||"object"!=typeof e)&&"hub-only"===e.agentVisibility}function zt(e){const t=e?.action;return Array.isArray(t)&&t.includes("ui.reveal")}function Jt(){const e=function(){try{const e=globalThis,t=e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.shell?.activeModules;return Array.isArray(t)?t:void 0}catch{return}}();if(e)return e.includes(Ht);try{const e=Gt.manager.registry.getActive()?.shell?.activeModules;return!Array.isArray(e)||e.includes(Ht)}catch{return!0}}const Ht="shell.views";const Qt={estimate:e=>Math.ceil(e.length/4)};function Zt(){return Qt}function Xt(e){const t=Zt();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 en={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 tn="[elided tool result:";function nn(e){const t=(e.content??"").length;return`${tn} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function rn(e,t){let n=0;for(let r=e.length-1;r>0;r--){const i=e[r].role;if(("assistant"===i||"user"===i)&&(n++,n>=t))return r}return 1}async function sn(e,t,n,r){const i=Xt(e);if(i<=t.maxContextTokens)return{messages:[...e],compacted:!1,strategy:"none",preTokens:i,postTokens:i,estSavedTokens:0};const s=Math.floor(.6*t.maxContextTokens),o=rn(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(tn)?{...e,content:nn(e)}:e);let c=Xt(a);if(c<=s||!t.summarizeWhenOver||!n){const e=c<i;return{messages:a,compacted:e,strategy:e?"elide":"none",preTokens:i,postTokens:c,estSavedTokens:i-c}}const l=a.slice(1,o),u=a.slice(o);try{const e="Summarize this agent conversation segment so a follow-up model call can continue the task without the originals. Keep: the user goal, decisions made, tool outcomes (names + key results), and open questions. Be dense and factual; no preamble.\n\n"+l.map(e=>`${e.role}: ${e.content??""}`).join("\n"),t=await n("llm.chat",{messages:[{role:"user",content:e}],profile:"fast"},r??{}),s=(t?.text??"").trim();if(s){const e=[a[0],{role:"assistant",content:`[conversation summary]\n${s}`},...u];return c=Xt(e),{messages:e,compacted:!0,strategy:"summarize",preTokens:i,postTokens:c,estSavedTokens:i-c}}}catch{}return{messages:a,compacted:c<i,strategy:"elide",preTokens:i,postTokens:c,estSavedTokens:i-c}}const on=Object.freeze({narrowThreshold:24,catalogTopN:100,topCategories:64,hotSetSize:40});function an(){const e=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.agent?.toolSelection}catch{return}}();if(e)return e;try{return Gt.manager.registry.getActive()?.agent?.toolSelection}catch{return}}function cn(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function ln(e,t){if(!(e&&e.calls>0))return 0;const n=Math.max(0,(t-e.last)/864e5);return Math.pow(2,-n/14)*(e.calls/(e.calls+1))*((Math.min(Math.max(e.ok,0),e.calls)+1)/(e.calls+2))}function un(e,t,n,r){return r>0?async(i,s)=>function(e,t,n,r){if(!(r>0&&t))return e;const i=e.map((e,i)=>{const s="number"==typeof e.score?e.score:0,o=ln(t[String(e.id)],n);return{r:e,i:i,score:s*(1+r*o)}});return i.sort((e,t)=>t.score-e.score||e.i-t.i),i.map(({r:e,score:t})=>({...e,score:t}))}(await e(i,s),t,n,r):e}function dn(e,t,n){return!!e&&(!n.includes(e)&&("success"===t||"failed"===t))}const pn="punica.kernel.ai.toolUsage.v1";function fn(e){const t=e;if(!t||"object"!=typeof t)return;const n=Number(t.calls),r=Number(t.ok),i=Number(t.last);return!Number.isFinite(n)||n<=0||!Number.isFinite(i)||i<=0?void 0:{calls:Math.floor(n),ok:Number.isFinite(r)?Math.min(Math.max(Math.floor(r),0),n):0,last:Math.floor(i)}}function hn(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const mn=new class{async read(){const e=hn();if(!e)return{};try{const t=e.getItem(pn);return t?function(e){const t=e,n=t?.tools;if(!n||"object"!=typeof n)return{};const r={};for(const[e,t]of Object.entries(n)){const n=fn(t);n&&e&&(r[e]=n)}return r}(JSON.parse(t)):{}}catch{return{}}}async record(e,t,n){const r=hn();var i;if(r)try{r.setItem(pn,(i=function(e,t,n,r,i=500){if(!t)return e;const s={...e},o=s[t];s[t]={calls:(o?.calls??0)+1,ok:(o?.ok??0)+(n?1:0),last:r};const a=Object.keys(s);return a.length>i&&a.sort((e,t)=>s[e].last-s[t].last||(e<t?-1:1)).slice(0,a.length-i).forEach(e=>delete s[e]),s}(await this.read(),e,t,n),JSON.stringify({v:1,tools:i},null,2)))}catch{}}async forget(){const e=hn();if(e)try{e.removeItem(pn)}catch{}}};let gn=mn;function yn(){return gn}async function wn(e,t,n){try{await yn().record(e,t,n)}catch{}}function vn(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}async function bn(e,t,n,r){try{const i=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))??[],s=new Map;let o=!1,a=0;i.forEach((e,t)=>{null!=e?.id&&s.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=vn(String(n.id)),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}(e);if(0===s.size||o&&a<=1e-9)return function(e,t){const n=[],r=[...e.values()],i=new Array(r.length).fill(0);let s=!0;for(;s&&n.length<t;){s=!1;for(let e=0;e<r.length&&n.length<t;e++){const t=i[e];t<r[e].length&&(n.push(r[e][t]),i[e]=t+1,s=!0)}}return n}(c,n.catalogTopN);const l=e=>s.has(String(e.id))?s.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=>s.has(String(e.id))).sort((e,t)=>l(e)-l(t)),r=t.filter(e=>!s.has(String(e.id)));f.push(...n,...r)}return f.slice(0,n.catalogTopN)}catch{return e}}async function In(e){const{entries:t,intent:n,budget:r,rank:i}=e,s=new Set((e.pinnedIds??[]).map(String)),o=s.size?t.filter(e=>s.has(String(e.id))):[],a=function(e){const t=e.usagePriorWeight;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:1}(r),c=un(i,e.usage??(a>0?await async function(){try{return await yn().read()??{}}catch{return{}}}():{}),e.nowMs??Date.now(),a),l=function(e,t,n,r=[]){const i=[],s=new Set,o=new Map,a=(e,t)=>{const n=String(e.id);if(i.push(e),s.add(n),t){const e=vn(n);o.set(e,(o.get(e)??0)+1)}};for(const e of r){if(i.length>=t)break;null==e?.id||s.has(String(e.id))||a(e,!1)}for(const r of e){if(i.length>=t)break;const e=String(r?.id??"");e&&!s.has(e)&&((o.get(vn(e))??0)>=n||a(r,!0))}for(const n of e){if(i.length>=t)break;const e=String(n?.id??"");e&&!s.has(e)&&a(n,!0)}return i}(await bn(t,n,r,c),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),u=new Set(l.map(e=>String(e.id)));return{hot:l,deferred:t.filter(e=>!u.has(String(e.id)))}}const kn=/<\/?(tool_call|function|parameter)\b/i;function En(e){const t=(e??"").trim();return 0===t.length||kn.test(t)&&t.replace(/<[^>]*>/g,"").trim().length<20}const Sn=["capability.search","capability.describe"];function An(e){const t=e?.code;if("CAPABILITY_APPROVAL_REQUIRED"===t)return!0;const n=String(e?.message??e);return n.includes("Approval required")||n.includes("CAPABILITY_APPROVAL_REQUIRED")}function xn(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Cn(e){const t=String(e?.message??e).trim();return""===t?"Unknown error.":t}function Tn(e,t,n){return new Promise(r=>{const i=punica.kernel.Events.manager;let s=!1;const o=e=>{if(!s){s=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=i.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed","ai.pendingApprovalEdited","ai.pendingApprovalReferred","ai.pendingApprovalSigned"],n=>{const r=n?.payload?.payload??n?.payload,i=r?.pending;if(i?.id===e&&(!i?.traceId||i.traceId===t))if("ai.pendingApprovalReferred"!==n?.name&&"ai.pendingApprovalSigned"!==n?.name){if("ai.pendingApprovalEdited"===n?.name){const e=r?.arguments;if(!e||"object"!=typeof e||Array.isArray(e))return;return void o({decision:"edited",arguments:e,preview:i?.argsPreview})}o({decision:"ai.approvalRecorded"===n?.name?"approved":"dismissed"})}else clearTimeout(l)})??void 0,c=setInterval(()=>{n()&&o({decision:"cancelled"})},250),l=setTimeout(()=>o({decision:"timeout"}),18e4)})}async function Pn(e,t,n,r,i){if(!n())return"resumed";const s=Date.now();for(Nn("ai.agentPaused",e,"audit",{runId:e,...t?{sessionId:t}:{}},i);n();){if(r())return"cancelled";await new Promise(e=>setTimeout(e,100))}return Nn("ai.agentResumed",e,"audit",{runId:e,pausedMs:Date.now()-s,...t?{sessionId:t}:{}},i),"resumed"}function Nn(e,t,n,r,i){const s=punica.kernel?.Events?.manager;s&&s.publishEvent({name:e,envelope:{id:s.createCorrelationId(),correlationId:t,traceId:t,...i?.spanId?{spanId:i.spanId}:{},...i?.parentSpanId?{parentSpanId:i.parentSpanId}:{},timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}function Mn(e){const{thinking:t,...n}=e;return n}function Rn(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function $n(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function _n(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 On(e,t,n){const r=await e("capability.schemaExport",{filter:t.toolFilter,mode:"ai-tools"},n);let i=r?.capabilities??[];if(console.log("[AgentLoop] schemaExport raw catalog",{total:i.length,byCategory:i.reduce((e,t)=>{const n=vn(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(Rn).sort($n),deferredIndex:[]};const s=i.filter(e=>Sn.includes(String(e.id)));i=i.filter(e=>!Sn.includes(String(e.id))&&(!function(e){const t=String(e?.id??"");return!("core"!==String(e?.origin??"core")||!t.startsWith("ai.")&&(t.startsWith("capability.")?Sn.includes(t):!t.startsWith("llm.")))}(e)&&(!Yt(e)&&(!(zt(e)&&!Jt())&&(!(!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={...on};for(const n of[an(),e]){if(!n)continue;for(const e of Object.keys(t))cn(n[e])&&(t[e]=Math.floor(n[e]));for(const e of["perCategoryCap","rankLimit"])cn(n[e])&&(t[e]=Math.floor(n[e]));const e=n.usagePriorWeight;"number"==typeof e&&Number.isFinite(e)&&e>=0&&(t.usagePriorWeight=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:i.length,includeIvyNodes:!!t.includeIvyNodes,includeMcp:!!t.includeMcp,allowedMcpServers:t.allowedMcpServers??[],willTier:!1!==t.deferToolLoading&&i.length>o.narrowThreshold,narrowThreshold:o.narrowThreshold}),i.length<=o.narrowThreshold)return{hot:i.map(Rn).sort($n),deferredIndex:[]};const a=async(t,r)=>{const i=await e("capability.recommend",{intent:t,limit:r},n);return i?.recommendations??[]};if(!1===t.deferToolLoading){return{hot:(await bn(i,t.query,o,a)).map(Rn).sort($n),deferredIndex:[]}}const{hot:c,deferred:l}=await(u={entries:i,intent:t.query,budget:o,pinnedIds:t.pinnedTools,rank:a},In(u));var u;const d=new Set(c.map(e=>String(e.id))),p="none"!==t.deferredIndex,f=p?s.length===Sn.length?s.map(Rn):[{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}}}}]:[],h=p?l.map(e=>({id:String(e.id),line:_n(e),category:vn(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:h.length,deferredIndex:t.deferredIndex??"full",hotSetSize:o.hotSetSize,pinned:t.pinnedTools??[],hotIds:[...d]}),{hot:[...f,...c.map(Rn)].sort($n),deferredIndex:h}}async function Ln(e,t,n,r,i){let s,o=t.arguments;const a=()=>({id:t.id,name:t.name,arguments:o,status:"success",...s?{edited:!0,editedFields:s}:{}}),c=String(n.trace?.traceId??n.sessionId??"");let l=0,u=!1;for(;;){let d;try{const r=await e(t.name,o,n);return{...a(),status:"success",resultPayload:r}}catch(e){const n=Dn(e),r=Boolean(n)&&n!==t.name;if(!An(e)||l>=jn||l>0&&!r&&!u)return{...a(),status:"failed",error:String(e?.message??e)};d=r?n:t.name,u=r}const p=await Tn(d,c,r);if("edited"===p.decision){const e=Tt(o,p.preview,p.arguments),n=Object.keys({...o,...e}).filter(t=>!Fn(o[t],e[t])),r={...s??{}};for(const e of n)e in p.arguments?r[e]=p.arguments[e]:delete r[e];o=e,s=r,i&&Nn("ai.agentArgumentsEdited",i.runId,"audit",{runId:i.runId,toolCallId:t.id,name:t.name,changedKeys:n,argsPreview:p.preview},{parentSpanId:i.parentSpanId});continue}if("approved"!==p.decision){const e="dismissed"===p.decision?"the person denied it":"cancelled"===p.decision?"the run was stopped":"nobody answered in time";return{...a(),status:"blocked",error:`tool "${t.name}" not approved: ${e}`}}l+=1}}const jn=3;function Dn(e){const t=e?.details;return"string"==typeof t?.capability?t.capability:void 0}function Fn(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}async function qn(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Vn(n)}\nRejected arguments:\n${Vn(r)}\nValidation errors: ${i}\nReturn ONLY a JSON object with the corrected arguments — no prose, no code fence.`;try{const t=await e("llm.chat",{messages:[{role:"user",content:o}],correlationId:s.sessionId},s);return function(e){let t=(e??"").trim();if(!t)return;const n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");e>=0&&n>e&&(t=t.slice(e,n+1))}try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch{}}(t?.text??"")}catch{return}}async function Bn(e,t,n,r,i,s){let o=t.arguments,a=!1,c="";for(let l=0;l<=2;l++){const u=await Ln(e,{...t,arguments:o},r,i,s);if("failed"!==u.status||!xn(u.error))return a&&!u.edited?{...u,arguments:o,repaired:!0}:u;if(c=u.error??"",2===l||i())break;const d=await qn(e,t.name,n,o,c,r);if(!d)break;o=d,a=!0}const l={id:t.id,name:t.name,arguments:o,status:"failed",error:c||"input validation failed"};return a&&(l.repaired=!0),l}function Un(e){return Zt().estimate(e)}function Vn(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Wn(e,n,r,i,s=()=>!1){const o=punica.kernel.Events.manager,a=i??o.createCorrelationId(),c=e.trace?.traceId??a,l="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,u=(d=e.profile,en[d??"balanced"]);var d;const p=[],f=e.sessionId?punica.kernel?.AI?.sessions:void 0,h=[];let m=0;const g=[],y=Date.now();let w=0,v=0,b=0,I=0,k=!1,E=0,S=!1,A=0;const x=(t,n,r)=>{const i={inputTokens:w,outputTokens:v,totalTokens:b,latencyMs:Date.now()-y,steps:p.length,toolCalls:A};S&&(i.totalCost=E),k&&(i.cacheReadTokens=I);const s={runId:a,finishReason:t,steps:p,usage:i};if(void 0!==n&&(s.finalText=n),void 0!==r&&(s.error=r),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:p.length}),(t=>{if(f&&e.sessionId&&0!==m)try{const n=[{role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}},...g];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}:{}}));f.appendMessages(e.sessionId,r,{runId:a})}catch(e){console.warn("[AgentLoop] session persist failed:",e)}})(n),f&&e.sessionId&&m>0)try{f.recordUsage?.(e.sessionId,i)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Nn("ai.agentFinished",a,"audit",{runId:a,finishReason:t,finalText:n,usage:i,...void 0!==r?{error:r}:{},...e.sessionId?{sessionId:e.sessionId}:{}}),s},C="string"==typeof e.coreId&&""!==e.coreId.trim()?e.coreId.trim():void 0;Nn("ai.agentStarted",a,"audit",{runId:a,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{},...e.stance?{stance:e.stance}:{},...C?{coreId:C}:{}});const T=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!T)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),x("error",void 0,"The capability gateway is unavailable.");const P=await t(),N=function(e,t,n,r,i,s){return{sessionId:e,workspaceId:r,actor:{type:"ai",id:"ai:agent"},origin:{kind:"ai",id:"kernel.agentLoop"},trace:{traceId:t,parentSpanId:n},policy:{mode:"execute",...s?{stance:s}:{}},...i?{signal:i}:{}}}(a,c,e.trace?.parentSpanId,P,r,e.stance);let M;if(e.sessionId&&(N.conversationId=e.sessionId),"ask"===e.stance)M={hot:[],deferredIndex:[]};else try{M=await On(T,e,N)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),x("error",void 0,Cn(e))}const R=[...M.hot];console.log("[AgentLoop] tool catalog built",{hot:R.length,deferred:M.deferredIndex.length,toolFilter:e.toolFilter??null,names:R.map(e=>e.name)});const $=new Map(R.map(e=>[e.name,e.parameters])),_=new Map(M.deferredIndex.map(e=>[e.id,e])),O=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!$.has(String(e.id))).map(Rn).sort($n);for(const e of n)R.push(e),$.set(e.name,e.parameters),_.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:R.length}),n.length};if(h.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 i=t.dependencies?.python;i&&n.push(`Python deps (${i.source}, ${i.count}): ${(i.names??[]).join(", ")}`);const s=t.dependencies?.node;s&&n.push(`Node deps (${s.source}, ${s.count}`+(s.dev?` + ${s.dev} dev`:"")+`): ${(s.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 T("workspace.projectContext",{},N));e&&h.push({role:"system",content:e})}catch(e){console.warn("[AgentLoop] projectContext orientation unavailable:",e)}if(M.deferredIndex.length>0&&h.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."}}(M.deferredIndex)),f&&e.sessionId)try{h.push(...f.getContextMessages(e.sessionId))}catch(e){console.warn("[AgentLoop] session seed failed; running cold:",e)}h.push({role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}}),m=h.length;let L=0,j=!1;for(let t=0;t<l;t++){if(n())return x("cancelled");if("cancelled"===await Pn(a,e.sessionId,s,n))return x("cancelled");const r=punica.kernel?.Events?.manager?.createCorrelationId?.()??`${a}-step-${t}`,i={...N,trace:{traceId:c,parentSpanId:r}},o=e=>{Nn("ai.agentStep",a,"audit",{runId:a,turn:Mn(e)},{spanId:r})};let l,d=!1;if(Xt(h)>u.maxContextTokens){const e=await sn(h,u,T,i);e.compacted&&(h.splice(0,h.length,...e.messages),L=0,d=!0,Nn("ai.agentContextCompacted",a,"info",{runId:a,step:t,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const f=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:t,messageCount:h.length,toolsSent:R.length,toolChoice:"auto",toolNames:R.map(e=>e.name)});const n={stableToolsAndSystem:!0,stableMessagePrefix:L,cacheKey:a};l=await T("llm.chatStream",{messages:h,...R.length>0?{tools:R,toolChoice:"auto"}:{},correlationId:a,cacheHints:n,...e.profile?{profile:e.profile}:{},...C?{providerId:C}:{}},i),L=h.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:t,textLen:(l?.text??"").length,toolCalls:l?.toolCalls?.length??0})}catch(e){console.error("[AgentLoop] llm.chatStream call failed; aborting run:",e);const n=e?.code,r="CAPABILITY_DENIED"===n||An(e);return o({index:t,toolCalls:[],latencyMs:Date.now()-f,outcome:r?"blocked":"error",error:Cn(e)}),x(r?"blocked":"error",void 0,Cn(e))}if(n())return o({index:t,toolCalls:[],latencyMs:Date.now()-f,outcome:"cancelled"}),x("cancelled");const m=Date.now()-f,y=(l.text??"").trim(),P="string"==typeof l.thinking?l.thinking:void 0,M=l.toolCalls??[],D={index:t,assistantText:y||void 0,thinking:P,toolCalls:[],latencyMs:m},F=l.usage,q=l.meta;F?(D.usage=F,w+=F.inputTokens??0,v+=F.outputTokens??0,b+=F.totalTokens??(F.inputTokens??0)+(F.outputTokens??0),"number"==typeof F.cacheReadInputTokens&&(I+=F.cacheReadInputTokens,k=!0)):q&&(D.usage={inputTokens:q.promptTokens,outputTokens:q.completionTokens,totalTokens:q.promptTokens+q.completionTokens},w+=q.promptTokens,v+=q.completionTokens,b+=q.promptTokens+q.completionTokens),q&&"number"==typeof q.totalCost&&(E+=q.totalCost,S=!0);const B={runId:a,step:t,estToolDefTokens:Un(JSON.stringify(R)),estHistoryTokens:h.filter(e=>"system"!==e.role).reduce((e,t)=>e+Un(t.content??""),0),estSystemTokens:h.filter(e=>"system"===e.role).reduce((e,t)=>e+Un(t.content??""),0),toolCount:R.length,deferredToolCount:_.size,compactionApplied:d};if(D.usage&&(B.reportedInputTokens=D.usage.inputTokens,B.reportedOutputTokens=D.usage.outputTokens,"number"==typeof D.usage.cacheReadInputTokens&&(B.cacheReadTokens=D.usage.cacheReadInputTokens)),Nn("ai.agentTurnUsage",a,"audit",{...B},{parentSpanId:r}),0===M.length){if(p.push(D),o(D),!j&&En(y)){j=!0,h.push({role:"assistant",content:y}),h.push({role:"user",content:"Your last message was empty. In one or two sentences, say what you did and what the result was, without calling any tool."});continue}return x("final",y)}p.push(D),o(D);const U=M.map(e=>`${e.name}(${Vn(e.arguments)})`).join(", "),V={role:"assistant",content:y?`${y}\n[calling tools: ${U}]`:`[calling tools: ${U}]`,toolCalls:M.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};h.push(V),g.push(V);let W=!1;for(const o of M){if(n())return x("cancelled");if("cancelled"===await Pn(a,e.sessionId,s,n,{parentSpanId:r}))return x("cancelled");if(Nn("ai.agentToolCall",a,"info",{runId:a,toolCall:{id:o.id,name:o.name,arguments:o.arguments},status:"running"},{parentSpanId:r}),!$.has(o.name)&&_.has(o.name))try{O(await T("capability.describe",{ids:[o.name]},i))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const c=await Bn(T,o,$.get(o.name),i,n,{runId:a,parentSpanId:r});D.toolCalls.push(c),A++,dn(c.name,c.status,Sn)&&await wn(c.name,"success"===c.status,Date.now()),"success"===c.status&&"capability.describe"===c.name&&O(c.resultPayload),console.log("[AgentLoop] tool dispatched",{step:t,name:c.name,arguments:c.arguments,status:c.status,repaired:c.repaired??!1,error:c.error,resultPreview:"success"===c.status?Vn(c.resultPayload).slice(0,300):void 0}),Nn("ai.agentToolResult",a,"result",{runId:a,toolCall:c,status:c.status},{parentSpanId:r});const l="success"===c.status?Vn(c.resultPayload,u.toolResultMaxChars):`ERROR: ${c.error??"tool failed"}`,d={role:"tool",content:c.edited?`NOTE: the person changed the arguments before this call ran. Fields changed by the person: ${Vn(c.editedFields??{})}. This is their decision; do not call the tool again with the original arguments.\n${l}`:l,name:c.name,toolCallId:c.id};h.push(d),g.push(d),"blocked"===c.status&&(W=!0)}if(W)return x("blocked")}return x("maxSteps")}function Kn(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 Gn={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",POLICY_RULES:"runtime.policyRules"},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"}},Yn={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",EDIT_PENDING:"ai.editPendingArguments",REFER_PENDING:"ai.referPending",PAUSE_RUN:"ai.pauseRun",RESUME_RUN:"ai.resumeRun",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",TOOL_USAGE_FORGET:"ai.toolUsage.forget",TOOL_USAGE_LIST:"ai.toolUsage.list"},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 zn(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 Jn(e,t,n,r,i,s,o,a){punica.kernel?.Events?.manager&&punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:r,spanId:i,parentSpanId:s,timestampMs:Date.now(),source:o,kind:t},payload:a})}function Hn(e,t,n){try{punica.kernel?.Notifications?.manager?.push({id:"",timestamp:"",level:e,title:t,message:n,source:"ai"})}catch{}}function Qn(e){const t=e.calls>0?Math.round(e.ok/e.calls*100):0,n=`${e.calls} ${1===e.calls?"call":"calls"}`;return`${e.capabilityId} (${n}, ${t}% ok, weight ${e.prior.toFixed(2)})`}function Zn(e){return`${e} ${1===e?"capability":"capabilities"}`}const Xn=["ai.cellRejected","ai.cellRestored"];function er(e,t){const n=`cell ${t.cellId} in ${t.path}`;return"ai.cellRejected"===e?"replace"===t.kind?`The person undid your change to ${n}; it holds its previous source again. Do not redo it unless they ask.`:`The person removed the cell you added (${n}). Do not add it back unless they ask.`:"ai.cellRestored"===e?"replace"===t.kind?`The person restored your change to ${n}.`:`The person put back the cell you added (${n}).`:null}function tr(e){const t=e;if(!t||"object"!=typeof t)return null;const n="string"==typeof t.name&&t.payload&&"object"==typeof t.payload?t.payload:t;return"string"!=typeof n.path||"string"!=typeof n.cellId||"insert"!==n.kind&&"replace"!==n.kind?null:n}const nr="punica.kernel.ai.sessions.index.v1",rr="punica.kernel.ai.session.",ir=".v1";function sr(e){return`${rr}${e}${ir}`}function or(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const ar=new class{readIndex(){const e=or();if(!e)return[];try{const t=e.getItem(nr);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=or();if(t)try{t.setItem(nr,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=or();if(t)try{const n=t.getItem(sr(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=or();if(t)try{t.setItem(sr(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=or();if(t)try{t.removeItem(sr(e))}catch{}}};let cr=ar;function lr(){return cr}const ur="New chat";function dr(){return Date.now()}function pr(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${dr().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function fr(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:dr(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function hr(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function mr(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 gr=new class{async list(){try{return function(e,t){return Object.entries(e).map(([e,n])=>({capabilityId:e,calls:n.calls,ok:n.ok,last:n.last,prior:ln(n,t)})).sort((e,t)=>t.prior-e.prior||(e.capabilityId<t.capabilityId?-1:1))}(await yn().read()??{},Date.now())}catch{return[]}}async forget(){await yn().forget()}setStore(e){!function(e){gn=e??mn}(e)}},yr=new class{#L=null;#j=null;#D=new Map;#F=!1;#q=new Map;initialize(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{!function(e,t){const n=e?.payload??e,r=n?.request;if(!r?.id)return;const i=e?.envelope?.correlationId,s=n?.context?.workspaceId,o=n?.context?.traceId,a=punica.kernel.Events.manager.createCorrelationId(),c={pendingId:a,kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:n?.context?.reason??r.reason,...r.argsBinding?{argsBinding:r.argsBinding}:{},...void 0!==r.argsPreview?{argsPreview:r.argsPreview}:{},...r.maxScope?{maxScope:r.maxScope}:{},...Array.isArray(r.approvers)&&r.approvers.length?{approvers:[...r.approvers]}:{},...r.org?{org:r.org}:{},..."number"==typeof r.signatures&&r.signatures>1?{signatures:r.signatures}:{},correlationId:i,...o?{traceId:o}:{},workspaceId:s,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#D)}),function(e,t){for(const n of Xn)e.subscribe(n,e=>{try{const r=tr(e);if(!r||!r.sessionId)return;const i=t();if(!i||!i.get(r.sessionId))return;const s=er(n,r);if(!s)return;i.appendMessages(r.sessionId,[{id:"",createdAtMs:0,role:"user",name:"notebook",content:s}])}catch{}})}(punica.kernel.Events.manager,()=>punica.kernel.AI?.sessions),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#L=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(Yn.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(Yn.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(Yn.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=Kn(punica.kernel.Policy.manager.exportState(),2);if(t){const e=globalThis;if(void 0===e.document||void 0===e.Blob||void 0===e.URL)return console.warn("[Policy] Download not available in this environment. Exporting to console:"),void console.log("[Policy] Export:\n"+n);const t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),i=e.document.createElement("a");i.href=r,i.download=`punica-policy-export-${Date.now()}.json`,e.document.body.appendChild(i),i.click(),e.document.body.removeChild(i),URL.revokeObjectURL(r)}else console.log("[Policy] Export:\n"+n)}}),t.registerCommand(Yn.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(Yn.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`+Kn(e,2))}}),t.registerCommand(Yn.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(Yn.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(Yn.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(Yn.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(Yn.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 i="always"===r?"always":"workspace"===r?"workspace":"once";e.approvePending(n,i)||console.warn("[AI] Failed to approve pending",n)}}),t.registerCommand(Yn.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(Yn.AI.EDIT_PENDING,{title:"AI: Edit Pending Action Arguments…",description:"Send a pending policy-gated action back with different arguments; the gate asks again.",execute:t=>{const n=t?.pendingId;n&&(e.editPending(n,t?.arguments)||console.warn("[AI] Failed to edit pending",n))}}),t.registerCommand(Yn.AI.REFER_PENDING,{title:"AI: Ask a Reviewer About a Pending Action",description:"Hand a pending policy-gated action to a named reviewer; the run waits for their answer.",execute:t=>{const n=t?.pendingId;n&&t?.to&&(e.referPending(n,t.to)||console.warn("[AI] Failed to refer pending",n))}}),t.registerCommand(Yn.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)}});const n=e=>e&&"object"==typeof e&&(e.runId||e.sessionId)?{runId:e.runId,sessionId:e.sessionId}:void 0;t.registerCommand(Yn.AI.PAUSE_RUN,{title:"AI: Pause Run",description:"Hold AI runs at their next step. Bare: every run. Pass { runId } or { sessionId } to pause one run / one conversation only.",execute:t=>{e.setPauseRequested(!0,n(t))}}),t.registerCommand(Yn.AI.RESUME_RUN,{title:"AI: Resume Run",description:"Let paused AI runs continue. Bare: every run. Pass { runId } or { sessionId } to resume one run / one conversation only.",execute:t=>{e.setPauseRequested(!1,n(t))}}),t.registerCommand(Yn.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(Yn.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(Yn.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(Yn.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(Yn.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(Yn.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"+Kn(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+Kn(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Yn.AI.TOOL_USAGE_LIST,{title:"AI: Show What Tool Selection Learned",description:"List the capabilities this installation has called, with the ranking weight each one currently carries.",execute:async()=>{const e=await(punica.kernel?.AI?.toolUsage?.list())??[];return console.log("[AI] toolUsage\n"+Kn(e)),0===e.length?(Hn("info","Tool selection has learned nothing yet","No capability has been called on this installation, so selection is ranking on the words of your request alone."),e):(Hn("info",`Tool selection has learned from ${Zn(e.length)}`,`Carrying the most weight right now: ${e.slice(0,3).map(Qn).join(", ")}. The full list is in the developer console.`),e)}}),t.registerCommand(Yn.AI.TOOL_USAGE_FORGET,{title:"AI: Forget What Tool Selection Learned",description:"Erase the record of which capabilities this installation has called. Tool ranking returns to what a fresh install would produce.",execute:async()=>{const e=await(punica.kernel?.AI?.toolUsage?.list())??[];try{await(punica.kernel?.AI?.toolUsage?.forget())}catch(e){throw Hn("error","Could not erase what tool selection learned",`The record is still on disk. ${e instanceof Error?e.message:String(e)}`),e}Hn("info",0===e.length?"There was nothing to forget":`Forgot ${Zn(e.length)}`,0===e.length?"Tool selection had no history on this installation.":"Tool ranking is back to what a fresh install produces.")}}),t.registerCommand(Yn.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(),i=t?.__punica?.traceId??r,s=t?.__punica?.spanId??punica.kernel.Events.manager.createCorrelationId(),o=t?.__punica?.source??"kernel:ai",a=e?.source;Jn("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:zn(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();Jn("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:zn(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),Jn("ai.summaryGenerated","result",r,i,punica.kernel.Events.manager.createCorrelationId(),u,o,{summary:l,usage:c?.usage,modelId:c?.modelId,provider:c?.provider,source:a})}catch(e){Jn("ai.response","error",r,i,punica.kernel.Events.manager.createCorrelationId(),s,o,{kind:"summarize",error:String(e?.message??e)})}}})}({runLastPlan:e=>this.runLastPlan(e),runAgent:e=>this.runAgent(e),getLastPlan:()=>this.getLastPlan(),approvePending:(e,t,n)=>this.approvePending(e,t,n),dismissPending:(e,t)=>this.dismissPending(e,t),referPending:(e,t)=>this.referPending(e,t),editPending:(e,t)=>this.editPending(e,t),getPendingApprovals:()=>this.getPendingApprovals(),getLastRun:()=>this.#j,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#q){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#F=e;for(const t of this.#q.values())t.cancelRequested=e,e&&t.controller.abort()}},setPauseRequested:(e,t)=>{for(const[n,r]of this.#q){(!t?.runId&&!t?.sessionId||(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId))&&(r.pauseRequested=e)}}})}getLastPlan(){return this.#L}getPendingApprovals(){return e=this.#D,Array.from(e.values()).sort((e,t)=>e.timestampMs-t.timestampMs);var e}approvePending(e,t,n){return At(e,t,this.#D,n)}dismissPending(e,t){return function(e,t,n){const r=t.get(e);if(!r)return!1;try{punica.kernel.Policy.manager.declineApproval?.({kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason,argsBinding:r.argsBinding,argsPreview:r.argsPreview},{workspaceId:r.workspaceId,...n?.decidedBy?{decidedBy:n.decidedBy}:{},...n?.decidedRole?{decidedRole:n.decidedRole}:{},...n?.reason?{reason:n.reason}:{},...r.traceId?{traceId:r.traceId}:{},...r.correlationId?{parentSpanId:r.correlationId}:{}})}catch(e){console.warn("[AI] the decline could not be recorded:",e)}return t.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalDismissed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r}}),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:"dismissed"}}),!0}(e,this.#D,t)}referPending(e,t){return function(e,t,n){const r=n.get(e);if(!r)return!1;const i=String(t??"").trim();if(!i)return!1;const s={...r,referredTo:i};return n.set(e,s),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalReferred",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"audit",...r.traceId?{traceId:r.traceId}:{}},payload:{pending:s,to:i}}),!0}(e,t,this.#D)}editPending(e,t){return function(e,t,n){const r=n.get(e);return!!r&&!!xt(t)&&(n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalEdited",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r,arguments: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:"edited"}}),!0)}(e,t,this.#D)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#L=e);const t=await Et(this.#L,this.#j,()=>this.#F,e=>{this.#L=e});return this.#j=t,this.#F=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,pauseRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#q.set(t,n);try{return await Wn(e,()=>n.cancelRequested,n.controller.signal,t,()=>n.pauseRequested)}finally{this.#q.delete(t)}}},wr=new class{#B;constructor(){this.#U()}#U(){const e=globalThis;"function"==typeof e?.addEventListener&&e.addEventListener("storage",e=>{try{this.#V(e?.key??null)}catch{}})}#V(e){const t=lr(),n=function(e){if(!e||!e.startsWith(rr)||!e.endsWith(ir))return;return e.slice(25,-3)||void 0}(e);if(n){const e=t.readSession(n);return void(e?fr("ai.sessionUpdated",e.meta,{external:!0}):fr("ai.sessionDeleted",{sessionId:n,title:"",createdAtMs:0,updatedAtMs:0,messageCount:0},{external:!0}))}if(e===nr){const e=t.readIndex().slice().sort((e,t)=>t.updatedAtMs-e.updatedAtMs)[0];e&&fr("ai.sessionUpdated",e,{external:!0,index:!0})}}create(e){const t=lr(),n={sessionId:pr("sess"),title:e?.title?.trim()||ur,createdAtMs:dr(),updatedAtMs:dr(),messageCount:0,tokenEstimate:0};e?.workspaceId&&(n.workspaceId=e.workspaceId);const r={version:1,meta:n,transcript:[]};t.writeSession(r);const i=t.readIndex();return i.push(n),this.#W(i,n),t.writeIndex(i),fr("ai.sessionCreated",n),{...n}}list(e){const t=lr().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return lr().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#K(e,e=>{e.title=n});return!!r&&(fr("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#K(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(fr("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=lr(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[i]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),fr("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=lr(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||pr("msg"),createdAtMs:e.createdAtMs||dr(),content:e.content.length>16e3?e.content.slice(0,16e3)+"…":e.content};return n?.runId&&!t.runId&&(t.runId=n.runId),t});i.transcript.push(...s),i.transcript.length>200&&i.transcript.splice(0,i.transcript.length-200);const o=i.meta;if(o.messageCount=i.transcript.length,o.updatedAtMs=dr(),n?.runId&&(o.lastRunId=n.runId),o.tokenEstimate=i.transcript.reduce((e,t)=>{return e+(n=t.content,Math.ceil(n.length/4));var n},0),o.title===ur){const e=i.transcript.find(e=>"user"===e.role);e&&(o.title=function(e){const t=e.replace(/\s+/g," ").trim();return t?t.length>48?t.slice(0,47)+"…":t:ur}(e.content))}r.writeSession(i),this.#G(o),fr("ai.sessionUpdated",o,{appendedCount:s.length,runId:n?.runId});const a=this.#B;a?.shouldCompact(i)&&Promise.resolve().then(()=>a.compact(i)).then(t=>{const n=lr().readSession(e);n&&(n.contextView=t,lr().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=lr().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(...hr(n.messages).map(mr)),e}return hr(t.transcript.slice(-40)).map(mr)}setCompactor(e){this.#B=e}recordUsage(e,t){const n=this.#K(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=dr(),e.usage=n});return!!n&&(fr("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#K(e,t){const n=lr(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=dr(),n.writeSession(r),this.#G(r.meta),{...r.meta}}#G(e){const t=lr(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#W(e,t){const n=lr(),r=e=>e.workspaceId===t.workspaceId;let i=e.filter(r);for(;i.length>50;){const s=i.filter(e=>e.sessionId!==t.sessionId).sort((e,t)=>{const n=e.archived?0:1,r=t.archived?0:1;return n!==r?n-r:e.updatedAtMs-t.updatedAtMs})[0];if(!s)break;const o=e.findIndex(e=>e.sessionId===s.sessionId);o>=0&&e.splice(o,1),n.deleteSession(s.sessionId),fr("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};wr.setCompactor(function(){const e=en.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=rn([{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(tn)?{...e,content:nn(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());const vr=gr;var br={manager:yr,sessions:wr,toolUsage:vr},Ir=Object.freeze({__proto__:null,default:br,manager:yr,sessions:wr,toolUsage:vr});function kr(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&&"assess"!==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}const Er=new class{#Y=new Map;#z=new Map;#J=new Map;#H=new Map;#Q=new Map;#Z=new Map;#X;registerProductOriginResolver(e){this.#X=e}#ee(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.#Y.has(e.id)){const n=this.#Y.get(e.id),r=n?.originExtension||this.#J.get(e.id),i=t||e.originExtension;if(!r||!i||r!==i)throw new Error(`Instruction class ID collision: "${e.id}" is already registered by a different extension. Each product extension must use namespaced IDs (e.g., "ivy.node.generator", "ivy.agent.generator").`)}!t&&e.productId&&this.#X&&(t=this.#X(e.productId)),t&&(e.originExtension=t,this.#J.set(e.id,t)),e.capability||(e.capability=kr(e)),this.#Y.set(e.id,e),this.#z.set(e.id,e.capability)}unregister(e){this.#H.has(e)?this.removeOverride(e):(this.#Y.delete(e),this.#z.delete(e),this.#J.delete(e))}unregisterByOrigin(e){const t=[];this.#J.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>{this.#Y.delete(e),this.#z.delete(e),this.#J.delete(e)});const n=[];this.#Z.forEach((t,r)=>{t===e&&n.push(r)}),n.forEach(e=>this.removeOverride(e))}registerOverride(e,t){if(!e.id)throw new Error("Instruction class override must have an id");if(!e.role)throw new Error("Instruction class override must have a role");if(!e.systemPrompt)throw new Error("Instruction class override must have a systemPrompt");const n=t||e.originExtension;n&&(e.originExtension=n,this.#Z.set(e.id,n)),e.capability||(e.capability=kr(e)),this.#H.set(e.id,e),this.#Q.set(e.id,e.capability)}removeOverride(e){this.#H.delete(e),this.#Q.delete(e),this.#Z.delete(e)}isOverridden(e){return this.#H.has(e)}getBase(e){return this.#Y.get(e)}get(e){return this.#H.get(e)??this.#Y.get(e)}list(e=!1){const t=new Map(this.#Y);this.#H.forEach((e,n)=>t.set(n,e));const n=Array.from(t.values());return e?n.filter(e=>{const t=e.originExtension||this.#te(e.id);return!t||this.#ee(t)}):n}#te(e){return this.#H.has(e)?this.#Z.get(e):this.#J.get(e)}listSummaries(e=!1){return this.list(e).map(e=>({id:e.id,role:e.role,originExtension:e.originExtension||this.#te(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0,...this.#H.has(e.id)?{overridden:!0,overridesExtension:this.#J.get(e.id)}:{}}))}has(e){return this.#H.has(e)||this.#Y.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#te(e);return!n||this.#ee(n)}getCapability(e){return this.#Q.get(e)??this.#z.get(e)}listCapabilities(){const e=new Map(this.#z);return this.#Q.forEach((t,n)=>e.set(n,t)),Array.from(e.values())}};async function Sr(e){const{primaryModelId:t,count:n,exclude:r}=e,i=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{return await e.listInstalled()}catch{return null}}();if(!i||!Array.isArray(i.installed)||0===i.installed.length)return t?[t]:[];const s=new Set(i.installed.map(e=>e.id)),o=[],a=e=>{e&&s.has(e)&&(function(e,t){return!(!t||0===t.length)&&t.includes(e)}(e,r)||o.includes(e)||o.push(e))};if(a(t),o.length<n)for(const e of i.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function Ar(e,t){const n=e.riskLevel;let r="assess"===n?void 0:n;if(!r){const n=await async function(e,t){if("risk-assessor"===e.id)return{riskLevel:"medium"};const n=Er.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,i=[];i.push("Assess the risk level for this task:"),i.push(""),i.push(`Instruction Class: ${e.id}`),i.push(`Role: ${e.role}`),i.push(""),i.push("User Prompt:"),i.push(t.userPrompt),i.push(""),i.push("Context:"),i.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),i.push(`- File Path: ${r?.filePath??"N/A"}`),i.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),i.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),i.push(""),i.push("Consider:"),i.push("- Is this production code?"),i.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),i.push("- Is it a critical business function?"),i.push("- Does it handle sensitive data?"),i.push("- Is it a simple utility or a complex system?"),i.push(""),i.push('Respond with ONLY one word: "low", "medium", or "high".');const s=i.join("\n");try{const e=punica.runtime.capabilities?.gateway,t=e?await e.call("llm.chat",{messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20,reasoning:"none"},{sessionId:"internal",workspaceId:void 0,actor:{type:"extension",extensionName:"kernel:policy"},origin:{kind:"command",id:"risk-assessment"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat({messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20,reasoning:"none"}),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);r=n.riskLevel}if(r||(r="medium"),"high"===r){const t=e.expertModelId,n=e.expertModelIds;let i=[];return i=n&&n.length>0?n.slice():await Sr({primaryModelId:t,count:3}),{strategy:i.length>1?"multi":"single",modelIds:i.length?i:[t].filter(Boolean),riskLevel:r,reason:"High risk detected via LLM-based assessment"}}let i=e.expertModelId??null;return i||(i=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:i?[i]:[],riskLevel:r,reason:"Low/medium risk, single expert sufficient"}}function xr(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 Cr(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function Tr(){const e=globalThis;return e.punica?.runtime?.fs}function Pr(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Nr={type:"ai",id:"llm:context"},Mr={kind:"ai",id:"context-builder"};async function Rr(e){if(e.filePath)try{const t=Cr(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:Nr,origin:Mr,trace:{traceId:Pr()},policy:{mode:"execute"}}):await(Tr()?.readFile?.(e.filePath));if(!n)return;const r=5e3,i=n.length>r?n.slice(0,r)+"\n... (truncated)":n;return`File content (${e.filePath}):\n\`\`\`\n${i}\n\`\`\``}catch{return}}async function $r(e){try{const t=Cr(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Nr,origin:Mr,trace:{traceId:Pr()},policy:{mode:"execute"}}):await(Tr()?.getFileTree?.());if(!n||!Array.isArray(n)||0===n.length)return;const r=n.filter(e=>!e.isDirectory).length,i=n.filter(e=>e.isDirectory).length;return`Workspace structure: ${r} files, ${i} directories\nTop-level items: ${n.filter(e=>{const t=String(e.path??"");return!t.includes("/")||2===t.split("/").length}).slice(0,20).map(e=>{const t=String(e.name??"");if(t)return t;return String(e.path??"").split("/").pop()??""}).join(", ")}`}catch{return}}function _r(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Or(){return"undefined"==typeof document?void 0:document}function Lr(){const e=Or();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 jr(e){try{const t=_r();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Lr();if(!n)return;const r=n.getSelection?.(),i=n.getModel?.();if(!r||!i||r.isEmpty())return;const s=i.getValueInRange(r),o=String(s??"").trim();if(!o)return;const a=2e3,c=o.length>a?o.slice(0,a)+"\n... (truncated)":o,l=r.startLineNumber;return`Selected code (lines ${l}-${r.endLineNumber}):\n\`\`\`\n${c}\n\`\`\``}catch{return}}function Dr(){try{const e=_r();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=Lr();if(e){const n=e.getPosition?.(),r=e.getModel?.();if(n&&r){const e=n.lineNumber,i=n.column,s=r.getOffsetAt(n);t.push(`Cursor position: Line ${e}, Column ${i} (offset: ${s})`)}}}catch{}try{const e=Or();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 Fr(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const qr={type:"ai",id:"llm:context"},Br={kind:"ai",id:"context-builder"};async function Ur(e){const t=function(){const e=globalThis;return e.punica?.runtime?.vcs}();if(!t)return;const n=[];if(t.status)try{const r=function(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}(),i=r?await r.call("vcs.status",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:qr,origin:Br,trace:{traceId:Fr()},policy:{mode:"execute"}}):await t.status();if(i){const e=[];i.current&&(e.push(`Branch: ${i.current}`),i.tracking&&e.push(`Tracking: ${i.tracking}`),i.ahead&&i.ahead>0&&e.push(`Ahead: ${i.ahead}`),i.behind&&i.behind>0&&e.push(`Behind: ${i.behind}`));const t=i.modified??[],r=i.staged??[],s=i.created??[],o=i.deleted??[],a=i.renamed??[],c=(t,n,r)=>{if(0===n.length)return;const i=n.slice(0,r).join(", "),s=n.length>r?"...":"";e.push(`${t} (${n.length}): ${i}${s}`)};c("Staged",r,5),c("Modified",t,5),c("Created",s,3),c("Deleted",o,3),c("Renamed",a,3),e.length>0&&n.push(`Git Status:\n${e.join("\n")}`)}}catch{}if(t.logs&&e.filePath)try{const e=await t.logs({limit:5});if(e&&Array.isArray(e)&&e.length>0){const t=e.slice(0,5).map(e=>{const t=e.hash?e.hash.substring(0,7):"unknown",n=e.date?new Date(e.date).toLocaleDateString():"",r=e.authorName??"",i=(e.message??"").split("\n")[0].substring(0,60);return` ${t} ${n} ${r?`(${r})`:""}: ${i}${i.length>=60?"...":""}`}).join("\n");n.push(`Recent Commits:\n${t}`)}}catch{}if(t.branches)try{const e=await t.branches();if(e&&Array.isArray(e)&&e.length>0){const t=e.find(e=>e.current),r=e.filter(e=>!e.current).slice(0,5),i=[];t?.name&&i.push(`Current: ${t.name}`),r.length>0&&i.push(`Other branches: ${r.map(e=>e.name).filter(Boolean).join(", ")}`),i.length>0&&n.push(`Branches:\n${i.join("\n")}`)}}catch{}return n.length>0?n.join("\n\n"):void 0}async function Vr(){const e=function(){const e=globalThis;return e.punica?.kernel?.Tasks?.manager}();if(!e)return;const t=[];try{const n=await(e.listRuns?.({status:["running","pending"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown";return` ${e.label??e.definitionId??"Unknown"} (${t})`}).join("\n");t.push(`Active Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listDefinitions?.());if(n&&n.length>0){const e=n.slice(0,10).map(e=>{const t=e.kind??"unknown",n=e.group?` [${e.group}]`:"";return` ${e.label??e.id??"Unknown"} (${t})${n}`}).join("\n");t.push(`Available Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listRuns?.({status:["success","failed","cancelled"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown",n=e.label??e.definitionId??"Unknown",r=null!=e.exitCode?` (exit: ${e.exitCode})`:"",i=e.startedAt?new Date(e.startedAt).toLocaleDateString():"";return` ${n}: ${t}${r}${i?` (${i})`:""}`}).join("\n");t.push(`Recent Task History:\n${e}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}async function Wr(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 Kr="problems.getDiagnostics";function Gr(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===Kr))return;let r;try{r=t.executeCommand?.(Kr)}catch{return}if(!r||!Array.isArray(r)||0===r.length)return;const i=e.filePath?r.filter(t=>t.file===e.filePath):r;if(0===i.length)return;const s=i.slice(0,10).map(e=>{const t=e.file?`${e.file}:${e.line??0}:${e.column??0}`:`${e.line??0}:${e.column??0}`;return` ${(e.severity??"error").toUpperCase()} ${t}${e.source?`[${e.source}]`:""}${e.code?`(${e.code})`:""}: ${e.message??""}`}).join("\n"),o=i.length;return`Diagnostics (${o} ${1===o?"issue":"issues"}):\n${s}${o>10?`\n ... and ${o-10} more`:""}`}catch{return}}function Yr(e){return{id:e.id,systemPrompt:e.systemPrompt,outputSchema:e.outputSchema??null,responseFormat:e.responseFormat??null}}const zr=new Map;function Jr(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 Hr=new class{#ne;#re=[];constructor(e){this.#ne=Math.max(1,e?.maxRecords??1e4)}record(e){this.#re.push(e),this.#re.length>this.#ne&&this.#re.splice(0,this.#re.length-this.#ne)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,i=new Map;let s=0,o=0,a=0,c=0,l=0;for(const e of this.#re){if(e.timestamp<n||e.timestamp>r)continue;const u=Jr(t,e),d=i.get(u)??{cost:0,calls:0,promptTokens:0,completionTokens:0,cachedPromptTokens:0};d.cost+=e.totalCost,d.calls+=1,d.promptTokens+=e.promptTokens,d.completionTokens+=e.completionTokens,d.cachedPromptTokens+=e.cachedPromptTokens??0,i.set(u,d),s+=e.totalCost,o+=1,a+=e.promptTokens,c+=e.completionTokens,l+=e.cachedPromptTokens??0}const u=Array.from(i.entries()).map(([e,t])=>({key:e,cost:t.cost,calls:t.calls,promptTokens:t.promptTokens,completionTokens:t.completionTokens,cachedPromptTokens:t.cachedPromptTokens})).sort((e,t)=>t.cost-e.cost);return{scope:t,totalCost:s,totalCalls:o,totalPromptTokens:a,totalCompletionTokens:c,totalCachedPromptTokens:l,byKey:u}}clear(){this.#re.length=0}};function Qr(e){return e.remaining[0]}function Zr(e,t,n,r){if(e.terminal)return e;const i=function(e,t){return"error"===e?t.onError??"fail":"timeout"===e?t.onTimeout??"fail":t.onRateLimit??"next"}(t,n),s=e.remaining[0];if(!s)return{...e,terminal:!0,lastError:r??e.lastError};if("fail"===i)return{...e,attempted:[...e.attempted,s],position:e.position+1,remaining:[],terminal:!0,pendingQueue:!1,lastError:r??e.lastError};if("queue"===i)return{...e,pendingQueue:!0,lastError:r??e.lastError};const o=e.remaining.slice(1);return{...e,position:e.position+1,attempted:[...e.attempted,s],remaining:o,terminal:0===o.length,pendingQueue:!1,lastError:r??e.lastError}}function Xr(e){return{...e,terminal:!0,pendingQueue:!1}}let ei;function ti(e){ei=e}function ni(e){return!!e&&"string"==typeof e.providerId&&""!==e.providerId.trim()}const ri={onError:"next",onTimeout:"next",onRateLimit:"next"};function ii(e){const t=e?.status??e?.statusCode;return"number"==typeof t&&(408!==t&&429!==t&&(401!==t&&403!==t&&(t>=400&&t<500)))}function si(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 oi(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}:{}}}function ai(e){const{llmRes:t,latencyMs:n,promptVersion:r,chainPosition:i,workspaceId:s}=e;try{const o=t.usage?.inputTokens??0,a=t.usage?.outputTokens??0,c=t.usage?.cacheReadInputTokens??0,l=String(t.provider??"unknown"),u=String(t.modelId??"unknown"),d=0,p={provider:l,model:u,promptTokens:o,completionTokens:a,totalCost:d,latencyMs:n,promptVersion:r,...t.meta?.cacheHit?{cacheHit:!0}:{},...void 0!==i?{fallbackChainPosition:i}:{}};Hr.record({capabilityId:e.capabilityId,provider:l,model:u,promptTokens:o,completionTokens:a,...c>0?{cachedPromptTokens:c}:{},totalCost:d,latencyMs:n,timestamp:Date.now(),workspaceId:s}),punica.kernel.Events.manager.publishEvent({name:"llm.call",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:e.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:e.capabilityId,workspaceId:s,meta:p}})}catch{}}async function ci(e,n){const r=Er;if(!r)return{ok:!1,error:"Instruction class registry not available",metadata:{instructionClass:e.instructionClass,role:"unknown"}};if(!(r.isAvailable?r.isAvailable(e.instructionClass):r.has(e.instructionClass))){const t=r.get(e.instructionClass);return t?{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_ORIGIN_EXTENSION_INACTIVE",error:`Instruction class "${e.instructionClass}" is registered but its origin extension is not active`,metadata:{instructionClass:e.instructionClass,role:t.role,originExtension:t.originExtension,productId:t.productId}}:{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}}}const i=r.get(e.instructionClass);if(!i)return{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}};try{const r=await async function(e){return e?(await Promise.all([Promise.resolve(xr(e)),Rr(e),Promise.resolve(jr(e)),$r(e),Ur(e),Vr(),Promise.resolve(Dr()),Wr(e),Promise.resolve(Gr(e))])).filter(e=>void 0!==e&&e.length>0).join("\n\n"):""}(e.context),s=r?`${r}\n\n${e.userPrompt}`:e.userPrompt,o=await Ar(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,reasoning:e.options?.reasoning??i.reasoning??"none",...!0===e.options?.skipCache?{skipCache:!0}:{},correlationId:n?.correlationId??punica.kernel.Events.manager.createCorrelationId()},c=!0===e.options?.stream?"llm.chatStream":"llm.chat";let l,u,d=0;const p=await t(),f=async(t,r)=>{const i=punica.kernel.Events.manager;return await punica.runtime.capabilities.gateway.call(t,{...a,...r},{sessionId:a.correlationId??i.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??i.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:i.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(ni);if(!ei)return[];try{const e=ei();return Array.isArray(e)?e.filter(ni):[]}catch{return[]}}(i);let g;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=Qr(t);if(!n)break;const r=Date.now();try{l=await f(c,oi(n)),d=Date.now()-r,g=t.position,t=Xr(t);break}catch(r){if(e=r,ii(r))break;const s=Zr(t,si(r),i.fallbackPolicy??ri,r);if(s.pendingQueue){t={...s,terminal:!0};break}const o=Qr(s);o&&h(n.providerId,o.providerId,r?.message??"unknown"),t=s}}if(!l)throw e??new Error(`No provider in the chain for "${i.id}" produced a response.`);0===d&&(d=Date.now()-n)}else if("single"===o.strategy||o.modelIds.length<=1){const t=o.modelIds[0],r=Date.now();try{const i=punica.kernel.Events.manager;l=await punica.runtime.capabilities.gateway.call(c,{...a,modelId:t},{sessionId:a.correlationId??i.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??i.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-r}catch(t){if(!(o.modelIds.length>1)||e.options?.skipFallback)throw t;{let r=t;for(const t of o.modelIds.slice(1))try{const s=Date.now(),c=punica.kernel.Events.manager;try{c.publishEvent({name:"llm.fallback",envelope:{id:c.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,fromModelId:o.modelIds[0],toModelId:t,reason:r?.message??"unknown"}})}catch{}l=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??c.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??c.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-s;break}catch(e){r=e;continue}if(!l)throw r}}}else{const t=Date.now(),r=punica.kernel.Events.manager,s=o.modelIds.map(async t=>{const s=Date.now(),o=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),c=Date.now()-s;let l;if(i.outputSchema&&"json_object"===i.responseFormat)try{l=JSON.parse(o.text)}catch{}return{res:o,expert:{modelId:o.modelId??t,text:o.text,structured:l,usage:o.usage,latencyMs:c}}}),c=await Promise.all(s);u=c.map(e=>e.expert);const f=function(e,t){if(!e.length)throw new Error("aggregateBestOfN called with no results");if("json_object"===t.responseFormat){const t=e.filter(e=>void 0!==e.structured);if(t.length>0)return t.reduce((e,t)=>t.latencyMs<e.latencyMs?t:e)}return e.reduce((e,t)=>{const n=e.text.length-e.latencyMs/1e3+.1*(e.usage?.outputTokens??0);return t.text.length-t.latencyMs/1e3+.1*(t.usage?.outputTokens??0)>n?t:e})}(u,i);l={text:f.text,modelId:f.modelId,provider:c.find(e=>e.expert.modelId===f.modelId)?.res.provider,usage:f.usage},d=Date.now()-t}const y=await async function(e){const t=Me(Yr(e)),n=zr.get(t);if(n)return n;const r=await Oe(Yr(e));if(zr.size>=64){const e=zr.keys().next().value;void 0!==e&&zr.delete(e)}return zr.set(t,r),r}(i),w=l.usage?.outputTokens,v=a.maxTokens,b="number"==typeof w&&"number"==typeof v&&v>0&&w>=v,I=l.text.trim().length>0||(l.toolCalls?.length??0)>0,k={instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId,promptVersion:y,tokensUsed:l.usage?.totalTokens,inputTokens:l.usage?.inputTokens,outputTokens:w,latencyMs:d,modelId:l.modelId,provider:l.provider,...b?{truncated:!0}:{},...l.meta?.cacheHit?{cacheHit:!0}:{}};if(ai({capabilityId:i.id,llmRes:l,latencyMs:d,promptVersion:y,chainPosition:g,workspaceId:p,correlationId:a.correlationId}),!I)return{ok:!1,reasonCode:"LLM_EMPTY_ANSWER",error:b?`The model returned no answer: it reached its output budget of ${v} tokens without emitting any text. A reasoning model spends this budget on thinking, so declare \`reasoning: none\` or raise maxTokens for "${i.id}".`:"The model returned no answer: the response carried no text and no tool calls.",metadata:k};let E;if(i.outputSchema&&"json_object"===i.responseFormat)try{E=JSON.parse(l.text)}catch(e){return{ok:!1,reasonCode:"LLM_STRUCTURED_PARSE_FAILED",error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}${b?` (the answer was cut off at its ${v}-token output budget, so it is incomplete rather than malformed)`:""}`,metadata:k}}return{ok:!0,text:l.text,structured:E,metadata:k}}catch(e){return{ok:!1,error:`LLM invocation failed: ${e?.message??String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}}async function li(e){return ci({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 ui(e){return ci({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function di(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 ci({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function pi(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function fi(e,t){const n=pi(e).split("/").filter(Boolean),r=pi(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function hi(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function mi(e,t){const n=pi(e).split("/").filter(Boolean),r=pi(t).split("/").filter(Boolean);let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;const s=n.length-i,o=r.slice(i);return[...Array(s).fill(".."),...o].join("/")}async function gi(e,t){const n=[];let r=0;const i=1048576;if("0.1"!==e.specVersion)throw new Error(`Unsupported CodegenBundle version: ${e.specVersion}`);if(!e.files||!Array.isArray(e.files))throw new Error("CodegenBundle must have a files array");if(0===e.files.length)throw new Error("CodegenBundle files array cannot be empty");if(e.files.length>50)throw new Error(`CodegenBundle exceeds max files limit: ${e.files.length} > 50`);let s=0;const o=/^(?!\/)(?!.*\.\.)([a-zA-Z0-9._-]+\/)*[a-zA-Z0-9._-]+$/;for(const r of e.files){if(!o.test(r.path)){n.push({path:r.path,error:"Invalid path: must be relative, no absolute paths, no .."});continue}if("delete"===r.action){if(void 0!==r.content){n.push({path:r.path,error:"Delete action cannot have content"});continue}}else if("create"===r.action||"update"===r.action){if(!r.content){n.push({path:r.path,error:`${r.action} action requires content`});continue}s+=r.content.length}const e=mi(t,fi(t,pi(r.path)));(e.startsWith("..")||hi(e))&&n.push({path:r.path,error:"Path traversal detected"})}if(s>i)throw new Error(`CodegenBundle exceeds max total size: ${s} > 1048576 bytes`);for(const t of e.files)if(!n.some(e=>e.path===t.path))try{const e=pi(t.path);if("create"===t.action){const n=e.split("/");if(n.length>1){const e=n.slice(0,-1).join("/");try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFolder(e)}catch{}}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFileWithContent(e,t.content),r++}else if("update"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{n.push({path:t.path,error:"File does not exist for update"});continue}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.updateFileContent(e,t.content),r++}else if("delete"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{continue}await punica.runtime.fs.deleteFile(e),r++}}catch(e){n.push({path:t.path,error:e?.message??String(e)})}return{applied:r,errors:n}}const yi={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 wi=new class{api;constructor(){this.api={instructionClassRegistry:Er,invoke:ci,plan:li,generateCode:ui,editWorkflow:di,listInstructionClasses:e=>Er.listSummaries(e),setDefaultProviderChainResolver:ti}}};var vi={manager:wi};const bi={Commands:g,History:w,TimeServer:v,Tasks:S,Events:ue,Notifications:he,Policy:It,AI:Ir,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:yi,applyCodegenBundle:gi,default:vi,manager:wi})};function Ii(e,t){switch(e.mode){case"extension":return function(e,t){const n=t.path.split(".").pop();return!(!n||!1===t.path.endsWith(`.${n}`))&&n.toLowerCase()===e.toLowerCase()}(e.pattern,t);case"mime":return function(e,t){if(!t.mimeType)return!1;const n=e.toLowerCase(),r=t.mimeType.toLowerCase();if(n.endsWith("/*")){const e=n.slice(0,-2);return r.startsWith(e+"/")}return r===n}(e.pattern,t);case"glob":return function(e,t){const n="__DOUBLE_STAR_PLACEHOLDER__",r="__SINGLE_STAR_PLACEHOLDER__",i=e.replace(/\*\*/g,n).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),".*").replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"[^/]*");return new RegExp(`^${i}$`,"i").test(t.path)}(e.pattern,t);default:return!1}}const ki=new class{#ie=[];register(e){this.#ie=this.#ie.filter(t=>t.id!==e.id),this.#ie.push({priority:0,...e}),this.#ie.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#ie=this.#ie.filter(t=>t.id!==e)}clear(){this.#ie=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#ie){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>Ii(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.#ie.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>Ii(t,e))}).map(e=>({opener:e,command:e.command}))}};function Ei(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 Si="runtime:fileOperations";function Ai(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function xi(e){return"object"==typeof e&&null!==e&&!0===e.veto}const Ci=new class{#se=new Map;#oe=new Set;#ae(){const e=globalThis.punica?.runtime?.fs;if(!e)throw new Error("[Runtime.fileOperations] No FileSystem provider is available.");return e}registerParticipant(e){const{id:t}=e;if(!t)throw new Error("[Runtime.fileOperations] A participant must declare an id.");return this.#se.set(t,e),{dispose:()=>{this.#se.get(t)===e&&this.#se.delete(t)}}}setDirty(e,t){t?this.#oe.add(e):this.#oe.delete(e)}isDirty(e){return this.#oe.has(e)}getDirtyPaths(e){const t=Array.from(this.#oe);return void 0===e?t:t.filter(t=>{return(r=t)===(n=e)||r.startsWith(`${n}/`);var n,r})}async rename(e,t,n){if(!e||!t)throw new Error("[Runtime.fileOperations] rename requires both oldPath and newPath.");if(e===t)return;const r=await this.#ce(e,n?.isDirectory),i={oldPath:e,newPath:t,isDirectory:r};await this.#le("rename",e=>e.willRename?.(i));const s=this.#ae();r?await s.renameFolder(e,t):await s.renameFile(e,t);for(const n of this.getDirtyPaths(e))this.#oe.delete(n),this.#oe.add(Ai(n,e,t));await this.#ue("rename",e=>e.didRename?.(i)),Ei({name:"workspace.files.didRename",source:Si,payload:{oldPath:e,newPath:t,isDirectory:r}})}async delete(e,t){if(!e)throw new Error("[Runtime.fileOperations] delete requires a path.");const n=await this.#ce(e,t?.isDirectory),r={path:e,isDirectory:n};await this.#le("delete",e=>e.willDelete?.(r));const i=this.#ae();n?await i.deleteFolder(e):await i.deleteFile(e,t?.ifExists?{ifExists:!0}:void 0);for(const t of this.getDirtyPaths(e))this.#oe.delete(t);await this.#ue("delete",e=>e.didDelete?.(r)),Ei({name:"workspace.files.didDelete",source:Si,payload:{path:e,isDirectory:n}})}async#ce(e,t){if("boolean"==typeof t)return t;const n=this.#ae().stat;if("function"!=typeof n)return!1;try{return(await n(e)).isDirectory}catch{return!1}}async#le(e,t){for(const n of this.#se.values()){const r=await t(n);if(xi(r))throw new Error(r.reason??`The ${e} was cancelled by "${n.id}".`)}}async#ue(e,t){for(const n of this.#se.values())try{await t(n)}catch(t){console.error(`[Runtime.fileOperations] participant "${n.id}" failed after ${e}`,t),Ei({name:"workspace.files.participantFailed",source:Si,kind:"error",payload:{participantId:n.id,operation:e,error:t instanceof Error?t.message:String(t)}})}}};function Ti(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}}}}const Pi=Ti({label:"Runtime.resources",noProviderMessage:"[Runtime.resources] No Resources provider registered. This host keeps no resource registry; a host that does calls punica.runtime.setResourcesProvider() (or attaches punica.runtime.resources before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.resources;if(void 0!==t&&!Mi(t))return t}});function Ni(e){Pi.set(e)}function Mi(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedResourcesFacade}const Ri=Ti({label:"Runtime.search",noProviderMessage:"[Runtime.search] No Search provider registered. This host indexes no workspace; a host that does calls punica.runtime.setSearchProvider() (or attaches punica.runtime.search before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.search;if(void 0!==t&&!_i(t))return t}});function $i(e){Ri.set(e)}function _i(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedSearchFacade}const Oi=Ti({label:"Runtime.tasks",noProviderMessage:"[Runtime.tasks] No Tasks provider registered. This host runs no local processes; a host that does calls punica.runtime.setTasksProvider() (or attaches punica.runtime.tasks before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.tasks;if(void 0!==t&&!ji(t))return t}});function Li(e){Oi.set(e)}function ji(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedTasksFacade}const Di=Ti({label:"Runtime.terminals",noProviderMessage:"[Runtime.terminals] No Terminal provider registered. This host opens no terminal; a host that does calls punica.runtime.setTerminalProvider() (or attaches punica.runtime.terminals before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.terminals;if(void 0!==t&&!qi(t))return t}});function Fi(e){Di.set(e)}function qi(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedTerminalFacade}let Bi;function Ui(){if(Bi)return Bi;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}const Vi=Ti({label:"Runtime.vcs",noProviderMessage:"[Runtime.vcs] No Vcs provider registered. This host reads no repository; a host that does calls punica.runtime.setVcsProvider() (or attaches punica.runtime.vcs before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.vcs;if(void 0!==t&&!Ki(t))return t}});function Wi(e){Vi.set(e)}function Ki(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedVcsFacade}const Gi=Ti({label:"Runtime.workspace",noProviderMessage:"[Runtime.workspace] No Workspace provider registered. Host must attach punica.runtime.workspace",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.workspace;if(!Ji(t))return t}});function Yi(){return Gi.get()}function zi(e){Gi.set(e),e&&Ei({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Ji(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedWorkspaceFacade}function Hi(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}}function Qi(e){return!!e&&"local"!==Zi(e)}function Zi(e){if(!e)return;const t=String(e).trim().toLowerCase();return""!==t?t.startsWith("local:")||"local"===t||"mock"===t||"ollama"===t||t.startsWith("ollama-")||"llama.cpp"===t||"llamacpp"===t?"local":"remote":void 0}async function Xi(e,t){if("remote"===e?.route)return"remote";if("local"===e?.route)return"local";const n=Zi(e?.providerId);if("remote"===n||"local"===n){const t=String(e?.providerId??"").trim().toLowerCase();if(t.startsWith("remote:")||t.startsWith("local:")||"local"===t)return n}const r=t?.describeDestination;if("function"==typeof r)try{const n=await r.call(t,e);if("local"===n||"remote"===n)return n}catch{}const i=t?.id;return"string"==typeof i&&""!==i?Qi(i)?"remote":"local":"unknown"}let es;function ts(){return es}function ns(e){const t=e.response;return{...t,usage:{inputTokens:0,outputTokens:0,totalTokens:0},meta:{...t.meta??{provider:String(t.provider??"unknown"),model:String(t.modelId??"unknown"),promptTokens:0,completionTokens:0,totalCost:0,latencyMs:0},promptTokens:0,completionTokens:0,totalCost:0,cacheHit:!0}}}const rs=Symbol("punica.llm.gatewayGovernedAi");let is,ss,os;function as(){if(is)return is;const e=punica.runtime.llm;if(!e||"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedLlmFacade)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");var t;return is=e,is}function cs(e){if(is=e,ss=void 0,os=void 0,!e)return;const t=e;Hi("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class ls{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 us=null;function ds(){return us||(us=new ls),us}class ps{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 fs{providerSession;id;providerId;language;kernelspec;languageRuntime;constructor(e,t,n,r,i,s){this.providerSession=e,this.id=t,this.providerId=n,this.language=r,this.kernelspec=i,this.languageRuntime=s}run(e,t){const n=t?.runId??function(e="id"){const t=globalThis;if(t.crypto?.randomUUID)return`${e}_${t.crypto.randomUUID()}`;const n=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${n}`}("run"),r={id:this.id,providerId:this.providerId,language:this.language,kernelspec:this.kernelspec},i=this.languageRuntime.prepare(e,r);return this.providerSession.run(i,n,t)}async interrupt(){return this.providerSession.interrupt()}async restart(){return this.providerSession.restart()}async close(){return this.providerSession.close()}}const hs={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}}},ms={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}}},gs={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},ys={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},ws={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 vs(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 bs{registry;router;constructor(e,t){this.registry=e,this.router=t}async open(e){const t=this.router.selectProvider(e),n=this.router.selectLanguageRuntime(e.language),r=this.router.resolveKernelSpec(e,n),i=await t.openSession({...e,kernelspec:r}),s=vs("session");return new fs(i,s,t.id,e.language,r,n)}}class Is{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 ks=null;function Es(){return ks||(ks=new Is),ks}class Ss{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 As{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 xs=null;function Cs(){return xs||(xs=new As),xs}class Ts{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 Ps{#de=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#de.set(e.id,e)}get(e){return this.#de.get(e)}list(){return Array.from(this.#de.values())}select(e){return this.list().find(t=>t.canRun(e))}}let Ns=null;function Ms(){return Ns||(Ns=new Ps),Ns}function Rs(e,t){const n=Math.min(e.length,t.length);let r=0,i=0,s=0;for(let o=0;o<n;o++)r+=e[o]*t[o],i+=e[o]*e[o],s+=t[o]*t[o];return 0===i||0===s?0:r/(Math.sqrt(i)*Math.sqrt(s))}const $s="default";class _s{#pe=new Map;#fe(e){const t=e||$s;let n=this.#pe.get(t);return n||(n=new Map,this.#pe.set(t,n)),n}upsert(e,t=$s){const n=this.#fe(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=$s){const r=this.#fe(n),i=[];for(const t of r.values())i.push({id:t.id,score:Rs(e,t.vector),text:t.text,metadata:t.metadata});return i.sort((e,t)=>t.score-e.score),i.slice(0,Math.max(0,t))}delete(e,t=$s){const n=this.#fe(t);for(const t of e)n.delete(t)}clear(e=$s){this.#pe.delete(e||$s)}count(e=$s){return this.#fe(e).size}export(e=$s){return Array.from(this.#fe(e).values())}import(e,t=$s){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#pe.set(t||$s,n)}}const Os=".punica/vectors";class Ls{#b=new _s;#he=new Set;#ae(){try{return punica.runtime?.fs}catch{return}}#me(e){return`${Os}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#ge(e){const t=e||"default";if(this.#he.has(t))return;this.#he.add(t);const n=this.#ae();if(n?.readFile)try{const e=await n.readFile(this.#me(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#b.import(r.records,t)}catch{}}async#ye(e){const t=this.#ae();if(t)try{if(t.mkdir)try{await t.mkdir(Os)}catch{}const n={version:1,records:this.#b.export(e)},r=this.#me(e),i=JSON.stringify(n);try{await t.updateFileContent(r,i)}catch{await t.createFileWithContent(r,i)}}catch(e){console.warn("[Runtime.vectors] Failed to persist collection:",e)}}async upsert(e,t){const n=t?.collection??"default";await this.#ge(n),this.#b.upsert(e,n),await this.#ye(n)}async query(e){const t=e.collection??"default";return await this.#ge(t),this.#b.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#ge(n),this.#b.delete(e,n),await this.#ye(n)}async clear(e){const t=e?.collection??"default";await this.#ge(t),this.#b.clear(t),await this.#ye(t)}async count(e){const t=e?.collection??"default";return await this.#ge(t),this.#b.count(t)}}let js,Ds,Fs;function qs(){return js||(Ds||(Ds=new Ls),Ds)}function Bs(){if(!Fs)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 Fs}var Us;!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"}(Us||(Us={}));class Vs extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const Ws=new class{#we=new Map;#ve=new Map;registerCapability(e){if(!e.name)throw new Vs(Us.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new Vs(Us.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 Vs(Us.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.#we.has(e.name))throw new Vs(Us.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 Vs(Us.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 Vs(Us.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.#be(t,e.name);if(n)throw new Vs(Us.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#we.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{}}#be(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#we.get(e);if(!r?.requires)return null;for(const i of r.requires){const r=this.#be(i,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#we.has(e.name))throw new Vs(Us.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ve.set(e.name,e)}getSpec(e){return this.#we.get(e)}getProvider(e){return this.#ve.get(e)}hasCapability(e){return this.#we.has(e)}hasProvider(e){return this.#ve.has(e)}listCapabilities(){return Array.from(this.#we.keys())}getAllSpecs(){return Array.from(this.#we.values())}clear(){this.#we.clear(),this.#ve.clear()}};function Ks(e){const t={id:e.name,title:e.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 e.description&&(t.description=e.description),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.action&&e.action.length>0&&(t.action=[...e.action]),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),e.dataClassification&&(t["x-dataClassification"]=e.dataClassification),t}function Gs(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:Hs(e.sideEffects),risk:e.policy?.risk??"low",permissions:n,inputSchema:e.inputs?.schema,outputSchema:e.outputs?.schema};e.title&&e.title!==e.id&&(r.title=e.title),e.description&&(r.description=e.description),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);const i=t["x-dataClassification"]??t.dataClassification;return"public"!==i&&"internal"!==i&&"sensitive"!==i||(r.dataClassification=i),e.deprecated&&(r.deprecated={...e.deprecated}),Array.isArray(e.requires)&&e.requires.length>0&&(r.requires=[...e.requires]),Array.isArray(e.action)&&e.action.length>0&&(r.action=[...e.action]),e.policy&&(r.policy={...e.policy}),r}const Ys=["write","delete","remove","modify","destroy","create","update","install","publish","process","spawn","exec","run"],zs=["network","http","fetch","request","upload","download"],Js=["read","list","get","query","inspect","search"];function Hs(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":Ys.some(t=>e.includes(t))?"write":zs.some(t=>e.includes(t))?"network":Js.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 Qs=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function Zs(){const e=globalThis;return e.punica?.extensions?.manager}function Xs(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function eo(){const e=globalThis;return e.punica?.flow?.registry}function to(e){const t=Array.isArray(e.action)?e.action:[];return t.includes("process.exec")?e:{...e,action:[...t,"process.exec"]}}function no(){const e=globalThis;return e.punica?.flow?.agents}function ro(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const io={core:function(e){const t=Ws.getSpec(e);if(t)return{origin:"core",definition:Ks(t)}},extension:function(e){const t=Zs();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=Xs();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=eo();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-node",definition:to(r),metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},"ivy-agent":function(e){const t=no();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=ro();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},so={core:function(){return Ws.getAllSpecs().map(e=>({origin:"core",definition:Ks(e)}))},extension:function(){const e=Zs();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=Xs();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=eo();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-node",definition:to(e),metadata:{packageRoot:n.manifestPath}})}return t},"ivy-agent":function(){const e=no();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=ro();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},oo={getCapability(e){for(const t of Qs){const n=io[t](e);if(n)return n}},listCapabilities(e){const t=(n=e?.origin,void 0===n?void 0:new Set(Array.isArray(n)?n:[n]));var n;const r=new Set,i=[];for(const e of Qs)if(!t||t.has(e))for(const t of so[e]()){const e=t.definition.id;r.has(e)||(r.add(e),i.push(t))}return i},hasCapability(e){return void 0!==this.getCapability(e)}};function ao(e,t,n){switch(e){case"mcp":return function(e,t){const{mcpServerId:n,mcpToolName:r}=t;return{name:e.id,async execute(t,i){const s=globalThis.punica?.runtime?.mcp;if(!s?.callTool)throw new Vs(Us.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 Vs(Us.CAPABILITY_PROVIDER_MISSING,`MCP capability "${e.id}" is missing serverId or toolName metadata`,{capability:e.id,origin:"mcp"});return await s.callTool(n,r,t??{})}}}(t,n??{});case"instruction-class":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.kernel?.llm?.api;if(!r?.invokeLlmCapability)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`LLM kernel API is not initialized — cannot invoke instruction-class capability "${e.id}".`,{capability:e.id,origin:"instruction-class"});const i=null!==t&&"object"==typeof t?t:{},s="string"==typeof i.instructionClass?i.instructionClass:e.id,o="string"==typeof i.userPrompt?i.userPrompt:"string"==typeof i.prompt?i.prompt:JSON.stringify(t);return await r.invokeLlmCapability({instructionClass:s,userPrompt:o,context:i.context??{}})}}}(t);case"ivy-node":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.runner;if(!r?.run)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Flow runner is not initialized — cannot invoke ivy-node capability "${e.id}". Ensure the flow module has started before calling IvyNode capabilities.`,{capability:e.id,origin:"ivy-node"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i});return s?.output??null}}}(t);case"ivy-agent":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.agents;if(!r?.run)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Agent registry is not initialized — cannot invoke ivy-agent capability "${e.id}". Ensure the flow module has started before calling IvyAgent capabilities.`,{capability:e.id,origin:"ivy-agent"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i});return s?.output??null}}}(t);case"extension":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.extensions?.manager;if(!r?.executeCapability)throw new Vs(Us.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 Vs(Us.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}const co={recordSpan:()=>{}};let lo=co;function uo(){return lo}function po(e){try{uo().recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function fo(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,o={capability:i,"actor.type":s.actor.type,"origin.kind":s.origin.kind};s.actor.extensionName&&(o["actor.extension"]=s.actor.extensionName),s.origin.extension&&(o["origin.extension"]=s.origin.extension),s.workspaceId&&(o["workspace.id"]=s.workspaceId),r.tags={...r.tags,...o};try{const e=await t();return r.durationMs=Date.now()-r.startTimeMs,po({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"success",attributes:{...r.tags}}),e}catch(e){r.error=e instanceof Error?e:new Error(String(e)),r.durationMs=Date.now()-r.startTimeMs;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.failed",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,spanId:s.trace.parentSpanId??n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"error"},payload:{invocationId:n.invocationId,capability:i,error:r.error.message,durationMs:r.durationMs}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.failed event:",e)}throw po({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"error",errorCode:e instanceof Vs?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function ho(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(ho);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=ho(r);return t}return e}const mo=new WeakMap;function go(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s}=n;if(!0===r.spec.secretBearing||i.startsWith("secrets."))r.redactedInput=ho(s);else{const e=function(e){const t=mo.get(e);if(t)return t;const n=u(e.inputSchema);return mo.set(e,n),n}(r.spec);r.redactedInput=e.length>0?f(s,e):s}return await t()}}function yo(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function wo(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===yo(t))}const vo=new class{validate(e,t){const n=[];if(!e||"object"!=typeof e)return{ok:!0,errors:n};const r=e,i=r.type;if(i&&(wo(i,t)||n.push(`Expected type "${i}", got "${yo(t)}"`)),"object"===i&&t&&"object"==typeof t&&!Array.isArray(t)){const e=t,i=r.required,s=r.properties;if(Array.isArray(i))for(const t of i)t in e&&void 0!==e[t]||n.push(`Missing required field: "${t}"`);if(s)for(const[t,r]of Object.entries(e)){if(void 0===r)continue;const e=s[t];if(!e)continue;const i=e.type;i&&(wo(i,r)||n.push(`Field "${t}": expected type "${i}", got "${yo(r)}"`))}}return{ok:0===n.length,errors:n}}};let bo=vo;function Io(){return bo}function ko(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=Io().validate(s,i);if(!o.ok)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const Eo=Ti({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function So(){return Eo.get()}const Ao=["path","oldPath","newPath","src","dst","target","linkPath"];function xo(e,t){if(e.includes("\0"))return{ok:!1,reason:"null byte in path"};if(/(%2e|\.)(?:%2e|\.)/i.test(e)&&/%2e/i.test(e))return{ok:!1,reason:"URL-encoded traversal segment"};if(/^[A-Za-z]:[\\/]?/.test(e))return{ok:!1,reason:"drive-relative path"};if(e.startsWith("\\\\"))return{ok:!1,reason:"UNC path"};const n=e.replace(/\\/g,"/"),r=n.startsWith("/"),i=n.split("/").filter(e=>""!==e&&"."!==e),s=[];for(const e of i)if(".."===e){if(0===s.length)return{ok:!1,reason:"traversal above root"};s.pop()}else s.push(e);let o=(r?"/":"")+s.join("/");if(""===o&&(o=r?"/":"."),t&&r){const e=function(e){let t=e.replace(/\\/g,"/");t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1));return t}(t);if("/"===e);else if(o!==e&&!o.startsWith(`${e}/`))return{ok:!1,reason:"path is outside the workspace root"}}return{ok:!0,canonical:o}}function Co(){try{return So().cwd}catch{return}}function To(){return async(e,t)=>{const{input:n}=e.req;if("object"!=typeof n||null===n)return await t();const r=n;let i,s=!1;for(const e of Ao){const t=r[e];if("string"!=typeof t)continue;s||(i=Co(),s=!0);const n=xo(t,i);if(!n.ok)throw new Vs(Us.CAPABILITY_PATH_TRAVERSAL_DENIED,`Path traversal denied on field "${e}": ${n.reason}`,{field:e,reason:n.reason,value:t,...void 0!==i?{cwd:i}:{}})}return await t()}}const Po="encrypted-at-rest";function No(){return async(e,t)=>{const n=e.state.spec;if("sensitive"!==(n.dataClassification??"internal"))return t();if(!(r=n.name).startsWith("fs.")&&!r.startsWith("workspace."))return t();var r;const i=function(){try{return So()}catch{return}}();if(!i)throw new Vs(Us.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:Po,reason:"provider not registered"});if(!i.capabilities?.has(Po))throw new Vs(Us.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${Po}" capability flag`,{capability:n.name,required:Po,reason:"capability not advertised"});return Ei({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:Po}}),t()}}const Mo=new Map;function Ro(e,t,n=0){if(n>=t.length)return null!=e&&""!==e;const r=t[n];return"*"===r?Array.isArray(e)&&e.some(e=>Ro(e,t,n+1)):!(!e||"object"!=typeof e||Array.isArray(e))&&Ro(e[r],t,n+1)}function $o(e,t){if("sensitive"===e.dataClassification)return!0;const n=e.inputSchema;if(!n)return!1;let r;try{r=u(n)}catch{return!1}return r.some(e=>Ro(t,e))}function _o(){return async(e,t)=>{const n=e.state.spec,r=e.req.ctx?.trace?.traceId,i=$o(n,e.req.input);i?e.state.sensitive="declared":function(e){if(e)return Mo.get(e.trim())}(r)&&(e.state.sensitive="taint");const s=()=>{i&&r&&function(e,t,n=Date.now()){const r=e.trim();if(r)for(Mo.has(r)&&Mo.delete(r),Mo.set(r,{atMs:n,by:t});Mo.size>4096;){const e=Mo.keys().next().value;if(void 0===e)break;Mo.delete(e)}}(r,n.name)},o=async()=>{const e=await t();return s(),e},a=n.egress??(Fe(n)?.includes("net.request")?"remote":"none");if("none"===a)return o();if("remote"===a)return e.state.egress="remote",o();const c=await Xi(e.req.input,function(){try{return as()}catch{return}}());return e.state.egress="local"===c?"local":"remote",o()}}function Oo(){const e=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()}catch{return}}();if(e)return e;try{return Gt.manager.registry.getActive()}catch{return}}function Lo(e,t,n,r,i){try{const s=globalThis.punica?.kernel?.Events?.manager;if(!s||"function"!=typeof s.publishEvent)return;s.publishEvent({name:"capability.denied_by_profile",source:"runtime:capabilities:middleware:profileBudget",kind:"warn",correlationId:i,payload:{invocationId:i,capability:e,profile:t,reason:n,origin:r??"unknown"}})}catch{}}function jo(){return async(e,t)=>{const n=Oo();if(!n)return t();const{allowedIds:r,deniedIds:i,allowedOrigins:s}=n.capabilities;if("*"===r&&!i?.length&&!s?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(s&&s.length>0){const e=oo.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw Lo(o,c,"origin-not-allowed",t,a),new Vs(Us.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" origin "${t??"unknown"}" is not in profile "${c}" allowedOrigins`,{capability:o,profile:c,reason:"origin-not-allowed",origin:t??"unknown"})}if(i&&i.includes(o))throw Lo(o,c,"in-denylist",void 0,a),new Vs(Us.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 Lo(o,c,"not-in-allowlist",void 0,a),new Vs(Us.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Do={alg:"HS256",typ:"PUNICA-APPROVAL"};class Fo extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function qo(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 Bo(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 Uo(e){return(new TextEncoder).encode(e)}function Vo(e){return qo(Uo(JSON.stringify(e)))}function Wo(e){return JSON.parse((t=Bo(e),(new TextDecoder).decode(t)));var t}function Ko(){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 Go(){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 Yo{#Ie;#ke;constructor(e){e?.secret instanceof Uint8Array?this.#Ie=e.secret:this.#Ie="string"==typeof e?.secret?Uo(e.secret):Go()}async sign(e){const t=await this.#Ee(),n=Vo(Do),r=Vo(e),i=Uo(`${n}.${r}`),s=await Ko().sign("HMAC",t,i);return`${n}.${r}.${qo(new Uint8Array(s))}`}getSecret(){return this.#Ie}async#Ee(){return this.#ke||(this.#ke=await Ko().importKey("raw",this.#Ie,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#ke}}class zo{#Ie;#ke;#Se=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#Ie=e.secret:this.#Ie="string"==typeof e?.secret?Uo(e.secret):Go()}async verify(e){const t=e.split(".");if(3!==t.length)throw new Fo("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=Wo(n)}catch{throw new Fo("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new Fo("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=Wo(r)}catch{throw new Fo("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#Ee(),c=Uo(`${n}.${r}`);let l;try{l=Bo(i)}catch{throw new Fo("MALFORMED","Token signature is not valid base64url")}const u=Ko();if(!await u.verify("HMAC",a,l,c))throw new Fo("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new Fo("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new Fo("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#Se.add(e)}isRevoked(e){return this.#Se.has(e)}async#Ee(){return this.#ke||(this.#ke=await Ko().importKey("raw",this.#Ie,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#ke}}let Jo,Ho,Qo;function Zo(){return Jo||(Jo=function(){const e=new Yo,t=new zo({secret:e.getSecret()});return{signer:e,verifier:t}}()),Jo}function Xo(e){Ho=e}function ea(){return Qo??Zo().verifier}function ta(e){Qo=e}const na=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";let ra;function ia(){return ra??na}function sa(e){ra=e}const oa=new WeakMap;function aa(e){const t=oa.get(e);if(t)return t;const n=function(e){return d(e,"policyKey")}(e.inputSchema);return oa.set(e,n),n}const ca=new WeakMap;function la(e){const t=ca.get(e);if(t)return t;const n=u(e.inputSchema);return ca.set(e,n),n}function ua(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=globalThis.punica?.kernel?.Policy?.manager;if(!a){const e=o.policy??{},a=e.risk??o.risk??"low",c=e.approval??"none",l="high"===a||"step"===c||"plan"===c,u=!0===globalThis.punica?.kernel?.Policy?.failClosed,d=u&&l;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"policy.manager.missing",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:d?"error":"warning"},payload:{capability:i,risk:a,approval:c,actor:s.actor,decision:d?"deny":"allow",failClosed:u}})}catch{}if(console.warn(`[CapabilityGateway] Policy manager not available for "${i}" (risk=${a}, approval=${c}); `+(d?"DENYING (fail-closed)":"allowing (fail-open)")+"."),d)throw new Vs(Us.CAPABILITY_DENIED,`Policy manager unavailable and capability "${i}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:i,reason:"policy-manager-missing",risk:a,approval:c});return r.policyDecision={allowed:!0,requiresApproval:!1,reason:"policy-manager-missing (fail-open)"},await t()}const c=o.policy??{},l=c.risk??o.risk??"low",u=c.approval??"none";let d=!1,p="";const f=s.policy?.stance;let h;if("ai"===s.actor.type&&"auto"!==f){"approval"===ia()({capabilityId:i,risk:o.risk,sideEffect:o.sideEffect})&&(d=!0,p=`agent-mode policy: ${o.sideEffect}/${o.risk}`,"observe"===f&&(h=`Observe refuses ${i} because it `+("high"===o.risk?"is high risk":"writes")+"; switch to Assist to be asked before it runs."))}"high"===o.risk&&(d=!0,p="High risk capability"),"step"!==u&&"plan"!==u||(d=!0,p=`Capability requires ${u} approval`);const{binding:m,preview:g}=await _e(r.redactedInput,{policyKeyPaths:aa(o)}),y={kind:"capability",id:i,risk:l,approval:u,reason:o.description??o.title??`Capability: ${i}`,argsBinding:m,argsPreview:g},w=Fe(o);w&&(y.action=w),"remote"===r.egress&&(y.egress="remote"),r.sensitive&&(y.sensitive=r.sensitive);const v=!0===o.secretBearing||i.startsWith("secrets."),b=a.evaluate(y,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId,parentSpanId:n.invocationId,args:r.redactedInput,redactedPaths:la(o),argsWhollyRedacted:v});r.policyDecision={allowed:b.allowed,requiresApproval:b.requiresApproval||d,approvalToken:s.policy.approvalToken,reason:b.reason||p,argsBinding:m};const I=b.policyRule;I&&(r.policyDecision.policyRule=I),b.maxScope&&(y.maxScope=b.maxScope),b.approvers&&(y.approvers=b.approvers),b.org&&(y.org=b.org),b.signatures&&(y.signatures=b.signatures);const k=ft(b.maxScope);if("deny"===I?.effect)throw new Vs(Us.CAPABILITY_DENIED,b.reason??"Policy denied execution",{capability:i,decision:b,policyRule:I});if(!h&&"observe"===f&&"ai"===s.actor.type&&(b.requiresApproval||d)&&function(e,t){return"high"===e.risk||("write"===e.sideEffect||(t??[]).some(e=>"process.exec"===e||e.endsWith(".write")||e.endsWith(".delete")||e.endsWith(".send")))}(o,w)&&(h=`Observe refuses ${i} because it `+("high"===o.risk?"is high risk":"writes")+"; switch to Assist to be asked before it runs."),h)throw r.policyDecision.allowed=!1,r.policyDecision.requiresApproval=!1,r.policyDecision.reason=h,new Vs(Us.CAPABILITY_DENIED,h,{capability:i,stance:f,decision:b});if("allow"===I?.effect&&(d=!1,r.policyDecision.requiresApproval=!1),d||b.requiresApproval)if(s.policy.approvalToken)try{await ea().verify(s.policy.approvalToken)}catch(e){if(e instanceof Fo){try{const t=globalThis.punica?.kernel?.Events?.manager;t&&t.publishEvent({name:"token.invalid",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:"error"},payload:{capability:i,tokenError:e.code,actor:s.actor}})}catch{}throw new Vs(Us.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:i,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!k.some(e=>a.hasApproval(y,e,{workspaceId:s.workspaceId}))){a.requestApproval(y,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId,...b.reason?{reason:b.reason}:{}});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:i,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}const e=b.reason||p;throw new Vs(Us.CAPABILITY_APPROVAL_REQUIRED,b.reason?b.reason:p?`Approval required: ${p}`:"Approval required.",{capability:i,reason:e})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:s.workspaceId};if(!k.filter(e=>"once"!==e).some(t=>a.hasApproval(y,t,e))&&"function"==typeof a.revokeApproval){const e=[y.argsBinding];y.argsBinding&&e.push("any");for(const t of e)try{a.revokeApproval({kind:y.kind,id:y.id,scope:"once",argsBinding:t})}catch{}}}}if(!b.allowed&&!d&&"suggest"!==b.mode)throw new Vs(Us.CAPABILITY_DENIED,b.reason??"Policy denied execution",{capability:i,decision:b});return r.policyDecision&&"suggest"===b.mode&&!b.allowed&&(r.policyDecision.allowed=!0,r.policyDecision.mode="suggest",r.policyDecision.reason="Policy mode is suggest; advisory at the gate, so the call ran."),await t()}}const da=new class{#g=new Map;#Ae;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#Ae=t<=0?1:t}get(e,t){const n=this.#xe(e,t),r=this.#g.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#g.delete(n),this.#g.set(n,r),r;this.#g.delete(n)}}set(e){const t=this.#xe(e.capabilityId,e.key);for(this.#g.delete(t),this.#g.set(t,e);this.#g.size>this.#Ae;){const e=this.#g.keys().next().value;if(void 0===e)break;this.#g.delete(e)}}delete(e,t){return this.#g.delete(this.#xe(e,t))}clear(){this.#g.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#g)r.expiresAtMs<=e&&(this.#g.delete(n),t++);return t}size(){return this.#g.size}#xe(e,t){return`${e}|${t}`}};let pa=da;function fa(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s,idempotencyKey:o}=n,a=r.spec.defaults?.idempotency??"none";if("none"===a)return t();if("required"===a&&!o)throw new Vs(Us.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=pa,l=function(e){const t=JSON.stringify(e??null);let n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}(s),u=c.get(i,o);if(u){if(u.inputHash!==l)throw function(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}({name:"idempotency.replay_blocked",envelope:{id:n.invocationId,correlationId:n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:idempotency",kind:"error"},payload:{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs,actor:n.ctx.actor}}),new Vs(Us.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED,`Capability "${i}" idempotencyKey "${o}" was previously used with a different input`,{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs});return r.output=u.response,r.tags["idempotency.hit"]="true",u.response}const d=await t(),p=Date.now();return c.set({key:o,capabilityId:i,inputHash:l,response:d,createdAtMs:p,expiresAtMs:p+864e5}),r.tags["idempotency.cached"]="true",d}}const ha=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(),i=(r-n.lastRefillMs)/1e3*t;return n.tokens=Math.min(n.maxTokens,n.tokens+i),n.lastRefillMs=r,n.tokens>=1&&(n.tokens-=1,!0)}};function ma(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=o.defaults?.rateLimit;if(!a||!a.perSecond)return await t();const c=function(e,t,n){const r=[e,t];return n&&r.push(n),r.join(":")}(i,s.actor.type,s.actor.extensionName??s.origin.extension);if(!ha.consumeToken(c,a.perSecond))throw new Vs(Us.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const ga=new class{#Te=new Map;getSemaphore(e,t){let n=this.#Te.get(e);return n||(n={count:0,max:t,queue:[]},this.#Te.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.#Te.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function ya(){return async(e,t)=>{const{req:n,state:r}=e,{ctx:i}=n,{spec:s}=r,o=s.defaults?.concurrency;if(!o||!o.key||!o.max)return await t();const a=function(e,t){let n=e;return n=n.replace(/\{workspaceId\}/g,t.workspaceId??""),n=n.replace(/\{tenantId\}/g,t.tenantId??""),n=n.replace(/\{extension\}/g,t.extension??""),n=n.replace(/\{actorType\}/g,t.actorType??""),n}(o.key,{workspaceId:i.workspaceId,tenantId:i.tenantId,extension:i.actor.extensionName??i.origin.extension,actorType:i.actor.type});try{await ga.acquire(a,o.max)}catch(e){throw new Vs(Us.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{ga.release(a)}}}const wa=new class{#Pe=new Map;getBreaker(e){let t=this.#Pe.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#Pe.set(e,t)),t}};function va(){return async(e,t)=>{const{req:n,state:r}=e,{name:i}=n,s=r.spec.defaults?.circuitBreaker;if(!s)return await t();const o=s.failureThreshold??3,a=s.cooldownMs??6e4,c=wa.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new Vs(Us.CAPABILITY_CIRCUIT_OPEN,`Circuit breaker open for "${i}"`,{capability:i,openedAtMs:c.openedAtMs,cooldownMs:a,remainingMs:a-(l-c.openedAtMs)});try{const e=await t();return c.consecutiveFailures=0,c.status="closed",e}catch(e){c.consecutiveFailures++;throw("half-open"===c.status||c.consecutiveFailures>=o)&&(c.status="open",c.openedAtMs=l),e}}}function ba(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 Ia(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new Vs(Us.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),s])}finally{void 0!==i&&clearTimeout(i)}}const ka=["dataset","file","model","prompt","collection","artifact"],Ea={subjects:[],digests:[]};function Sa(e){if(!e||"object"!=typeof e)return Ea;const t=[];for(const n of p(e,"subject")){if("string"!=typeof n.value)continue;const e=n.value.trim();0!==e.length&&t.push({path:n.path,kind:e})}return 0===t.length?Ea:{subjects:t,digests:d(e,"subjectDigest")}}function Aa(e,t){let n=[{path:[],value:e}];for(const e of t){const t=[];for(const r of n){if("*"===e){if(!Array.isArray(r.value))continue;r.value.forEach((e,n)=>{t.push({path:[...r.path,String(n)],value:e})});continue}if(!r.value||"object"!=typeof r.value)continue;if(Array.isArray(r.value))continue;const n=r.value;e in n&&t.push({path:[...r.path,e],value:n[e]})}if(n=t,0===n.length)return[]}return n}const xa=new Set(["[REDACTED]","***"]);function Ca(e){let t;if("string"==typeof e)t=e;else{if("number"!=typeof e||!Number.isFinite(e))return;t=String(e)}const n=t.trim();if(0!==n.length&&!(n.length>1024||xa.has(n)))return n}function Ta(e){return e.slice(0,-1).join(" ")}function Pa(e,t,n,r){const i=Sa(e);if(0===i.subjects.length)return;const s=[],o=new Map;for(const e of i.subjects)for(const r of Aa(t,e.path)){const t=Ca(r.value);if(void 0===t)continue;const i=Ta(r.path);o.set(i,(o.get(i)??0)+1),s.push({subject:{kind:e.kind,id:t,from:n},parent:i})}if(0===s.length)return;const a=function(e,t,n){const r=new Map;for(const n of t.digests)for(const t of Aa(e,n)){const e=Ca(t.value);if(void 0===e)continue;const n=Ta(t.path),i=r.get(n);i?i.push(e):r.set(n,[e])}const i=new Map;for(const[e,t]of r)1===t.length&&1===n.get(e)&&i.set(e,t[0]);return i}(t,i,o);for(const e of s){const t=a.get(e.parent);r.push(void 0===t?e.subject:{...e.subject,digest:t})}}function Na(e){return{invocationId:e.invocationId,runId:e.trace?.traceId,conversationId:e.conversationId,spanId:e.trace?.spanId??e.invocationId,parentSpanId:e.trace?.parentSpanId,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,argsBinding:e.policyDecision.argsBinding,policyRule:e.policyDecision.policyRule}:void 0,input:e.redactedInput,output:e.redactedOutput,egress:e.egress,subjects:e.subjects?.length?e.subjects:void 0,subjectsOmitted:e.subjectsOmitted,sensitive:e.sensitive,duration:e.durationMs,error:e.error?{message:e.error.message,name:e.error.name,code:e.error.code}:void 0,timestamp:e.timestamp}}async function Ma(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,traceId:e.trace?.traceId,spanId:e.trace?.spanId??e.invocationId,parentSpanId:e.trace?.parentSpanId,timestampMs:e.timestamp,source:"runtime:capabilities:gateway",kind:"audit"},payload:Na(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(Na(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=So()}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(Na(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 Ra=new WeakMap;const $a=new WeakMap;function _a(e,t,n){const r=$a.get(e);if(r)return r;const i=function(e,t,n){if(!0===e.secretBearing)return{subjects:[]};const r=[];if(Pa(e.inputSchema,t,"input",r),Pa(e.outputSchema,n,"output",r),0===r.length)return{subjects:[]};const i=new Set,s=[];for(const e of r){const t=[e.kind,e.id,e.digest??"",e.from].join(" ");i.has(t)||(i.add(t),s.push(e))}return s.length<=64?{subjects:s}:{subjects:s.slice(0,64),omitted:s.length-64}}(e,t,n);return 0!==i.subjects.length||function(e){return Sa(e.inputSchema).subjects.length>0||Sa(e.outputSchema).subjects.length>0}(e)||$a.set(e,i),i}function Oa(e,t){if(!0===t.secretBearing)return La(e);const n=function(e){const t=Ra.get(e);if(t)return t;const n=u(e.outputSchema);return Ra.set(e,n),n}(t);return n.length>0?f(e,n):e}function La(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(La);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=La(r);return t}return e}function ja(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a="object"==typeof n.input&&null!==n.input&&"path"in n.input&&"string"==typeof n.input.path&&/^\.punica\/audit\//.test(n.input.path);let c,l;try{c=await t(),r.output=c}catch(e){throw l=e instanceof Error?e:new Error(String(e)),r.error=l,e}finally{const e=globalThis.punica?.runtime,t=!e||"bootstrapping"===e.lifecyclePhase||"noWorkspace"===e.lifecyclePhase;if(!a&&!t){const e=Oa(r.output,o),t=_a(o,r.redactedInput,e);await Ma({invocationId:n.invocationId,capability:i,actor:s.actor,origin:s.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:s.workspaceId,conversationId:s.conversationId,trace:s.trace?{traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId}:void 0,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,egress:r.egress,sensitive:r.sensitive,subjects:t.subjects,subjectsOmitted:t.omitted,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Da=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","egressGuard","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Fa(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const qa=new class{async call(e,t,n,r){const i="user"!==n.actor.type||n.actor.id?n:{...n,actor:{...n.actor,id:ye()}},s=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let o=Ws.getSpec(e),a=o?Ws.getProvider(e):void 0,c="core";if(!o){const t=oo.getCapability(e);if(!t)throw Fa({name:"capability.unknown_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:i.actor}}),new Vs(Us.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);c=t.origin,o=Gs(t.definition),a=ao(t.origin,t.definition,t.metadata)}if(!a)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(o.requires)for(const t of o.requires)if(!Ws.hasCapability(t))throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});o.deprecated&&Fa({name:"capability.deprecated_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:c,since:o.deprecated.since,reason:o.deprecated.reason,replacement:o.deprecated.replacement,actor:i.actor}});const l={req:{invocationId:s,name:e,input:t,ctx:{...i,invocationId:s},idempotencyKey:r},state:{spec:o,capabilityOrigin:c,startTimeMs:Date.now(),tags:{}}},u=this.#Ne(a);try{return await this.#Me(u,l)}catch(e){if(e instanceof Vs)throw e;const t=e instanceof Error&&e.message?e.message:`Provider execution failed: ${String(e)}`;throw new Vs(Us.CAPABILITY_PROVIDER_ERROR,t,{originalError:String(e),errorName:e instanceof Error?e.name:void 0})}}#Ne(e){const t={auditTrail:ja,traceMetrics:fo,redaction:go,validateInput:ko,pathTraversalGuard:To,encryptionRouting:No,egressGuard:_o,profileBudget:jo,policyGate:ua,idempotency:fa,rateLimit:ma,concurrency:ya,circuitBreaker:va,timeoutRetry:()=>function(e){return async(t,n)=>{const{req:r,state:i}=t,{input:s,idempotencyKey:o}=r,{spec:a}=i,c=a.defaults?.timeoutMs??3e4,l=a.defaults?.retries??0,u=a.defaults?.retryBackoffMs??1e3,d="write"!==a.sideEffect||Boolean(o);let p=null,f=0;for(;f<=l;){f++;try{const n=await Ia(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),f<=l&&d&&ba(p)){const e=u*Math.pow(2,f-1);await new Promise(t=>setTimeout(t,e));continue}throw i.error=p,p}}throw i.error=p??new Error("Execution failed"),i.error}}(e)};return Da.map(e=>t[e]())}#Me(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const i=e[n];return n++,await i(t,r)};return r()}};function Ba(e,t){const n=So(),r=n[t];if("function"!=typeof r)throw new Vs(Us.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 Ua(e,t,n){const r=So();if(!r.capabilities?.has(n))throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires the FileSystemProvider to advertise the "${n}" capability flag, but it does not`,{capability:e,method:String(t),requiredProviderCapability:n});const i=r[t];if("function"!=typeof i)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires FileSystemProvider.${String(t)}() but the registered provider does not expose it`,{capability:e,method:String(t),requiredProviderCapability:n});return i.bind(r)}class Va{name="fs.readFile";async execute(e,t){const n=So(),r=await n.readFile(e.path);if(null==r)throw new Error(`No such file: ${e.path}`);return r}}class Wa{name="fs.writeFile";async execute(e,t){const n=So();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}const Ka=89478485;class Ga{name="fs.writeBytes";async execute(e,t){if(e.base64.length>Ka)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Capability "fs.writeBytes" received a ${e.base64.length}-character base64 payload, over the 89478485 limit`,{capability:"fs.writeBytes",limit:Ka});let n;try{n=function(e){if("undefined"!=typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}const t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t).buffer}(e.base64)}catch{throw new Vs(Us.CAPABILITY_INPUT_INVALID,'Capability "fs.writeBytes" received a malformed base64 payload',{capability:"fs.writeBytes"})}await Ba("fs.writeBytes","writeBytes")(e.path,n)}}class Ya{name="fs.listFiles";async execute(e,t){const n=So();return await n.getFileTree()}}class za{name="fs.stat";async execute(e,t){return await Ba("fs.stat","stat")(e.path)}}class Ja{name="fs.exists";async execute(e,t){return await Ba("fs.exists","exists")(e.path)}}class Ha{name="fs.copy";async execute(e,t){await Ba("fs.copy","copy")(e.src,e.dst)}}class Qa{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Ba("fs.mkdir","mkdir")(e.path,n)}}class Za{name="fs.history";async execute(e,t){return await Ua("fs.history","history","versioning")(e.path)}}class Xa{name="fs.readAtVersion";async execute(e,t){return await Ua("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class ec{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Ba("fs.list","list")(e.path,n)}}const tc=Ti({label:"Runtime.secrets",noProviderMessage:"[Runtime.secrets] No Secrets provider registered. Host must call punica.runtime.setSecretsProvider() before using Secrets API",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.secrets;return void 0===t||ic(t)?function(){const e=new Map,t=new Map;return{set(n,r){const i=String(n??"").trim();if(!i)throw new Error("[Runtime.secrets] Secret name is required");const s=Date.now();if(t.has(i)){const e=t.get(i);t.set(i,{...e,updatedAtMs:s})}else t.set(i,{createdAtMs:s,updatedAtMs:s});e.set(i,String(r??""))},get(t){const n=String(t??"").trim();return n&&e.has(n)?e.get(n):null},delete(n){const r=String(n??"").trim();return!!r&&(t.delete(r),e.delete(r))},list(){const e=[];for(const[n,r]of t.entries())e.push({name:n,createdAtMs:r.createdAtMs,updatedAtMs:r.updatedAtMs});return e.sort((e,t)=>e.name.localeCompare(t.name)),e}}}():t}});function nc(){return tc.get()}function rc(e){tc.set(e),e&&Ei({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}function ic(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedSecretsFacade}class sc{name="secrets.get";async execute(e,t){return nc().get(e.name)}}class oc{name="secrets.set";async execute(e,t){nc().set(e.name,e.value)}}function ac(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[rs]=!0,n}class cc{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=ac(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class lc{name="llm.chatStream";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=globalThis.punica?.kernel?.Events?.manager,i=t.sessionId??t.trace?.traceId,s=e=>{if(r)try{r.publishEvent({name:"llm.chunk",envelope:{id:r.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"progress"},payload:{capabilityId:this.name,chunk:e}})}catch{}},o=ac(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);if("function"!=typeof n.chatStream){const e=await n.chat(o);return s({type:"done",response:e}),e}let a="",c="";const l=[];let u;for await(const e of n.chatStream(o)){if(t.signal?.aborted)break;switch(s(e),e.type){case"content":a+=e.text;break;case"thinking":c+=e.text;break;case"tool_call":l.push(e.toolCall);break;case"done":u=e.response;break;case"error":throw new Error(`[llm.chatStream] ${e.error.code}: ${e.error.message}`)}}const d={text:a||u?.text||"",modelId:u?.modelId,provider:u?.provider,usage:u?.usage,meta:u?.meta};return l.length>0&&(d.toolCalls=l),c&&(d.thinking=c),d}}class uc{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,...t.trace?.traceId?{trace:{traceId:t.trace.traceId,...t.invocationId?{parentSpanId:t.invocationId}:t.trace.parentSpanId?{parentSpanId:t.trace.parentSpanId}:{}}}:{}})}}class dc{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 pc{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 fc{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 hc{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 mc{name="workspace.readFile";async execute(e,t){const n=So();return await n.readFile(e.path)}}class gc{name="workspace.writeFile";async execute(e,t){const n=So();await n.createFileWithContent(e.path,e.content)}}class yc{name="workspace.listFiles";async execute(e,t){const n=So(),r=await n.getFileTree(),i=[],s=e=>{for(const t of e??[])i.push({path:t.path,name:t.name,isDirectory:t.isDirectory}),t.isDirectory&&Array.isArray(t.children)&&t.children.length&&s(t.children)};return s(r??[]),{entries:i}}}const wc=[".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"],vc=["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 bc(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("/"),i=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),s=new RegExp(`^${r||n?"":"(?:.*/)?"}${i}(?:/.*)?$`);return e=>s.test(e)}const Ic={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"},kc=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 Ec(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 Sc(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function Ac(e,t,n){const r=new Map;for(const t of e){if(t.endsWith("/"))continue;const e=Ic[Sc(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 xc(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(kc.has(e)&&n.add(t),n.size>=8)break}return[...n].slice(0,8)}function Cc(e){const t={};let n,r;if(e.packageJson)try{const i=JSON.parse(e.packageJson),s=Object.keys(i.dependencies??{}),o=Object.keys(i.devDependencies??{});if(t.node={source:"package.json",count:s.length,dev:o.length,names:[...s,...o].slice(0,60)},i.scripts&&Object.keys(i.scripts).length){n={};for(const[e,t]of Object.entries(i.scripts).slice(0,30))n[e]=t}"string"==typeof i.main&&(r=i.main)}catch{t.node={source:"package.json",count:0,dev:0,names:[]}}const i=e.requirementsTxt?function(e){const t=[];for(const n of e.split(/\r?\n/)){const e=Ec(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,i=-1;for(let t=n;t<e.length;t++)if("["===e[t])r++;else if("]"===e[t]&&0===--r){i=t;break}if(i<0)return[];const s=[];for(const t of e.slice(n+1,i).match(/["']([^"']+)["']/g)??[]){const e=Ec(t.replace(/["']/g,""));e&&s.push(e)}return s}(e.pyproject):null;i&&(t.python={source:e.requirementsTxt?"requirements.txt":"pyproject.toml",count:i.length,names:i.slice(0,60)});const s={workspace:e.workspace,stack:Ac(e.layout,!!t.node,!!t.python),dependencies:t,entrypoints:xc(e.layout,r),layout:e.layout.slice(0,250),truncated:e.layoutTruncated||e.layout.length>250};if(n&&(s.scripts=n),e.readme&&(s.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);s.vcs={branch:t.current??null,...null!=t.ahead?{ahead:t.ahead}:{},...null!=t.behind?{behind:t.behind}:{},dirtyFiles:n}}return s}const Tc=["readme.md","readme.rst","readme.txt","readme"];async function Pc(e,t){try{return await e.readFile(t)}catch{return}}async function Nc(){const e=So(),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(wc),n=new Set(vc),r=(e.gitignore??"").split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")&&!e.startsWith("!")),i=r.map(bc).filter(e=>null!=e),s=[],o=new Set,a=e=>{o.has(e)||(o.add(e),s.push(e))};for(const e of wc)a(`${e}/`);for(const e of vc)a(`*.${e}`);for(const e of r)a(e);return{patterns:s,isNoise:e=>{const r=String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"");if(!r)return!1;const s=r.split("/");for(const e of s)if(t.has(e))return!0;const o=s[s.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 i)if(e(r))return!0;return!1}}}({gitignore:n.has(".gitignore")?await Pc(e,n.get(".gitignore")):void 0}),{layout:i,truncated:s}=function(e,t){const n=[];let r=!1;const i=(e,s)=>{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&&s<2&&i(o.children,s+1)}}};return i(e??[],0),{layout:n,truncated:r}}(t,r.isNoise),o=t=>n.has(t)?Pc(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 Tc)if(n.has(t)&&(u=await Pc(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:Cc({workspace:d,layout:i,layoutTruncated:s,packageJson:a,requirementsTxt:c,pyproject:l,readme:u,vcs:p}),noisePatterns:r.patterns}}class Mc{name="workspace.projectContext";async execute(e,t){const{context:n}=await Nc();return n}}async function Rc(e,t,n){try{await e.updateFileContent(t,n)}catch{await e.createFileWithContent(t,n)}}class $c{name="workspace.writeOrientation";async execute(e,t){const n=!1!==e?.claudeMd,r=!1!==e?.claudeignore,i=So(),{context:s,noisePatterns:o}=await Nc(),a=[];if(n&&(await Rc(i,"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,i=e.dependencies.node;if((r||i)&&(t.push("## Dependencies",""),r&&t.push(`**Python** (\`${r.source}\`, ${r.count}): ${r.names.join(", ")}`,""),i&&t.push(`**Node** (\`${i.source}\`, ${i.count} + ${i.dev} dev): ${i.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")}(s)),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 Rc(i,".claudeignore",e),a.push(".claudeignore")}return{written:a}}}const _c=".punica/facts",Oc=`${_c}/facts.json`;async function Lc(e){let t;try{t=await e.readFile(Oc)}catch{return{}}try{const e=JSON.parse(t);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}class jc{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=So(),i=await Lc(r);return i[n]=e.value??null,await async function(e,t){const n=`${JSON.stringify(t,null,2)}\n`;try{await e.updateFileContent(Oc,n)}catch{try{await e.createFolder(".punica")}catch{}try{await e.createFolder(_c)}catch{}await e.createFileWithContent(Oc,n)}}(r,i),{key:n,count:Object.keys(i).length}}}class Dc{name="context.recall";async execute(e,t){const n=So(),r=await Lc(n),i=e?.key?String(e.key).trim():"";if(i){const e=Object.prototype.hasOwnProperty.call(r,i);return{key:i,value:e?r[i]:null,found:e}}const s=Object.keys(r),o={};for(const e of s.slice(0,200))o[e]=r[e];return{facts:o,count:s.length,truncated:s.length>200}}}class Fc{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 qc{name="terminals.send";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");const r=e.text??"";n.write(e.id,/[\r\n]$/.test(r)?r:`${r}\n`)}}class Bc{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)}}const Uc={name:"ECDSA",namedCurve:"P-256"},Vc={name:"ECDSA",hash:"SHA-256"};function Wc(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("[Runtime.packageSigner] No WebCrypto available; cannot sign or verify a package.");return e.subtle}function Kc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t.padEnd(4*Math.ceil(t.length/4),"=")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}async function Gc(e){const t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y}),n=await Wc().digest("SHA-256",(new TextEncoder).encode(t));return function(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(new Uint8Array(n))}async function Yc(e,t){try{if("ES256"!==t?.alg)return!1;const n=await Wc().importKey("jwk",t.publicKeyJwk,Uc,!1,["verify"]);return await Gc(t.publicKeyJwk)===t.keyId&&await Wc().verify(Vc,n,Kc(t.signature),function(e){const t=(new TextEncoder).encode("PUNICA-PACKAGE-v1\0"),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}(e))}catch{return!1}}const zc=Ti({label:"Runtime.packageSigner",noProviderMessage:"[Runtime.packageSigner] No package signer registered. A host installs one with punica.runtime.setPackageSigner() during bootstrap; without it a package cannot be signed, and the substrate does not substitute a key nobody can verify against."});function Jc(){return zc.get()}function Hc(){return zc.hasProvider()}function Qc(){return new Vs(Us.CAPABILITY_PROVIDER_MISSING,"No package signer is installed on this host, so nothing can be signed here.",{capability:"signing.sign",reason:"no-package-signer"})}class Zc{name="signing.sign";async execute(e,t){if(!Hc())throw Qc();return Jc().sign(Kc(e.bytes))}}class Xc{name="signing.verify";async execute(e,t){return{valid:await Yc(Kc(e.bytes),e.signature)}}}class el{name="signing.publicKey";async execute(e,t){if(!Hc())throw Qc();return Jc().publicKey()}}class tl{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 nl{name="flow.runSubflow";async execute(e,t){const n=globalThis.punica,r=n?.flow?.engine?.manager;if(!r||"function"!=typeof r.runSubflow)throw new Error("[FlowRunSubflowProvider] Flow engine is not available — substrate bootstrap incomplete");const i={...e,workspaceId:e.workspaceId??t.workspaceId,parentTraceId:e.parentTraceId??t.trace?.traceId};return r.runSubflow(i)}}const rl="capability.catalog";class il{name=rl;async execute(e,t){const n=e??{},r=oo.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>sl(e,n));return{capabilities:r,count:r.length}}}function sl(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=ol(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=ol(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=ol(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 ol(e){return Array.isArray(e)?e:[e]}const al=["examples","$comment","default","title"];function cl(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 ll=["properties","patternProperties","definitions","$defs"];function ul(e){if(Array.isArray(e))return e.map(e=>ul(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!al.includes(n))if("description"!==n||"string"!=typeof r){if(ll.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=ul(n);t[n]=e;continue}t[n]=ul(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const dl="capability.schemaExport";class pl{name=dl;async execute(e,t){const n=e??{},r=n.filter??{},i=oo.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>sl(e,r)),s=n.mode??"full",o=i.map(e=>{const t=function(e){const t=e.definition,n={id:t.id,origin:e.origin,version:t.version,title:t.title};void 0!==t.description&&(n.description=t.description);void 0!==t.inputs?.schema&&(n.inputSchema=t.inputs.schema);void 0!==t.outputs?.schema&&(n.outputSchema=t.outputs.schema);t.policy&&(n.policy={risk:t.policy.risk,approval:t.policy.approval});t.tags&&t.tags.length>0&&(n.tags=[...t.tags]);Yt(t)&&(n.agentVisibility="hub-only");const r=t.action;Array.isArray(r)&&r.length>0&&(n.action=r.map(String));t.sideEffects&&t.sideEffects.length>0&&(n.sideEffects=[...t.sideEffects]);const i=t.requires;i&&i.length>0&&(n.requires=[...i]);t.deprecated&&(n.deprecated={...t.deprecated});if(e.metadata){const t={};for(const[n,r]of Object.entries(e.metadata))void 0!==r&&(t[n]=r);Object.keys(t).length>0&&(n.metadata=t)}return n}(e);return"ai-tools"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=cl(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=ul(e.inputSchema));e.policy&&(t.policy={...e.policy});e.agentVisibility&&(t.agentVisibility=e.agentVisibility);e.action&&e.action.length>0&&(t.action=[...e.action]);return t}(t):"summary"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=cl(e.description??e.title,100);n&&(t.description=n);return t}(t):t});return{schemaVersion:"v1",generatedAt:Date.now(),capabilities:o,count:o.length}}}const fl={"ı":"i","ø":"o","đ":"d","ł":"l","ß":"ss","æ":"ae","œ":"oe"};function hl(e){return e.length<4||!e.endsWith("s")||/(?:ss|us|is)$/.test(e)?e:e.slice(0,-1)}function ml(e){return function(e){let t="";for(const n of e)t+=fl[n]??n;return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}(e.toLowerCase()).split(/[^a-z0-9]+/).filter(e=>e.length>=2).map(hl)}function gl(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function yl(e,t){if(0===e.size||0===t.size)return 0;let n=0,r=0,i=0;for(const[,t]of e)r+=t*t;for(const[,e]of t)i+=e*e;for(const[r,i]of e){const e=t.get(r);void 0!==e&&(n+=i*e)}const s=Math.sqrt(r)*Math.sqrt(i);return 0===s?0:n/s}function wl(e,t){const n=gl(ml(e));return t.map(e=>({...e,score:yl(n,gl(ml(e.text)))}))}const vl={tr:{roots:{ac:"open",kapat:"close",kaydet:"save",sil:"delete remove",olustur:"create new build",yarat:"create new",ekle:"add insert",oku:"read",yaz:"write",bul:"find search",ara:"search find",degis:"change replace modify diff",liste:"list",goster:"show display view",calis:"run execute working",calisiy:"running active",calisan:"running active",basla:"start begin run",durdur:"stop",dur:"stop",durum:"status state",yukle:"upload install load",indir:"download",kur:"install setup",gonder:"push send",cek:"pull fetch",birlestir:"merge",adlandir:"rename name",tasi:"move",kopyala:"copy",yapistir:"paste",kes:"cut",bicim:"format",ozet:"summary summarize",sec:"select",secim:"selection select",isaretle:"mark toggle",bagla:"connect",baglan:"connect",sorgu:"query",derle:"build compile",ayikla:"debug",guncelle:"update upgrade",kaldir:"remove uninstall",yenile:"refresh reload",gec:"switch",koy:"set place",koyu:"dark",calistir:"run execute",onizle:"preview",dene:"try test",onar:"fix repair",duzelt:"fix format",bekle:"wait",iptal:"cancel abort",onayla:"confirm approve",paylas:"share",disari:"export",ice:"import",dosya:"file",klasor:"folder directory",dizin:"directory folder",proje:"project workspace",depo:"repository repo",depolama:"storage",dal:"branch",islem:"commit operation",satir:"line",sutun:"column",kesme:"breakpoint break",nokta:"point",terminal:"terminal shell",ucbirim:"terminal shell",kabuk:"shell",komut:"command",ayar:"settings preferences configuration",secenek:"option",tercih:"preferences",konteyner:"container",kapsayici:"container",imaj:"image",gunluk:"log",kova:"bucket",ortam:"environment",sanal:"virtual",paket:"package pack",betik:"script",gorev:"task job",veritaban:"database",tablo:"table",gezgin:"explorer browser",duzenleyici:"editor",editor:"editor",pencere:"window panel",sekme:"tab",panel:"panel",kenar:"sidebar side",icerik:"content contents",icerig:"content contents",metin:"text",yol:"path",uzanti:"extension",islev:"function",fonksiyon:"function",sinif:"class",degisken:"variable",hata:"error bug debug",uyari:"warning",cikti:"output",girdi:"input",tema:"theme",boyut:"size",sunucu:"server",uzak:"remote",yerel:"local",yeni:"new",konsol:"console terminal",taban:"base",alan:"area workspace field",imlec:"cursor",resim:"image",anahtar:"key",gizli:"secret hidden",sifre:"password",belge:"document",sayfa:"page",baglanti:"link connection",kod:"code",surec:"process",bellek:"memory",klavye:"keyboard",kisayol:"shortcut",yorum:"comment",isim:"name",tur:"type",deger:"value",yigin:"stack",onbellek:"cache",yedek:"backup",gunce:"log",veri:"data",set:"set dataset",model:"model",aktif:"active current",indeks:"index",anlamsal:"semantic",profil:"profile",nesne:"object",bilgi:"knowledge information",kesf:"discover collect list",politika:"policy rule",kural:"rule policy",onay:"approval approve",bekleyen:"pending waiting",kanit:"evidence",disa:"export",aktar:"export transfer",soy:"lineage",grafik:"graph",agac:"tree graph",hiperparametre:"hyperparameter sweep",tara:"sweep scan",kursl:"course",kursu:"course",dugum:"node",katalog:"catalog list",kosu:"run",hucre:"cell",defter:"notebook",deney:"experiment",motor:"engine",izi:"trace",izle:"watch follow",gecerli:"apply effective valid",test:"test",kayit:"record log registry",kuyruk:"queue",dagit:"deploy",boru:"pipeline",asama:"stage step",kapi:"gate",surum:"version"},stopWords:["bu","su","bir","ve","veya","ile","icin","gibi","kadar","daha","cok","az","olan","olarak","her","hep","tum","butun","ben","sen","biz","siz","benim","senin","bizim","kendi","mi","mu","de","da","ki","ama","fakat","ancak","yine","yeniden","hangi","ne","nasil","neden","nicin","nerede","nereye","nereden","neler","kim","yok","degil","evet","hayir","sey","cunku","sonra","once","simdi","artik","bile","ise","eger","hem"]}},bl=new Map,Il=new Set;for(const e of Object.values(vl)){for(const[t,n]of Object.entries(e.roots)){const e=ml(t).join("");e.length>0&&bl.set(e,ml(n))}for(const t of e.stopWords){const e=ml(t).join("");e.length>0&&Il.add(e)}}const kl=[...bl.keys()].sort((e,t)=>t.length-e.length);function El(e){let t=0;for(const n of e)n.score>t&&(t=n.score);return t}const Sl=new WeakMap;async function Al(e,t,n){const r=wl(e,t);let i={scores:r,score:El(r),path:"text-similarity"};const s=ml(e),o=function(e,t){const n=[];for(const r of e){if(Il.has(r))continue;if(t?.has(r)){n.push(r);continue}const e=kl.find(e=>r.startsWith(e));e?n.push(r,...bl.get(e).filter(e=>e!==r)):n.push(r)}return n}(s,function(e){let t=Sl.get(e);if(!t){t=new Set;for(const n of e)for(const e of ml(n.text))t.add(e);Sl.set(e,t)}return t}(t)),a=o.join(" ");if(a.length>0&&o.join("\0")!==s.join("\0")){const e=wl(a,t);i={scores:e,score:El(e),path:"lexicon",text:a}}return i.score,"text-similarity"!==(c=i).path&&Hi("llm.normalizeIntent",{intent:e,path:c.path,normalizedAs:c.text,topScore:c.score}),{scores:c.scores,path:c.path,...void 0===c.text?{}:{normalizedAs:c.text}};var c}async function xl(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return{recommendations:[],path:"text-similarity"};const i=oo.listCapabilities();if(0===i.length)return{recommendations:[],path:"text-similarity"};const s=i.map(e=>({id:e.definition.id,description:e.definition.description,text:Cl(e.definition)}));let o,a,c;{const e=await Al(r,s);o=e.path,a=e.normalizedAs,c=e.scores}const l=c.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 Hi("llm.recommendIntent",{intent:r,limit:n,path:o,normalizedAs:a,topIds:l.map(e=>e.id),topScore:l[0]?.score??0}),{recommendations:l,path:o,...void 0===a?{}:{normalizedAs:a}}}function Cl(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(" ")}const Tl="capability.recommend";class Pl{name=Tl;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await xl(r,"number"==typeof n.limit?{limit:n.limit}:void 0);return{recommendations:i.recommendations.map(e=>({id:e.id,score:e.score,description:e.description})),path:i.path,count:i.recommendations.length,...void 0===i.normalizedAs?{}:{normalizedAs:i.normalizedAs}}}}const Nl="capability.describe",Ml="capability.search";function Rl(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class $l{name=Nl;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new pl).execute({mode:"ai-tools"},t)).capabilities.filter(e=>r.has(String(e.id))),s=new Set(i.map(e=>String(e.id)));return{tools:i,missing:n.filter(e=>!s.has(e))}}}class _l{name=Ml;async execute(e,t){const n=e??{},r=String(n.query??"").trim(),i=Math.min(Math.max(1,Math.floor(n.limit??16)),50);if(!r)return{results:[],count:0};const s=oo.listCapabilities().filter(e=>!(Yt(e.definition)||zt(e.definition)&&!Jt())),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await async function(e,t){return(await xl(e,t)).recommendations}(r,{limit:i});e.reduce((e,t)=>"number"==typeof t.score&&t.score>e?t.score:e,0)>1e-9&&(a=e.map(e=>String(e.id)).filter(e=>o.has(e)))}catch{}if(0===a.length){const e=r.toLowerCase().split(/\s+/).filter(Boolean);a=s.filter(t=>{const n=`${t.definition.id} ${t.definition.title??""} ${t.definition.description??""}`.toLowerCase();return e.some(e=>n.includes(e))}).map(e=>String(e.definition.id))}const c=a.slice(0,i).map(e=>{const t=o.get(e);return{id:e,description:cl(t?.description??t?.title??e,100),category:Rl(e)}});return{results:c,count:c.length}}}function Ol(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Ll(e,t){return{name:e,title:t.title,description:t.description,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 jl{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Ol().create(n)}}}class Dl{name="ai.session.list";async execute(e,t){const n=Ol().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Fl{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Ol().get(n)}}}class ql{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Ol().rename(String(n?.sessionId??""),String(n?.title??""))}}}class Bl{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Ol().archive(String(n?.sessionId??""),n?.archived)}}}class Ul{name="ai.session.delete";async execute(e,t){return{ok:Ol().delete(String(e?.sessionId??""))}}}const Vl={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"}]}},Wl={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"}]}},Kl=new Set(["low","medium","high"]),Gl={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&Kl.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"}]:[]}},Yl=new Set(["none","plan","step"]),zl={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Yl.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 Jl={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"}]:[]}},Hl=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Ql={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Hl.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"}]}},Zl=new Set(["low","medium","high"]),Xl=["write","delete","remove","modify","destroy"],eu={id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Zl.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&&Xl.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 tu={id:"policy-key-on-sensitive",severity:"error",check(e){const t=function(e){const t=e.inputs;if(t&&"object"==typeof t)return t.schema}(e);if(!t||"object"!=typeof t)return[];const n=d(t,"policyKey");if(0===n.length)return[];const r=new Set(d(t,"sensitive").map(e=>e.join("."))),i=[];for(const t of n){const n=t.join(".");r.has(n)&&i.push({ruleId:"policy-key-on-sensitive",severity:"error",message:`Capability "${e.id}" marks input field "${n}" as both sensitive and policyKey — the binding is computed from the redacted input, so this field cannot narrow an approval; remove one of the two annotations`,capabilityId:String(e.id),path:`inputs.schema.${n}`,code:"CAP_POLICY_KEY_ON_SENSITIVE"})}return i}},nu=new Set(ka);const ru={id:"subject-declaration",severity:"error",check(e){const t=[],n=String(e.id);for(const r of function(e){const t=[];for(const n of["inputs","outputs"]){const r=e[n];if(!r||"object"!=typeof r)continue;const i=r.schema;i&&"object"==typeof i&&t.push({prefix:`${n}.schema`,schema:i})}return t}(e)){const e=p(r.schema,"subject"),i=d(r.schema,"subjectDigest");if(0===e.length&&0===i.length)continue;const s=new Set(d(r.schema,"sensitive").map(e=>e.join(".")));let o=0;for(const i of e){const e=i.path.join("."),a=`${r.prefix}.${e}`;if("string"!=typeof i.value||""===i.value.trim()){t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" marks field "${e}" as a subject without naming a kind — the audit record labels every subject, so this field is dropped instead of recorded; set subject to one of ${ka.join(", ")}`,capabilityId:n,path:a,code:"CAP_SUBJECT_WITHOUT_KIND"});continue}const c=i.value.trim();nu.has(c)?s.has(e)?t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" marks field "${e}" as both sensitive and subject — subjects are read from the redacted payload, so this field's value is always [REDACTED] and no subject is recorded; remove one of the two annotations`,capabilityId:n,path:a,code:"CAP_SUBJECT_ON_SENSITIVE"}):o+=1:t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" declares field "${e}" as subject kind "${c}", which is not one of ${ka.join(", ")} — the vocabulary is closed so a reader can compare two evidence packages`,capabilityId:n,path:a,code:"CAP_SUBJECT_UNKNOWN_KIND"})}i.length>0&&0===o&&t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" declares subjectDigest in ${r.prefix} with no usable subject beside it — a digest is recorded only as a property of a subject, so this one is dropped`,capabilityId:n,path:`${r.prefix}.${i[0].join(".")}`,code:"CAP_SUBJECT_DIGEST_ORPHAN"})}return t}},iu=[Vl,Wl,Gl,zl,Jl,Ql,eu,tu,ru,{id:"action-declaration",severity:"warning",check(e){const t=[],n=e?.id??"(unknown)",r=e?.action;if(void 0!==r&&!Array.isArray(r))return t.push({ruleId:"action-declaration",severity:"error",message:`Capability "${n}" declares action as ${typeof r} — it must be a list, e.g. action: [file.read]`,capabilityId:n,path:"action",code:"CAP_ACTION_NOT_A_LIST"}),t;const i=Array.isArray(r)?r:[];for(let e=0;e<i.length;e++){const r=i[e];De(r)||t.push({ruleId:"action-declaration",severity:"error",message:`Capability "${n}" declares action ${JSON.stringify(r)}, which is not one of ${Le.join(", ")} — a policy rule written against it matches nothing`,capabilityId:n,path:`action.${e}`,code:"CAP_ACTION_UNKNOWN"})}const s=Array.isArray(e?.sideEffects)?e.sideEffects:[];return 0===i.length&&s.length>0&&t.push({ruleId:"action-declaration",severity:"warning",message:`Capability "${n}" declares side effects (${s.join(", ")}) and no action — no policy rule addressing an action can reach it, so a rule denying that action leaves this id open`,capabilityId:n,path:"action",code:"CAP_ACTION_UNDECLARED"}),t}}];const su=new class{#Re=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#Re.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.#Re.set(e.id,e)}unregister(e){return this.#Re.delete(e)}list(){return Array.from(this.#Re.keys())}reset(){this.#Re.clear();for(const e of iu)this.#Re.set(e.id,e)}},ou="capability.lint";class au{name=ou;async execute(e,t){const n=e??{},r=oo.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=su.lintAll(r).map(e=>({id:e.id,ok:e.ok,issues:e.issues}));return{results:i,ok:i.every(e=>e.ok),count:i.length}}}const cu={type:"object"};function lu(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function uu(e){let t;return t=function(e){if(e instanceof Vs)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:lu(e),{content:[{type:"text",text:t}],isError:!0}}const du="capability.serveList",pu="capability.serveCall",fu=new Set([du,pu]);class hu{name=du;async execute(e,t){const n=(e??{}).filter??{},r=oo.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!fu.has(e.definition.id)).filter(e=>sl(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??cu,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class mu{name=pu;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||fu.has(r)||!oo.getCapability(r))return uu(new Error(`unknown tool: ${r||"(empty)"}`));try{const e=t.trace?.traceId?{...t,trace:{...t.trace,...t.invocationId?{parentSpanId:t.invocationId}:{}}}:t;return function(e){return{content:[{type:"text",text:lu(e)}],isError:!1}}(await qa.call(r,n.arguments??{},e))}catch(e){return uu(e)}}}const gu="shell.revealView",yu="shell.hideView",wu="shell.listViews",vu="shell.toggleView",bu="shell.toggleSlot",Iu="shell.moveView";function ku(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:gu});return e}function Eu(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 Su{name=gu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=ku();if(!i.getPlacement(n))throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:gu,viewId:n});return await i.reveal(n,Eu(t),{focus:r}),{viewId:n,revealed:!0}}}class Au{name=yu;async execute(e,t){const{viewId:n}=e??{};return ku().hide(n,Eu(t)),{viewId:n,hidden:!0}}}class xu{name=wu;async execute(e,t){return{views:ku().listViews()}}}class Cu{name=vu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=ku();if(!i.getPlacement(n))throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:vu,viewId:n});return"visible"===i.getState(n)?(i.hide(n,Eu(t)),{viewId:n,visible:!1}):(await i.reveal(n,Eu(t),{focus:r}),{viewId:n,visible:!0})}}const Tu=new Map;class Pu{name=bu;async execute(e,t){const{slot:n,focus:r}=e??{},i=ku(),s=function(){const e=globalThis.punica?.shell?.Layout?.manager;return e&&"function"==typeof e.setSlotCollapsed?e:void 0}();if(s?.isSlotCollapsed?.(n)){s.setSlotCollapsed?.(n,!1);const e=i.getVisibleView(n);if(e)return{slot:n,visible:!0,viewId:e}}else{const e=i.getVisibleView(n);if(e)return Tu.set(n,e),s?.setSlotCollapsed?.(n,!0),s?.isSlotCollapsed?.(n)||i.hide(e,Eu(t)),{slot:n,visible:!1,viewId:e}}const o=Tu.get(n);let a=o&&i.getPlacement(o)?o:void 0;return a||(a=i.listViews().find(e=>e.slot===n)?.viewId),a?(await i.reveal(a,Eu(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}class Nu{name=Iu;async execute(e,t){const{viewId:n,slot:r}=e??{},i=ku(),s=i.getPlacement(n);if(!s)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover movable views.`,{capability:Iu,viewId:n});const o=s.allowedSlots??[];if(!o.includes(r))throw new Vs(Us.CAPABILITY_INPUT_INVALID,`View "${n}" cannot be moved to slot "${r}". Allowed slots: ${o.length?o.join(", "):"(none)"}.`,{capability:Iu,viewId:n,slot:r});return await i.moveView(n,r,Eu(t)),{viewId:n,slot:r,moved:!0}}}function Mu(e){try{Ws.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function Ru(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 $u(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 _u(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=oo.getCapability(e.id);return t?void $u(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=oo.listCapabilities(n),i=r.map(Ru);if(console.log("[Punica] Trinity capability catalog",{count:i.length}),i.length>0){if(console.table(i),e?.verbose){console.log("[Punica] Full definitions (same fields as .punica/capabilities.yaml):");for(const e of r)$u(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Ou(e){return _u({...e,verbose:!0})}function Lu(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 ju(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,i=t.policy?.risk??"—",s=function(e){const t=e.indexOf("\n");return(-1===t?e:e.slice(0,t)).trim()}(t.description??t.title??"")||"—";return`| ${n} | ${r} | ${i} | ${o=s,o.replace(/\|/g,"\\|")} |`;var o}function Du(e){return JSON.stringify(e,null,2)}const Fu=new class{#$e=new Map;get(e){return this.#$e.get(e)}list(){return[...this.#$e.values()]}register(e,t){for(const e of t)this.#$e.set(e.definition.id,e),this.#_e(e.definition.id)}unregister(e){for(const[t,n]of this.#$e)n.serverId===e&&(this.#$e.delete(t),this.#Oe(t))}hasServer(e){for(const t of this.#$e.values())if(t.serverId===e)return!0;return!1}#_e(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{}}#Oe(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{}}},qu=16384,Bu="runtime:mcp:client";function Uu(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Vu(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 Vu(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=>Vu(e,t+1));return e.length>50&&n.push(`…[${e.length-50} more items truncated]`),n}if(e&&"object"==typeof e){if(t>=12)return"…[truncated]";const n={};for(const[r,i]of Object.entries(e))n[r]=Vu(i,t+1);return n}return e}function Wu(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=qu)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Vu(e,0),null,2)??"null";if(r.length<=qu)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,qu)+"\n… [truncated]",bytes:n,truncated:!0}}function Ku(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}function Gu(e,t){let n=e;const r=()=>(n===e&&(n={...e}),n);for(const e of t){const t=e.split(".").filter(e=>e.length>0);if(0===t.length)continue;let n=r();for(let e=0;e<t.length&&n;e++){const r=t[e],i="*"===r?n.items:n.properties?.[r];if(!i||"object"!=typeof i){n=void 0;break}const s={...i};"*"===r?n.items=s:n.properties={...n.properties,[r]:s},n=s}n&&(n.policyKey=!0)}return n}const Yu=new class{#Le=new Map;async connect(e){if(this.#Le.has(e.id))return this.#Le.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return td}),r=e.toolOverrides??await t(e.id),i="stdio"===e.kind?await n(e.env):e.env,s="streamable-http"===e.kind||"sse"===e.kind?await n(e.headers):e.headers,o={...e,env:i,headers:s,toolOverrides:r&&Object.keys(r).length?r:void 0},a=function(e,t){const n=(t,n,r)=>({direction:"outbound",serverId:e.serverId,serverName:e.serverName,transport:e.transport,method:n,toolName:Ku(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Uu(),s=Wu(r??{});Ei({name:"mcp.request",source:Bu,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:Zt().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Uu(),s=Date.now(),o=Wu(r??{});Ei({name:"mcp.request",source:Bu,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:Zt().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=Wu(o??null);return Ei({name:"mcp.response",source:Bu,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:Zt().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw Ei({name:"mcp.response",source:Bu,correlationId:i,kind:"error",payload:{...n(i,e,r),kind:"request",isError:!0,durationMs:Date.now()-s,errorMessage:t instanceof Error?t.message:String(t)}}),t}}}}({serverId:o.id,serverName:o.name,transport:o.kind},await async function(e){if("stdio"===e.kind){if(!e.command)throw new Error(`MCP server "${e.id}": stdio transport requires 'command'`);const{StdioTransport:t}=await Promise.resolve().then(function(){return bv});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 Iv});return new t(e.url,e.headers??{})}throw new Error(`MCP server "${e.id}": unknown transport kind "${e.kind}"`)}(o));await a.connect(),await a.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"punica-editor",version:"1.0.0"}}),a.notify("notifications/initialized",{});const c=await a.request("tools/list",{}),l=c?.tools??[],u=l.map(e=>{const t=o.toolOverrides?.[e.name]??{},n=function(e,t,n={}){const r=t._meta?.punica??{},i={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},s=n.policy?.keyPaths??r.policy?.keyPaths??[],o={timeoutMs:n.executionDefaults?.timeoutMs??r.executionDefaults?.timeoutMs??3e4,idempotency:n.executionDefaults?.idempotency??r.executionDefaults?.idempotency??"none"},a=["mcp",e],c=r.tags??[],l=n.tags??[],u=[...new Set([...a,...c,...l])],d=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:Gu(t.inputSchema??{type:"object"},s)},outputs:{schema:{type:"object",properties:{content:{type:"array",items:{type:"object",properties:{type:{type:"string"},text:{type:"string"}}}},isError:{type:"boolean"}}},kind:"direct"},policy:i,sideEffects:d,executionDefaults:o,tags:u}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});Fu.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(),Fu.unregister(e.id),this.#Le.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#Le.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#Le.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#Le.values()].map(e=>e.handle)}listTools(e){return e?this.#Le.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#Le.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},zu=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/,Ju=/^\$\{secret\.([A-Za-z0-9_.-]+)\}$/;async function Hu(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 Qu(e){if(!e)return{};const t={},n=function(){const e=globalThis.process,t=e?.env;return t&&"object"==typeof t?t:void 0}(),r=void 0!==n;for(const[i,s]of Object.entries(e)){if("string"!=typeof s){t[i]=s;continue}const e=s.match(Ju);if(e){const n=e[1],r=await Hu(n);void 0!==r?t[i]=r:console.warn(`[Punica] MCP secret placeholder \${secret.${n}} — not found in Secret Manager`);continue}const o=s.match(zu);if(o){const e=o[1];if(!r){console.warn(`[Punica] MCP env placeholder \${env.${e}} skipped — not in Node/Electron`);continue}const s=n[e];void 0!==s?t[i]=s:console.warn(`[Punica] MCP env placeholder \${env.${e}} — variable unset`)}else t[i]=s}return t}async function Zu(e){try{const t=globalThis,n=t.punica?.runtime?.fs,r=n?.readFile,i=n?.exists;if(!r)return{};if(i){const t=`.punica/mcp/${e}.yaml`;if(!await i(t))return{}}let s;try{s=await r(`.punica/mcp/${e}.yaml`,{encoding:"utf8"})}catch{return{}}if("string"!=typeof s||""===s.trim())return{};const{parse:o}=await Promise.resolve().then(function(){return rm}),a=o(s);return a?.tools&&"object"==typeof a.tools?a.tools:{}}catch(t){return console.warn(`[Punica] MCP overrides for "${e}" failed:`,t?.message??t),{}}}async function Xu(){try{const e=globalThis,t=e.punica?.runtime?.fs,n=t?.readFile,r=t?.exists;if(!n)return[];if(r){if(!await r(".punica/mcp.yaml"))return[]}let i;try{i=await n(".punica/mcp.yaml",{encoding:"utf8"})}catch{return[]}const{parseYamlMcpConfig:s}=await Promise.resolve().then(function(){return kv}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await Zu(e.id),n="stdio"===e.kind?await Qu(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?await Qu(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 ed(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 td=Object.freeze({__proto__:null,loadMcpConfig:Xu,loadServerOverrides:Zu,parseStaticConfig:ed,resolveEnvPlaceholders:Qu});class nd{name=Gn.RUNTIME.MCP;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.RUNTIME.FS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){this.#je=e.BOOTSTRAPPING;const n=await Xu();this.#De(n),this.#je=e.BOOTSTRAPPED}async#De(e){for(const t of e)try{await Yu.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#je=e.STARTING,this.#je=e.STARTED,console.log(`[Punica] MCP module started — ${Fu.list().length} capability(ies) active`)}}const rd=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const id={get capabilities(){return Eo.hasProvider()?Eo.get().capabilities:void 0},get cwd(){return Eo.hasProvider()?Eo.get().cwd:void 0},hasProvider:()=>Eo.hasProvider(),getFileTree:()=>Eo.get().getFileTree(),readFile:e=>Eo.get().readFile(e),get readBytes(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.readBytes?e.readBytes.bind(e):void 0},get writeBytes(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.writeBytes?e.writeBytes.bind(e):void 0},updateFileContent:(e,t)=>Eo.get().updateFileContent(e,t),createFolder:e=>Eo.get().createFolder(e),deleteFolder:e=>Eo.get().deleteFolder(e),deleteFile:(e,t)=>Eo.get().deleteFile(e,t),renameFile:(e,t)=>Eo.get().renameFile(e,t),renameFolder:(e,t)=>Eo.get().renameFolder(e,t),get revealInOS(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.revealInOS?e.revealInOS.bind(e):void 0},createFileWithContent:(e,t)=>Eo.get().createFileWithContent(e,t),get list(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.list?e.list.bind(e):void 0},get stat(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.stat?e.stat.bind(e):void 0},get mkdir(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.mkdir?e.mkdir.bind(e):void 0},get copy(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.copy?e.copy.bind(e):void 0},get exists(){if(!Eo.hasProvider())return;const e=Eo.get();return"function"==typeof e.exists?e.exists.bind(e):void 0},__punicaWrappedFsFacade:!0},sd=function(e){return _i(e)?e:(void 0!==e&&$i(e),{__punicaWrappedSearchFacade:!0,query:e=>Ri.get().query(e),startIndex:e=>{const t=Ri.get();return t.startIndex?t.startIndex(e):Promise.resolve()}})}(rd?.search),od=function(e){return Ki(e)?e:(void 0!==e&&Wi(e),{__punicaWrappedVcsFacade:!0,status:()=>Vi.get().status(),branches:()=>Vi.get().branches(),logs:e=>Vi.get().logs(e),init:e=>Vi.get().init(e),clone:e=>Vi.get().clone(e),commit:e=>Vi.get().commit(e),stage:e=>Vi.get().stage(e),unstage:e=>Vi.get().unstage(e),discard:e=>Vi.get().discard(e),reset:e=>Vi.get().reset(e),switchBranch:e=>Vi.get().switchBranch(e),createBranch:(e,t)=>Vi.get().createBranch(e,t),fetch:e=>Vi.get().fetch(e),pull:e=>Vi.get().pull(e),push:e=>Vi.get().push(e)})}(rd?.vcs),ad=function(e){return qi(e)?e:(void 0!==e&&Fi(e),{__punicaWrappedTerminalFacade:!0,create:e=>Di.get().create(e),write:(e,t)=>Di.get().write(e,t),resize:(e,t,n)=>Di.get().resize(e,t,n),close:e=>Di.get().close(e),onData:(e,t)=>Di.get().onData(e,t),onExit:(e,t)=>Di.get().onExit(e,t),list:()=>Di.get().list()})}(rd?.terminals),cd=function(e){return e||{start:e=>Ui().start(e),send:(e,t)=>Ui().send(e,t),onMessage:(e,t)=>Ui().onMessage(e,t),onStderr:(e,t)=>Ui().onStderr(e,t),onExit:(e,t)=>Ui().onExit(e,t),stop:e=>Ui().stop(e),list:()=>Ui().list()}}(rd?.debug),ld=function(e){return ji(e)?e:(void 0!==e&&Li(e),{__punicaWrappedTasksFacade:!0,run:e=>Oi.get().run(e)})}(rd?.tasks),ud=function(e){return Ji(e)?e:(void 0!==e&&zi(e),{getCurrent:()=>Gi.get().getCurrent(),list:()=>Gi.get().list(),open:e=>Gi.get().open(e),setEnvironment:(e,t)=>Gi.get().setEnvironment(e,t),onDidChange:e=>Gi.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0})}(rd?.workspace),dd=function(e){return Mi(e)?e:(void 0!==e&&Ni(e),{__punicaWrappedResourcesFacade:!0,list:e=>Pi.get().list(e),get:e=>Pi.get().get(e),register:e=>Pi.get().register(e),unregister:e=>Pi.get().unregister(e),onDidChange:e=>Pi.get().onDidChange(e)})}(rd?.resources),pd=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&cs(e),t)return e;async function n(e,t){return"local"!==await Xi(e,t)}async function r(e,t,n){!function(e,t){(ss&&ss!==e||os&&t&&os!==t)&&se.publishEvent({name:"llm.providerChanged",envelope:{id:se.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:ss,newProviderId:e,previousEndpoint:os,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),ss=e,t&&(os=t)}(t,n);const r=await i(),s=e?.correlationId??se.createCorrelationId(),o=vt.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!o.allowed)throw o.requiresApproval&&vt.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:s}),se.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:se.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(o.reason??"[Policy] Remote LLM request denied");return se.publishEvent({name:"llm.remoteRequestSent",envelope:{id:se.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}}async function i(){try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch(e){return void console.error("[LLM Facade] Error accessing punica.runtime.workspace:",e?.message??e)}}async function s(e){const t=ts();if(!t)return{cache:void 0,cacheKey:void 0,cached:void 0};try{const n=await i(),r=await async function(e){try{const t=globalThis.crypto?.subtle;if(!t)return;const n=(new TextEncoder).encode(Me(function(e){return{workspaceId:e.workspaceId??null,userId:e.userId??null,messages:e.messages??null,profile:e.profile??null,temperature:e.temperature??null,maxTokens:e.maxTokens??null,route:e.route??null,providerId:e.providerId??null,responseFormat:e.responseFormat??null,modelId:e.modelId??null,modelIds:e.modelIds??null,tools:e.tools??null,toolChoice:e.toolChoice??null,reasoning:e.reasoning??null}}(e))),r=await t.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{return}}(function(e,t){return{workspaceId:t,userId:ge()?.email,messages:e.messages,profile:e.profile,temperature:e.temperature,maxTokens:e.maxTokens,route:e.route,providerId:e.providerId,responseFormat:e.responseFormat,modelId:e.modelId,modelIds:e.modelIds,tools:e.tools,toolChoice:e.toolChoice,reasoning:e.reasoning}}(e,n));return r?!0===e?.skipCache?{cache:t,cacheKey:r,cached:void 0}:{cache:t,cacheKey:r,cached:await t.get(r)??void 0}:{cache:void 0,cacheKey:void 0,cached:void 0}}catch(e){return console.warn("[LLM Facade] Response cache lookup failed; calling the model:",e?.message??e),{cache:void 0,cacheKey:void 0,cached:void 0}}}function o(e,t,n){if(e&&t&&function(e){return!!e&&("string"==typeof e.text&&e.text.trim().length>0||(e.toolCalls?.length??0)>0)}(n))try{const r=e.set(t,{response:n,storedAtMs:Date.now()});r&&"function"==typeof r.catch&&r.catch(()=>{})}catch{}}const a={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",a=e?.providerId??"remote",c=as(),l=!0===e?.[rs],{cache:u,cacheKey:d,cached:p}=await s(e);if(!l&&("remote"===t||await n(e,c))){const t=e?.endpoint,n=await r(e,a,t);if(p)return ns(p);const i=await c.chat(n);return o(u,d,i),i}const f=p?ns(p):await c.chat(e);if(!f)throw new Error("[LLM Facade] No response returned from LLM provider");const h=f?.provider;if(!l&&Qi(h)){const n=h&&"remote"!==h?h:a,r=await i(),s=e?.correlationId??se.createCorrelationId(),o=vt.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw se.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:se.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"error"},payload:{providerId:n,route:t,workspaceId:r,messageCount:e.messages?.length??0,reason:p?"Policy denies this provider; a cached answer is refused for the same reason a fresh one would be":"Policy gate bypassed via auto route",...p?{cacheHit:!0}:{}}}),o.requiresApproval&&vt.requestApproval({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r,correlationId:s}),new Error(o.reason??"[Policy] Remote LLM request denied (auto route bypass detected)");p||se.publishEvent({name:"llm.remoteRequestSent",envelope:{id:se.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:n,workspaceId:r,messageCount:e.messages?.length??0,retroactive:!0,route:t}})}return p||o(u,d,f),f},chatStream:async function*(e){if(e?.signal?.aborted)return;const t=e?.route??"auto",i=e?.providerId??"remote",a=as();let c=e;if(!(!0===e?.[rs])&&("remote"===t||await n(e,a))){const t=e?.endpoint;c=await r(e,i,t)}const{cache:l,cacheKey:u,cached:d}=await s(c);if(d){const e=ns(d);if(c?.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})}if("function"!=typeof a.chatStream){const e=await a.chat(c);if(!e)throw new Error("[LLM Facade] No response returned from LLM provider");if(o(l,u,e),c?.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 a.chatStream(c)){if(c?.signal?.aborted)return;"done"===e?.type&&o(l,u,e.response),yield e}},__punicaWrappedLlmFacade:!0};return a.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?.())}}}(),a}(rd?.llm),fd=function(e){if(e)return e;const t=ds(),n=new ps(t),r=new bs(t,n);t.registerLanguageRuntime(hs),t.registerLanguageRuntime(ms),t.registerLanguageRuntime(gs),t.registerLanguageRuntime(ys),t.registerLanguageRuntime(ws);const i=new Map;return{async*run(e,t){const n=t?.runId??vs("run"),s=await r.open({language:e.language,provider:e.metadata?.provider,kernelspec:e.metadata?.kernelspec,env:e.env,cwd:e.cwd,resources:e.resources,metadata:e.metadata});i.set(n,s);try{for await(const n of s.run(e,t))yield n}finally{i.delete(n),await s.close()}},async cancel(e){const t=i.get(e);t&&(await t.interrupt(),i.delete(e))},session:r,registry:t}}(rd?.compute),hd=function(e){if(e)return e;const t=Es(),n=new Ss(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],i=t.getProvider(r);if(!i)throw new Error(`Dataset provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Dataset provider not found: ${e.provider}`);return n.list({query:e.query,tags:e.tags})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({query:e?.query,tags:e?.tags});r.push(...n)}catch(e){console.warn(`Failed to list datasets from provider ${t.id}:`,e)}return r},registry:t}}(rd?.datasets),md=function(e){if(e)return e;const t=Cs(),n=new Ts(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],i=t.getProvider(r);if(!i)throw new Error(`Model provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Model provider not found: ${e.provider}`);return n.list({task:e.task,query:e.query})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({task:e?.task,query:e?.query});r.push(...n)}catch(e){console.warn(`Failed to list models from provider ${t.id}:`,e)}return r},registry:t}}(rd?.models),gd=function(e){if(e)return e;const t=Ms();return{registry:t,async start(e){const n=function(e){if(e.format&&"unknown"!==e.format)return e.format;const t=e.filePath?.trim().toLowerCase();if(t){if(t.endsWith(".gguf"))return"gguf";if(t.endsWith(".safetensors"))return"safetensors";if(t.endsWith(".onnx"))return"onnx"}return"unknown"}(e),r=n!==e.format?{...e,format:n}:e,i=t.select(r);if(!i){const e=t.list().map(e=>e.id);throw new Error(`No model runtime can run record "${r.id}" (format=${r.format??"unknown"}). Registered runtimes: [${e.join(", ")||"none"}].`)}return i.start(r)},async stop(e){const n=t.get(e.runtimeId);if(!n)throw new Error(`No model runtime registered for handle runtimeId="${e.runtimeId}".`);await n.stop(e)}}}(rd?.modelRuntimes),yd=function(e){if(e)return e;const t=Ms();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}.`);const i=e.handle?.tasks??r.tasks;if(e.task&&i&&!i.includes(e.task)){const t=e.handle?.tasks?"this handle":`runtime "${n}"`;throw new Error(`Task "${e.task}" is not served by ${t}. Declared: [${i.join(", ")||"none"}].`)}return r.infer(e)}}}(rd?.inference),wd=function(e){return e||{upsert:(e,t)=>qs().upsert(e,t),query:e=>qs().query(e),delete:(e,t)=>qs().delete(e,t),clear:e=>qs().clear(e),count:e=>qs().count(e)}}(rd?.vectors),vd=function(e){if(e)return e;function t(){const e=Bs().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=Bs().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=Bs().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 i={start:e=>r().start(e),stop:()=>r().stop(),status:()=>r().status(),onRequest:e=>r().onRequest(e),reply:(e,t)=>r().reply(e,t)},s={info:e=>{const t=Bs().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:()=>Bs().dataDir(),dataFs:{list:(e,t)=>Bs().dataFs.list(e,t),readFile:e=>Bs().dataFs.readFile(e),stat:e=>Bs().dataFs.stat(e),mkdir:(e,t)=>Bs().dataFs.mkdir(e,t),deleteFile:e=>Bs().dataFs.deleteFile(e),deleteFolder:e=>Bs().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=Bs().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=Bs().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=Fs?.http?.download;if(e)return e=>n().download(e)},get onDownloadProgress(){const e=Fs?.http?.onDownloadProgress;if(e)return e=>n().onDownloadProgress(e)}},get mcpServer(){return Fs?.mcpServer?i:void 0},get system(){return Fs?.system?s:void 0}}}(rd?.host),bd=function(e){return ic(e)?e:(void 0!==e&&rc(e),{set:(e,t)=>tc.get().set(e,t),get:e=>tc.get().get(e),delete:e=>tc.get().delete(e),list:()=>tc.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:tc.get().get(`secret-manager.${e}`)},__punicaWrappedSecretsFacade:!0})}(rd?.secrets);console.log("[Runtime] Facades created"),function(){Mu({name:"fs.readFile",title:"Read a file",description:"Read a file's full text content from disk by path. The usual first step before changing a file: look at what it says.",version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",subject:"file"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Va),Mu({name:"fs.writeFile",title:"Write a file",description:"Write text to a file, creating it when it does not exist and replacing its contents when it does. The canonical way to save, edit, or generate a file.",version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string",subject:"file"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),Ws.registerProvider(new Wa),Mu({name:"fs.writeBytes",title:"Write binary file content",description:"Write raw bytes to a file, creating it when it does not exist and replacing its contents when it does. The binary counterpart to fs.writeFile, which encodes as UTF-8 and would corrupt an image or any other non-text payload. Bytes travel base64-encoded because capability inputs are JSON.",version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","base64"],properties:{path:{type:"string",subject:"file"},base64:{type:"string",sensitive:!0,maxLength:89478485}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),Ws.registerProvider(new Ga),Mu({name:"fs.listFiles",title:"List the whole file tree",description:"List every file and folder in the workspace as a nested tree, showing the whole project layout rather than the contents of one directory.",version:"1.0.0",sideEffect:"read",action:["file.list"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Ya),Mu({name:"fs.stat",title:"File size and dates",description:"Get a path's size, modification time, and whether it is a directory, without reading its contents.",version:"1.0.0",sideEffect:"read",action:["file.stat"],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}}),Ws.registerProvider(new za),Mu({name:"fs.exists",title:"Check a path exists",description:"Check whether a file or folder exists at a path, before reading it or overwriting it.",version:"1.0.0",sideEffect:"read",action:["file.stat"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"boolean"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Ja),Mu({name:"fs.copy",title:"Copy a file",description:"Copy a file or folder to another path, leaving the original in place.",version:"1.0.0",sideEffect:"write",action:["file.read","file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["src","dst"],properties:{src:{type:"string",subject:"file"},dst:{type:"string",subject:"file"}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),Ws.registerProvider(new Ha),Mu({name:"fs.mkdir",title:"Create a folder",description:"Create a folder, optionally creating the missing parent folders above it.",version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),Ws.registerProvider(new Qa),Mu({name:"fs.list",title:"List one folder",description:"List the files and folders directly inside one directory, optionally recursing into subfolders.",version:"1.0.0",sideEffect:"read",action:["file.list"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new ec),Mu({name:"fs.history",title:"File version history",description:"List the earlier saved versions of one file, so a change can be reviewed or rolled back.",version:"1.0.0",sideEffect:"read",action:["file.stat"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Za),Mu({name:"fs.readAtVersion",title:"Read an earlier version",description:"Read a file's contents as they were at one of its earlier saved versions.",version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path","versionId"],properties:{path:{type:"string",subject:"file"},versionId:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Xa),Mu({name:"secrets.get",title:"Read a stored secret",description:"Read a stored credential — an API key, token, or password — from the host's secret store by name; the result is the secret itself, so it must never be written to a file, a log, or a message.",version:"1.0.0",sideEffect:"read",action:["secret.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"}}},outputSchema:{type:["string","null"]},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3}}),Ws.registerProvider(new sc),Mu({name:"secrets.set",title:"Store a secret",description:"Store a credential — an API key, token, or password — in the host's secret store under a name, so other capabilities can use it without the value being written anywhere else.",version:"1.0.0",sideEffect:"write",action:["secret.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"}}),Ws.registerProvider(new oc),Mu({name:"llm.chat",title:"Chat with a model",description:"Send a conversation to a language model and get the reply back as text.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],egress:"dynamic",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",subject:"model"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),Ws.registerProvider(new cc),Mu({name:"llm.chatStream",title:"Stream a model reply",description:"Send a conversation to a language model and stream the reply as it is generated. Same contract as llm.chat, with live tokens delivered as events.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],egress:"dynamic",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",subject:"model"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),Ws.registerProvider(new lc),Mu({name:"llm.plan",title:"Plan a workflow",description:"Turn a request written in plain language into a runnable workflow plan.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],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}}}),Ws.registerProvider(new dc),Mu({name:"llm.invoke",title:"Run an instruction class",description:"Run one named instruction class — planner, code generator, validator — against a prompt, using the model and the provider chain that class is configured with.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],egress:"dynamic",risk:"low",permissions:[],inputSchema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",subject:"prompt"},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"},text:{type:"string"},structured:{},metadata:{type:"object",properties:{instructionClass:{type:"string"},modelId:{type:"string",subject:"model"},provider:{type:"string"},tokensUsed:{type:"number"},cacheHit:{type:"boolean"}}}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),Ws.registerProvider(new uc),Mu({name:"search.query",title:"Search across all files",description:"Search the text of every file in the workspace and return the matching files with their matching lines and line numbers. This is how to answer where something is, which files mention a word, or where a function is defined.",version:"1.0.0",sideEffect:"read",action:["file.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}}),Ws.registerProvider(new pc),Mu({name:"vcs.status",title:"Uncommitted changes",description:"Show what has changed in the repository: which files have uncommitted changes — modified, added, deleted, and untracked.",version:"1.0.0",sideEffect:"read",action:["vcs.read"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new fc),Mu({name:"vcs.commit",title:"Commit changes",description:"Commit the current changes to version control with a message.",version:"1.0.0",sideEffect:"write",action:["vcs.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["message"],properties:{message:{type:"string"},all:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),Ws.registerProvider(new hc),Mu({name:"workspace.readFile",title:"Read a workspace file",description:"Read a file's text from the workspace — the same operation as fs.readFile, kept for compatibility, and fs.readFile is the one to prefer.",deprecated:{since:"1.37.0",reason:"Duplicates fs.readFile exactly; kept so older flows and manifests keep working.",replacement:"fs.readFile"},version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",subject:"file"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new mc),Mu({name:"workspace.writeFile",title:"Write a workspace file",description:"Create a workspace file with the given text, kept for compatibility; prefer fs.writeFile, which also updates a file that already exists.",deprecated:{since:"1.37.0",reason:"Creates only; fs.writeFile also updates a file that already exists.",replacement:"fs.writeFile"},version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string",subject:"file"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),Ws.registerProvider(new gc),Mu({name:"workspace.listFiles",title:"Flat list of workspace files",description:"List every file in the workspace as one flat list of paths, without the folder structure that fs.listFiles returns.",version:"1.0.0",sideEffect:"read",action:["file.list"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object"}}}},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new yc),Mu({name:"workspace.projectContext",title:"What this project is",description:"Summarize the project in a single read: language and stack, dependencies, the scripts it can run, version control state, a digest of the README, and the meaningful parts of the folder layout. The fastest way to get oriented in an unfamiliar project.",version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Mc),Mu({name:"workspace.writeOrientation",title:"Write the project summary to files",description:"Write the project summary into the workspace as CLAUDE.md and .claudeignore, so a terminal agent gets oriented from a file read.",version:"1.0.0",sideEffect:"write",action:["file.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"}}),Ws.registerProvider(new $c),Mu({name:"context.remember",title:"Remember a fact",description:"Save a durable fact about this project under a key so it survives across sessions and is not rediscovered every time.",version:"1.0.0",sideEffect:"write",action:["memory.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"}}),Ws.registerProvider(new jc),Mu({name:"context.recall",title:"Recall saved facts",description:"Read back the facts saved for this project — all of them, or the one under a key.",version:"1.0.0",sideEffect:"read",action:["memory.read"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{key:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Dc),Mu({name:"terminals.create",title:"Open a terminal",description:"Open a new terminal in the app and return its id.",version:"1.0.0",sideEffect:"write",action:["process.exec"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{title:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),Ws.registerProvider(new Fc),Mu({name:"terminals.send",title:"Run a line in an open terminal",description:"Type a line into an already open terminal and run it, using the terminal id returned by terminals.create.",version:"1.0.0",sideEffect:"write",action:["process.exec"],risk:"low",permissions:[],inputSchema:{type:"object",required:["id","text"],properties:{id:{type:"string"},text:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:5e3,idempotency:"optional"}}),Ws.registerProvider(new qc),Mu({name:"tasks.runCommand",title:"Run a shell command",description:"Run a shell command or program and return its exit code together with everything it printed. This is how tests, builds, installs, and any other command-line work get done.",version:"1.0.0",sideEffect:"write",action:["process.exec"],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"}}),Ws.registerProvider(new Bc),Mu({name:"signing.sign",title:"Sign bytes with this workstation key",description:"Sign the given bytes with the host's package-signing key and return a detached signature carrying the public half, so a later reader can check the bytes were not altered without holding any secret.",version:"1.0.0",sideEffect:"read",risk:"medium",permissions:[],inputSchema:{type:"object",required:["bytes"],properties:{bytes:{type:"string",description:"base64url-encoded payload"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Zc),Mu({name:"signing.verify",title:"Verify a signature",description:"Check a detached signature against the given bytes and report whether they were altered since signing; this needs no key and works on a machine that did not produce them.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["bytes","signature"],properties:{bytes:{type:"string",description:"base64url-encoded payload"},signature:{type:"object"}}},outputSchema:{type:"object",required:["valid"],properties:{valid:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Xc),Mu({name:"signing.publicKey",title:"Read the signing public key",description:"Read the public half of the host's package-signing key, so a package can name the key in its header before its bytes are signed.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new el),Mu({name:"flow.migrate",title:"Migrate a workflow document",description:"Bring a saved workflow document up to a newer schema version, or report what migrating it would change. Reads only; nothing runs.",version:"1.0.0",sideEffect:"read",action:["flow.run"],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}}),Ws.registerProvider(new tl),Mu({name:"flow.runSubflow",title:"Run a subflow",description:"Run another workflow as a child of the current one and return its result.",version:"1.0.0",sideEffect:"write",action:["flow.run"],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"}}),Ws.registerProvider(new nl),Mu({name:rl,title:"Browse the capability catalog",description:"List the capabilities available on this installation, filtered by where they came from, which extension declared them, their tags, their risk, or their side effects.",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}}),Ws.registerProvider(new il),Mu({name:dl,title:"Export capability schemas",description:"Export the installed capabilities as machine-readable tool schemas, in the format a model provider expects.",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}}),Ws.registerProvider(new pl),Mu({name:Tl,title:"Find capabilities for a goal",description:"Rank the installed capabilities against a goal written in plain language and return the closest ones. The way to find a tool when its name is not known.",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"},normalizedAs:{type:"string"}}},defaults:{timeoutMs:5e3}}),Ws.registerProvider(new Pl),Mu({name:Ml,title:"Search for a capability",description:"Search the installed capabilities by keyword and return the matches with a one-line summary each. Use it when the right tool is not in the list already at hand.",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}}),Ws.registerProvider(new _l),Mu({name:Nl,title:"Describe a capability",description:"Return one capability in full: what it does, the exact arguments it takes, what it returns, and whether calling it needs approval. Read this before calling a capability that is not already described.",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}}),Ws.registerProvider(new $l);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Ll("ai.session.create",{title:"Start a new chat session",description:"Create a new persistent assistant conversation in a workspace and return it.",properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),Ll("ai.session.list",{title:"List chat sessions",description:"List the saved assistant conversations, optionally limited to one workspace.",properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),Ll("ai.session.get",{title:"Read one chat session",description:"Read one saved assistant conversation, including its messages.",required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),Ll("ai.session.rename",{title:"Rename a chat session",description:"Give a saved assistant conversation a different title.",required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),Ll("ai.session.archive",{title:"Archive a chat session",description:"Move a saved assistant conversation out of the active list without deleting it.",required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),Ll("ai.session.delete",{title:"Delete a chat session",description:"Delete a saved assistant conversation and its whole message history. Cannot be undone.",risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())Mu(e);for(const e of[new jl,new Dl,new Fl,new ql,new Bl,new Ul])Ws.registerProvider(e);Mu({name:ou,title:"Check capability declarations",description:"Check the installed capability declarations against the substrate conventions and report what is missing or malformed.",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}}),Ws.registerProvider(new au),Mu({name:du,title:"List capabilities offered to remote callers",description:"List the capabilities this installation exposes to a remote caller, with the schema each one accepts.",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}}),Ws.registerProvider(new hu),Mu({name:pu,title:"Call a capability on behalf of a remote caller",description:"Run one capability for a remote caller through the full policy, approval, and audit pipeline.",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}}),Ws.registerProvider(new mu),Mu({name:gu,action:["ui.reveal"],title:"Show a panel",description:"Open a named panel such as settings, source control, the file explorer or the terminal, and focus it.",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string",description:"Id of the panel to open, as `shell.listViews` reports it."},focus:{type:"boolean",description:"Also move keyboard focus into the panel."}}},outputSchema:{type:"object",required:["viewId","revealed"],properties:{viewId:{type:"string"},revealed:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Su),Mu({name:yu,title:"Hide a panel",description:"Hide a panel, sidebar, or editor view.",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}}),Ws.registerProvider(new Au),Mu({name:wu,title:"List the panels",description:"List the panels, sidebars, and editor views this window has, and which of them are currently visible.",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}}),Ws.registerProvider(new xu),Mu({name:vu,action:["ui.reveal"],title:"Toggle a panel",description:"Show a panel if it is hidden, hide it if it is showing.",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}}),Ws.registerProvider(new Cu),Mu({name:bu,action:["ui.reveal"],title:"Toggle a whole area of the window",description:"Show or hide one whole area of the window — the left sidebar, the right sidebar, or the bottom panel — rather than a single view inside it.",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}}),Ws.registerProvider(new Pu),Mu({name:Iu,title:"Move a panel somewhere else",description:"Move a view into a different area of the window, for example from the bottom panel into the right sidebar.",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}}),Ws.registerProvider(new Nu)}(),console.log("[Runtime] Capabilities registered");const Id={lifecyclePhase:rd?.lifecyclePhase??"bootstrapping",fs:id,fileOpeners:rd?.fileOpeners??ki,fileOperations:rd?.fileOperations??Ci,search:sd,vcs:od,terminals:ad,debug:cd,tasks:ld,workspace:ud,resources:dd,secrets:bd,llm:pd,compute:fd,datasets:hd,models:md,modelRuntimes:gd,inference:yd,vectors:wd,host:vd,capabilities:{gateway:qa,unifiedRegistry:oo,logTrinityCatalog:_u,docs:{formatCapabilityMarkdown:function(e){const t=e.definition,n=[];n.push(`# \`${t.id}\``),n.push(""),n.push(function(e){const t=e.definition,n=[];n.push(`**Origin:** ${e.origin}`),n.push(`**Version:** ${t.version}`);const r=t.policy?.risk??"—",i=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${i}`);const s=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";n.push(`**Side effects:** ${s}`);const o=Array.isArray(t.action)&&t.action.length>0?t.action.join(", "):"—";return n.push(`**Action:** ${o}`),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(Du(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Du(t.outputs.schema)),n.push("```"),n.push("")),t.tags&&t.tags.length>0&&(n.push("## Tags"),n.push(""),n.push(t.tags.join(", ")),n.push(""));const i=t.requires;if(i&&i.length>0){n.push("## Requires"),n.push("");for(const e of i)n.push(`- \`${e}\``);n.push("")}if(t.deprecated){n.push("## Deprecated"),n.push("");const e=[];e.push(`**Since:** ${t.deprecated.since}`),t.deprecated.reason&&e.push(`— ${t.deprecated.reason}`),n.push(e.join(" ")),t.deprecated.replacement&&(n.push(""),n.push(`**Replacement:** \`${t.deprecated.replacement}\``)),n.push("")}const s=function(e){const t=e.metadata;if(!t)return;const n=[];t.extensionName&&n.push(`- Extension: \`${t.extensionName}\``);t.productId&&n.push(`- Product: \`${t.productId}\``);t.packageRoot&&n.push(`- Manifest: \`${t.packageRoot}\``);return n.length>0?n.join("\n"):void 0}(e);for(s&&(n.push("## Source"),n.push(""),n.push(s),n.push(""));n.length>1&&""===n[n.length-1];)n.pop();return n.join("\n")+"\n"},formatCapabilitiesIndex:function(e){const t=[];t.push("# Capability Reference"),t.push(""),t.push("Auto-generated from the substrate's unified capability registry."),t.push("Run `npm run docs:capabilities` to regenerate — CI gates drift."),t.push("");const n=function(e){const t=new Map;for(const n of e){const e=t.get(n.origin)??[];e.push(n),t.set(n.origin,e)}for(const e of t.values())e.sort((e,t)=>e.definition.id.localeCompare(t.definition.id));return t}(e),r=["core","extension","instruction-class","ivy-node"];for(const e of r){const r=n.get(e);if(r&&0!==r.length){t.push(`## ${Lu(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(ju(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:Fu,connect:e=>Yu.connect(e),disconnect:e=>Yu.disconnect(e),listServers:()=>Yu.listServers(),listTools:e=>Yu.listTools(e),callTool:(e,t,n)=>Yu.callTool(e,t,n)},setFsProvider:function(e){Eo.set(e),e&&Ei({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:cs,setComputeProvider:function(e){ds().registerProvider(e)},setComputeRuntime:function(e){ds().registerLanguageRuntime(e)},setDatasetProvider:function(e){Es().registerProvider(e)},setModelProvider:function(e){Cs().registerProvider(e)},setModelRuntime:function(e){Ms().register(e)},setHostProvider:function(e){Fs=e},setVectorsProvider:function(e){js=e},setSearchProvider:$i,setWorkspaceProvider:zi,setTerminalProvider:Fi,setDebugProvider:function(e){Bi=e},setVcsProvider:Wi,setResourcesProvider:Ni,setTasksProvider:Li,setSecretsProvider:rc,installDefaultApprovalTokenPair:e=>{!function(e){const t=new Yo({secret:e}),n=new zo({secret:t.getSecret()});Xo(t),ta(n)}(e)},setApprovalTokenSigner:Xo,setApprovalTokenVerifier:ta,getApprovalTokenSigner:function(){return Ho??Zo().signer},getApprovalTokenVerifier:ea,setHostIdentity:function(e){me=e},getHostIdentity:ge,setPackageSigner:function(e){zc.set(e),e&&Ei({name:"packageSigner.providerRegistered",source:"runtime:packageSigner",payload:{}})},hasPackageSigner:Hc,verifyPackageSignature:Yc,setCapabilityTelemetryExporter:function(e){lo=e??co},getCapabilityTelemetryExporter:uo,setEventTelemetryExporter:function(e){H=e??J},getEventTelemetryExporter:Q,setLlmResponseCache:function(e){es=e},getLlmResponseCache:ts,InMemoryLlmResponseCache:class{#Ae;#Fe;#$e=new Map;#qe=0;#Be=0;#Ue=0;#Ve=0;constructor(e){this.#Ae=Math.max(1,e?.maxEntries??200),this.#Fe=Math.max(0,e?.ttlMs??36e5)}get(e){const t=this.#$e.get(e);if(t)return this.#Fe>0&&Date.now()-t.storedAtMs>this.#Fe?(this.#$e.delete(e),void(this.#Be+=1)):(this.#$e.delete(e),this.#$e.set(e,t),this.#qe+=1,this.#Ve+=t.response.usage?.totalTokens??0,t);this.#Be+=1}set(e,t){for(this.#$e.delete(e),this.#$e.set(e,t),this.#Ue+=1;this.#$e.size>this.#Ae;){const e=this.#$e.keys().next().value;if(void 0===e)break;this.#$e.delete(e)}}clear(){this.#$e.clear()}stats(){return{entries:this.#$e.size,hits:this.#qe,misses:this.#Be,stores:this.#Ue,tokensSaved:this.#Ve}}}};class kd{#We;constructor(e){this.#We=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#We);n?e(n):t(new Error("Extension not found"))})}}let Ed=class{#Ke;constructor(e){this.#Ke=e}async execute(){return await this.#Ke.execute()}},Sd=class extends Ed{constructor(e){super(e)}async execute(){return await super.execute()}},Ad=class extends Ed{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))}}},xd=class extends Ed{constructor(e){super(e)}async execute(){return await super.execute()}};const Cd=Symbol.for("yaml.alias"),Td=Symbol.for("yaml.document"),Pd=Symbol.for("yaml.map"),Nd=Symbol.for("yaml.pair"),Md=Symbol.for("yaml.scalar"),Rd=Symbol.for("yaml.seq"),$d=Symbol.for("yaml.node.type"),_d=e=>!!e&&"object"==typeof e&&e[$d]===Cd,Od=e=>!!e&&"object"==typeof e&&e[$d]===Td,Ld=e=>!!e&&"object"==typeof e&&e[$d]===Pd,jd=e=>!!e&&"object"==typeof e&&e[$d]===Nd,Dd=e=>!!e&&"object"==typeof e&&e[$d]===Md,Fd=e=>!!e&&"object"==typeof e&&e[$d]===Rd;function qd(e){if(e&&"object"==typeof e)switch(e[$d]){case Pd:case Rd:return!0}return!1}function Bd(e){if(e&&"object"==typeof e)switch(e[$d]){case Cd:case Pd:case Md:case Rd:return!0}return!1}const Ud=Symbol("break visit"),Vd=Symbol("skip children"),Wd=Symbol("remove node");function Kd(e,t){const n=Jd(t);if(Od(e)){Gd(null,e.contents,n,Object.freeze([e]))===Wd&&(e.contents=null)}else Gd(null,e,n,Object.freeze([]))}function Gd(e,t,n,r){const i=Hd(e,t,n,r);if(Bd(i)||jd(i))return Qd(e,r,i),Gd(e,i,n,r);if("symbol"!=typeof i)if(qd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Gd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Ud)return Ud;i===Wd&&(t.items.splice(e,1),e-=1)}}}else if(jd(t)){r=Object.freeze(r.concat(t));const e=Gd("key",t.key,n,r);if(e===Ud)return Ud;e===Wd&&(t.key=null);const i=Gd("value",t.value,n,r);if(i===Ud)return Ud;i===Wd&&(t.value=null)}return i}async function Yd(e,t){const n=Jd(t);if(Od(e)){await zd(null,e.contents,n,Object.freeze([e]))===Wd&&(e.contents=null)}else await zd(null,e,n,Object.freeze([]))}async function zd(e,t,n,r){const i=await Hd(e,t,n,r);if(Bd(i)||jd(i))return Qd(e,r,i),zd(e,i,n,r);if("symbol"!=typeof i)if(qd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await zd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Ud)return Ud;i===Wd&&(t.items.splice(e,1),e-=1)}}}else if(jd(t)){r=Object.freeze(r.concat(t));const e=await zd("key",t.key,n,r);if(e===Ud)return Ud;e===Wd&&(t.key=null);const i=await zd("value",t.value,n,r);if(i===Ud)return Ud;i===Wd&&(t.value=null)}return i}function Jd(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 Hd(e,t,n,r){return"function"==typeof n?n(e,t,r):Ld(t)?n.Map?.(e,t,r):Fd(t)?n.Seq?.(e,t,r):jd(t)?n.Pair?.(e,t,r):Dd(t)?n.Scalar?.(e,t,r):_d(t)?n.Alias?.(e,t,r):void 0}function Qd(e,t,n){const r=t[t.length-1];if(qd(r))r.items[e]=n;else if(jd(r))"key"===e?r.key=n:r.value=n;else{if(!Od(r)){const e=_d(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Kd.BREAK=Ud,Kd.SKIP=Vd,Kd.REMOVE=Wd,Yd.BREAK=Ud,Yd.SKIP=Vd,Yd.REMOVE=Wd;const Zd={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Xd=e=>e.replace(/[!,[\]{}]/g,e=>Zd[e]);class ep{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},ep.defaultYaml,e),this.tags=Object.assign({},ep.defaultTags,t)}clone(){const e=new ep(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new ep(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:ep.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},ep.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:ep.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},ep.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(2!==n.length&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[e,r]=n;return this.tags[e]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==n.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=n;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const n=e.slice(2,-1);return"!"===n||"!!"===n?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),n)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return"!"===n?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Xd(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&&Bd(e.contents)){const t={};Kd(e.contents,(e,n)=>{Bd(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(const[i,s]of n)"!!"===i&&"tag:yaml.org,2002:"===s||e&&!r.some(e=>e.startsWith(s))||t.push(`%TAG ${i} ${s}`);return t.join("\n")}}function tp(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 np(e){const t=new Set;return Kd(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function rp(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function ip(e,t,n,r){if(r&&"object"==typeof r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){const n=r[t],i=ip(e,r,String(t),n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),i=ip(e,r,t,n);void 0===i?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(const t of Array.from(r)){const n=ip(e,r,t,t);void 0===n?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(const[t,n]of Object.entries(r)){const i=ip(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function sp(e,t,n){if(Array.isArray(e))return e.map((e,t)=>sp(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Dd(r=e)&&!qd(r)||!r.anchor))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=e=>{i.res=e,delete n.onCreate};const s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}var r;return"bigint"!=typeof e||n?.keep?e:Number(e)}ep.defaultYaml={explicit:!1,version:"1.2"},ep.defaultTags={"!!":"tag:yaml.org,2002:"};class op{constructor(e){Object.defineProperty(this,$d,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Od(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=sp(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?ip(i,{"":o},"",o):o}}class ap extends op{constructor(e){super(Cd),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Kd(e,{Node:(e,n)=>{if(n===this)return Kd.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,s=this.resolve(r);if(!s){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(s);if(o||(sp(s,null,t),o=n.get(s)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(i>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=cp(r,s,n)),o.count*o.aliasCount>i)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return o.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(tp(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 cp(e,t,n){if(_d(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(qd(t)){let r=0;for(const i of t.items){const t=cp(e,i,n);t>r&&(r=t)}return r}if(jd(t)){const r=cp(e,t.key,n),i=cp(e,t.value,n);return Math.max(r,i)}return 1}const lp=e=>!e||"function"!=typeof e&&"object"!=typeof e;class up extends op{constructor(e){super(Md),this.value=e}toJSON(e,t){return t?.keep?this.value:sp(this.value,e,t)}toString(){return String(this.value)}}up.BLOCK_FOLDED="BLOCK_FOLDED",up.BLOCK_LITERAL="BLOCK_LITERAL",up.PLAIN="PLAIN",up.QUOTE_DOUBLE="QUOTE_DOUBLE",up.QUOTE_SINGLE="QUOTE_SINGLE";function dp(e,t,n){if(Od(e)&&(e=e.contents),Bd(e))return e;if(jd(e)){const t=n.schema[Pd].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||"undefined"!=typeof BigInt&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n;let c;if(r&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=i(e)),new ap(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 up(e);return c&&(c.node=t),t}l=e instanceof Map?o[Pd]:Symbol.iterator in Object(e)?o[Rd]:o[Pd]}s&&(s(l),delete n.onTagObj);const u=l?.createNode?l.createNode(n.schema,e,n):"function"==typeof l?.nodeClass?.from?l.nodeClass.from(n.schema,e,n):new up(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function pp(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 dp(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 fp=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class hp extends op{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=>Bd(t)||jd(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(fp(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(qd(i))i.addIn(r,t);else{if(void 0!==i||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,pp(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(qd(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return 0===r.length?!t&&Dd(i)?i.value:i:qd(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!jd(t))return!1;const n=t.value;return null==n||e&&Dd(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!!qd(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(qd(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,pp(this.schema,r,t))}}}}hp.maxFlowStringSingleLineLength=60;const mp=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function gp(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const yp=(e,t,n)=>e.endsWith("\n")?gp(n,t):n.includes("\n")?"\n"+gp(n,t):(e.endsWith(" ")?"":" ")+n,wp="flow",vp="block",bp="quoted";function Ip(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let d,p,f=i-t.length;"number"==typeof r&&(r>i-Math.max(2,s)?l.push(0):f=i-r);let h=!1,m=-1,g=-1,y=-1;n===vp&&(m=kp(e,m,t.length),-1!==m&&(f=m+c));for(let r;r=e[m+=1];){if(n===bp&&"\\"===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===vp&&(m=kp(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===bp){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 i=l[r],s=l[r+1]||e.length;0===i?w=`\n${t}${e.slice(0,s)}`:(n===bp&&u[i]&&(w+=`${e[i]}\\`),w+=`\n${t}${e.slice(i+1,s)}`)}return w}function kp(e,t,n){let r=t,i=t+1,s=e[i];for(;" "===s||"\t"===s;)if(t<i+n)s=e[++t];else{do{s=e[++t]}while(s&&"\n"!==s);r=t,i=t+1,s=e[i]}return r}const Ep=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Sp=e=>/^(%|---|\.\.\.)/m.test(e);function Ap(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(Sp(e)?" ":"");let o="",a=0;for(let e=0,t=n[e];t;t=n[++e])if(" "===t&&"\\"===n[e+1]&&"n"===n[e+2]&&(o+=n.slice(a,e)+"\\ ",e+=1,a=e,t="\\"),"\\"===t)switch(n[e+1]){case"u":{o+=n.slice(a,e);const t=n.substr(e+2,4);switch(t){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===t.substr(0,2)?o+="\\x"+t.substr(2):o+=n.substr(e,6)}e+=5,a=e+1}break;case"n":if(r||'"'===n[e+2]||n.length<i)e+=1;else{for(o+=n.slice(a,e)+"\n\n";"\\"===n[e+2]&&"n"===n[e+3]&&'"'!==n[e+4];)o+="\n",e+=2;o+=s," "===n[e+2]&&(o+="\\"),e+=1,a=e+1}break;default:e+=1}return o=a?o+n.slice(a):n,r?o:Ip(o,s,bp,Ep(t,!1))}function xp(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return Ap(e,t);const n=t.indent||(Sp(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:Ip(r,n,wp,Ep(t,!1))}function Cp(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=Ap;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?xp:i&&!t?Ap:n?xp:Ap}return r(e,t)}let Tp;try{Tp=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{Tp=/\n+(?!\n|$)/g}function Pp({comment:e,type:t,value:n},r,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return Cp(n,r);const l=r.indent||(r.forceBlockIndent||Sp(n)?" ":""),u="literal"===o||"folded"!==o&&t!==up.BLOCK_FOLDED&&(t===up.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}(n,c,l.length));if(!n)return u?"|\n":">\n";let d,p;for(p=n.length;p>0;--p){const e=n[p-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let f=n.substring(p);const h=f.indexOf("\n");-1===h?d="-":n===f||h!==f.length-1?(d="+",s&&s()):d="",f&&(n=n.slice(0,-f.length),"\n"===f[f.length-1]&&(f=f.slice(0,-1)),f=f.replace(Tp,`$&${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," ")),i&&i()),u)return`${v}\n${l}${w}${n=n.replace(/\n+/g,`$&${l}`)}${f}`;return`${v}\n${l}${Ip(`${w}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${f}`,l,vp,Ep(r,!0))}`}function Np(e,t,n,r){const{implicitKey:i,inFlow:s}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==up.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=up.QUOTE_DOUBLE);const c=e=>{switch(e){case up.BLOCK_FOLDED:case up.BLOCK_LITERAL:return i||s?Cp(o.value,t):Pp(o,t,n,r);case up.QUOTE_DOUBLE:return Ap(o.value,t);case up.QUOTE_SINGLE:return xp(o.value,t);case up.PLAIN:return function(e,t,n,r){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&s.includes("\n")||u&&/[[\]{},]/.test(s))return Cp(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?Cp(s,t):Pp(e,t,n,r);if(!a&&!u&&i!==up.PLAIN&&s.includes("\n"))return Pp(e,t,n,r);if(Sp(s)){if(""===c)return t.forceBlockIndent=!0,Pp(e,t,n,r);if(a&&c===l)return Cp(s,t)}const d=s.replace(/\n+/g,`$&\n${c}`);if(o){const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return Cp(s,t)}return a?d:Ip(d,c,wp,Ep(t,!1))}(o,t,n,r);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}function Mp(e,t){const n=Object.assign({blockQuote:!0,commentString:mp,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 Rp(e,t,n,r){if(jd(e))return e.toString(t,n,r);if(_d(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=Bd(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i||(i=function(e,t){if(t.tag){const n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(Dd(t)){r=t.value;const i=e.filter(e=>e.identify?.(r));n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n)throw new Error(`Tag not resolved for ${r?.constructor?.name??typeof r} value`);return n}(t.doc.schema.tags,s));const o=function(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const i=[],s=(Dd(e)||qd(e))&&e.anchor;s&&tp(s)&&(n.add(s),i.push(`&${s}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&i.push(r.directives.tagString(o)),i.join(" ")}(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof i.stringify?i.stringify(s,t,n,r):Dd(s)?Np(s,t,n,r):s.toString(t,n,r);return o?Dd(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function $p(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function _p(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&Op(n))if(r=_d(r)?r.resolve(e.doc):r,Fd(r))for(const n of r.items)Lp(e,t,n);else if(Array.isArray(r))for(const n of r)Lp(e,t,n);else Lp(e,t,r);else{const i=sp(n,"",e);if(t instanceof Map)t.set(i,sp(r,i,e));else if(t instanceof Set)t.add(i);else{const s=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(Bd(e)&&n?.doc){const t=Mp(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;const r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+'..."'),$p(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}(n,i,e),o=sp(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const Op=e=>"<<"===e||Dd(e)&&"<<"===e.value&&(!e.type||e.type===up.PLAIN);function Lp(e,t,n){const r=e&&_d(n)?n.resolve(e.doc):n;if(!Ld(r))throw new Error("Merge sources must be maps or map aliases");const i=r.toJSON(null,e,Map);for(const[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function jp(e,t,n){const r=dp(e,void 0,n),i=dp(t,void 0,n);return new Dp(r,i)}class Dp{constructor(e,t=null){Object.defineProperty(this,$d,{value:Nd}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Bd(t)&&(t=t.clone(e)),Bd(n)&&(n=n.clone(e)),new Dp(t,n)}toJSON(e,t){return _p(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,r,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n;let p=Bd(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(qd(e)||!Bd(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||qd(e)||(Dd(e)?e.type===up.BLOCK_FOLDED||e.type===up.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!f&&(d||!s),indent:a+c});let h,m,g,y=!1,w=!1,v=Rp(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(s||null==t)return y&&r&&r(),""===v?"?":f?`? ${v}`:v}else if(s&&!d||null==t&&f)return v=`? ${v}`,p&&!y?v+=yp(v,n.indent,l(p)):w&&i&&i(),v;y&&(p=null),f?(p&&(v+=yp(v,n.indent,l(p))),v=`? ${v}\n${a}:`):(v=`${v}:`,p&&(v+=yp(v,n.indent,l(p)))),Bd(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||!Dd(t)||(n.indentAtStart=v.length+1),w=!1,u||!(c.length>=2)||n.inFlow||f||!Fd(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let b=!1;const I=Rp(t,n,()=>b=!0,()=>w=!0);let k=" ";if(p||h||m)k=h?"\n":"",m&&(k+=`\n${gp(l(m),n.indent)}`),""!==I||n.inFlow?k+=`\n${n.indent}`:"\n"===k&&(k="\n\n");else if(!f&&qd(t)){const e=I[0],r=I.indexOf("\n"),i=-1!==r,s=n.inFlow??t.flow??0===t.items.length;if(i||!s){let t=!1;if(i&&("&"===e||"!"===e)){let n=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+=yp(v,n.indent,l(g)):w&&i&&i(),v}(this,e,t,n):JSON.stringify(this)}}function Fp(e,t,n){return(t.inFlow??e.flow?Bp:qp)(e,t,n)}function qp({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null});let d=!1;const p=[];for(let e=0;e<t.length;++e){const i=t[e];let o=null;if(Bd(i))!d&&i.spaceBefore&&p.push(""),Up(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(jd(i)){const e=Bd(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),Up(n,p,e.commentBefore,d))}d=!1;let a=Rp(i,u,()=>o=null,()=>d=!0);o&&(a+=yp(a,s,l(o))),d&&o&&(d=!1),p.push(r+a)}let f;if(0===p.length)f=i.start+i.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"+gp(l(e),c),a&&a()):d&&o&&o(),f}function Bp({items:e},t,{flowChars:n,itemIndent:r}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;r+=s;const c=Object.assign({},t,{indent:r,inFlow:!0,type:null});let l=!1,u=0;const d=[];for(let n=0;n<e.length;++n){const i=e[n];let s=null;if(Bd(i))i.spaceBefore&&d.push(""),Up(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(jd(i)){const e=Bd(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),Up(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Bd(i.value)?i.value:null;n?(n.comment&&(s=n.comment),n.commentBefore&&(l=!0)):null==i.value&&e?.comment&&(s=e.comment)}s&&(l=!0);let o=Rp(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=yp(o,r,a(s))),!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${s}${i}${t}`:"\n";return`${e}\n${i}${f}`}return`${p}${o}${d.join(" ")}${o}${f}`}function Up({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=gp(t(r),e);n.push(i.trimStart())}}function Vp(e,t){const n=Dd(t)?t.value:t;for(const r of e)if(jd(r)){if(r.key===t||r.key===n)return r;if(Dd(r.key)&&r.key.value===n)return r}}class Wp extends hp{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Pd,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:i}=n,s=new this(e),o=(e,o)=>{if("function"==typeof i)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(void 0!==o||r)&&s.items.push(jp(e,o,n))};if(t instanceof Map)for(const[e,n]of t)o(e,n);else if(t&&"object"==typeof t)for(const e of Object.keys(t))o(e,t[e]);return"function"==typeof e.sortMapEntries&&s.items.sort(e.sortMapEntries),s}add(e,t){let n;n=jd(e)?e:e&&"object"==typeof e&&"key"in e?new Dp(e.key,e.value):new Dp(e,e?.value);const r=Vp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Dd(r.value)&&lp(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const e=this.items.findIndex(e=>i(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=Vp(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=Vp(this.items,e),r=n?.value;return(!t&&Dd(r)?r.value:r)??void 0}has(e){return!!Vp(this.items,e)}set(e,t){this.add(new Dp(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)_p(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!jd(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})),Fp(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Kp={collection:"map",default:!0,nodeClass:Wp,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(Ld(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Wp.from(e,t,n)};class Gp extends hp{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Rd,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Yp(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Yp(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Dd(r)?r.value:r}has(e){const t=Yp(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Yp(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Dd(r)&&lp(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(sp(e,String(r++),t));return n}toString(e,t,n){return e?Fp(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let s of t){if("function"==typeof r){const n=t instanceof Set?s:String(e++);s=r.call(t,n,s)}i.items.push(dp(s,void 0,n))}}return i}}function Yp(e){let t=Dd(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const zp={collection:"seq",default:!0,nodeClass:Gp,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Fd(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Gp.from(e,t,n)},Jp={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>Np(e,t=Object.assign({actualString:!0},t),n,r)},Hp={identify:e=>null==e,createNode:()=>new up(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new up(null),stringify:({source:e},t)=>"string"==typeof e&&Hp.test.test(e)?e:t.options.nullStr},Qp={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new up("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Qp.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Zp({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const i="number"==typeof r?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(s)){let e=s.indexOf(".");e<0&&(e=s.length,s+=".");let n=t-(s.length-e-1);for(;n-- >0;)s+="0"}return s}const Xp={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:Zp},ef={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():Zp(e)}},tf={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 up(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Zp},nf=e=>"bigint"==typeof e||Number.isInteger(e),rf=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function sf(e,t,n){const{value:r}=e;return nf(r)&&r>=0?n+r.toString(t):Zp(e)}const of={identify:e=>nf(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>rf(e,2,8,n),stringify:e=>sf(e,8,"0o")},af={identify:nf,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>rf(e,0,10,n),stringify:Zp},cf={identify:e=>nf(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>rf(e,2,16,n),stringify:e=>sf(e,16,"0x")},lf=[Kp,zp,Jp,Hp,Qp,of,af,cf,Xp,ef,tf];function uf(e){return"bigint"==typeof e||Number.isInteger(e)}const df=({value:e})=>JSON.stringify(e),pf=[Kp,zp].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:df},{identify:e=>null==e,createNode:()=>new up(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:df},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:df},{identify:uf,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})=>uf(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:df}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),ff={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if("function"==typeof Buffer)return Buffer.from(e,"base64");if("function"==typeof atob){const t=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,i,s){const o=n;let a;if("function"==typeof Buffer)a=o instanceof Buffer?o.toString("base64"):Buffer.from(o.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);a=btoa(e)}}if(t||(t=up.BLOCK_LITERAL),t!==up.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(a.length/e),i=new Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=a.substr(r,e);a=i.join(t===up.BLOCK_LITERAL?"\n":" ")}return Np({comment:e,type:t,value:a},r,i,s)}};function hf(e,t){if(Fd(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!jd(r)){if(Ld(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Dp(new up(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]=jd(r)?r:new Dp(r)}}else t("Expected a sequence for this tag");return e}function mf(e,t,n){const{replacer:r}=n,i=new Gp(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){let o,a;if("function"==typeof r&&(e=r.call(t,String(s++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);o=e[0],a=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);o=t[0],a=e[o]}else o=e;i.items.push(jp(o,a,n))}return i}const gf={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hf,createNode:mf};class yf extends Gp{constructor(){super(),this.add=Wp.prototype.add.bind(this),this.delete=Wp.prototype.delete.bind(this),this.get=Wp.prototype.get.bind(this),this.has=Wp.prototype.has.bind(this),this.set=Wp.prototype.set.bind(this),this.tag=yf.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const e of this.items){let r,i;if(jd(e)?(r=sp(e.key,"",t),i=sp(e.value,r,t)):r=sp(e,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,i)}return n}static from(e,t,n){const r=mf(e,t,n),i=new this;return i.items=r.items,i}}yf.tag="tag:yaml.org,2002:omap";const wf={collection:"seq",identify:e=>e instanceof Map,nodeClass:yf,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=hf(e,t),r=[];for(const{key:e}of n.items)Dd(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new yf,n)},createNode:(e,t,n)=>yf.from(e,t,n)};function vf({value:e,source:t},n){return t&&(e?bf:If).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const bf={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 up(!0),stringify:vf},If={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 up(!1),stringify:vf},kf={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:Zp},Ef={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():Zp(e)}},Sf={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 up(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:Zp},Af=e=>"bigint"==typeof e||Number.isInteger(e);function xf(e,t,n,{intAsBigInt:r}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const s=parseInt(e,n);return"-"===i?-1*s:s}function Cf(e,t,n){const{value:r}=e;if(Af(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return Zp(e)}const Tf={identify:Af,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>xf(e,2,2,n),stringify:e=>Cf(e,2,"0b")},Pf={identify:Af,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>xf(e,1,8,n),stringify:e=>Cf(e,8,"0")},Nf={identify:Af,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>xf(e,0,10,n),stringify:Zp},Mf={identify:Af,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>xf(e,2,16,n),stringify:e=>Cf(e,16,"0x")};class Rf extends Wp{constructor(e){super(e),this.tag=Rf.tag}add(e){let t;t=jd(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Dp(e.key,null):new Dp(e,null);Vp(this.items,t.key)||this.items.push(t)}get(e,t){const n=Vp(this.items,e);return!t&&jd(n)?Dd(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=Vp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Dp(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof r&&(e=r.call(t,e,e)),i.items.push(jp(e,null,n));return i}}Rf.tag="tag:yaml.org,2002:set";const $f={collection:"map",identify:e=>e instanceof Set,nodeClass:Rf,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Rf.from(e,t,n),resolve(e,t){if(Ld(e)){if(e.hasAllNullValues(!0))return Object.assign(new Rf,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function _f(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,i=e=>t?BigInt(e):Number(e),s=r.replace(/_/g,"").split(":").reduce((e,t)=>e*i(60)+i(t),i(0));return"-"===n?i(-1)*s:s}function Of(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Zp(e);let r="";t<0&&(r="-",t*=n(-1));const i=n(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),r+s.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const Lf={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})=>_f(e,n),stringify:Of},jf={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=>_f(e,!1),stringify:Of},Df={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(Df.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,i,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=_f(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$/,"")},Ff=[Kp,zp,Jp,Hp,bf,If,Tf,Pf,Nf,Mf,kf,Ef,Sf,ff,wf,gf,$f,Lf,jf,Df],qf=new Map([["core",lf],["failsafe",[Kp,zp,Jp]],["json",pf],["yaml11",Ff],["yaml-1.1",Ff]]),Bf={binary:ff,bool:Qp,float:tf,floatExp:ef,floatNaN:Xp,floatTime:jf,int:af,intHex:cf,intOct:of,intTime:Lf,map:Kp,null:Hp,omap:wf,pairs:gf,seq:zp,set:$f,timestamp:Df},Uf={"tag:yaml.org,2002:binary":ff,"tag:yaml.org,2002:omap":wf,"tag:yaml.org,2002:pairs":gf,"tag:yaml.org,2002:set":$f,"tag:yaml.org,2002:timestamp":Df};function Vf(e,t){let n=qf.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(qf.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=Bf[e];if(t)return t;const n=Object.keys(Bf).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const Wf=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Kf{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?Vf(e,"compat"):e?Vf(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Uf:{},this.tags=Vf(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,Pd,{value:Kp}),Object.defineProperty(this,Md,{value:Jp}),Object.defineProperty(this,Rd,{value:zp}),this.sortMapEntries="function"==typeof s?s:!0===s?Wf:null}clone(){const e=Object.create(Kf.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Gf{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,$d,{value:Td});let r=null;"function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:s}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new ep({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Gf.prototype,{[$d]:{value:Td}});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=Bd(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Yf(this.contents)&&this.contents.add(e)}addIn(e,t){Yf(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=np(this);e.anchor=!t||n.has(t)?rp(t||"a",n):t}return new ap(e.anchor)}createNode(e,t,n){let r;if("function"==typeof t)e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,n=t.filter(e).map(String);n.length>0&&(t=t.concat(n)),r=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:s,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=function(e,t){const n=[],r=new Map;let i=null;return{onAnchor:r=>{n.push(r),i||(i=np(e));const s=rp(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Dd(t.node)&&!qd(t.node)){const t=new Error("Failed to resolve repeated object (this should not happen)");throw t.source=e,t}t.node.anchor=t.anchor}},sourceObjects:r}}(this,s||"a"),f=dp(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&qd(f)&&(f.flow=!0),d(),f}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Dp(r,i)}delete(e){return!!Yf(this.contents)&&this.contents.delete(e)}deleteIn(e){return fp(e)?null!=this.contents&&(this.contents=null,!0):!!Yf(this.contents)&&this.contents.deleteIn(e)}get(e,t){return qd(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return fp(e)?!t&&Dd(this.contents)?this.contents.value:this.contents:qd(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!qd(this.contents)&&this.contents.has(e)}hasIn(e){return fp(e)?void 0!==this.contents:!!qd(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=pp(this.schema,[e],t):Yf(this.contents)&&this.contents.set(e,t)}setIn(e,t){fp(e)?this.contents=t:null==this.contents?this.contents=pp(this.schema,Array.from(e),t):Yf(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 ep({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 ep({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 Kf(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},a=sp(this.contents,t??"",o);if("function"==typeof i)for(const{count:e,res:t}of o.anchors.values())i(t,e);return"function"==typeof s?ip(s,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return function(e,t){const n=[];let r=!0===t.directives;if(!1!==t.directives&&e.directives){const t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");const i=Mp(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(gp(t,""))}let o=!1,a=null;if(e.contents){if(Bd(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(gp(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=Rp(e.contents,i,()=>a=null,t);a&&(c+=yp(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(Rp(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(gp(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(gp(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Yf(e){if(qd(e))return!0;throw new Error("Expected a YAML collection as document contents")}class zf extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Jf extends zf{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Hf extends zf{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Qf=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){const e=Math.min(s-39,o.length-79);o="…"+o.substring(e),s-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+"…\n"),o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];t&&t.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-s)));const a=" ".repeat(s)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function Zf(e,{flow:t,indicator:n,next:r,offset:i,onError:s,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 i of e)switch(m&&("space"!==i.type&&"newline"!==i.type&&"comma"!==i.type&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&"comment"!==i.type&&"newline"!==i.type&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),i.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!i.source.includes("\t")||(g=i),u=!0;break;case"comment":{u||s(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=i.source.substring(1)||" ";d?d+=p+e:d=e,p="",l=!1;break}case"newline":l?d?d+=i.source:c=!0:p+=i.source,l=!0,f=!0,(y||w)&&(h=!0),u=!0;break;case"anchor":y&&s(i,"MULTIPLE_ANCHORS","A node can have at most one anchor"),i.source.endsWith(":")&&s(i.offset+i.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=i,null===I&&(I=i.offset),l=!1,u=!1,m=!0;break;case"tag":w&&s(i,"MULTIPLE_TAGS","A node can have at most one tag"),w=i,null===I&&(I=i.offset),l=!1,u=!1,m=!0;break;case n:(y||w)&&s(i,"BAD_PROP_ORDER",`Anchors and tags must be after the ${i.source} indicator`),b&&s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.source} in ${t??"collection"}`),b=i,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){v&&s(i,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),v=i,l=!1,u=!1;break}default:s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.type} token`),l=!1,u=!1}const k=e[e.length-1],E=k?k.offset+k.source.length:i;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||"block-map"===r?.type||"block-seq"===r?.type)&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:b,spaceBefore:c,comment:d,hasNewline:f,hasNewlineAfterProp:h,anchor:y,tag:w,end:E,start:I??E}}function Xf(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(Xf(t.key)||Xf(t.value))return!0}return!1;default:return!0}}function eh(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&Xf(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function th(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Dd(t)&&Dd(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const nh="All mapping items must start at the same column";function rh(e,t,n,r){let i="";if(e){let s=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}const ih="Block collections are not allowed within flow collections",sh=e=>e&&("block-map"===e.type||"block-seq"===e.type);function oh(e,t,n,r,i,s){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Wp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const s of r.items){const{start:l,key:u,sep:d,value:p}=s,f=Zf(l,{indicator:"explicit-key-ind",next:u??d?.[0],offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0}),h=!f.found;if(h){if(u&&("block-seq"===u.type?i(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&i(a,"BAD_INDENT",nh)),!f.anchor&&!f.tag&&!d){c=f.end,f.comment&&(o.comment?o.comment+="\n"+f.comment:o.comment=f.comment);continue}(f.hasNewlineAfterProp||Xf(u))&&i(u??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==r.indent&&i(a,"BAD_INDENT",nh);const m=f.end,g=u?e(n,u,f,i):t(n,m,l,null,f,i);n.schema.compat&&eh(r.indent,u,i),th(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Zf(d??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){h&&("block-map"!==p?.type||y.hasNewline||i(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&f.start<y.found.offset-1024&&i(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const c=p?e(n,p,y,i):t(n,a,d,null,y,i);n.schema.compat&&eh(r.indent,p,i),a=c.range[2];const l=new Dp(g,c);n.options.keepSourceTokens&&(l.srcToken=s),o.items.push(l)}else{h&&i(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const e=new Dp(g);n.options.keepSourceTokens&&(e.srcToken=s),o.items.push(e)}}return c&&c<a&&i(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[r.offset,a,c??a],o}(e,t,n,r,s):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Gp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Zf(s,{indicator:"seq-item-ind",next:l,offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(!(u.anchor||u.tag||l)){c=u.end,u.comment&&(o.comment=u.comment);continue}l&&"block-seq"===l.type?i(u.end,"BAD_INDENT","All sequence items must start at the same column"):i(a,"MISSING_CHAR","Sequence item without - indicator")}const d=l?e(n,l,u,i):t(n,u.end,s,null,u,i);n.schema.compat&&eh(r.indent,l,i),a=d.range[2],o.items.push(d)}return o.range=[r.offset,a,c??a],o}(e,t,n,r,s):function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o="{"===r.start.source,a=o?"flow map":"flow sequence",c=new(s?.nodeClass??(o?Wp:Gp))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1);let u=r.offset+r.start.source.length;for(let s=0;s<r.items.length;++s){const l=r.items[s],{start:d,key:p,sep:f,value:h}=l,m=Zf(d,{flow:a,indicator:"explicit-key-ind",next:p??f?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!m.found){if(!(m.anchor||m.tag||f||h)){0===s&&m.comma?i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):s<r.items.length-1&&i(m.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),m.comment&&(c.comment?c.comment+="\n"+m.comment:c.comment=m.comment),u=m.end;continue}!o&&n.options.strict&&Xf(p)&&i(p,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===s)m.comma&&i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||i(m.start,"MISSING_CHAR",`Missing , between ${a} items`),m.comment){let e="";e:for(const t of d)switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}if(e){let t=c.items[c.items.length-1];jd(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 s=m.end,g=p?e(n,p,m,i):t(n,s,d,null,m,i);sh(p)&&i(g.range,"BLOCK_IN_FLOW",ih);const y=Zf(f??[],{flow:a,indicator:"map-value-ind",next:h,offset:g.range[2],onError:i,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){i(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<y.found.offset-1024&&i(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else h&&("source"in h&&h.source&&":"===h.source[0]?i(h,"MISSING_CHAR",`Missing space after : in ${a}`):i(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const w=h?e(n,h,y,i):y.found?t(n,y.end,f,null,y,i):null;w?sh(h)&&i(w.range,"BLOCK_IN_FLOW",ih):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const v=new Dp(g,w);if(n.options.keepSourceTokens&&(v.srcToken=l),o){const e=c;th(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(v)}else{const e=new Wp(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,i):t(n,m.end,f,null,m,i);c.items.push(r),u=r.range[2],sh(h)&&i(r.range,"BLOCK_IN_FLOW",ih)}}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);i(u,l?"MISSING_CHAR":"BAD_INDENT",l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`),p&&1!==p.source.length&&f.unshift(p)}if(f.length>0){const e=rh(f,h,n.options.strict,i);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,s),a=o.constructor;return"!"===i||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function ah(e,t,n){const r=t.offset,i=function({offset:e,props:t},n,r){if("block-scalar-header"!==t[0].type)return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=t[0],s=i[0];let o=0,a="",c=-1;for(let t=1;t<i.length;++t){const n=i[t];if(a||"-"!==n&&"+"!==n){const r=Number(n);!o&&r?o=r:-1===c&&(c=e+t)}else a=n}-1!==c&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":l=!0;case"newline":d+=i.source.length;break;case"comment":if(n&&!l){r(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=i.source.length,u=i.source.substring(1);break;case"error":r(i,"UNEXPECTED_TOKEN",i.message),d+=i.source.length;break;default:{r(i,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${i.type}`);const e=i.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:s,indent:o,chomp:a,comment:u,length:d}}(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};const s=">"===i.mode?up.BLOCK_FOLDED:up.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}(t.source):[];let a=o.length;for(let e=o.length-1;e>=0;--e){const t=o[e][1];if(""!==t&&"\r"!==t)break;a=e}if(0===a){const e="+"===i.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:s,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<a;++t){const[r,s]=o[t];if(""!==s&&"\r"!==s){if(r.length<c){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+r.length,"MISSING_CHAR",e)}if(0===i.indent&&(c=r.length),u=t,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===i.indent&&r.length>c&&(c=r.length),l+=r.length+s.length+1}for(let e=o.length-1;e>=a;--e)o[e][0].length>c&&(a=e+1);let d="",p="",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 ${i.indent?"explicit indentation indicator":"first line"}`;n(l-r.length-(a?2:1),"BAD_INDENT",e),t=""}s===up.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(i.chomp){case"-":break;case"+":for(let e=a;e<o.length;++e)d+="\n"+o[e][0].slice(c);"\n"!==d[d.length-1]&&(d+="\n");break;default:d+="\n"}const h=r+i.length+t.source.length;return{value:d,type:s,comment:i.comment,range:[r,h,h]}}function ch(e,t,n){const{offset:r,type:i,source:s,end:o}=e;let a,c;const l=(e,t,i)=>n(r+e,t,i);switch(i){case"scalar":a=up.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 lh(e)}(s,l);break;case"single-quoted-scalar":a=up.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return lh(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=up.QUOTE_DOUBLE,c=function(e,t){let n="";for(let r=1;r<e.length-1;++r){const i=e[r];if("\r"!==i||"\n"!==e[r+1])if("\n"===i){const{fold:t,offset:i}=uh(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=dh[i];if(s)n+=s;else if("\n"===i)for(i=e[r+1];" "===i||"\t"===i;)i=e[1+ ++r];else if("\r"===i&&"\n"===e[r+1])for(i=e[1+ ++r];" "===i||"\t"===i;)i=e[1+ ++r];else if("x"===i||"u"===i||"U"===i){const s={x:2,u:4,U:8}[i];n+=ph(e,r+1,s,t),r+=s}else{const i=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),n+=i}}else if(" "===i||"\t"===i){const t=r;let s=e[r+1];for(;" "===s||"\t"===s;)s=e[1+ ++r];"\n"===s||"\r"===s&&"\n"===e[r+2]||(n+=r>t?e.slice(t,r+1):i)}else n+=i}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}const u=r+s.length,d=rh(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function lh(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch(e){t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],s=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)""===r[1]?"\n"===s?i+=s:s="\n":(i+=s+r[1],s=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,r=a.exec(e),i+s+(r?.[1]??"")}function uh(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 dh={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function ph(e,t,n,r){const i=e.substr(t,n),s=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(s)){const i=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}return String.fromCodePoint(s)}function fh(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?ah(e,t,r):ch(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,"TAG_RESOLVE_FAILED",e)):null,l=n&&c?function(e,t,n,r,i){if("!"===n)return e[Md];const s=[];for(const t of e.tags)if(!t.collection&&t.tag===n){if(!t.default||!t.test)return t;s.push(t)}for(const e of s)if(e.test?.test(t))return e;const o=e.knownTags[n];if(o&&!o.collection)return e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o;return i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[Md]}(e.schema,i,c,n,r):"scalar"===t.type?function({directives:e,schema:t},n,r,i){const s=t.tags.find(e=>e.default&&e.test?.test(n))||t[Md];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[Md];if(s.tag!==o.tag){i(r,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${e.tagString(s.tag)} or ${e.tagString(o.tag)}`,!0)}}return s}(e,i,t,r):e.schema[Md];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Dd(s)?s:new up(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new up(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function hh(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 mh={composeNode:gh,composeEmptyNode:yh};function gh(e,t,n,r){const{spaceBefore:i,comment:s,anchor:o,tag:a}=n;let c,l=!0;switch(t.type){case"alias":c=function({options:e},{offset:t,source:n,end:r},i){const s=new ap(n.substring(1));""===s.source&&i(t,"BAD_ALIAS","Alias cannot be an empty string");s.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=rh(r,o,e.strict,i);s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment);return s}(e,t,r),(o||a)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=fh(e,t,a,r),o&&(c.anchor=o.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":c=function(e,t,n,r,i){const s=r?t.directives.tagName(r.source,e=>i(r,"TAG_RESOLVE_FAILED",e)):null,o="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!s||"!"===s||s===Wp.tagName&&"map"===o||s===Gp.tagName&&"seq"===o||!o)return oh(e,t,n,i,s);let a=t.schema.tags.find(e=>e.tag===s&&e.collection===o);if(!a){const c=t.schema.knownTags[s];if(!c||c.collection!==o)return c?.collection?i(r,"BAD_COLLECTION_TYPE",`${c.tag} used for ${o} collection, but expects ${c.collection}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),oh(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=oh(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Bd(l)?l:new up(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(mh,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=yh(e,t.offset,void 0,null,n,r),l=!1}return o&&""===c.anchor&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),i&&(c.spaceBefore=!0),s&&("scalar"===t.type&&""===t.source?c.comment=s:c.commentBefore=s),e.options.keepSourceTokens&&l&&(c.srcToken=t),c}function yh(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=fh(e,{type:"scalar",offset:hh(t,n,r),indent:-1,source:""},a,l);return o&&(u.anchor=o.source.substring(1),""===u.anchor&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function wh(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 vh(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){const s=e[i];switch(s[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(s.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[i+1]?.[0]&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}class bh{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=wh(e);r?this.warnings.push(new Hf(i,t,n)):this.errors.push(new Jf(i,t,n))},this.directives=new ep({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=vh(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(qd(i)&&!i.flow&&i.items.length>0){let e=i.items[0];jd(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:vh(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=wh(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=function(e,t,{offset:n,start:r,value:i,end:s},o){const a=Object.assign({_directives:t},e),c=new Gf(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Zf(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!i||"block-map"!==i.type&&"block-seq"!==i.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?gh(l,i,u,o):yh(l,u.end,r,null,u,o);const d=c.contents.range[2],p=rh(s,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[n,d,p.offset],c}(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Jf(wh(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 Jf(wh(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=rh(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 Jf(wh(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 Gf(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 Ih(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 kh(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{const r=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{const r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{const r="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}function Eh(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=Eh(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=Sh(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=Sh(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=Sh(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 Sh({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=Eh(t)),n)for(const e of n)i+=e.source;return r&&(i+=Eh(r)),i}const Ah=Symbol("break visit"),xh=Symbol("skip children"),Ch=Symbol("remove item");function Th(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),Ph(Object.freeze([]),e,t)}function Ph(e,t,n){let r=n(t,e);if("symbol"==typeof r)return r;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let t=0;t<s.items.length;++t){const r=Ph(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===Ah)return Ah;r===Ch&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}Th.BREAK=Ah,Th.SKIP=xh,Th.REMOVE=Ch,Th.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},Th.parentCollection=(e,t)=>{const n=Th.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};const Nh="\ufeff",Mh="",Rh="",$h="";function _h(e){switch(e){case Nh:return"byte-order-mark";case Mh:return"doc-mode";case Rh:return"flow-error-end";case $h: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 Oh=Object.freeze({__proto__:null,BOM:Nh,DOCUMENT:Mh,FLOW_END:Rh,SCALAR:$h,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=Np({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:"\n"}];switch(a[0]){case"|":case">":{const e=a.indexOf("\n"),t=a.substring(0,e),n=a.substring(e+1)+"\n",i=[{type:"block-scalar-header",offset:s,indent:r,source:t}];return Ih(i,c)||i.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:s,indent:r,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:c};default:return{type:"scalar",offset:s,indent:r,source:a,end:c}}},isCollection:e=>!!e&&"items"in e,isScalar:e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),prettyToken:function(e){switch(e){case Nh:return"<BOM>";case Mh:return"<DOC>";case Rh:return"<FLOW_END>";case $h:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const r=(e,t,r)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new Jf([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ch(e,t,r);case"block-scalar":return ah({options:{strict:t}},e,r)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(r&&"number"==typeof a&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");o=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=Np({type:o,value:t},{implicitKey:i||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),i=t.substring(n+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=r,e.source=i}else{const{offset:t}=e,n="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:t,indent:n,source:r}];Ih(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:s,source:i})}}(e,c);break;case'"':kh(e,c,"double-quoted-scalar");break;case"'":kh(e,c,"single-quoted-scalar");break;default:kh(e,c,"scalar")}},stringify:e=>"type"in e?Eh(e):Sh(e),tokenType:_h,visit:Th});function Lh(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const jh=new Set("0123456789ABCDEFabcdef"),Dh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fh=new Set(",[]{}"),qh=new Set(" ,[]{}\n\r\t"),Bh=e=>!e||qh.has(e);class Uh{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)&&Lh(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]===Nh&&(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 Mh,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&&Lh(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&Lh(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Lh(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)&&Lh(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(Bh),"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("..."))&&Lh(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield Rh,yield*this.parseLineStart()}let i=0;for(;","===r[i];)i+=(yield*this.pushCount(1)),i+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(i+=(yield*this.pushIndicators()),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Bh),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Lh(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=>Lh(e)||"#"===e)}*parseBlockScalar(){let e,t=this.pos-1,n=0;e:for(let r=this.pos;e=this.buffer[r];++r)switch(e){case" ":n+=1;break;case"\n":t=r,n=0;break;case"\r":{const e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if("\n"===e)break}default:break e}if(!e&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(t+1);if(-1===e)break;t=this.buffer.indexOf("\n",e)}while(-1!==t);if(-1===t){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(e=this.buffer[r];" "===e;)e=this.buffer[++r];if("\t"===e){for(;"\t"===e||" "===e||"\r"===e||"\n"===e;)e=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)for(;;){let e=t-1,r=this.buffer[e];"\r"===r&&(r=this.buffer[--e]);const i=e;for(;" "===r;)r=this.buffer[--e];if(!("\n"===r&&e>=this.pos&&e+1+n>i))break;t=e}return yield $h,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(Lh(t)||e&&Fh.has(t))break;n=r}else if(Lh(t)){let i=this.buffer[r+1];if("\r"===t&&("\n"===i?(r+=1,t="\n",i=this.buffer[r+1]):n=r),"#"===i||e&&Fh.has(i))break;if("\n"===t){const e=this.continueScalar(r+1);if(-1===e)break;r=Math.max(r,e-2)}}else{if(e&&Fh.has(t))break;n=r}return t||this.atEnd?(yield $h,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(Bh))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Lh(t)||e&&Fh.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(;!Lh(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(Dh.has(t))t=this.buffer[++e];else{if("%"!==t||!jh.has(this.buffer[e+1])||!jh.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 Vh{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 Wh(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Kh(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 Gh(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 Yh(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 zh(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 Jh(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Wh(t.start,"explicit-key-ind")||Wh(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Gh(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 Hh{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 Uh,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=_h(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&&Jh(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===Kh(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!==Kh(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=zh(Yh(this.peek(2)));let n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let i=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const i=t.sep[r];switch(i.type){case"newline":n.push(r);break;case"space":break;case"comment":i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Wh(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Gh(t.key)&&!Wh(t.sep,"newline")){const e=zh(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Wh(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=zh(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Wh(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0))}default:{const t=this.startBlockValue(e);if(t)return n&&"block-seq"!==t.type&&e.items.push({start:i}),void this.stack.push(t)}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||Wh(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=zh(Yh(t));Jh(e);const r=e.end.splice(1,e.end.length);r.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=zh(Yh(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=zh(Yh(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 Qh(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new Vh||null,prettyErrors:t}}function Zh(e,t={}){const{lineCounter:n,prettyErrors:r}=Qh(t),i=new Hh(n?.addNewLine),s=new bh(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(Qf(e,n)),t.warnings.forEach(Qf(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Xh(e,t={}){const{lineCounter:n,prettyErrors:r}=Qh(t),i=new Hh(n?.addNewLine),s=new bh(t);let o=null;for(const t of s.compose(i.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new Jf(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(Qf(e,n)),o.warnings.forEach(Qf(e,n))),o}function em(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=Xh(e,n);if(!i)return null;if(i.warnings.forEach(e=>$p(i.options.logLevel,e)),i.errors.length>0){if("silent"!==i.options.logLevel)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function tm(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 Gf(e,r,n).toString(n)}var nm=Object.freeze({__proto__:null,Alias:ap,CST:Oh,Composer:bh,Document:Gf,Lexer:Uh,LineCounter:Vh,Pair:Dp,Parser:Hh,Scalar:up,Schema:Kf,YAMLError:zf,YAMLMap:Wp,YAMLParseError:Jf,YAMLSeq:Gp,YAMLWarning:Hf,isAlias:_d,isCollection:qd,isDocument:Od,isMap:Ld,isNode:Bd,isPair:jd,isScalar:Dd,isSeq:Fd,parse:em,parseAllDocuments:Zh,parseDocument:Xh,stringify:tm,visit:Kd,visitAsync:Yd}),rm=Object.freeze({__proto__:null,Alias:ap,CST:Oh,Composer:bh,Document:Gf,Lexer:Uh,LineCounter:Vh,Pair:Dp,Parser:Hh,Scalar:up,Schema:Kf,YAMLError:zf,YAMLMap:Wp,YAMLParseError:Jf,YAMLSeq:Gp,YAMLWarning:Hf,default:nm,isAlias:_d,isCollection:qd,isDocument:Od,isMap:Ld,isNode:Bd,isPair:jd,isScalar:Dd,isSeq:Fd,parse:em,parseAllDocuments:Zh,parseDocument:Xh,stringify:tm,visit:Kd,visitAsync:Yd});class im{#Ge;constructor(e){this.#Ge=e}execute(){return new Promise((e,t)=>{const n=`${this.#Ge}.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=nm.parse(t);if(n.moduleURL=this.#Ge,n.hasCapabilities){const e=`${this.#Ge}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=nm.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.#Ge}.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 nm.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class sm{#Ke;constructor(e){this.#Ke=e}async execute(){return await this.#Ke.execute()}}class om{#n;#Ye;constructor(){this.#n=new Map,this.#Ye=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#Ye.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#Ye.has(t)||console.warn(`Unknown event type: ${t}`)}}class am{}class cm extends am{#ze;constructor(e){super(),this.#ze=e}execute(){}}let lm=class extends sm{#Je;constructor(e){super(e),this.#Je=new om,this.#Je.register("onExtension",cm),this.#Je.markKnown("onCommand"),this.#Je.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Je.handleEvent(e)),e}},um=class extends sm{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,activationEvents:n}=e,r=e.capabilities,i=[];if(r&&"object"==typeof r)for(const[e,t]of Object.entries(r)){if(!e)continue;const n="string"==typeof t?.title?t.title:e,r="string"==typeof t?.description?t.description:void 0;i.push({id:e,title:n,description:r})}return i.length&&i.forEach(({id:t,title:i,description:s})=>{if(!t)return;const o=punica.kernel.Commands.manager,a=punica.extensions.manager,c=punica.kernel.Events.manager;if(n?.some(e=>e===`onCommand:${t}`||"onCommand"===e)??!1)return;const l=r?.[t],u=l?.outputs?.resultEvent,d=l?.outputs?.errorEvent;o.registerCommand(t,{title:i??t,description:s,execute:(...n)=>{const r=n.length?n[n.length-1]:void 0,i=r?.__punica?.correlationId;a.activate(e.name,{reason:"command",trigger:t}).then(()=>{u&&c.publishEvent({name:u,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"result"},payload:{ok:!0,dispatched:!0,capabilityId:t,activatedExtension:e.name}})}).catch(n=>{d&&c.publishEvent({name:d,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"error"},payload:{ok:!1,capabilityId:t,activatedExtension:e.name,error:String(n?.message??n)}})})}})}),e}};function dm(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}function pm(e,t=dm()){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 fm=class extends sm{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(t){const{keybindings:e}=t,n=globalThis.punica?.shell?.KeyboardShortcuts?.manager;e&&n&&e.forEach(e=>{if(!e.capability)return void console.warn(`[Keybindings] Missing capability for keybinding: ${e.key}`);const t=e.capability,r=e.key,i=e.when;n.registerShortcut({command:t,keys:[pm(r)],when:i})})}return e}},hm=class extends sm{constructor(e){super(e)}async execute(){return await super.execute()}};class mm extends sm{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=Id.fileOpeners;e.forEach((e,t)=>{if(!e.capability)return void console.warn(`[FileOpeners] Missing capability for file opener: ${e.id??t}`);const i=e.capability,s=e.id??`${n}:${i||"opener"}:${t.toString(10)}`;r.register({id:s,label:e.label,command:i,priority:e.priority,matches:e.matches})})}return e}}const gm={"shell.activityBar":["activityBar","primarySidebar","contentSidebar"],"shell.statusbar":["statusbar"]},ym=["content"];function wm(e,t){if(e&&"object"==typeof e)if("slot"!==e.type){if(Array.isArray(e.children))for(const n of e.children)wm(n,t)}else"string"==typeof e.id&&e.id.length>0&&t.add(e.id)}function vm(e){const t=new Set,n=e?.shell?.layout?.root;if(n)wm(n,t);else for(const e of ym)t.add(e);for(const n of e?.shell?.activeModules??[])for(const e of gm[n]??[])t.add(e);return t}function bm(e){try{const t=globalThis.punica?.shell?.Profile?.manager?.registry,n=t?.getActive?.();if(!n)return;return vm(n).has(e)}catch{return}}function Im(e){if(!function(){const e=globalThis,t=e.punica?.shell;return!!t&&Object.keys(t).length>0}())return;const{integrations:t}=e;if(!t)return;const{views:n}=t;if(!n)return;const{activityBar:r,statusBar:i,primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c}=n;if(r&&!1!==bm("activityBar")){const e={...r};e.capability&&(e.command=e.capability),s&&!e.viewId&&(e.viewId=s.id),punica.shell.ActivityBar.manager.addItem(e)}if(i){const e={...i};e.capability&&(e.command=e.capability),punica.shell.Statusbar.manager.addItem(e)}!function(e,t){const n=punica.shell?.Views?.manager;if(!n?.registerPlacement)return;const{primarySidebar:r,secondarySidebar:i,contentSidebar:s,panel:o,activityBar:a}=t;if(r?.id){const t=Sm(r.id),i=t??Em("primarySidebar");n.registerPlacement({viewId:r.id,slot:i,homeSlot:"primarySidebar",allowedSlots:t?["primarySidebar",t]:[i],extensionName:e.name,title:r.title??r.name,icon:r.icon,onDemand:"content"===i,fallbackCommand:r.capability??a?.capability??a?.command})}if(s?.id){const t=Sm(s.id),r=t??Em("contentSidebar");n.registerPlacement({viewId:s.id,slot:r,homeSlot:"contentSidebar",allowedSlots:t?["contentSidebar",t]:[r],extensionName:e.name,title:s.title??s.name,icon:s.icon,onDemand:"content"===r,fallbackCommand:s.capability})}if(o?.id){const t=Array.isArray(o.toolbar)?o.toolbar:void 0;km(e,o,"panel",{order:o.order,panelToolbar:t})}i?.id&&km(e,i,"secondarySidebar",{})}(e,{primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r})}function km(e,t,n,r){const i=punica.shell?.Views?.manager;if(!i?.registerPlacement)return;const s=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=Sm(t.id);l&&!c.includes(l)&&c.push(l);const u=s?.getSlotOverride?.(t.id),d=u&&c.includes(u)?u:l??n,p=Em(d),f=p!==d,h=!1===t.showOnStartup||f;if(i.registerPlacement({viewId:t.id,slot:p,homeSlot:n,allowedSlots:f?["content"]:c,extensionName:e.name,title:t.title??t.name,icon:t.icon,order:r.order,fallbackCommand:t.capability,onDemand:h,panelToolbar:r.panelToolbar}),!h){const e=o?.forSlot?.(p)??("panel"===p?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})}}function Em(e){return"content"===e?e:!1===bm(e)?"content":e}function Sm(e){try{const t=punica.shell?.Profile?.manager?.registry,n=t?.getActive?.(),r=n?.shell?.viewDefaults?.slotOverrides,i=r?.[e];return"string"==typeof i&&i.length>0?i:void 0}catch{return}}let Am=0;function xm(){Am++}function Cm(){Am>0&&Am--}function Tm(){return Am>0}async function Pm(e){xm();try{return await e()}finally{Cm()}}const Nm=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#He(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#He(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}#He(e){const t=e.integrations?.configuration?{title:e.integrations.configuration.title,properties:Object.freeze(Object.fromEntries(Object.entries(e.integrations.configuration.properties??{}).map(([e,t])=>{const n=t,r={type:n.type,default:n.default,description:n.description};let i;return"string"===n.type&&"enum"in n&&Array.isArray(n.enum)&&(i=Object.freeze([...n.enum])),[e,Object.freeze({...r,enum:i})]})))}:void 0;return Object.freeze({name:e.name,displayName:e.displayName,description:e.description,version:e.version,configuration:t?Object.freeze(t):void 0,capabilities:this.getExtensionCapabilities(e.name)})}};const Mm=new class{#Qe=".punica/settings.json";#Ze;#Xe=null;#et=null;#tt=new Map;#nt=null;#he=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Ze=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Ze="localStorage:punica.settings":this.#Ze="settings.json"}async load(){this.#he||(await this.#rt(),await this.#it(),this.#he=!0)}async#rt(){try{if(this.#Ze.startsWith("localStorage:")){const e=this.#Ze.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#et=await this.#st(e)}else this.#et={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Ze),t=JSON.parse(e);this.#et=await this.#st(t)}catch{this.#et={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#et={version:"1.0",extensions:{},system:{}}}}async#it(){try{const e=await punica.runtime.fs.readFile(this.#Qe),t=JSON.parse(e);this.#Xe=await this.#st(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Xe=null}}async save(e="project"){this.#nt&&clearTimeout(this.#nt),this.#nt=window.setTimeout(async()=>{"global"===e?await this.#ot():await this.#at(),this.#nt=null},500)}async#ot(){if(this.#et)if(this.#Ze.startsWith("localStorage:")){const e=this.#Ze.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#et,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Ze,JSON.stringify(this.#et,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#at(){this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Qe,JSON.stringify(this.#Xe,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#he)return void this.load();if("system"===e){const e=this.#Xe?.system?.[t];if(void 0!==e)return e;const n=this.#et?.system?.[t];return void 0!==n?n:void 0}const n=this.#Xe?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#et?.extensions?.[e]?.[t];if(void 0!==r)return r;const i=punica.extensions.metadata.manager.getExtension(e);return i?.configuration?.properties?.[t]?.default}async set(e,t,n,r="project"){if(this.#he||await this.load(),"system"===e){const i=this.get(e,t);return"global"===r?(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.system||(this.#et.system={}),this.#et.system[t]=n,await this.save("global")):(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.system||(this.#Xe.system={}),this.#Xe.system[t]=n,await this.save("project")),void this.#ct(e,t,n,i)}const i=this.validate(e,t,n);if(!i.ok)throw new Error(`Invalid setting value: ${i.errors?.join(", ")}`);const s=this.get(e,t);"global"===r?(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.extensions[e]||(this.#et.extensions[e]={}),this.#et.extensions[e][t]=n,await this.save("global")):(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.extensions[e]||(this.#Xe.extensions[e]={}),this.#Xe.extensions[e][t]=n,await this.save("project")),this.#ct(e,t,n,s)}getAll(e){if(!this.#he)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#et?.extensions?.[e]??{},i=this.#Xe?.extensions?.[e]??{},s={};for(const[e,t]of Object.entries(n)){const n=t;s[e]=n.default}return{...s,...r,...i}}validate(e,t,n){const r=punica.extensions.metadata.manager.getExtension(e),i=r?.configuration?.properties?.[t];if(!i)return{ok:!1,errors:[`Setting "${t}" not found in extension "${e}"`]};const s=[];switch(i.type){case"boolean":"boolean"!=typeof n&&s.push(`Setting "${t}" must be a boolean`);break;case"string":"string"!=typeof n?s.push(`Setting "${t}" must be a string`):i.enum&&!i.enum.includes(n)&&s.push(`Setting "${t}" must be one of: ${i.enum.join(", ")}`);break;case"number":("number"!=typeof n||isNaN(n))&&s.push(`Setting "${t}" must be a number`)}return{ok:0===s.length,errors:s.length>0?s:void 0}}getTyped(e,t,n){const r=this.get(e,t);if(void 0!==r&&typeof r===n)return r}async reset(e,t){if("system"===e){const n=this.get(e,t),r=void 0!==this.#Xe?.system?.[t],i=void 0!==this.#et?.system?.[t];if(!r&&!i)return;return r&&delete this.#Xe.system[t],i&&delete this.#et.system[t],r&&await this.#at(),i&&await this.#ot(),void this.#ct(e,t,void 0,n)}const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Xe?.extensions?.[e]&&(delete this.#Xe.extensions[e][t],await this.save("project")),this.#et?.extensions?.[e]&&(delete this.#et.extensions[e][t],await this.save("global"))):await this.set(e,t,r,"project")}async resetExtension(e){const t=punica.extensions.metadata.manager.getExtension(e);if(t?.configuration?.properties)for(const n of Object.keys(t.configuration.properties))await this.reset(e,n)}getScope(e,t){return this.#he?"system"===e?void 0!==this.#Xe?.system?.[t]?"project":void 0!==this.#et?.system?.[t]?"global":"default":void 0!==this.#Xe?.extensions?.[e]?.[t]?"project":void 0!==this.#et?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#tt.has(e)||this.#tt.set(e,new Set),this.#tt.get(e).add(t),()=>{this.#tt.get(e)?.delete(t)}}async export(e){this.#he||await this.load();const t=e?.scope??"merged",n={version:this.#et?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Xe?.system:"global"===t?this.#et?.system:{...this.#et?.system,...this.#Xe?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#et?.extensions??{}),...Object.keys(this.#Xe?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Xe?.extensions?.[e]??{}:"global"===t?this.#et?.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.#Xe:this.#et)||("project"===r?this.#Xe={version:"1.0",extensions:{},system:{}}:this.#et={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Xe:this.#et;for(const[r,i]of Object.entries(n.extensions??{}))t.extensions&&!t.extensions.includes(r)||(e.extensions[r]={...e.extensions[r],...i});n.system&&(e.system={...e.system,...n.system})}else{if(t?.extensions)for(const e of t.extensions)n.extensions[e]&&("project"===r?(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.extensions[e]=n.extensions[e]):(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.extensions[e]=n.extensions[e]));else"project"===r?this.#Xe={...this.#Xe,...n,version:this.#Xe?.version??"1.0"}:this.#et={...this.#et,...n,version:this.#et?.version??"1.0"};n.system&&("project"===r?(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.system=n.system):(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.system=n.system))}await this.save(r)}async#st(e){return e.version,e}#ct(e,t,n,r){const i=this.#tt.get(e);i&&i.forEach(e=>e(t,n,r)),punica.kernel.Events.manager&&punica.kernel.Events.manager.publishEvent({name:"settings.changed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"extension-settings",kind:"info"},payload:{extensionName:e,key:t,newValue:n,oldValue:r}})}},Rm="system",$m="ui.language",_m="en";const Om=new class{#lt=new Map;#tt=new Set;#ut=null;#dt=new Set;#pt=new Map;getLocale(){return this.#ut??=this.#ft(),this.#ut}supportedLocales(){const e=this.#ht()?.supported;return Array.isArray(e)&&e.length?e:[_m]}async setLocale(e){const t=String(e||"").trim();if(t&&t!==this.getLocale()){try{await punica.extensions.settings.manager.set(Rm,$m,t,"global")}catch(e){throw e instanceof Error?e:new Error(String(e))}this.#ut=t,this.#mt(t)}}onDidChange(e){return this.#tt.add(e),()=>{this.#tt.delete(e)}}#mt(e){for(const t of[...this.#tt])try{t(e)}catch{}}#ht(){try{return punica.shell?.Profile?.manager?.registry?.getActive?.()?.localization}catch{return}}#ft(){const e=this.supportedLocales();try{const t=punica.extensions?.settings?.manager?.get?.(Rm,$m);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.#ht()?.default;return t&&e.includes(t)?t:e.includes(_m)?_m:e[0]}refresh(){const e=this.#ft();e!==this.#ut&&(this.#ut=e,this.#mt(e))}register(e,t){e&&t&&this.#lt.set(e,t)}t(e,t,n){const r=this.#gt(e,t,n?.count);return void 0===r?(this.#yt(`${e}:${t}`,e,t),t):n?r.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):r}#gt(e,t,n){const r=this.#lt.get(e);if(!r)return;const i=[],s=e=>{e&&!i.includes(e)&&i.push(e)};s(this.getLocale()),s(this.#ht()?.default),s(_m);const o=[];"number"==typeof n&&Number.isFinite(n)&&o.push(`${t}.${this.#wt(this.getLocale(),n)}`,`${t}.other`),o.push(t);for(const e of i){const t=r[e];if(t)for(const e of o){const n=t[e];if("string"==typeof n)return n}}}#wt(e,t){let n=this.#pt.get(e);if(!n){try{n=new Intl.PluralRules(e)}catch{n=new Intl.PluralRules(_m)}this.#pt.set(e,n)}return n.select(t)}#yt(e,t,n){this.#dt.has(e)||(this.#dt.add(e),console.warn(`[i18n] missing message "${n}" for ${t} (${this.getLocale()})`))}resetForTesting(){this.#lt.clear(),this.#tt.clear(),this.#ut=null,this.#dt.clear(),this.#pt.clear()}};const Lm=new Set;function jm(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 Dm=new Map;function Fm(){return"undefined"!=typeof document&&!!document}function qm(e){if(!Fm())return void Dm.delete(e);const t=Dm.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),Dm.delete(e)}const Bm={register(e,t,n){if(!Fm())return{id:e,dispose(){}};const r=n?.target??document.head,i=Dm.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),Dm.set(e,i),{id:e,dispose(){qm(e)}};const s=document.createElement("style");if(s.id=e,n?.attrs)for(const[e,t]of Object.entries(n.attrs))s.setAttribute(e,t);return s.textContent=t,r.appendChild(s),Dm.set(e,s),{id:e,dispose(){qm(e)}}},unregister(e){qm(e)},has:e=>!!Dm.has(e)||!!Fm()&&!!document.getElementById(e)};const Um={manager:new class{#vt;#bt;#It;#kt;#Et;#St;#At;#xt;#Ct;constructor(){this.#vt=new Map,this.#bt=new Map,this.#It=new Map,this.#kt=new Map,this.#Et=new Set,this.#St=new Set,this.#At=new Map,this.#xt=new Map,this.#Ct=new Map}getRuntimeState(e){return this.#bt.get(e)}registerBuiltinCapabilities(e){const t=Array.isArray(e)?e:[];for(const e of t){const t=String(e?.id??""),n=String(e?.extensionName??""),r=e?.definition??{};if(!t)throw new Error("[Extensions] registerBuiltinCapabilities: Missing id");if(!n)throw new Error(`[Extensions] registerBuiltinCapabilities: Missing extensionName (id="${t}")`);const i=this.#xt.get(t);if(i&&i.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${i.extensionName}" and "${n}".`);this.#xt.set(t,{id:t,extensionName:n,definition:r})}}#Tt(e){const t=e,n=t?.capabilities;if(n&&"object"==typeof n){for(const[t,r]of Object.entries(n)){if(!t)continue;const n=r??{};n.id||(n.id=t);const i={id:t,extensionName:e.name,definition:n},s=this.#xt.get(t);s&&s.extensionName!==e.name&&console.warn(`[Extensions] Capability id collision "${t}" between "${s.extensionName}" and "${e.name}". Keeping the last loaded.`),this.#xt.set(t,i)}this.#Pt(e,n)}}#Pt(e,t){const n=su.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`)}#Nt(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 im(e),n=new um(t),r=new fm(n),i=new hm(r),s=new mm(i);return new lm(s)})(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.#vt.set(r.name,r),this.#bt.set(r.name,"loaded"),this.#Tt(r),this.#Nt(r);try{Im(r)}catch(e){console.error(`[Extensions] view registration failed for ${r.name}:`,e)}const i=r.activationEvents??[];(i.includes("onStartup")||i.includes("onStartup:begin"))&&this.#Et.add(r.name),i.includes("onStartup:finish")&&this.#St.add(r.name),i.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#At.get(t);n||(n=new Set,this.#At.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#bt.get(e))return;const n=this.#It.get(e);if(n)return n;if(!this.#vt.get(e))return void console.error(`Extension "${e}" not found.`);const r=function(e){const t=e?.reason??"host",n=e?.presentation??("capability"===t||"extension"===t?"headless":"interactive");return{reason:t,trigger:e?.trigger,presentation:n}}(t),i=this.#Mt(e,r);this.#It.set(e,i);try{await i}finally{this.#It.delete(e)}}async#Mt(e,t){this.#bt.set(e,"activating"),jm("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new kd(e),n=new Ad(t),r=new xd(n);return new Sd(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.#Rt(e,t),i="startup:begin"===t.reason||"startup:finish"===t.reason;i&&Lm.add(e);try{"headless"===t.presentation?await Pm(()=>r.module.activate(n)):await r.module.activate(n)}finally{i&&Lm.delete(e)}const s=this.#kt.get(e);s&&(s.module=r.module),this.#bt.set(e,"active"),jm("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#bt.set(e,"failed"),jm("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}}#Rt(e,t){const n=[];this.#kt.set(e,{subscriptions:n});return{activation:Object.freeze({reason:t.reason,trigger:t.trigger,presentation:t.presentation}),subscriptions:n,capabilities:{registerHandler:(t,n)=>{this.#Ct.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const i=globalThis.punica?.shell?.Views?.manager;if(!i?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const s=i.registerProvider(t,r,e);return n.push(s),s},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway,s=r.punica?.shell?.Views?.manager?.getPlacement?.(e);if(function(e,t){return t&&function(e){return!!e&&"content"===e.slot&&"string"==typeof e.homeSlot&&"content"!==e.homeSlot}(e)}(s,Lm.has(t)))return void Wt({name:"shell.view.revealBlocked",source:"extensions:activation",payload:{viewId:e,extensionName:t,reason:"no-home-slot-at-startup",homeSlot:s?.homeSlot}});if(i?.call){const s=r.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await i.call("shell.revealView",{viewId:e,focus:n?.focus??!1},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:o},policy:{mode:"execute"}})}const o=r.punica?.shell?.Views?.manager;if(!o?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await o.reveal(e,{kind:"extension",id:t})}(t,e,n)},hide:async t=>{await async function(e,t){const n=globalThis,r=n.punica?.runtime?.capabilities?.gateway;if(r?.call){const i=n.punica?.kernel?.Events?.manager,s=i?.createCorrelationId?.()??`ext-hide-${Date.now()}`;return void await r.call("shell.hideView",{viewId:e},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:s},policy:{mode:"execute"}})}const i=n.punica?.shell?.Views?.manager;if(!i?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);i.hide(e,{kind:"extension",id:t})}(t,e)},setViewStatus:(t,n)=>{const r=globalThis.punica?.shell?.Views?.manager;r?.setViewStatus?r.setViewStatus(t,n,e):console.warn(`[Extensions] shell.Views unavailable — view status for "${t}" not published (${e}).`)}}}}async startupBegin(){await this.#$t(this.#Et,"startup:begin")}async startupFinish(){await this.#$t(this.#St,"startup:finish")}async#$t(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.#vt.get(e)}getAllExtensions(){return Array.from(this.#vt.values())}getCapability(e){return this.#xt.get(e)?.definition}listCapabilities(){return Array.from(this.#xt.values())}validateCapabilityInput(e,t){const n=this.getCapability(e);if(!n)return{ok:!0};const r=n.inputs?.schema;if(!r)return{ok:!0};const i=Io().validate(r,t);return i.ok?{ok:!0}:{ok:!1,errors:i.errors}}registerCapabilityHandler(e,t){this.#Ct.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#xt.get(e);if(!r)throw new Vs(Us.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#bt.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new Vs(Us.EXTENSION_ACTIVATION_FAILED,`Extension "${r.extensionName}" failed to activate for capability "${e}": `+(t instanceof Error?t.message:String(t)),{capability:e,extensionName:r.extensionName})}const i=this.#Ct.get(e);if(!i)throw new Vs(Us.CAPABILITY_HANDLER_MISSING,`Extension "${r.extensionName}" declared capability "${e}" but did not register a handler. Call context.capabilities.registerHandler("${e}", handler) inside activate().`,{capability:e,extensionName:r.extensionName});return await i.fn(t,n)}async deactivate(e){if("active"!==this.#bt.get(e))return;const t=this.#vt.get(e);this.#bt.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.#kt.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#kt.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.#kt.delete(e)}for(const[t,n]of this.#Ct)n.extensionName===e&&this.#Ct.delete(t)}finally{this.#bt.set(e,"loaded"),jm("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#bt.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.#xt)n.extensionName===e&&this.#xt.delete(t);for(const[t,n]of this.#At)n.delete(e)&&0===n.size&&this.#At.delete(t);const n=this.#vt.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.#Et.delete(e),this.#St.delete(e),this.#It.delete(e),this.#kt.delete(e),this.#vt.delete(e),this.#bt.delete(e),jm("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.#bt.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.#At.get(e);return t?Array.from(t):[]}},Styles:Bm,metadata:{manager:Nm},settings:{manager:Mm},i18n:{manager:Om}};function Vm(e){if(null==e)return!1;if(Array.isArray(e))return e.some(Vm);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(Vm)}return!1}function Wm(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=Km(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=Km(r.outputs.schema,"capability.outputs.schema");t.push(...e)}else t.push({path:"capability.outputs.schema",message:"capability.outputs.schema is required",code:"MISSING_OUTPUTS_SCHEMA",severity:"error"});if(n.program&&"object"==typeof n.program){if("cells"!==n.program.format&&t.push({path:"program.format",message:'program.format must be "cells"',code:"INVALID_PROGRAM_FORMAT",severity:"error"}),Array.isArray(n.program.cells)){n.program.cells.forEach((e,n)=>{e&&"object"==typeof e?(e.id&&"string"==typeof e.id||t.push({path:`program.cells[${n}].id`,message:"Cell id is required and must be a string",code:"MISSING_CELL_ID",severity:"error"}),e.cell_type&&["code","markdown","raw"].includes(e.cell_type)||t.push({path:`program.cells[${n}].cell_type`,message:'Cell cell_type must be "code", "markdown", or "raw"',code:"INVALID_CELL_TYPE",severity:"error"}),void 0===e.source&&t.push({path:`program.cells[${n}].source`,message:"Cell source is required",code:"MISSING_CELL_SOURCE",severity:"error"})):t.push({path:`program.cells[${n}]`,message:"Cell must be an object",code:"INVALID_CELL_TYPE",severity:"error"})});const e=n.program;if(e?.roles){if(e.roles.inputCellId||t.push({path:"program.roles.inputCellId",message:"program.roles.inputCellId is required",code:"MISSING_INPUT_CELL_ID",severity:"error"}),e.roles.outputCellId||t.push({path:"program.roles.outputCellId",message:"program.roles.outputCellId is required",code:"MISSING_OUTPUT_CELL_ID",severity:"error"}),e.roles.inputCellId){if(e.cells.some(t=>t.id===e.roles.inputCellId)){const n=e.cells.find(t=>t.id===e.roles.inputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["input"]')||r.includes("['input']"));r.includes("__ivy_input__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_input__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["input"].',code:"LEGACY_INPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Input cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["input"] protocol.',code:"INVALID_INPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.inputCellId",message:`Input cell id "${e.roles.inputCellId}" not found in cells`,code:"INVALID_INPUT_CELL_ID",severity:"error"})}if(e.roles.outputCellId){if(e.cells.some(t=>t.id===e.roles.outputCellId)){const n=e.cells.find(t=>t.id===e.roles.outputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["output"]')||r.includes("['output']"));r.includes("__ivy_output__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_output__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["output"].',code:"LEGACY_OUTPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Output cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["output"] protocol.',code:"INVALID_OUTPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.outputCellId",message:`Output cell id "${e.roles.outputCellId}" not found in cells`,code:"INVALID_OUTPUT_CELL_ID",severity:"error"})}}else t.push({path:"program.roles",message:"program.roles is required for ivy.node/v0.2 (inputCellId/outputCellId)",code:"MISSING_PROGRAM_ROLES",severity:"error"})}else t.push({path:"program.cells",message:"program.cells is required and must be an array",code:"MISSING_PROGRAM_CELLS",severity:"error"});n.program.language&&"string"==typeof n.program.language||t.push({path:"program.language",message:"program.language is required and must be a string",code:"MISSING_PROGRAM_LANGUAGE",severity:"error"})}else t.push({path:"program",message:"program is required and must be an object",code:"MISSING_PROGRAM",severity:"error"});if(r.policy){const e=["low","medium","high"];r.policy.risk&&e.includes(r.policy.risk)||t.push({path:"capability.policy.risk",message:`capability.policy.risk must be one of: ${e.join(", ")}`,code:"INVALID_POLICY_RISK",severity:"error"});const n=["none","plan","step"];r.policy.approval&&n.includes(r.policy.approval)||t.push({path:"capability.policy.approval",message:`capability.policy.approval must be one of: ${n.join(", ")}`,code:"INVALID_POLICY_APPROVAL",severity:"error"})}else t.push({path:"capability.policy",message:"capability.policy is required",code:"MISSING_POLICY",severity:"error"});if(void 0!==n.runtime&&"object"!=typeof n.runtime&&t.push({path:"runtime",message:"runtime must be an object",code:"INVALID_RUNTIME_TYPE",severity:"error"}),void 0!==n.tests)if("object"!=typeof n.tests)t.push({path:"tests",message:"tests must be an object",code:"INVALID_TESTS_TYPE",severity:"error"});else{const e=["draft","verified","certified"];n.tests.tier&&e.includes(n.tests.tier)||t.push({path:"tests.tier",message:`tests.tier must be one of: ${e.join(", ")}`,code:"INVALID_TESTS_TIER",severity:"error"}),n.tests.cases&&!Array.isArray(n.tests.cases)?t.push({path:"tests.cases",message:"tests.cases must be an array",code:"INVALID_TESTS_CASES",severity:"error"}):Array.isArray(n.tests.cases)&&n.tests.cases.forEach((e,n)=>{e&&"object"==typeof e?("string"==typeof e.id&&e.id||t.push({path:`tests.cases[${n}].id`,message:"Test case id is required and must be a string",code:"MISSING_TEST_CASE_ID",severity:"error"}),"string"==typeof e.description&&e.description||t.push({path:`tests.cases[${n}].description`,message:"Test case description is required and must be a string",code:"MISSING_TEST_CASE_DESCRIPTION",severity:"error"}),"input"in e?Vm(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 Km(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 Gm{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{let e;try{e=await Yi().getCurrent()}catch{return void console.warn("[NodeRegistry] No workspace provider — nothing to discover")}if(!e)return void console.warn("[NodeRegistry] No workspace available");const t=So();let n;try{n=await t.getFileTree()}catch(e){return void console.warn("[NodeRegistry] Failed to get file tree:",e)}const r=function(e){const t=[];return Ym(e,t),t}(n);await Promise.all(r.map(e=>this.loadManifest(t,e)))}catch(e){console.error("[NodeRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n),i=Wm(r);if(!i.ok)return void console.warn(`[NodeRegistry] Invalid manifest at ${t}:`,i.issues);const s=r,o=s.capability;if(!o||"object"!=typeof o||!("id"in o))return void console.warn(`[NodeRegistry] Missing capability.id in ${t}`);const a=t.lastIndexOf("/"),c=a>=0?t.slice(0,a):"";this.packages.set(o.id,{packageRoot:c,manifestPath:t,manifest:s})}catch(e){console.warn(`[NodeRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.runtime&&(t=t.filter(t=>t.manifest.runtime?.kind===e.runtime)),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}setTestReport(e,t){this.testReports.set(e,t)}getLatestTestReport(e){return this.testReports.get(e)}clear(){this.packages.clear(),this.testReports.clear()}}function Ym(e,t){for(const n of e)n.isDirectory?n.children&&Ym(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let zm;function Jm(){return zm||(zm=new Gm),zm}function Hm(e,t,n,r=!1){if("code"!==e.cell_type)throw new Error("Cell must be a code cell");let i=Array.isArray(e.source)?e.source.join(""):String(e.source||"");const s=JSON.stringify(t);return i=i.replace(/__ivy_node_id__/g,s),i}async function Qm(e,t,n,r){let i={};for await(const s of e.run({id:"ivy-snapshot",language:"python",code:"import json as __ivy_json\ndef __ivy_snapshot__():\n out = {}\n __ivy_skip = ('In', 'Out', 'get_ipython', 'exit', 'quit', 'json')\n for __ivy_k in list(globals().keys()):\n if __ivy_k.startswith('_'):\n continue\n if __ivy_k in __ivy_skip:\n continue\n try:\n __ivy_v = globals()[__ivy_k]\n except Exception:\n continue\n if callable(__ivy_v):\n continue\n __ivy_tn = type(__ivy_v).__name__\n __ivy_m = getattr(type(__ivy_v), '__module__', '') or ''\n if __ivy_tn == 'module':\n continue\n try:\n if __ivy_tn in ('DataFrame', 'Series') and 'pandas' in __ivy_m:\n __ivy_shape = getattr(__ivy_v, 'shape', None)\n out[__ivy_k] = {'__type__': __ivy_tn, 'shape': list(__ivy_shape) if __ivy_shape is not None else None}\n elif __ivy_tn == 'ndarray' and 'numpy' in __ivy_m:\n out[__ivy_k] = {'__type__': 'ndarray', 'shape': list(__ivy_v.shape), 'dtype': str(__ivy_v.dtype)}\n else:\n try:\n __ivy_enc = __ivy_json.dumps(__ivy_v)\n if len(__ivy_enc) > 2000:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n else:\n out[__ivy_k] = __ivy_v\n except Exception:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n except Exception:\n try:\n out[__ivy_k] = repr(__ivy_v)[:500]\n except Exception:\n out[__ivy_k] = '<unrepr>'\n return out\nprint(__ivy_json.dumps(__ivy_snapshot__(), default=lambda o: repr(o)[:500]))\n",resources:r?{timeoutMs:r}:void 0},{runId:`${t}:snapshot:${n}`}))if("stdout"===s.type&&"text"in s){const e=s.text;try{const t=JSON.parse(e.trim());t&&"object"==typeof t&&(i=t)}catch{}}return i}function Zm(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 Xm=/token|secret|key|password|passwd|api[_-]?key/i;function eg(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=Xm.test(i)?"[REDACTED]":e[i],o=i.length+JSON.stringify(s??null).length;n+o>16e3?r=!0:(n+=o,t[i]=s)}return r&&(t.__truncated__=!0),t}function tg(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function ng(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function rg(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function ig(e,t){const n=e.value;switch(e.type){case"isType":return{passed:ng(t)===String(n??""),expected:String(n??""),actual:ng(t)};case"equals":return{passed:rg(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=>rg(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:ng(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:ng(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):ng(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:ng(t)}}}function sg(e,t,n=""){const r=e.assertions||{},i={},s=[];if(void 0!==r.schema){const e=!0===r.schema;i.schema={passed:e},s.push(!e)}if(void 0!==r.expectsError){const e=!1===r.expectsError;i.error={passed:e},s.push(!e)}if(r.errorPattern&&r.expectsError){const e=new RegExp(r.errorPattern).test(n);i.error={passed:e,expected:r.errorPattern,actual:n||void 0},s.push(!e)}if(r.properties&&"object"==typeof r.properties){const e={};for(const[n,i]of Object.entries(r.properties)){if(!i||"object"!=typeof i)continue;const r=tg(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=ig(a,r);else if("string"==typeof a)o=ig({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=ig({type:"equals",value:i.expected},r)}e[n]=o,s.push(!o.passed)}Object.keys(e).length&&(i.properties=e)}return{status:s.some(Boolean)?"fail":"pass",assertions:Object.keys(i).length>0?i:void 0}}function og(e,t,n){const r=!0===e.assertions?.expectsError,i=e.assertions?.errorPattern;let s;return s=r?i?new RegExp(i).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:s,error:t,assertions:{error:{passed:"pass"===s,expected:i,actual:t}}}}function ag(e){const{capabilityId:t,version:n,tier:r,results:i,startedAtMs:s}=e,o=i.filter(e=>"pass"===e.status).length,a=i.filter(e=>"fail"===e.status).length,c=i.filter(e=>"skip"===e.status).length,l=i.filter(e=>"error"===e.status).length;return{reportId:`report-${t}-${n}-${Date.now()}`,capabilityId:t,capabilityVersion:n,specVersion:"v0.1",timestampMs:Date.now(),runner:{version:"0.1.0",environment:"punica-editor"},summary:{tier:r,status:0===a&&0===l?"pass":a>0?"fail":"flaky",totalCases:i.length,passedCases:o,failedCases:a,skippedCases:c,durationMs:Date.now()-s},cases:i}}function cg(){return Date.now()}function lg(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function ug(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function dg(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function pg(){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 fg(){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 hg(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 mg(e){try{const n=pg();if(!n)throw new Error("[FlowEngine] Capability gateway not available. Gateway is mandatory for all FS operations.");{const r=await t();await n.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}}catch{}}async function gg(e,n){const r=pg();if(!r)throw new Error("[FlowEngine] writeTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");const i=await t();await r.call("fs.writeFile",{path:e,content:n},{sessionId:"internal",workspaceId:i,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}function yg(e,t,n,r,i){const s=i?.traceId??t;punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:t,traceId:s,spanId:i?.spanId,parentSpanId:i?.parentSpanId,timestampMs:cg(),source:i?.source??"flow:engine",kind:n},payload:r})}const wg=new Set(["sensitive","secret"]);function vg(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function bg(e,t,n,r){if(!function(e,t,n){return!(!n||!wg.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:vg(e)}}const Ig=new class{#_t=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#_t.set(e,(this.#_t.get(e)??0)+r),!0;const i=this.#_t.get(e)??0;return!(i+r>n)&&(this.#_t.set(e,i+r),!0)}used(e){return this.#_t.get(e)??0}release(e){this.#_t.delete(e)}reset(){this.#_t.clear()}};class kg{async ensureBase(){await mg(".punica"),await mg(dg(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await mg(dg(".punica","workflow-runs",e)),await mg(dg(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=cg();await this.ensureRunDirs(e);const s=n.surface??"output",o=n.payload,a=n.text;let c,l=o,u=a;if(n.redactionPolicy||n.capabilityClassification){const e=bg(o??a,n.redactionPolicy,s,n.capabilityClassification);e&&"object"==typeof e&&!0===e.redacted&&(c=e,l=c,u=void 0)}const d="string"==typeof u,p=dg(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let f;f=d?String(u??""):lg(l??{},2);const h=n.sizeBudget?.maxBytes;if(c||"number"!=typeof h)"number"==typeof h&&Ig.acquire(e,f.length,h);else{Ig.acquire(e,f.length,h)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,f.length),f=lg(c,2),Ig.acquire(e,f.length,h))}await gg(p,f);const m=f.length,g=ug(d?String(u??""):lg(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs:i,name:n.name,mimeType:n.mimeType,uri:p,preview:g,sizeBytes:m,meta:c?{...n.meta??{source:"flow:engine"},redacted:c}:n.meta??{source:"flow:engine"}};return yg("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function Eg(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 Sg(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Ag(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 xg(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 Cg(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 Tg(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Pg(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 Ng(e,t,n){const r=Pg(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 Mg(e,t){const n=Pg(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 Rg(e,t){const n=Pg(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 $g(e,t=".punica"){const n=Tg(t,"workflow-runs",e.runId),r=Tg(n,"checkpoint.json"),i=Tg(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await Mg("writeCheckpoint",n),await Ng("writeCheckpoint",i,s);try{await async function(e,t,n){const r=Pg(e);await r.call("fs.rename",{from:t,to:n},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}("writeCheckpoint",i,r)}catch{try{await Rg("writeCheckpoint",r)}catch{}await Ng("writeCheckpoint",r,s);try{await Rg("writeCheckpoint",i)}catch{}}}async function _g(e,t=".punica"){const n=Tg(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=Pg(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 Og(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 Lg{runs;runIdToSession;artifactStore;constructor(e,t,n){this.runs=e,this.runIdToSession=t,this.artifactStore=n}async startRun(e){const t=e?.spec,n=e?.workspaceId,r=e?.filePathOrUri,i=e?.input??null;if(!t||"ivy.workflow/v0.1"!==t.apiVersion||"Workflow"!==t.kind)throw new Error('Invalid WorkflowDocument: must have apiVersion="ivy.workflow/v0.1" and kind="Workflow"');if(!t.graph||!t.graph.nodes||!t.graph.edges)throw new Error("Invalid WorkflowDocument: missing graph.nodes or graph.edges");if(!t.graph.entryNodeId)throw new Error("Invalid WorkflowDocument: missing graph.entryNodeId");if(!t.graph.nodes.some(e=>e.id===t.graph.entryNodeId))throw new Error(`Invalid WorkflowDocument: entryNodeId "${t.graph.entryNodeId}" not found in graph.nodes`);const s=t,o=function(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=e.graph.edges.filter(e=>n.has(e.fromId)&&n.has(e.toId)),i=new Map,s=new Map;t.forEach(e=>{i.set(e.id,0),s.set(e.id,[])}),r.forEach(e=>{s.get(e.fromId).push(e.toId),i.set(e.toId,(i.get(e.toId)??0)+1)});const o=[];for(const[e,t]of i.entries())0===t&&o.push(e);const a=[];for(;o.length;){const e=o.shift();a.push(e);for(const t of s.get(e)??[])i.set(t,(i.get(t)??0)-1),0===(i.get(t)??0)&&o.push(t)}if(a.length!==t.length)throw new Error("Workflow graph is not a DAG (cycle detected).");return a}(s),a=punica.kernel.Events.manager.createCorrelationId(),c=a,l=punica.kernel.Events.manager.createCorrelationId(),u={runId:a,specVersion:"0.1",status:"QUEUED",createdAtMs:cg(),startedAtMs:cg(),traceId:c,entryNodeId:s.graph.entryNodeId,metadata:{title:s.title,tags:s.tags},steps:[]};for(const e of o){const t=s.graph.nodes.find(t=>t.id===e);if(!t)continue;const n="ivyNode"===t.ref.kind?"capability.call":"workflow"===t.ref.kind?"workflow.run":"flowInput"===t.ref.kind?"flow.input":"flowOutput"===t.ref.kind?"flow.output":"primitive"===t.ref.kind?`primitive.${t.ref.primitive}`:"unknown",r={stepId:t.id,nodeId:t.id,nodeType:n,attempt:0,status:t.disabled?"SKIPPED":"PENDING",cellId:void 0};u.steps.push(r)}u.status="RUNNING";const d=Ag(s),p=s.graph.runBudget?.maxInFlight;return this.runs.set(a,{run:u,spec:s,order:o,cursor:0,paused:!1,cancelled:!1,rootSpanId:l,filePathOrUri:r,dependencyGraph:d,inFlightNodes:new Set,maxInFlight:p,nodeOutputs:new Map,input:i}),yg("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),Og({name:"flow.run.started",correlationId:a,traceId:c,payload:{runId:a,flowId:s.id,workspaceId:n,startedAtMs:u.startedAtMs??u.createdAtMs,entryNodeId:u.entryNodeId}}),await this.persistRun(a),await this.persistIndex(),{runId:a,workspaceId:n}}async pauseRun(e){const t=this.runs.get(e);return!!t&&(t.paused=!0,t.run.status="PAUSED",yg("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 _g(e);if(!n)return!1;{const r=n.dependencyGraphState?Ag(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"),yg("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=cg();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 yg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),yg("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=dg(".punica","workflow-runs",e,"run.json");await gg(n,lg({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=dg(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await gg(e,lg({version:1,updatedAtMs:cg(),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 $g(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=dg(".punica","workflow-runs","index.json"),n=await async function(e){const n=pg();if(!n)throw new Error("[FlowEngine] readTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");try{const r=await t();return await n.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}catch{return null}}(e);if(n)try{const e=JSON.parse(n);yg("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class jg{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,i,s){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=i,this.resumeRunLoop=s}setupApprovalSubscription(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{const t=e?.event?.payload?e.event:e,n=t?.envelope?.correlationId;if(!n)return;const r=this.pendingToRunStep.get(n);if(!r)return;const i=t?.payload??{},s=i?.request??{},o=i?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(s?.kind??"capability"),id:String(s?.id??""),risk:String(s?.risk??"low"),approval:String(s?.approval??"once"),reason:"string"==typeof s?.reason?s.reason:void 0,argsBinding:"string"==typeof s?.argsBinding?s.argsBinding:void 0,argsPreview:s?.argsPreview,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:cg()};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:cg(),resolved:!1},yg("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",yg("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}),yg("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),Og({name:"flow.approval.requested",correlationId:l.run.runId,traceId:l.run.traceId,payload:{runId:l.run.runId,stepId:r.stepId,pendingId:c.pendingId,attemptCorrelationId:n,capability:{kind:c.kind,id:c.id},risk:c.risk,approval:c.approval,workspaceId:c.workspaceId}}),this.persistRun(l.run.runId)}})}approvePending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=e?.scope??"once",r=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!r)return!1;const i=this.pendingToRunStep.get(r.attemptCorrelationId);if(!i)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id,argsBinding:r.argsBinding,argsPreview:r.argsPreview},n,{workspaceId:r.workspaceId})}catch{}yg("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:cg()},{traceId:i.runId}),Og({name:"flow.approval.granted",correlationId:i.runId,traceId:i.runId,payload:{runId:i.runId,stepId:i.stepId,pendingId:t,scope:n,capability:{kind:r.kind,id:r.id}}}),this.pendingByCorrelation.delete(r.attemptCorrelationId);const s=this.runs.get(i.runId);if(s){const e=s.run.steps.find(e=>e.stepId===i.stepId);e?.approval&&(e.approval.resolved=!0,e.approval.decision="approved"),s.run.status="RUNNING",yg("workflow.runUpdated",s.run.runId,"info",{runId:s.run.runId,patch:{status:"RUNNING"}},{traceId:s.run.traceId,spanId:s.rootSpanId}),this.persistRun(s.run.runId),this.resumeRunLoop(s.run.runId)}return!0}rejectPending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!n)return!1;const r=this.pendingToRunStep.get(n.attemptCorrelationId);if(!r)return!1;yg("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:cg()},{traceId:r.runId}),Og({name:"flow.approval.rejected",kind:"warn",correlationId:r.runId,traceId:r.runId,payload:{runId:r.runId,stepId:r.stepId,pendingId:t,capability:{kind:n.kind,id:n.id}}}),this.pendingByCorrelation.delete(n.attemptCorrelationId);const i=this.runs.get(r.runId);return i&&(i.run.status="FAILED",i.run.endedAtMs=cg(),yg("workflow.runUpdated",i.run.runId,"error",{runId:i.run.runId,patch:{status:"FAILED",endedAtMs:i.run.endedAtMs,error:{message:"Approval rejected",nodeId:r.stepId}}},{traceId:i.run.traceId,spanId:i.rootSpanId}),yg("workflow.runFinished",i.run.runId,"error",{runId:i.run.runId,status:"FAILED",endedAtMs:i.run.endedAtMs},{traceId:i.run.traceId,spanId:i.rootSpanId}),this.persistRun(i.run.runId),this.persistIndex()),!0}}const Dg=3e4,Fg={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const qg=new class{#Te=new Map;getSemaphore(e,t){let n=this.#Te.get(e);return n||(n={count:0,max:t,queue:[]},this.#Te.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.#Te.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function Bg(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function Ug(e,t){if(!t.retry)return 0;const n=t.retry.initialDelayMs??1e3,r=t.retry.maxDelayMs??3e4,i=t.retry.backoffMultiplier??2,s=t.retry.jitter??"none";return function(e,t){if("none"===t)return e;if("full"===t)return Math.floor(Math.random()*e);if("decorrelated"===t){const t=e/2;return Math.floor(t+Math.random()*t)}return e}(Math.min(n*Math.pow(i,e-1),r),s)}const Vg=new class{#Ot=new Map;register(e,t){this.#Ot.set(e,t)}get(e){return this.#Ot.get(e)}resolveOrThrow(e){const t=this.#Ot.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.#Ot.clear()}};function Wg(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 Kg(e,t){if(!e||"object"!=typeof e)return{ok:!1,reason:"invalid-ref"};if("literal"===e.kind)return{ok:!0,value:e.value};if("path"===e.kind){const n=String(e.path??"").split(".").filter(e=>e.length>0);if(0===n.length)return{ok:!1,reason:"invalid-ref"};const[r,...i]=n;if(!t.has(r))return{ok:!1,reason:"missing-node"};const s=t.get(r);if(0===i.length)return{ok:!0,value:s??null};const o=Wg(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function Gg(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 Yg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function zg(e){return String(e??"").split(".").filter(e=>e.length>0)}function Jg(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];Yg(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function Hg(e,t,n){const r=t.filter(t=>t.toId===e.id&&(void 0!==t.fromPath||void 0!==t.toPath)),i=e.data?.input;if(0===r.length)return void 0!==i?i:void 0!==e.defaults?e.defaults:void 0;const s={...Yg(e.defaults)?e.defaults:{},...Yg(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?zg(e.fromPath):[],i=r.length?Wg(t,r):t;if(void 0===i)continue;const o=e.toPath?zg(e.toPath):[];o.length?Jg(s,o,i):Yg(i)?Object.assign(s,i):s[e.fromId]=i}return s}class Qg 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 Zg(e,t){if(function(e){return!0===e.cancelled}(e))throw new Qg(e.run?.runId,t)}class Xg{runs;pendingToRunStep;runIdToSession;artifactStore;persistRun;persistCheckpoint;persistIndex;notifyTerminal;constructor(e,t,n,r,i,s,o,a){this.runs=e,this.pendingToRunStep=t,this.runIdToSession=n,this.artifactStore=r,this.persistRun=i,this.persistCheckpoint=s,this.persistIndex=o,this.notifyTerminal=a}async executeSequential(e,t){const n=this.runs.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;if(!n.notebook&&n.filePathOrUri)try{const e=pg();if(!e)throw new Error("[FlowEngine] notebook lazy-load: capability gateway is mandatory — substrate refuses to fall back to runtime.fs.");const r=await e.call("fs.readFile",{path:n.filePathOrUri},{sessionId:"internal",workspaceId:t?.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:n.run.traceId,parentSpanId:n.rootSpanId},policy:{mode:"execute"}});n.notebook=JSON.parse(r)}catch{}const r=n.run.traceId,i=n.rootSpanId;for(;n.cursor<n.order.length;){if(n.cancelled)return;if(n.paused)return;const s=n.order[n.cursor];n.run.currentNodeId=s;const o=n.spec.graph.nodes.find(e=>e.id===s),a=n.run.steps.find(e=>e.stepId===s);if(!o||!a){n.cursor++;continue}if(o.disabled){a.status="SKIPPED",n.cursor++;continue}const c=o.data?.breakpoint;if(c&&"PAUSED"!==n.run.status)return n.paused=!0,n.run.status="PAUSED",yg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const l=this.prepareNodeExecutionConfig(o,n),u=l.retry,d=u?.maxAttempts??0,p=u?.retryOnTimeout??!1,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=cg(),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}),yg("workflow.stepStarted",e,"info",{runId:e,step:{stepId:a.stepId,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,status:"RUNNING",startedAtMs:a.startedAtMs,cellId:a.cellId,attemptCorrelationId:c,spanId:u,inputsPreview:a.inputsPreview}},{traceId:r,spanId:u,parentSpanId:i}),Og({name:"flow.node.started",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,attemptCorrelationId:c,spanId:u}});try{const s=await this.executeNodeAttempt(o,a,l,{attemptCorrelationId:c,spanId:u,rootSpanId:i,traceId:r,workspaceId:t?.workspaceId,filePathOrUri:n.filePathOrUri,notebook:n.notebook,timeoutMs:f,nodeOutputs:n.nodeOutputs,runBudget:n.spec.graph.runBudget,runInput:n.input,resolvedInput:Hg(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),yg("workflow.stepFinished",e,"result",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"SUCCESS",endedAtMs:a.endedAtMs,outputsPreview:a.outputsPreview,artifactIds:a.artifactIds}},{traceId:r,spanId:u,parentSpanId:i}),Og({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",yg("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",yg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const 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=cg(),a.error={message:o},yg("workflow.stepFinished",e,"error",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"FAILED",endedAtMs:a.endedAtMs,error:{message:o},artifactIds:a.artifactIds??[]}},{traceId:r,spanId:u,parentSpanId:i}),Og({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=cg(),n.run.error={message:o,nodeId:s,correlationId:c},yg("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),yg("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),Og({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=Ug(h,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",yg("workflow.stepRetry",e,"info",{runId:e,stepId:a.stepId,attempt:h,maxAttempts:d,delayMs:m,error:o},{traceId:r,spanId:u,parentSpanId:i}),await new Promise(e=>setTimeout(e,m))}}}"RUNNING"!==n.run.status&&"PAUSED"!==n.run.status&&console.warn(`[FlowEngine] Invalid state transition to COMPLETED from ${n.run.status}`),n.run.status="COMPLETED",n.run.endedAtMs=cg(),yg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),yg("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),Og({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=Tg(n,"workflow-runs",e.runId),i=Tg(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await Mg("writeRunHistory",r),await Ng("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=Tg(t,"workflow-runs",e,"checkpoint.json");try{await Rg("deleteCheckpoint",n)}catch{}}(e);const s=this.runIdToSession.get(e);if(s){try{await s.close()}catch(t){console.warn(`[FlowEngine] Error closing session for run ${e}:`,t)}this.runIdToSession.delete(e)}this.notifyTerminal?.(e,"COMPLETED")}async executeParallel(e,t,n,r){const i=r.run.traceId,s=r.rootSpanId,o=r.maxInFlight??1/0,a=!!(c=r.spec.graph.runBudget)&&!0===c.failFast;for(var c;!Sg(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=Eg(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=>{Cg(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 xg(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void xg(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;){Zg(r),f++,l.attempt=f,l.status="RUNNING",l.startedAtMs=cg();const e=punica.kernel.Events.manager.createCorrelationId(),n=punica.kernel.Events.manager.createCorrelationId();l.attemptCorrelationId=e,l.spanId=n;try{const o=await this.executeNodeAttempt(c,l,a,{attemptCorrelationId:e,spanId:n,rootSpanId:s,traceId:i,workspaceId:t?.workspaceId,filePathOrUri:r.filePathOrUri,notebook:r.notebook,timeoutMs:p,nodeOutputs:r.nodeOutputs,runBudget:r.spec.graph.runBudget,runInput:r.input,resolvedInput:Hg(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 Qg)throw l.status="CANCELLED",l.endedAtMs=cg(),e;const t=String(e?.message??e);if(f<=d){const e=Ug(f,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=cg(),l.error={message:t},e}}h&&(xg(o,!0,n),await this.persistRun(e))}catch(t){xg(o,!1,n),t instanceof Qg||(r.run.status="FAILED",r.run.endedAtMs=cg(),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=cg(),yg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),yg("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),Og({name:"flow.run.completed",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs}}),await this.persistRun(e),await this.persistIndex(),this.notifyTerminal?.(e,"COMPLETED")):"FAILED"===r.run.status&&(Og({name:"flow.run.failed",kind:"error",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs,error:r.run.error}}),this.notifyTerminal?.(e,"FAILED"))}prepareNodeExecutionConfig(e,t){const n=Vg.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:Dg,retry:{...Fg},requireIdempotencyKeyForWriteRetry:!1};return e&&(void 0!==e.timeoutMs&&(n.timeoutMs=e.timeoutMs),e.retry&&(n.retry={...n.retry,...e.retry}),e.rateLimit&&(n.rateLimit={...e.rateLimit}),e.concurrency&&(n.concurrency={...e.concurrency}),void 0!==e.requireIdempotencyKeyForWriteRetry&&(n.requireIdempotencyKeyForWriteRetry=e.requireIdempotencyKeyForWriteRetry)),t&&(void 0!==t.timeoutMs&&(n.timeoutMs=t.timeoutMs),t.retry&&(n.retry={...n.retry,...t.retry}),t.rateLimit&&(n.rateLimit={...t.rateLimit}),t.concurrency&&(n.concurrency={...t.concurrency})),n}(r,e.executionOverride,t.spec.graph.runBudget)}async executeNodeAttempt(e,t,n,r){const i=Vg.get(e.ref.kind);let s;try{s=await(i?.acquireResources?.(e,n,{workspaceId:r.workspaceId}))}catch(e){throw new Error(`Concurrency limit reached: ${e?.message??String(e)}`)}try{const n=this.executeNode(e,r),i=r.timeoutMs?await async function(e,t){return Promise.race([e,Bg(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=cg(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return Vg.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class ey 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 ty(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new ey(e??0,t);return n}const ny="__default__";class ry{workspaceId;#Lt=new Map;#jt=new Map;#Dt=new Map;#Ft=new kg;#qt=!1;#Bt=new Map;#Ut;#Vt;#Wt;constructor(e=ny){this.workspaceId=e,this.#Ut=new Lg(this.#Lt,this.#Bt,this.#Ft),this.#Vt=new jg(this.#Lt,this.#jt,this.#Dt,e=>this.#Ut.persistRun(e),()=>this.#Ut.persistIndex(),e=>this.#Kt(e)),this.#Wt=new Xg(this.#Lt,this.#Dt,this.#Bt,this.#Ft,e=>this.#Ut.persistRun(e),e=>this.#Ut.persistCheckpoint(e),()=>this.#Ut.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#qt||(this.#qt=!0,this.#Vt.setupApprovalSubscription(),this.#Ut.loadIndex())}async startRun(e){const t=await this.#Ut.startRun(e);return this.#Kt(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#Ut.pauseRun(e)}async resumeRun(e){const t=await this.#Ut.resumeRun(e);return t&&this.#Kt(e,{}),t}async cancelRun(e,t){return this.#Ut.cancelRun(e,t)}getRun(e){return this.#Ut.getRun(e)}listRuns(e){return this.#Ut.listRuns(e)}approvePending(e){return this.#Vt.approvePending(e)}rejectPending(e){return this.#Vt.rejectPending(e)}hasRun(e){return this.#Lt.has(e)}getNodeOutput(e,t){const n=this.#Lt.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=ty(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#Ut.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;Og({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.#Gt.get(n);if(t)return this.#Gt.delete(n),void e(t);this.#Yt.set(n,e)});this.#Kt(n,{workspaceId:this.workspaceId});const i=await r,s=this.getRun(n),o=this.getNodeOutput(n,"flow-output");return{runId:n,parentRunId:e.parentRunId,depth:t,status:i,output:o,startedAtMs:s?.startedAtMs,endedAtMs:s?.endedAtMs,error:s?.error}}notifyTerminal(e,t){const n=this.#Yt.get(e);if(n)return this.#Yt.delete(e),void n(t);this.#Gt.set(e,t)}#Yt=new Map;#Gt=new Map;hasPending(e){return this.#Dt.has(e)}async#Kt(e,t){const n=this.#Lt.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;const r=void 0!==n.dependencyGraph,i=n.dependencyGraph;r&&i?await this.#Wt.executeParallel(e,t,i,n):await this.#Wt.executeSequential(e,t)}}const iy=new Map,sy=new Map,oy=new Map;function ay(e){const t=e??ny;let n=iy.get(t);return n||(n=new ry(t),iy.set(t,n)),n}let cy=!1;const ly=new class{initialize(){if(cy)return;cy=!0;const e=punica.kernel.Commands.manager;e.registerCommand(Yn.WORKFLOW.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(Yn.WORKFLOW.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(Yn.WORKFLOW.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(Yn.WORKFLOW.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(Yn.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:ny}(e),n=ay(t);n.initialize();const r=await n.startRun(e);return sy.set(r.runId,t),r}async pauseRun(e){const t=this.#zt(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#zt(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#zt(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#zt(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#zt(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of iy.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.#Jt(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#Jt(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(ty(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=ay(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return sy.set(n.runId,t.workspaceId),n}#zt(e){const t=sy.get(e);if(t)return iy.get(t);for(const[t,n]of iy.entries())if(n.hasRun(e))return sy.set(e,t),n}#Jt(e){const t=oy.get(e);if(t)return iy.get(t);for(const[t,n]of iy.entries())if(n.hasPending(e))return oy.set(e,t),n}};function uy(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 dy(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class py{packages=new Map;async discover(){this.packages.clear();try{let e;try{e=await Yi().getCurrent()}catch{return void console.warn("[AgentRegistry] No workspace provider — nothing to discover")}if(!e)return void console.warn("[AgentRegistry] No workspace available");const t=So();let n;try{n=await t.getFileTree()}catch(e){return void console.warn("[AgentRegistry] Failed to get file tree:",e)}const r=function(e){const t=[];return fy(e,t),t}(n);await Promise.all(r.map(e=>this.loadManifest(t,e)))}catch(e){console.error("[AgentRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n);if(!dy(r))return void console.warn(`[AgentRegistry] Not an IvyAgent manifest: ${t}`);const i=r,s=i.capability;if(!s||"object"!=typeof s||!("id"in s))return void console.warn(`[AgentRegistry] Missing capability.id in ${t}`);const o=t.lastIndexOf("/"),a=o>=0?t.slice(0,o):"";this.packages.set(s.id,{packageRoot:a,manifestPath:t,manifest:i})}catch(e){console.warn(`[AgentRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}unregister(e){return this.packages.delete(e)}clear(){this.packages.clear()}}function fy(e,t){for(const n of e)n.isDirectory?n.children&&fy(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let hy;function my(){return hy||(hy=new py),hy}const gy=new Set(["COMPLETED","FAILED","CANCELLED"]);function yy(e){return new Promise(t=>setTimeout(t,e))}async function wy(e,t,n){const r=Date.now()+n;let i=e.getRun(t);for(;Date.now()<r;){i=e.getRun(t);const n=i?.status;if(n&&(gy.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await yy(250)}return{record:i,timedOut:!0}}async function vy(e,t,n,r,i){const s=Date.now(),o=(e,t)=>({caseId:n.id,status:e.status,durationMs:Date.now()-s,...void 0!==t?{output:t}:{},...void 0!==e.error?{error:e.error}:{},...e.assertions?{assertions:e.assertions}:{}});let a;try{const r=await e.startRun({spec:t,workspaceId:i,input:n.input});if(a=r?.runId,!a)throw new Error("Engine did not return a runId")}catch(e){const t=e instanceof Error?e.message:String(e);return o(og(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await wy(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(og(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(og(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(sg(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(og(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}async function by(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway;if(!i?.call)throw new Error(`Capability gateway is not initialized — cannot test "${e}".`);const s=[];let o;try{const e=r.punica?.kernel?.Events?.manager?.subscribe?.("ivy.node.cell.failed",e=>{const t=e?.payload,n=t?.message??e?.message;"string"==typeof n&&n&&s.push(n)});o="function"==typeof e?e:e?.dispose?.bind(e)}catch{}try{return{output:await i.call(e,t??{},{sessionId:`test-${e}`,workspaceId:void 0,actor:{type:"system",id:"flow.test"},origin:{kind:"command",id:"flow.test.run"},trace:{traceId:`test-${e}-${Date.now()}`,spanId:"case"},policy:{},timeoutMs:n}),errorText:s.join(" ")}}finally{try{o?.()}catch{}}}const Iy={validator:{validate:Wm},registry:{discover:()=>Jm().discover(),get:e=>Jm().get(e),list:()=>Jm().list(),search:e=>Jm().search(e),setTestReport:(e,t)=>Jm().setTestReport(e,t),getLatestTestReport:e=>Jm().getLatestTestReport(e)},runner:{run:async function(e,t){const n=Date.now(),r=Jm().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=Wm(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(Vm(t.input))throw new Error('Input contains a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }). punica.ivy.runner.run executes a single node in isolation and cannot resolve references. Resolve inputs before calling runner, or execute inside the workflow engine.');const o=s.capability;if(!o||"object"!=typeof o||!("inputs"in o))throw new Error("Manifest missing capability.inputs");const a=o.inputs;if(!a.schema)throw new Error("Manifest missing capability.inputs.schema");const c=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Input must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required property: ${e}`)}return{valid:0===n.length,errors:n}}(t.input,a.schema);if(!c.valid)throw new Error(`Input validation failed: ${c.errors.join(", ")}`);if(!s.program)throw new Error("Manifest missing program");const l=s.program,u=l.cells,d=l.roles?.inputCellId,p=l.roles?.outputCellId;if(!d)throw new Error("Program missing roles.inputCellId");if(!p)throw new Error("Program missing roles.outputCellId");const 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||(s.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 i=Hm(r,e),s=r.id||`cell-${n}`,o=b(r,n),a=Date.now();let c,l="";v("ivy.node.cell.started",{runId:w,nodeId:e,cellId:s,index:n,label:o,startedAtMs:a});try{let e=null;for await(const n of k.run({id:s,language:y,code:i,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${E}:cell:${s}`})){g.push({type:n.type,data:n}),l+=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:s,index:n,label:o,durationMs:Date.now()-a,error:t instanceof Error?t.message:String(t),logs:l}),t}try{const e=await Qm(k,E,s,t.timeoutMs),n=eg(Zm(S,e));Object.keys(n).length&&(c=n),S=e}catch{}v("ivy.node.cell.finished",{runId:w,nodeId:e,cellId:s,index:n,label:o,durationMs:Date.now()-a,logs:l,...c?{variables:c}:{}})}const i=await async function(e,t,n,r){const i=JSON.stringify(t),s=`\nimport json\ntry:\n if '__ivy_ctx__' in globals() and isinstance(__ivy_ctx__, dict):\n if "nodes" in __ivy_ctx__ and ${i} in __ivy_ctx__["nodes"]:\n node_data = __ivy_ctx__["nodes"][${i}]\n if "output" in node_data:\n print(json.dumps(node_data["output"]))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\nexcept Exception as e:\n print(json.dumps({"error": str(e)}))\n`;for await(const t of e.run({id:"extract-output",language:"python",code:s,resources:r?{timeoutMs:r}:void 0},{runId:`${n}:extract-output`}))if("stdout"===t.type&&"text"in t){const e=t.text;try{const t=JSON.parse(e.trim());if(t&&"object"==typeof t)return t}catch(e){}}throw new Error("Failed to extract output from execution context")}(k,e,E,t.timeoutMs),s=o.outputs;if(!s?.schema)throw new Error("Manifest missing capability.outputs.schema");const a=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Output must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required output property: ${e}`)}return{valid:0===n.length,errors:n}}(i,s.schema);if(!a.valid)throw new Error(`Output validation failed: ${a.errors.join(", ")}`);return{output:i,events:g,durationMs:Date.now()-n}}finally{await k.close()}}},test:{run:async function(e,t){const n=Jm(),r=n.get(e);if(!r){if(t?.manifest){if(dy(t.manifest))return async function(e,t){const n=e,r=String(n?.capability?.id??n?.id??"");if(!r)throw new Error("Agent manifest has no capability id — cannot run tests.");const i=n?.tests;if(!i||!Array.isArray(i.cases)||!i.cases.length)throw new Error(`No test specification found for agent: ${r}`);const s=ly,o=uy(n),a=Date.now(),c=[];for(const e of i.cases){if(e.skip){c.push({caseId:e.id,status:"skip",durationMs:0,error:"string"==typeof e.skip?e.skip:void 0});continue}const n=e.timeoutMs??i.timeoutMs??3e4;c.push(await vy(s,o,e,n,t?.workspaceId))}const l=ag({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{Jm().setTestReport(r,l)}catch{}return l}(t.manifest);throw new Error(`Manifest for ${e} is not a testable IvyAgent (expected kind 'IvyAgent' with a graph).`)}throw new Error(`IvyNode not found: ${e}`)}const i=r.manifest,s=i.tests;if(!s)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of s.cases||[]){if(t.skip){a.push({caseId:t.id,status:"skip",durationMs:0,error:"string"==typeof t.skip?t.skip:void 0});continue}const n=Date.now();let r;try{const{output:i,errorText:o}=await by(e,t.input,s.timeoutMs||3e4),a=sg(t,i,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:i,assertions:a.assertions}}catch(e){const i=og(t,e instanceof Error?e.message:String(e));r={caseId:t.id,status:"error"===i.status?"fail":i.status,durationMs:Date.now()-n,error:i.error,assertions:i.assertions}}a.push(r)}const c=i.capability,l=ag({capabilityId:e,version:c&&"object"==typeof c&&"version"in c?String(c.version||"0.0.0"):"0.0.0",tier:s.tier,results:a,startedAtMs:o});return n.setTestReport(e,l),l}}},ky={discover:()=>my().discover(),get:e=>my().get(e),list:()=>my().list(),search:e=>my().search(e),unregister:e=>my().unregister(e),run:(e,t)=>async function(e,t){const n=my().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??ly,i=t?.timeoutMs??3e4,s=uy(n.manifest),o=Date.now(),a=await r.startRun({spec:s,workspaceId:t?.workspaceId,input:t?.input??{}}),c=a?.runId;if(!c)throw new Error(`Engine did not return a runId for agent ${e}`);const{record:l,timedOut:u}=await wy(r,c,i);if(u){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} did not complete in ${i}ms (status ${l?.status??"unknown"})`)}const d=l?.status;if("WAITING_APPROVAL"===d){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} requires approval — approve the workflow run or lower the capability's approval policy`)}if("COMPLETED"===d){let e;try{e=r.getNodeOutput(c,"flow-output")}catch{e=void 0}return{output:e,runId:c,durationMs:Date.now()-o}}const p=l?.steps?.find(e=>"FAILED"===e.status);throw new Error(`Agent ${e} failed: ${l?.error?.message??p?.error?.message??`Run ended with status ${d??"unknown"}`}`)}(e,t),envelope:uy,isAgentManifest:dy},Ey=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",[]]]),Sy=new Set(["COMPLETED","FAILED","CANCELLED"]);const Ay=new class{canTransitionTo(e,t){if(e===t)return!1;const n=Ey.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 Ey.get(e)??[]}isTerminal(e){return Sy.has(e)}},xy=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Cy={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Ty={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function Py(e){return{x:Ty.marginX+e%6*240,y:Ty.marginY+120*Math.floor(e/6)}}function Ny(e){const t=Math.max(0,e.inputCount??0),n=Math.max(0,e.outputCount??0),r=22*(t+n),i=t>0&&n>0?9:0;return 60+Math.max(56,16+r+i)}function My(e,t){const n={...Ty,...t??{}},r=e.nodes??[],i={};if(!r.length)return i;const s=new Map;r.forEach((e,t)=>s.set(e.id,t));const o=(e.edges??[]).filter(e=>e.source!==e.target&&s.has(e.source)&&s.has(e.target));if(1===r.length)return i[r[0].id]={x:n.marginX,y:n.marginY},i;const a=new Map,c=new Map;for(const e of r)a.set(e.id,[]),c.set(e.id,[]);for(const e of o)a.get(e.source).push(e.target),c.get(e.target).push(e.source);const l=new Map;for(const e of r)l.set(e.id,c.get(e.id).length);const u=r.filter(e=>0===l.get(e.id)).map(e=>e.id),d=[];for(;u.length;){const e=u.shift();d.push(e);for(const t of a.get(e)){const e=l.get(t)-1;l.set(t,e),0===e&&u.push(t)}}if(d.length<r.length)return r.forEach((e,t)=>{i[e.id]=Py(t)}),i;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)=>{i[e.id]=Py(t)}),i;const m=new Map;for(const e of d){if(!p(e))continue;const t=c.get(e),n=t.length?Math.max(...t.map(e=>m.get(e)??0))+1:0;m.set(e,n)}const g=Math.max(...Array.from(m.values())),y=Array.from({length:g+1},()=>[]);for(const e of 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,Ny(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 s=S-k(e)/2;for(const t of e)i[t]={x:r,y:s},s+=I.get(t)+n.verticalGap});const A=n.marginY+E+2*n.verticalGap;return f.forEach((e,t)=>{i[e.id]={x:n.marginX+t*(n.cardWidth+n.horizontalGap/2),y:A}}),i}let Ry;function $y(e){if(!Ry)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 Ry}function _y(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");Ry=e}function Oy(){Ry=void 0}function Ly(){return Ry}function jy(e){return $y("createFlowRenderer").createRenderer(e)}function Dy(e){return $y("createViewportController").createViewportController(e)}function Fy(e,t){return $y("attachZoomControl").attachZoomControl(e,t)}function qy(e,t){return $y("attachMinimap").attachMinimap(e,t)}function By(e,t){const n={...e,metadata:{...e.metadata??{}}},r=n.metadata,i=r.ivy=r.ivy?{...r.ivy}:{},s=i.view??{},o={x:t.viewport?.x??s.viewport?.x??0,y:t.viewport?.y??s.viewport?.y??0,zoom:t.viewport?.zoom??s.viewport?.zoom??1},a={...s.nodes??{}};return t.nodes.forEach(e=>{e&&e.id&&(a[e.id]={x:e.x,y:e.y})}),i.view={...s,viewport:o,nodes:a},n}var Uy={setRendererProvider:_y,resetRendererProvider:Oy,getRendererProvider:Ly,createFlowRenderer:jy,createViewportController:Dy,attachZoomControl:Fy,attachMinimap:qy,mergeViewSnapshotIntoNotebook:By,computeFlowLayout:My,gridFallbackPosition:Py,get rendererProvider(){return Ry}},Vy=Object.freeze({__proto__:null,attachMinimap:qy,attachZoomControl:Fy,computeFlowLayout:My,createFlowRenderer:jy,createViewportController:Dy,default:Uy,getRendererProvider:Ly,gridFallbackPosition:Py,mergeViewSnapshotIntoNotebook:By,resetRendererProvider:Oy,setRendererProvider:_y});function Wy(e,t,n){return{path:e,message:t,severity:"error",code:n}}function Ky(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const Gy="WF_INVALID_VERSION",Yy="WF_INVALID_EDGE_REF",zy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Jy(e){return"string"==typeof e&&zy.test(e)}const Hy=new class{#Ht=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.#Ht.set(e,t)}unregister(e){return this.#Ht.delete(e)}get(e){return this.#Ht.get(e)}list(){return Array.from(this.#Ht.keys())}clear(){this.#Ht.clear()}},Qy={id:"capability-not-declared",severity:"error",check(e,t){const n=t.hasCapability??(e=>!!t.getCapability?.(e));if(!t.hasCapability&&!t.getCapability)return[];const r=[];for(let t=0;t<e.graph.nodes.length;t++){const i=e.graph.nodes[t];if(i.disabled)continue;const s=i.ref;if("ivyNode"!==s.kind&&"workflow"!==s.kind)continue;const o=s.id;"string"==typeof o&&0!==o.length&&(n(o)||r.push({ruleId:"capability-not-declared",severity:"error",message:`Capability "${o}" is not declared in the unified registry — flow refs must exist in at least one origin (extension / instruction-class / ivy-node)`,path:`graph.nodes[${t}].ref.id`,nodeId:i.id,code:"WF_UNKNOWN_CAPABILITY"}))}return r}},Zy={id:"unreachable-node",severity:"warning",check(e){const t=[],n=e.graph.nodes.filter(e=>!e.disabled),r=new Set(n.map(e=>e.id)),i=e.graph.entryNodeId;if(!i||!r.has(i))return t;const s=new Map;for(const e of r)s.set(e,[]);for(const t of e.graph.edges)r.has(t.fromId)&&r.has(t.toId)&&s.get(t.fromId).push(t.toId);const o=new Set([i]),a=[i];for(;a.length>0;){const e=a.shift();for(const t of s.get(e)??[])o.has(t)||(o.add(t),a.push(t))}for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];r.disabled||(o.has(r.id)||t.push({ruleId:"unreachable-node",severity:"warning",message:`Node "${r.id}" is unreachable from entry node "${i}"`,path:`graph.nodes[${n}].id`,nodeId:r.id,code:"WF_UNREACHABLE_NODE"}))}return t}},Xy={id:"dep-cycle",severity:"error",check(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=new Map,i=new Map;for(const e of t)r.set(e.id,0),i.set(e.id,[]);for(const t of e.graph.edges)n.has(t.fromId)&&n.has(t.toId)&&(i.get(t.fromId).push(t.toId),r.set(t.toId,(r.get(t.toId)??0)+1));const s=[];for(const[e,t]of r.entries())0===t&&s.push(e);let o=0;const a=new Set;for(;s.length>0;){const e=s.shift();a.add(e),o++;for(const t of i.get(e)??[])r.set(t,(r.get(t)??0)-1),0===(r.get(t)??0)&&s.push(t)}if(o===t.length)return[];const c=[],l=[];for(const e of t)a.has(e.id)||l.push(e.id);return c.push({ruleId:"dep-cycle",severity:"error",message:`Workflow graph contains a cycle among enabled nodes: ${l.join(", ")}`,path:"graph.edges",code:"WF_CYCLE"}),c}},ew={id:"idempotency-required-but-no-key",severity:"error",check(e,t){if(!t.getCapability)return[];const n=[];for(let r=0;r<e.graph.nodes.length;r++){const i=e.graph.nodes[r];if(i.disabled)continue;if("ivyNode"!==i.ref.kind)continue;const s=i.ref.id;if("string"!=typeof s||0===s.length)continue;const o=t.getCapability(s);if(!o)continue;const a=o.defaults;if(!("required"===a?.execution?.idempotency))continue;const c=i.executionOverride;("none"===c?.idempotency||!0===i.data?.skipIdempotencyKey)&&n.push({ruleId:"idempotency-required-but-no-key",severity:"error",message:`Capability "${s}" declares idempotency: 'required' but node "${i.id}" opts out of key derivation — write/retry semantics will double-execute on a network retry`,path:`graph.nodes[${r}]`,nodeId:i.id,code:"WF_IDEMPOTENCY_REQUIRED"})}return n}};function tw(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function nw(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 rw={id:"schema-mismatch",severity:"warning",check(e,t){if(!t.getCapability)return[];const n=[],r=new Map(e.graph.nodes.map(e=>[e.id,e]));for(let i=0;i<e.graph.edges.length;i++){const s=e.graph.edges[i],o=r.get(s.fromId),a=r.get(s.toId);if(!o||!a)continue;if(o.disabled||a.disabled)continue;const c=tw(o.ref),l=tw(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=nw(p,s.fromPath),m=nw(f,s.toPath);h&&m&&(h.type&&m.type&&h.type!==m.type&&n.push({ruleId:"schema-mismatch",severity:"warning",message:`Edge ${s.fromId} → ${s.toId} type mismatch: upstream emits "${h.type}" but downstream expects "${m.type}"`,path:`graph.edges[${i}]`,code:"WF_SCHEMA_MISMATCH"}))}return n}},iw=["while","forEach"],sw={id:"infinite-loop",severity:"error",check(e){const t=[];for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];if(r.disabled)continue;if("primitive"!==r.ref.kind)continue;const i=r.ref.primitive;if(!iw.includes(i))continue;const s=r.data,o=s?.maxIterations;"number"==typeof o?o<=0&&t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" has maxIterations=${o} — loops with zero or negative caps never execute the body`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"}):t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" is missing maxIterations — substrate refuses to ship unbounded loops`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"})}return t}};function ow(e,t,n){let r=0;for(const i of e.graph.nodes){if(i.disabled)continue;if("workflow"!==i.ref.kind)continue;const e=i.ref,s=e.id??"<unnamed>";if(n.has(s))return t+1;if(!e.inline)continue;const o=new Set(n);o.add(s);const a=1+ow(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const aw={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=ow(e,n,new Set([i]));return s<=n||r.push({ruleId:"subflow-depth-exceeded",severity:"error",message:`Flow "${i}" has a statically-derivable inline subflow chain of depth ${s} — exceeds cap (${n}). Direct cycles count as depth > cap.`,path:"graph",code:"WF_SUBFLOW_DEPTH_EXCEEDED"}),r}},cw=[Qy,Zy,Xy,ew,rw,sw,aw];const lw=new class{#Re=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#Re.values())try{const i=t.check(e,r);i&&i.length>0&&n.push(...i)}catch(e){n.push({ruleId:t.id,severity:"info",message:`Lint rule "${t.id}" threw during analysis: ${String(e?.message??e)}`,code:"WF_LINT_RULE_ERROR"})}return{ok:!n.some(e=>"error"===e.severity),issues:n}}register(e){if(!e||"function"!=typeof e.check)throw new Error("FlowLinter.register: rule must have a check(spec, ctx) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("FlowLinter.register: rule.id must be a non-empty string");this.#Re.set(e.id,e)}unregister(e){return this.#Re.delete(e)}list(){return Array.from(this.#Re.keys())}reset(){this.#Re.clear();for(const e of cw)this.#Re.set(e.id,e)}};function uw(e,t,n){if(t===n)return[];const r=new Map;for(const t of e.values()){const e=r.get(t.from)??[];e.push(t),r.set(t.from,e)}const i=new Set([t]),s=new Map,o=[t];for(;o.length>0;){const e=o.shift();if(e===n)break;for(const t of r.get(e)??[])if(!i.has(t.to)){if(i.add(t.to),s.set(t.to,t),t.to===n){o.length=0;break}o.push(t.to)}}if(!i.has(n))return;const a=[];let c=n;for(;c!==t;){const e=s.get(c);if(!e)return;a.unshift(e),c=e.from}return a}function dw(e){return e.map(e=>`${e.from}=>${e.to}`)}function pw(e,t){return`${e}=>${t}`}const fw=new class{#Qt=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.#Qt.set(pw(e.from,e.to),e)}unregister(e,t){return this.#Qt.delete(pw(e,t))}find(e,t){return this.#Qt.get(pw(e,t))}list(){return Array.from(this.#Qt.values())}clear(){this.#Qt.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,i=e.targetVersion;if(!Jy(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(!Jy(i))return{ok:!1,reason:"invalid-result",message:`targetVersion "${String(i)}" is not a valid semver — substrate refuses to migrate to an unrecognized version.`,appliedTransformers:[]};if(r===i)return{ok:!0,document:e.document,appliedTransformers:[],fromVersion:r,toVersion:i};if("reject"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'reject'. Re-invoke with 'auto-migrate' to apply registered transformers.`,appliedTransformers:[]};if("warn"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'warn'. Substrate did not migrate; downstream consumers may see a stale IR.`,partialDocument:e.document,appliedTransformers:[]};const s=("function"==typeof t.__plan?t.__plan.bind(t):(e,n)=>uw(new Map(t.list().map(e=>[`${e.from}=>${e.to}`,e])),e,n))(r,i);if(!s||0===s.length)return{ok:!1,reason:"no-path",message:`No transformer chain from ${r} to ${i}. Register transformers via punica.flow.primitives.migrations.register(...).`,appliedTransformers:[]};let o=e.document;const a=[];for(const e of s)try{const t=e.transform(o);if(!t||"object"!=typeof t)return{ok:!1,reason:"invalid-result",message:`Transformer ${e.from}=>${e.to} returned a non-object — substrate refuses to thread an invalid document through the chain.`,partialDocument:o,appliedTransformers:dw(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:dw(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:dw(a)}}return{ok:!0,document:o,appliedTransformers:dw(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return uw(this.#Qt,e,t)}};function hw(){return Date.now()}class mw{#$e=new Map;#tt=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.#$e.set(e.id,n),this.#mt({type:"registered",triggerId:e.id,kind:e.kind,ts:hw()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#$e.get(e.id)===n&&(this.#$e.delete(e.id),this.#mt({type:"unregistered",triggerId:e.id,ts:hw()}))}}}unregister(e){const t=this.#$e.get(e);return!!t&&(t.unsubscribed=!0,this.#$e.delete(e),this.#mt({type:"unregistered",triggerId:e,ts:hw()}),!0)}list(){return Array.from(this.#$e.values()).map(e=>e.trigger)}subscribe(e){return this.#tt.add(e),()=>{this.#tt.delete(e)}}async fire(e,t){const n=this.#$e.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${hw()}-${Math.floor(1e6*Math.random())}`,i=hw();this.#mt({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),Og({name:"flow.trigger.fired",source:"flow:triggers",correlationId:r,payload:{triggerId:e,kind:n.trigger.kind,flowId:n.trigger.flowId,firedAtMs:i,payload:t??null}});try{return await n.callback({triggerId:e,firedAtMs:i,payload:t,correlationId:r}),!0}catch(t){return this.#mt({type:"error",triggerId:e,ts:hw(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#$e.values())e.unsubscribed=!0;this.#$e.clear(),this.#tt.clear()}#mt(e){for(const t of this.#tt)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const gw=new mw;let yw=gw;const ww={get manager(){return yw},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()");yw!==e&&yw instanceof mw&&yw.clear(),yw=e},resetProvider(){yw instanceof mw&&yw.clear(),yw=gw}};function vw(e,t){return`${e}=>${t}`}const bw={migrators:new class{#Zt=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.#Zt.set(vw(e.from,e.to),e)}unregister(e,t){return this.#Zt.delete(vw(e,t))}find(e,t){return this.#Zt.get(vw(e,t))}list(){return Array.from(this.#Zt.values())}clear(){this.#Zt.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}},Iw={...Iy,agents:ky,engine:{manager:ly,statusStateMachine:Ay,subscribeNodeStatuses:function(e,t){const n=new Set(e.nodeIds);let r=null;const i=(e,i,s)=>{const o=String(e??"");if(!o||!n.has(o))return;const a=String(i??"").toUpperCase(),c=Cy[a];if(!c)return;const l=s?String(s):null,u=null!==l&&l!==r;u&&(r=l),t({nodeId:o,status:c,runId:l,isNewRun:u,stepStatus:a})},s=e=>{const t=e?.payload?.payload??e?.payload??{};switch(e?.name){case"workflow.stepStarted":return i(t?.step?.stepId,t?.step?.status??"RUNNING",t?.runId);case"workflow.stepUpdated":return i(t?.stepId,t?.patch?.status,t?.runId);case"workflow.stepFinished":return i(t?.step?.stepId,t?.step?.status,t?.runId);default:return}};let o=null;try{o=punica.kernel.Events.manager.subscribeMany(xy,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:Vy,validateWorkflowDocument:function(e,t){const n=[],r=[],i=t?.mode??"best-effort",s=t?.hasCapability;if(!e||"ivy.workflow/v0.1"!==e.apiVersion)return n.push(Wy("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',Gy)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(Wy("kind",'kind must equal "Workflow"',Gy)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!Jy(o)){const e=Wy("version","version must be a semver string (major.minor.patch[-prerelease][+build]); got "+("string"==typeof o?`"${o}"`:typeof o),"WF_INVALID_SEMVER");"strict"===i?n.push(e):r.push({...e,severity:"warning"})}if(!e.graph||"object"!=typeof e.graph)return n.push(Wy("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(Wy("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(Wy("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(Wy(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(Wy(`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(Wy(`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(Wy(`graph.nodes[${t}].ref.id`,"ref.id is required for ivyNode/workflow refs")),"primitive"===r.kind){const e=["if","else","forEach","while","try","catch","finally","lambda"],i=r.primitive;"string"==typeof i&&e.includes(i)||n.push(Wy(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(Wy(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(Wy(`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(Wy("graph.nodes","flow-input node is required when edges reference it")),f&&!d&&n.push(Wy("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(Wy("graph.entryNodeId",`entryNodeId "${e.graph.entryNodeId}" must reference an existing node`,"WF_INVALID_ENTRY")),c.forEach((e,t)=>{const r=String(e?.fromId??""),i=String(e?.toId??"");r||n.push(Wy(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(Wy(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(Wy(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,Yy)),i&&!l.has(i)&&n.push(Wy(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,Yy))}),"strict"===i&&function(e,t,n){const r=e.filter(e=>!e.disabled),i=new Set(r.map(e=>e.id)),s=t.filter(e=>i.has(e.fromId)&&i.has(e.toId)),o=new Map,a=new Map;for(const e of r)o.set(e.id,0),a.set(e.id,[]);for(const e of s)a.get(e.fromId).push(e.toId),o.set(e.toId,(o.get(e.toId)??0)+1);const c=[];for(const[e,t]of o.entries())0===t&&c.push(e);let l=0;for(;c.length;){const e=c.shift();l++;for(const t of a.get(e)??[])o.set(t,(o.get(t)??0)-1),0===(o.get(t)??0)&&c.push(t)}l!==r.length&&n.push(Wy("edges","Workflow graph is not a DAG (cycle detected among enabled nodes).","WF_CYCLE"))}(a,c,n),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)&&function(e,t,n,r){const i=e.filter(e=>!e.disabled),s=new Set(i.map(e=>e.id));if(!s.has(n))return;const o=t.filter(e=>s.has(e.fromId)&&s.has(e.toId)),a=new Set,c=[n];for(a.add(n);c.length>0;){const e=c.shift();for(const t of o)t.fromId!==e||a.has(t.toId)||(a.add(t.toId),c.push(t.toId))}for(const t of i)if(!a.has(t.id)){const i=e.indexOf(t);r.push(Ky(`graph.nodes[${i}].id`,`Node "${t.id}" is unreachable from entry node "${n}"`,"WF_UNREACHABLE_NODE"))}}(a,c,e.graph.entryNodeId,r),s&&a.forEach((e,t)=>{if(e.disabled)return;const o=e.ref;if(!o||"ivyNode"!==o.kind&&"workflow"!==o.kind)return;const a=o.id;if("string"!=typeof a||0===a.length)return;if(s(a))return;("strict"===i?n:r).push(("strict"===i?Wy:Ky)(`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:Hy,linter:lw,migrations:fw,checkpoints:bw},triggers:ww};class kw{name=Gn.EXTENSIONS.MANAGER;version="1.0.0";dependencies=[Gn.KERNEL.COMMANDS,Gn.KERNEL.EVENTS,Gn.RUNTIME.WORKSPACE];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.COMMANDS),s=r.getState(Gn.KERNEL.EVENTS),o=r.getState(Gn.RUNTIME.WORKSPACE),a=r.getState(Gn.SHELL.LAYOUT);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(void 0!==a&&a!==e.BOOTSTRAPPED)throw new Error("shell.layout must be bootstrapped before extensions.manager");if(!n.extensions?.manager)throw new Error("Extensions manager not available")}async start(e){}}class Ew{name=Gn.FLOW.VALIDATOR;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}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 Sw(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 Aw{prepareExecutionConfig(e){const t=Sw(e);if(!t)return{};const n=fg(),r=n?.getSpec?.(t);return{capabilityDefaults:hg(r)}}async acquireResources(e,t,n){const r=Sw(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 qg.acquire(n,e.concurrency.max),()=>{qg.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=Sw(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=pg();if(!o)throw new Error("[FlowEngine] Capability gateway not available");const a=function(e,t){return`${e.attemptCorrelationId}::${t}`}(t,e.id),c=await o.call(i,s,{sessionId:t.workspaceId??"default",workspaceId:t.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:t.traceId},trace:{traceId:t.traceId,parentSpanId:t.rootSpanId},policy:{mode:"execute"}},a),l=fg(),u=l?.getSpec?.(i),d=u?.defaults?.dataClassification,p=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`${i}.result`,payload:c,meta:{source:"capability.call",capabilityId:i},redactionPolicy:e.redactionPolicy,surface:"output",capabilityClassification:d,sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:ug(lg(c??{},0),320),artifactIds:[p.id],output:c??null}}}function xw(e){return e.data??{}}function Cw(e){return e.nodeOutputs??new Map}async function Tw(e,t,n,r,i){const s=await e.artifactStore.writeArtifact(t.traceId,n.id,{type:"json",name:`primitive.${r}.decision`,payload:i,meta:{source:"primitive",primitive:r},redactionPolicy:n.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:ug(lg(i,0),320),artifactIds:[s.id]}}class Pw{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=xw(e),i=Kg(r.predicate,Cw(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:Gg(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Tw(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Tw(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=xw(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:forEach] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:forEach] bodyFlowId is required on node "${e.id}"`);const i=Kg(r.collection,Cw(t));if(!i.ok&&"missing-node"!==i.reason)throw new Error(`[primitive:forEach] collection did not resolve (${i.reason}) on node "${e.id}"`);const s=i.ok?i.value:null,o=Array.isArray(s)?s:[],a=o.length>r.maxIterations,c=Math.min(o.length,r.maxIterations),l={bodyFlowId:r.bodyFlowId,itemBinding:r.itemBinding??"item",maxIterations:r.maxIterations,plannedIterations:c,sourceLength:o.length,truncated:a};return{...await Tw(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=xw(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:while] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:while] bodyFlowId is required on node "${e.id}"`);const i=Kg(r.predicate,Cw(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=Gg(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Tw(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=xw(e);if(!r.tryBodyFlowId)throw new Error(`[primitive:try] tryBodyFlowId is required on node "${e.id}"`);const i={tryBodyFlowId:r.tryBodyFlowId,catchBodyFlowId:r.catchBodyFlowId??null,finallyBodyFlowId:r.finallyBodyFlowId??null};return{...await Tw(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Tw(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Tw(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=xw(e),i=r.lambdaId??"";if("string"!=typeof i||0===i.length)throw new Error(`[primitive:lambda] lambdaId is required on node "${e.id}"`);const s=Hy.get(i);if(!s)throw new Error(`[primitive:lambda] lambdaId "${i}" is not registered (node "${e.id}")`);let o=null;if(void 0!==r.input){const n=Kg(r.input,Cw(t));if(!n.ok)throw new Error(`[primitive:lambda] input did not resolve (${n.reason}) on node "${e.id}"`);o=n.value}const a=await s(o,{nodeId:e.id,attemptCorrelationId:t.attemptCorrelationId,traceId:t.traceId}),c=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`primitive.lambda.${i}.result`,payload:a,meta:{source:"primitive",primitive:"lambda",lambdaId:i},redactionPolicy:e.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:ug(lg(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 Nw{async execute(e,t){return{output:t.runInput??null}}}class Mw{async execute(e,t){return{output:t.resolvedInput??null}}}let Rw=!1;class $w{name=Gn.FLOW.ENGINE;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.KERNEL.POLICY,Gn.KERNEL.COMMANDS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.EVENTS),s=r.getState(Gn.KERNEL.POLICY),o=r.getState(Gn.KERNEL.COMMANDS);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(Rw||(Vg.register("ivyNode",new Aw),Vg.register("primitive",new Pw),Vg.register("flowInput",new Nw),Vg.register("flowOutput",new Mw),Rw=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class _w{name=Gn.FLOW.SHELL;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before shell.flow");if(!n.flow?.shell)throw new Error("Flow shell API not available")}async start(e){}}class Ow{name=Gn.KERNEL.EVENTS;version="1.0.0";dependencies=[];#je=e.CREATED;#l=null;get state(){return this.#je}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 Lw{name=Gn.KERNEL.COMMANDS;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class jw{name=Gn.KERNEL.POLICY;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.policy");if(!n.kernel?.Policy?.manager)throw new Error("Policy manager not available")}async start(e){}}class Dw{name=Gn.KERNEL.HISTORY;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class Fw{name=Gn.KERNEL.TIME_SERVER;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class qw{name=Gn.KERNEL.TASKS;version="1.0.0";dependencies=[Gn.RUNTIME.TERMINALS,Gn.RUNTIME.WORKSPACE];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.RUNTIME.TERMINALS),s=r.getState(Gn.RUNTIME.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before kernel.tasks");if(!n.kernel?.Tasks)throw new Error("Tasks API not available")}async start(e){}}class Bw{name=Gn.KERNEL.NOTIFICATIONS;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class Uw{name=Gn.KERNEL.AI;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.KERNEL.POLICY,Gn.KERNEL.LLM];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.EVENTS),s=r.getState(Gn.KERNEL.POLICY),o=r.getState(Gn.KERNEL.LLM);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.llm must be bootstrapped before kernel.ai");if(!n.kernel?.AI?.manager?.initialize)throw new Error("AI manager not available");n.kernel.AI.manager.initialize()}async start(e){}}let Vw=class{name=Gn.KERNEL.LLM;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.KERNEL.POLICY];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.EVENTS),s=r.getState(Gn.KERNEL.POLICY);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.llm");if(!n.kernel?.llm?.manager)throw new Error("LLM manager not available");const o=n;if(o.kernel||(o.kernel={}),o.kernel.llm||(o.kernel.llm={}),!Object.prototype.hasOwnProperty.call(o.kernel.llm,"CodegenBundleV0_1Schema"))try{Object.defineProperty(o.kernel.llm,"CodegenBundleV0_1Schema",{value:yi,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class Ww{name=Gn.RUNTIME.FS;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class Kw{name=Gn.RUNTIME.SEARCH;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.search");if(!n.runtime?.search)throw new Error("Search facade not available")}async start(e){}}class Gw{name=Gn.RUNTIME.VCS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.vcs");if(!n.runtime?.vcs)throw new Error("VCS facade not available")}async start(e){}}class Yw{name=Gn.RUNTIME.WORKSPACE;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.workspace");if(!n.runtime?.workspace)throw new Error("Workspace facade not available")}async start(e){}}class zw{name=Gn.RUNTIME.LLM;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.llm");if(!n.runtime?.llm)throw new Error("LLM facade not available")}async start(e){}}class Jw{name=Gn.RUNTIME.TASKS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.tasks");if(!n.runtime?.tasks)throw new Error("Tasks facade not available")}async start(e){}}class Hw{name=Gn.RUNTIME.SECRETS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.secrets");if(!n.runtime?.secrets)throw new Error("Secrets API not available")}async start(e){}}class Qw{name=Gn.RUNTIME.TERMINALS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.terminals");if(!n.runtime?.terminals)throw new Error("Terminals facade not available")}async start(e){}}const Zw=".punica/policy.yaml",Xw=void 0;async function ev(){const e=function(){const e=globalThis;return e.punica?.runtime?.fs}(),t=e?.readFile;if("function"!=typeof t)return;if("function"==typeof e?.exists)try{if(!await e.exists(Zw))return}catch{}let n;try{n=await t(Zw,{encoding:"utf8"})}catch{return}if("string"!=typeof n||""===n.trim())return;const{parse:r}=await Promise.resolve().then(function(){return rm});return r(n)}function tv(e){for(const t of e.problems){const e=t.path?` at ${t.path}`:"";console.warn(`[Punica] ${Zw}${e}: ${t.message}`)}try{se.publishEvent({name:e.problems.length>0?"policy.rulesRejected":"policy.rulesLoaded",envelope:{id:se.createCorrelationId(),timestampMs:Date.now(),source:"runtime:policy:rules",kind:e.problems.length>0?"warn":"info"},payload:{file:Zw,present:e.present,installed:e.installed.map(e=>({name:e.name,rules:e.rules.length,digest:e.digest})),retired:e.retired,problems:e.problems}})}catch{}}async function nv(){const e={installed:[],retired:[],problems:[],present:!1};let t;try{t=await ev()}catch(t){return e.problems.push({path:"",message:`could not be parsed: ${t?.message??String(t)}`}),e.present=!0,e.retired=rv(new Set),tv(e),e}e.present=void 0!==t;const{templates:n,problems:r}=tt(t??{});e.problems=r;const i=new Set;for(const t of n){const n=await Oe(t.rules);vt.saveTemplate(t.name,{...t,source:"file",digest:n},Xw),i.add(t.name),e.installed.push({...t,source:"file",digest:n})}return e.retired=rv(i),tv(e),e}function rv(e){const t=[];for(const n of vt.listTemplates(Xw))"file"===n.source&&(e.has(n.name)||vt.deleteTemplate(n.name,Xw)&&t.push(n.name));return t}class iv{name=Gn.RUNTIME.POLICY_RULES;version="1.0.0";dependencies=[Gn.KERNEL.POLICY,Gn.RUNTIME.FS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){this.#je=e.BOOTSTRAPPING;try{await nv()}catch(e){console.warn("[Punica] Policy rules could not be loaded:",e?.message??e)}this.#je=e.BOOTSTRAPPED}async start(t){this.#je=e.STARTING;try{punica.kernel.Commands.manager.registerCommand("policy.rules.reload",{title:"Policy: reload workspace rules",execute:async()=>await nv()})}catch(e){console.warn("[Punica] policy.rules.reload could not be registered:",e?.message??e)}this.#je=e.STARTED}}function sv(){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 ov(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 av(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 cv(e,n,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await t(),actor:{type:"user",id:ye()},origin:{kind:n,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function lv(){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=sv();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");ov("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await cv("workspace.readFile","command",t))})}catch(e){av("capability.workspace.readFile.error",t,{error:String(e?.message??e)})}}}),e("workspace.writeFile",{title:"Core: workspace.writeFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=String(e?.content??""),i=sv();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await cv("workspace.writeFile","command",t)),ov("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){av("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();ov("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){av("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{ov("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await cv("vcs.status","command",t))})}catch(e){av("capability.vcs.status.error",t,{error:String(e?.message??e)})}}}),e("tasks.runCommand",{title:"Core: tasks.runCommand",execute:async(e,t)=>{try{const n=String(e?.command??""),r=Array.isArray(e?.args)?e.args.map(String):[],i=null!=e?.cwd?String(e.cwd):void 0,s=e?.env&&"object"==typeof e.env?e.env:void 0;ov("capability.tasks.runCommand.result",t,{command:n,args:r,cwd:i,...await punica.runtime.capabilities.gateway.call("tasks.runCommand",{command:n,args:r,cwd:i,env:s},await cv("tasks.runCommand","command",t))})}catch(e){av("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?ov("capability.llm.invoke.result",t,r):av(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return av(n,t,i),i}}}),e("llm.plan",{title:"Core: llm.plan",execute:async(e,t)=>{const n="capability.llm.plan.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.plan(e);r.ok?ov("capability.llm.plan.result",t,r):av(n,t,r)}catch(e){av(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"planner",role:"planner"}})}}}),e("llm.generate-code",{title:"Core: llm.generate-code",execute:async(e,t)=>{const n="capability.llm.generate-code.result",r="capability.llm.generate-code.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const i=await punica.kernel.llm.manager.api.generateCode(e);if(i.ok)if(i.structured&&"object"==typeof i.structured){const e=i.structured;if("0.1"===e.specVersion&&Array.isArray(e.files)){const r=await(punica.runtime.workspace?.getCurrent?.());if(!r?.rootUri)throw new Error("No active workspace");const s=r.rootUri.replace(/^file:\/\//,""),o=punica.shell?.View?.showChangesPreview;if("function"!=typeof o)throw new Error("UnsupportedError: shell.View.showChangesPreview is not available (headless substrate — no shell contribution)");ov(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 gi(e,s);if(t.errors.length>0)throw new Error(`Failed to apply some files:\n${t.errors.map(e=>`${e.path}: ${e.error}`).join("\n")}`)}})?{...i,metadata:{...i.metadata,applied:!0}}:{...i,metadata:{...i.metadata,applied:!1,cancelled:!0}})}else ov(n,t,i)}else ov(n,t,i);else av(r,t,i)}catch(e){av(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?ov("capability.llm.edit-workflow.result",t,r):av(n,t,r)}catch(e){av(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 cv("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(Yn.SHELL.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(Yn.SHELL.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(Yn.SHELL.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const uv="1.0.0",dv=bi,pv={},fv=Id,hv=Um,mv=Iw,gv=new class{#Xt=new Map;#en=new Map;#tn=new Map;register(t){if(this.#Xt.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#Xt.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#Xt.set(t.name,t),this.#en.set(t.name,e.CREATED)}get(e){return this.#Xt.get(e)}getAll(){return Array.from(this.#Xt.values())}resolveBootstrapOrder(){return this.#nn()}resolveStartOrder(){return this.#nn()}#nn(){const e=new Set,t=new Set,n=[],r=i=>{if(t.has(i)){const e=Array.from(t).concat(i);throw new Error(`Circular dependency detected: ${e.join(" → ")}`)}if(e.has(i))return;t.add(i);const s=this.#Xt.get(i);if(!s)throw new Error(`Module ${i} not found`);for(const e of s.dependencies)r(e);t.delete(i),e.add(i),n.push(i)};for(const t of this.#Xt.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.#Xt.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#en.set(n,e.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#en.set(n,e.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#en.set(n,e.BOOTSTRAP_FAILED),this.#tn.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.#Xt.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#en.get(n);if(r!==e.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#en.set(n,e.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#en.set(n,e.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#en.set(n,e.START_FAILED),this.#tn.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} start failed:`,r),new Error(`Critical module ${n} failed to start: ${r.message}`)}}for(const n of t){this.#en.get(n)===e.STARTED&&this.#en.set(n,e.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#en.get(e)}areAllModulesReady(){for(const[t,n]of this.#Xt){if(this.#en.get(t)!==e.READY)return!1}return!0}getError(e){return this.#tn.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#Xt.keys())t.includes(n)&&e.push(n);return e}};function yv(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:uv,kernel:dv,shell:pv,runtime:fv,extensions:hv,flow:mv};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=Nt;const t=e.debug??{};t.logTrinityCatalog=_u,t.logTrinityCatalogVerbose=Ou,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=_u,n.logTrinityCatalogVerbose=Ou);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{lv(),console.log("[Punica] Core commands registered")}catch(e){console.error("[Punica] Failed to register core commands:",e?.message??e,e?.stack)}console.log("[Punica] Initialization completed successfully")}catch(e){throw console.error("[Punica] CRITICAL: Initialization failed:",e?.message??e,e?.stack),e}}async function wv(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 Pt)t.facade&&Object.assign(e,t.facade);return e}()));const n=Gt.manager;for(const e of function(){const e=[];for(const t of Pt)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 Pt)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(gv.register(new Ow),gv.register(new Lw),gv.register(new Dw),gv.register(new Fw),gv.register(new Bw),gv.register(new Ew),gv.register(new jw),gv.register(new Vw),gv.register(new Uw),gv.register(new $w),gv.register(new Ww),gv.register(new Kw),gv.register(new Gw),gv.register(new Yw),gv.register(new zw),gv.register(new Hw),gv.register(new Qw),gv.register(new Jw),gv.register(new nd),gv.register(new iv),gv.register(new qw),r){const e=Mt(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(gv.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}gv.register(new kw),console.log(`[Punica] Module registry initialized with ${gv.getAll().length} modules`),await gv.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}}async function vv(){try{console.log("[Punica] Starting system..."),await gv.startAll(),gv.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:uv}}),console.log("[Punica] System started successfully"),_u()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}}Nt({moduleFactories:{"flow.shell":()=>new _w}});var bv=Object.freeze({__proto__:null,StdioTransport:class{#rn;#in;#sn;#on=null;#an=null;#cn=null;#ln=null;#un=null;#dn=new Map;#pn=1;#fn="";constructor(e,t=[],n={}){this.#rn=e,this.#in=t,this.#sn=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#hn(e):await this.#mn()}async#hn(e){this.#cn=e;const{sessionId:t}=await e.spawn({command:this.#rn,args:this.#in,env:this.#sn});this.#an=t,this.#ln=e.onData(e=>{e.sessionId===t&&this.#gn(e.chunk)}),this.#un=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.#dn.values())e(n);this.#dn.clear()})}async#mn(){const e=await import(
2
- /* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#on=e.spawn(this.#rn,this.#in,{env:{...n,...this.#sn},stdio:["pipe","pipe","inherit"]}),this.#on.stdout.setEncoding("utf8"),this.#on.stdout.on("data",e=>{this.#gn(e)}),this.#on.on("error",e=>{for(const{reject:t}of this.#dn.values())t(e);this.#dn.clear()})}#gn(e){let t;for(this.#fn+=e;-1!==(t=this.#fn.indexOf("\n"));){const e=this.#fn.slice(0,t).trim();this.#fn=this.#fn.slice(t+1),e&&this.#yn(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#wn(n)}async request(e,t={}){const n=this.#pn++;return new Promise((r,i)=>{this.#dn.set(n,{resolve:r,reject:i});const s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#wn(s)}catch(e){this.#dn.delete(n),i(e instanceof Error?e:new Error(String(e)))}})}#wn(e){if(this.#cn&&this.#an)this.#cn.write(this.#an,e);else{if(!this.#on?.stdin)throw new Error("MCP stdio transport is not connected");this.#on.stdin.write(e)}}close(){this.#ln?.(),this.#un?.(),this.#ln=null,this.#un=null,this.#cn&&this.#an&&this.#cn.close(this.#an),this.#on?.kill(),this.#on=null,this.#an=null,this.#cn=null;for(const{reject:e}of this.#dn.values())e(new Error("MCP stdio transport closed"));this.#dn.clear()}#yn(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#dn.get(t.id);n&&(this.#dn.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var Iv=Object.freeze({__proto__:null,StreamableHttpTransport:class{#vn;#bn;#pn=1;#an;constructor(e,t={}){this.#vn=e.replace(/\/$/,""),this.#bn=t}async connect(){const e=await fetch(`${this.#vn}/sse`,{headers:{...this.#bn,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#an=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#In({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#pn++,r=await this.#In({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#In(e){const t={...this.#bn,"Content-Type":"application/json",Accept:"application/json"};this.#an&&(t["mcp-session-id"]=this.#an);const n=await fetch(`${this.#vn}/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.#an=void 0}}});var kv=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return ed(em(e))}});export{Yn as COMMAND_IDS,Gn as MODULE_NAMES,e as ModuleLifecycleState,Gt as Profile,gm as STRUCTURAL_SLOTS_BY_MODULE,R as WORKSPACE_STATE_GITIGNORE,wv as bootstrap,na as defaultAgentPolicyProfile,Wt as emitShellEvent,xm as enterHeadlessScope,Cm as exitHeadlessScope,hv as extensions,mv as flow,ia as getAgentPolicyProfile,Vt as getProfileValidator,yv as initialize,re as isEventPersistenceEnabled,Tm as isHeadlessScope,dm as isMacPlatform,dv as kernel,pm as parseKeyChord,vm as presentedSlots,bm as profilePresentsSlot,Nt as registerShell,Pm as runInHeadlessScope,fv as runtime,sa as setAgentPolicyProfile,ne as setEventPersistence,Ut as setProfileValidator,pv as shell,Hs as sideEffectArrayToEnum,vv as start,uv as version};
1
+ var e;!function(e){e.CREATED="created",e.BOOTSTRAPPING="bootstrapping",e.BOOTSTRAPPED="bootstrapped",e.BOOTSTRAP_FAILED="bootstrap_failed",e.STARTING="starting",e.STARTED="started",e.START_FAILED="start_failed",e.READY="ready"}(e||(e={}));async function t(){try{const e=punica.runtime?.workspace;if(!e)return;const t=await e.getCurrent();return t?.id}catch(e){return void console.warn("[hostAccess] Failed to get current workspace id:",e)}}function n(){return!!punica.runtime?.workspace}function r(){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>=12&&(t=t.split(n).join("[REDACTED]"))}}}catch{}return t}function s(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 o=["password","passwd","secret","token","apikey","authorization","creditcard","cardnumber","cvv","cvc","privatekey"];function a(e){const t=function(e){return e.toLowerCase().replace(/[_\-\s]/g,"")}(e);return"pwd"===t||o.some(e=>t===e||t.endsWith(e)||t.startsWith(e))}function c(e){const t=new WeakSet;return function e(n){if(null===n||"object"!=typeof n)return n;if(t.has(n))return"[Circular]";if(t.add(n),Array.isArray(n))return n.map(e);const r={};for(const[t,i]of Object.entries(n))a(t)?r[t]=null==i?i:"[REDACTED]":r[t]=e(i);return r}(e)}function l(e,t=2){const n=c(e);return s(JSON.stringify(n,null,t))}function u(e){return d(e,"sensitive")}function d(e,t){return p(e,t).filter(e=>!0===e.value).map(e=>e.path)}function p(e,t){const n=[],r=new Set;function i(e,i){if(!e||"object"!=typeof e)return;const o=e;if(t in o){const e=i.join(" ");r.has(e)||(r.add(e),n.push({path:i,value:o[t]}))}s(o,i)}function s(e,t){if(!e||"object"!=typeof e)return;const n=e,r=n.properties;if(r&&"object"==typeof r)for(const[e,n]of Object.entries(r))i(n,[...t,e]);const o=n.items;if(o&&"object"==typeof o)if(Array.isArray(o))for(const e of o)i(e,[...t,"*"]);else i(o,[...t,"*"]);for(const e of["anyOf","oneOf","allOf"]){const r=n[e];if(Array.isArray(r))for(const e of r)s(e,t)}}return s(e,[]),n}function f(e,t){if(0===t.length)return e;return function e(t,n){if(null===t||"object"!=typeof t)return t;if(0===n.length)return t;if(Array.isArray(t)){const r=[];let i=!1;for(const e of n)"*"===e[0]&&(1===e.length?i=!0:r.push(e.slice(1)));return i&&0===r.length?t.map(e=>null==e?e:"[REDACTED]"):t.map(t=>e(t,r))}const r={};for(const[i,s]of Object.entries(t)){const t=[];let o=!1;for(const e of n)e[0]===i&&(1===e.length?o=!0:t.push(e.slice(1)));o?r[i]=null==s?s:"[REDACTED]":t.length>0?r[i]=e(s,t):r[i]=s}return r}(e,t)}const h=/^(?:secrets|secret-manager)\./,m=new Set(["value"]);const g={manager:new class{#e=new Map;#t=new Map;registerCommand(e,t){const n={dispose:()=>{this.#e.delete(e),this.#t.delete(e)}};t.disposable=n,this.#t.set(e,n),this.#e.set(e,t)}executeCommand(e,...t){const n=this.#e.get(e);if(!n){const n=punica.extensions?.manager;if(!n)return void console.error(`[Commands] Command ${e} not found (extension manager unavailable)`);const r=n.getExtensionsForCommand(e);if(0===r.length)return void console.error(`[Commands] Command ${e} not found`);const i=r[0];return n.activate(i,{reason:"command",trigger:e}).then(()=>{const n=this.#e.get(e);return n?(console.log("[Commands] execute after activate",e,"via extension",i),n.execute(...t)):void console.error(`Command ${e} not found after activating extension "${i}"`)}).catch(t=>{console.error(`Error activating extension "${i}" for command ${e}:`,t)})}console.log("[Commands] execute",e,"with args",function(e,t){const n=h.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]=m.has(n)?"[REDACTED]":r;return c(t)}return c(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 y=new class{async write(e){try{const t=r();if(!t)return;const n=".punica/audit";await t.createFolder(n).catch(()=>{});const i=new Date(e.timestamp).toISOString().split("T")[0],s=`${n}/${`${i}_${e.invocationId}.json`}`;await t.createFileWithContent(s,JSON.stringify(e,null,2))}catch(e){console.warn("[AuditWriter] Failed to write audit record:",e)}}async read(e){try{const t=r();if(!t)return[];const n=".punica/audit",i=await t.getFileTree(),s=(e,t)=>{const n=[];for(const r of e)(r.path.startsWith(t+"/")||r.path===t)&&(r.isDirectory||n.push(r),r.isDirectory&&r.children&&n.push(...s(r.children,t)));return n},o=s(i,n),a=[];for(const n of o)if(n.name.endsWith(".json"))try{const r=await t.readFile(n.path),i=JSON.parse(r);if(e?.since&&i.timestamp<e.since)continue;if(e?.until&&i.timestamp>e.until)continue;if(e?.capability&&i.capability!==e.capability)continue;if(e?.workspaceId&&i.workspace!==e.workspaceId)continue;a.push(i)}catch(e){console.warn(`[AuditWriter] Failed to read audit file ${n.name}:`,e)}return a.sort((e,t)=>t.timestamp-e.timestamp),a}catch(e){return console.warn("[AuditWriter] Failed to read audit records:",e),[]}}};const w={manager:new class{#n=new Map;#r=[];#i=[];registerCommand(e){this.#n.set(e.id,e)}executeCommand(e){const t=this.#n.get(e);t?(t.execute(),this.#r.push(t),this.#i=[]):console.error(`Command with ID ${e} not found.`)}undo(){const e=this.#r.pop();e?(e.undo(),this.#i.push(e)):console.error("No command to undo.")}redo(){const e=this.#i.pop();e?(e.execute(),this.#r.push(e)):console.error("No command to redo.")}},auditWriter:y};const v={manager:new class{#s=[];#o=null;#a(){null===this.#o&&(this.#o=window.setInterval(()=>{const e=new Date;this.#s.forEach(t=>t.update(e))},1e3))}#c(){null!==this.#o&&(window.clearInterval(this.#o),this.#o=null)}subscribe(e){this.#s.push(e),1==this.#s.length&&this.#a()}unsubscribe(e){this.#s=this.#s.filter(t=>t!==e),0==this.#s.length&&this.#c()}}};function b(){return(new Date).toISOString()}function I(e,t){const n=new Map,r=new Map,i=new Set;function s(e){for(const t of i)try{t(e)}catch{}try{const t=window,n=t.punica?.Commands?.manager,r=t.punica?.runtime,i="failed"===e.status?"error":"cancelled"===e.status?"warning":"info";let s=`[${e.label}] ${e.status}`;null!=e.exitCode&&(s+=` (exitCode=${e.exitCode})`),n&&n.executeCommand("output.append",{channel:"Tasks",text:s,level:i}),r?.events?.publish("tasks.runChanged",{run:e}),!r?.notifications||"failed"!==e.status&&"success"!==e.status||r.notifications.push({id:"",level:"failed"===e.status?"error":"success",title:e.label,message:s,timestamp:"",source:"tasks",actionCommandId:"tasks.open"})}catch{}}const o={listDefinitions:async()=>Array.from(n.values()),registerDefinition(e){n.set(e.id,e)},unregisterDefinition(e){n.delete(e)},async run(i,a){const c=n.get(i);if(!c)throw new Error(`[Runtime.tasks] Task definition not found: ${i}`);const l=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`task_${Date.now()}_${Math.floor(1e6*Math.random())}`}(),u=b(),{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 i=n??r.currentEnvironmentId,s=r.environments.find(e=>e.id===i),o={...s?.variables??{},...e??{}};return{env:Object.keys(o).length?o:void 0,workspaceId:r.id,resolvedEnvironmentId:s?.id}}catch{return{env:e}}}(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),s(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:b(),exitCode:e??null};r.set(l,n),s(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 i={...n,status:"cancelled",finishedAt:b()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const k=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=I(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 E={manager:k},S=Object.freeze({__proto__:null,createTasksApi:I,default:E,manager:k});const A=7776e6,x={rules:[],defaultTtlMs:A};function C(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 T(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(C(e,i.pattern)){const e=i.pattern.length;e>r&&(n=i,r=e)}return n}(e,t.rules??[]);return n-(r?.ttlMs??t.defaultTtlMs??A)}function _(e){return new Date(e).toISOString().slice(0,10)}function P(e,t,n){const r=function(e){const t=e.slice(e.lastIndexOf("/")+1),n=/^(\d{4}-\d{2}-\d{2})_/.exec(t);return n?n[1]:null}(e);return r?r>_(n-t.shortestTtlMs)?"keep":r<_(n-t.longestTtlMs)?"expire":"unknown":"unknown"}const N=".punica/.gitignore",$="# 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# Governance, and the whole reason it is a file. A policy that lives in the\n# commit is one that shows up in a diff and gets argued about in review — the\n# claim the argument-level policy engine and the policy export are both built\n# on. It was ignored here, so in a fresh workspace it was reviewable by nobody.\n# serve.yaml is its pair: what this project exposes to a remote caller.\n!/policy.yaml\n!/serve.yaml\n\n# Authored process definitions. The same case as mlops.yaml below — a person\n# writes them, presses Save, and a teammate cloning the project needs them or\n# gets no process at all.\n!/llmops.yaml\n!/evals.yaml\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 M(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.startsWith("!"))}async function R(){const e=r();if(e&&(!n()||await t()))try{if(!!e.exists&&await e.exists(N)){const t=function(e){if(!e.includes("# Punica editor — workspace internal state."))return null;const t=new Set(M(e)),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(N)??"");return void(t&&e.updateFileContent&&await e.updateFileContent(N,t))}try{await e.createFolder(".punica")}catch{}await e.createFileWithContent(N,$)}catch{}}const O=".punica/events";let L={};function j(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(O)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function D(e){const t=e.split("/").pop()??"";return t.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]}function F(e){return new Date(e).toISOString().split("T")[0]}function B(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.traceId&&n?.traceId!==t.traceId)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 q=new class{#d;#p=!1;#f=!1;constructor(e){this.#d=e?.maxDiskEvents??1e4}async write(e){const i=r();if(!i)return;if(n()&&!await t())return;const s=Date.now();try{await i.createFolder(O)}catch{}if(!this.#p){this.#p=!0;try{await i.createFileWithContent(`${O}/.gitignore`,"*\n!.gitignore\n")}catch{}}this.#f||(this.#f=!0,await R());for(const t of e)try{const e=t.envelope?.timestampMs??Date.now(),n=new Date(e).toISOString().split("T")[0],r=t.envelope?.id??`evt_${e}_${Math.random().toString(16).slice(2)}`,s=`${O}/${n}_${r}.json`,o=l(t);await i.createFileWithContent(s,o)}catch{}try{L.onWrite?.(Date.now()-s,e.length)}catch{}}async query(e){const t=r();if(!t)return[];let n;try{n=await t.getFileTree()}catch{return[]}if(!Array.isArray(n))return[];const i=void 0!==e?.since?F(e.since):void 0,s=void 0!==e?.until?F(e.until):void 0,o=new Map;for(const e of j(n)){const t=D(e);if(t){if(void 0!==i&&t<i)continue;if(void 0!==s&&t>s)continue}const n=t??"",r=o.get(n);r?r.push(e):o.set(n,[e])}const a=[...o.keys()].sort((e,t)=>t.localeCompare(e)),c=e?.limit&&e.limit>0?e.limit:void 0,l=[];for(const n of a){for(const r of o.get(n))try{const n=await t.readFile(r),i=JSON.parse(n);B(i,e)&&l.push(i)}catch{}if(void 0!==c&&l.length>=c)break}return l.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),void 0!==c?l.slice(-c):l}async delete(e){const t=r();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const i=j(n);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(B(JSON.parse(r),e))await t.deleteFile(n),s++;else{const e=n.split("/").pop()??"",t=e.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]??"";o.push({path:n,dateKey:t})}}catch{}if(o.length>this.#d){o.sort((e,t)=>e.dateKey.localeCompare(t.dateKey));const e=o.length-this.#d;for(const n of o.slice(0,e))try{await t.deleteFile(n.path),s++}catch{}}return s}async#h(e,t){const n=[];for(const e of t){const t=D(e);t&&n.push({path:e,day:t})}if(n.length<=this.#d)return 0;n.sort((e,t)=>e.day.localeCompare(t.day));let r=0;for(const t of n.slice(0,n.length-this.#d))try{await e.deleteFile(t.path),r++}catch{}return r}async applyRetention(e,t=Date.now()){const n=r();if(!n)return 0;let i;try{i=await n.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=j(i),o=function(e){const t=e.defaultTtlMs??A;let n=t,r=t;for(const t of e.rules??[])Number.isFinite(t.ttlMs)&&(t.ttlMs<n&&(n=t.ttlMs),t.ttlMs>r&&(r=t.ttlMs));return{shortestTtlMs:n,longestTtlMs:r}}(e);let a=0;for(const r of s)try{const i=P(r,o,t);if("keep"===i)continue;if("expire"===i){await n.deleteFile(r),a++;continue}const s=await n.readFile(r),c=JSON.parse(s),l=c.envelope?.timestampMs??0;l<T(c.name,e,t)&&(await n.deleteFile(r),a++)}catch{}return a+=await this.#h(n,s),a}};let U=q;function V(){return U}const W=new class{#m=void 0;get(){return this.#m}runWith(e,t){const n=this.#m;let r;this.#m=e;try{r=t()}catch(e){throw this.#m=n,e}return r&&"function"==typeof r.then?r.then(e=>(this.#m=n,e),e=>{throw this.#m=n,e}):(this.#m=n,r)}};let K=W;function G(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=K.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function Y(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(C(e.name,t)){r=!0;break}if(!r)return!1}return!0}class z extends Error{constructor(e){super(e),this.name="EventReplayError"}}const J={exportSpan:()=>{}};let H=J;function Q(){return H}function Z(e){const t=e;return t&&void 0===t.name&&void 0!==t.names?{...t,name:t.names}:e}function X(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function ee(){return Date.now()}let te=!0;function ne(e){te=e}function re(){return te}function ie(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;let o=0;function a(){try{L.onQueueDepthChange?.(i.length)}catch{}}async function c(){if(0===i.length)return;const e=[...i];i=[],a(),s&&(clearTimeout(s),s=null);try{await V().write(e),ee()-o>=6e4&&(o=ee(),le())}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function u(e){te&&function(e){if("audit"===e.envelope?.kind)return!0;const t=e.name;return r.some(e=>e.test(t))}(e)&&(i.push(e),a(),i.length>=10?c():s||(s=setTimeout(()=>{c()},5e3)))}function d(n,r){if("string"==typeof n){const t=n;let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(r),()=>{i?.delete(r),i&&0===i.size&&e.delete(t)}}const i={filter:n,listener:r};return t.push(i),()=>{const e=t.indexOf(i);e>=0&&t.splice(e,1)}}function p(r,i){const s=i,o=s&&"object"==typeof s&&s.name===r?s:{name:r,envelope:{id:X(),timestampMs:ee()},payload:i};try{n.push(o),n.length>200&&n.splice(0,n.length-200),u(o)}catch{}const a=e.get(r);if(a&&a.size>0)for(const e of a)try{e(i)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(Y(o,t.filter))try{t.listener(o)}catch{}}}async function f(e){try{return await V().query(Z(e))}catch{return[]}}function h(e){let t=[...n];if(e=Z(e),e?.correlationId){const n=e.correlationId;t=t.filter(e=>e.envelope?.correlationId===n||e.envelope?.id===n)}if(e?.traceId){const n=e.traceId;t=t.filter(e=>e.envelope?.traceId===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:p,subscribe:d,subscribeMany(e,t){const n=e.map(e=>d(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:X,publishEvent:function(e){const t=G({id:e.envelope?.id??X(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??ee(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{Q().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=l(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 p(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:h,getTrace:function(e){return h({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?h(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??"",l(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 l({exportedAt:ee(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:f,replay:async function(e){"dispatch"===e.mode&&function(){throw new z('events.replay({ mode: "dispatch" }) is disabled. Host must call setReplayDispatchAllowed(true) during bootstrap (test/dev only — side-effectful listeners will fire again).')}();const t=!1!==e.includePersisted,r=[...n];let i=[];if(t)try{i=await f({name:e.name,traceId:e.traceId,since:e.since,until:e.until})}catch{i=[]}const s=function(e,t,n){const r=new Set,i=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}i.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}i.push(e)}const s={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=i.filter(e=>{if(!Y(e,s))return!1;const t=e.envelope?.timestampMs??0;return!(void 0!==n.since&&t<n.since||void 0!==n.until&&t>n.until)});return o.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),void 0!==n.limit&&n.limit>0&&(o=o.slice(-n.limit)),o}(r,i,{name:e.name,correlationId:e.correlationId,traceId:e.traceId,kind:e.kind,source:e.source,since:e.since,until:e.until,limit:e.limit});if("log"===e.mode)for(const e of s)console.log("[Punica Replay]",e.name,e);else for(const e of s)p(e.name,e);return{count:s.length,events:s}},async flush(){await c()}}}const se=ie();var oe={manager:se};let ae=x;function ce(){return ae}async function le(){try{const e=V(),t=ce();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??A;return await e.delete({until:ee()-n})??0}catch{return 0}}var ue=Object.freeze({__proto__:null,createCorrelationId:X,createEventsApi:ie,default:oe,getRetentionConfig:ce,isEventPersistenceEnabled:re,manager:se,runEventRetentionCleanup:le,setEventPersistence:ne,setRetentionConfig:function(e){ae=e??x}});function de(){let e=[];const t=new Set;function n(){for(const e of t)try{e()}catch{}}const r={list:async()=>e.slice(),push(t){const r=t.id||`notif_${Date.now()}_${Math.random().toString(36).slice(2)}`,i=t.timestamp||(new Date).toISOString(),s={...t,id:r,timestamp:i};e=[s,...e],n()},markRead(t){e=e.map(e=>e.id===t?{...e,read:!0}:e),n()},clear(t){e=t?e.filter(e=>e.source!==t):[],n()},onDidChange:e=>(t.add(e),()=>{t.delete(e)})};return r}const pe=de();var fe={manager:pe},he=Object.freeze({__proto__:null,createNotificationsApi:de,default:fe,manager:pe});let me;function ge(){return me}function ye(){return me?.email}function we(){const e=me?.roles;return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}const ve=/^[a-z0-9][a-z0-9-]{0,31}$/,be=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Ie(e){if("string"!=typeof e)return;const t=e.trim();if("owner"===t)return{kind:"owner"};if(t.startsWith("role:")){const e=t.slice(5).trim().toLowerCase();return ve.test(e)?{kind:"role",role:e}:void 0}if(t.startsWith("user:")){const e=t.slice(5).trim().toLowerCase();return be.test(e)?{kind:"user",email:e}:void 0}}function ke(e){const t=Ie(e);if(t)switch(t.kind){case"owner":return"owner";case"role":return`role:${t.role}`;case"user":return`user:${t.email}`}}function Ee(e,t,n){if(!t||0===t.length)return;const r=e?.email?.trim().toLowerCase(),i=function(e,t){const n=e=>String(e).trim().toLowerCase();return t&&Array.isArray(e?.orgs)?new Set(e.orgs.filter(e=>function(e,t){const n=t.trim().toLowerCase();return""!==n&&(e.id.trim().toLowerCase()===n||e.name.trim().toLowerCase()===n)}(e,t)).map(e=>n(e.role))):new Set((e?.roles??[]).map(n))}(e,n);for(const e of t){const t=Ie(e);if(t){if("owner"===t.kind&&i.has("owner"))return"owner";if("role"===t.kind&&i.has(t.role))return`role:${t.role}`;if("user"===t.kind&&r&&r===t.email)return`user:${t.email}`}}}const Se="punica.kernel.policy.v2";function Ae(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function xe(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class Ce{#g=new Map;constructor(){this.#y()}set(e,t,n){let r=this.#g.get(e);r||(r=new Map,this.#g.set(e,r)),r.set(t,n),this.#w()}get(e,t){return this.#g.get(e)?.get(t)}has(e,t){return this.#g.get(e)?.has(t)??!1}delete(e,t){const n=this.#g.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#g.delete(e),r&&this.#w(),r}list(){const e=[];for(const t of this.#g.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#g.size&&(this.#g.clear(),this.#w())}restoreAll(e){this.#g.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=xe(n);if(!e)continue;let r=this.#g.get(n.key);r||(r=new Map,this.#g.set(n.key,r)),r.set(e,n),t++}return this.#w(),t}#y(){const e=Ae();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=xe(e);if(!t)continue;let n=this.#g.get(e.key);n||(n=new Map,this.#g.set(e.key,n)),n.set(t,e)}}catch{}}#w(){const e=Ae();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 Te=new Ce;const _e="any",Pe=2048;function Ne(e){if(void 0===e)return"null";if(null===e||"object"!=typeof e)return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(e=>Ne(e)).join(",")}]`;return`{${Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Ne(t)}`).join(",")}}`}function $e(e,t){if(0===t.length)return;if(t.some(e=>0===e.length))return e;if(Array.isArray(e)){const n=t.filter(e=>"*"===e[0]).map(e=>e.slice(1));if(0===n.length)return;return e.map(e=>$e(e,n))}if(!e||"object"!=typeof e)return;const n={},r=e;for(const e of Object.keys(r)){const i=t.filter(t=>t[0]===e).map(e=>e.slice(1));if(0===i.length)continue;const s=$e(r[e],i);void 0!==s&&(n[e]=s)}return Object.keys(n).length>0?n:void 0}function Me(e){const t=Ne(e);return t.length<=Pe?e:{truncated:!0,droppedChars:t.length-Pe,head:`${t.slice(0,Pe)}…`}}async function Re(e,t={}){const n=t.policyKeyPaths??[],r=n.length>0?$e(e,n):e;return{binding:await Oe(r),preview:Me(r)}}async function Oe(e){const t=(new TextEncoder).encode(Ne(e)),n=await function(){const e=globalThis.crypto?.subtle;if(!e)throw new Error("[ArgsBinding] crypto.subtle is unavailable, so an approval cannot be bound to its arguments. Run in an environment with Web Crypto (browser, Node 18+).");return e}().digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("").slice(0,32)}const Le=["file.read","file.write","file.list","file.stat","secret.read","secret.write","process.exec","net.request","model.invoke","memory.read","memory.write","vcs.read","vcs.write","flow.run","ui.reveal"],je=new Set(Le);function De(e){return"string"==typeof e&&je.has(e)}function Fe(e){const t=e?.action;if(!Array.isArray(t))return;const n=t.filter(De);return n.length>0?n:void 0}const Be=new Set(["kind","id","action","egress","sensitive","effect","when","approval","scope","approvers","signatures","reason"]),qe=["eq","neq","in","notIn","startsWith","endsWith","glob","exists","absent","lt","lte","gt","gte"],Ue=["allow","deny","require"],Ve={deny:0,require:1,allow:2};function We(e,t){const n=e.split(".").filter(e=>e.length>0);for(const e of t){const t=Math.min(n.length,e.length);let r=!0;for(let i=0;i<t;i++)if(n[i]!==e[i]&&"*"!==e[i]){r=!1;break}if(r)return!0}return!1}function Ke(e){return"string"==typeof e?e:"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e?String(e):null}function Ge(e,t){return Ne(e)===Ne(t)}function Ye(e,t){const{op:n,value:r}=t;switch(n){case"eq":return Ge(e,r);case"neq":return!Ge(e,r);case"in":return Array.isArray(r)&&r.some(t=>Ge(e,t));case"notIn":return Array.isArray(r)&&!r.some(t=>Ge(e,t));case"startsWith":{const t=Ke(e),n=Ke(r);return null!==t&&null!==n&&t.startsWith(n)}case"endsWith":{const t=Ke(e),n=Ke(r);return null!==t&&null!==n&&t.endsWith(n)}case"glob":{const t=Ke(e),n=Ke(r);return null!==t&&null!==n&&function(e,t){const n=t.split("*").map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`).test(e)}(t,n)}case"exists":return void 0!==e;case"absent":return void 0===e;case"lt":case"lte":case"gt":case"gte":return function(e,t,n){if("number"!=typeof e||!Number.isFinite(e))return!1;if("number"!=typeof t||!Number.isFinite(t))return!1;switch(n){case"lt":return e<t;case"lte":return e<=t;case"gt":return e>t;case"gte":return e>=t}}(e,r,n);default:return!1}}function ze(e,t,n){const r=function(e,t){const n=t.split(".").filter(e=>e.length>0);let r=[e];for(const e of n){const t=[];for(const n of r){if(null==n)continue;if("*"===e){Array.isArray(n)&&t.push(...n);continue}if(Array.isArray(n)||"object"!=typeof n)continue;const r=n[e];void 0!==r&&t.push(r)}if(r=t,0===r.length)return[]}return r}(e,t.path);if(0===r.length)return"absent"===t.op;return"allow"===n?r.every(e=>Ye(e,t)):r.some(e=>Ye(e,t))}function Je(e,t){return void 0===e||""===e||"*"===e||(e.endsWith("*")?t.startsWith(e.slice(0,-1)):e===t)}function He(e,t,n){if(void 0===e||0===e.length)return!0;if(void 0===t||0===t.length)return!1;const r=new Set(e);return"allow"===n?t.every(e=>r.has(e)):t.some(e=>r.has(e))}function Qe(e,t,n,r={}){const i=r.sensitivePaths??[];let s=null,o=Number.POSITIVE_INFINITY;for(const a of e){const e=Array.isArray(a?.rules)?a.rules:[];for(let c=0;c<e.length;c++){const l=e[c];if(!l||l.kind!==t.kind)continue;if(!Je(l.id,t.id))continue;if(!He(l.action,t.action,l.effect))continue;if(l.egress&&"remote"!==t.egress)continue;if(l.sensitive&&!t.sensitive)continue;const u=Ve[l.effect];if(void 0===u)continue;if(u>=o)continue;const d=Array.isArray(l.when)?l.when:[];let p=!0;for(const e of d){if(!0===r.argsWhollyRedacted||We(e.path,i)){r.onRedactedCondition?.(a.name,c,e.path),p=!1;break}if(!ze(n,e,l.effect)){p=!1;break}}if(p&&(s={ref:{template:a.name,ruleIndex:c,effect:l.effect,reason:l.reason,...l.scope?{scope:l.scope}:{},...l.approvers?{approvers:l.approvers}:{},...a.org?{org:a.org}:{},...l.signatures?{signatures:l.signatures}:{},...l.sensitive?{sensitive:!0}:{},digest:a.digest,matchedBy:l.action&&l.action.length>0&&!l.id?"action":l.egress&&!l.id?"egress":l.sensitive&&!l.id?"sensitive":"id"},rule:l},o=u,0===u))return s}}return s}function Ze(e,t){return{path:e,message:t}}function Xe(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return n.push(Ze(t,"a condition must be a mapping")),null;const r=e,i=r.path;if("string"!=typeof i||""===i.trim())return n.push(Ze(`${t}.path`,"a condition needs a path")),null;const s=r.op;if("string"!=typeof s||!qe.includes(s))return n.push(Ze(`${t}.op`,`unknown operator ${JSON.stringify(s)} — one of ${qe.join(", ")}`)),null;return"exists"!==s&&"absent"!==s&&void 0===r.value?(n.push(Ze(`${t}.value`,`operator "${s}" needs a value`)),null):"in"!==s&&"notIn"!==s||Array.isArray(r.value)?{path:i,op:s,value:r.value}:(n.push(Ze(`${t}.value`,`operator "${s}" needs a list of values`)),null)}function et(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return n.push(Ze(t,"a rule must be a mapping")),null;const r=e,i=r.kind;if("string"!=typeof i||""===i.trim())return n.push(Ze(`${t}.kind`,'a rule needs a kind, e.g. "capability"')),null;const s=r.effect;if("string"!=typeof s||!Ue.includes(s))return n.push(Ze(`${t}.effect`,`effect must be one of ${Ue.join(", ")} — got ${JSON.stringify(s)}`)),null;const o={kind:i,effect:s};if(void 0!==r.id){if("string"!=typeof r.id)return n.push(Ze(`${t}.id`,"id must be a string")),null;o.id=r.id}if(void 0!==r.action){if(!Array.isArray(r.action)||0===r.action.length)return n.push(Ze(`${t}.action`,"action must be a non-empty list of actions")),null;const e=[];for(let i=0;i<r.action.length;i++){const s=r.action[i];if(!De(s))return n.push(Ze(`${t}.action.${i}`,`unknown action ${JSON.stringify(s)} — see docs/capability-actions.md`)),null;e.push(s)}o.action=e}if(void 0!==r.egress){if("remote"!==r.egress)return n.push(Ze(`${t}.egress`,`egress must be "remote", got ${JSON.stringify(r.egress)}`)),null;o.egress="remote"}if(void 0!==r.reason){if("string"!=typeof r.reason)return n.push(Ze(`${t}.reason`,"reason must be a string")),null;o.reason=r.reason}if(void 0!==r.approval){if("plan"!==r.approval&&"step"!==r.approval)return n.push(Ze(`${t}.approval`,"approval must be plan or step — for silent execution write effect: allow")),null;if("require"!==o.effect)return n.push(Ze(`${t}.approval`,`approval only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;o.approval=r.approval}if(void 0!==r.scope){if("once"!==r.scope&&"workspace"!==r.scope&&"always"!==r.scope)return n.push(Ze(`${t}.scope`,"scope must be once, workspace or always")),null;if("require"!==o.effect)return n.push(Ze(`${t}.scope`,`scope only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;o.scope=r.scope}if(void 0!==r.approvers){if(!Array.isArray(r.approvers)||0===r.approvers.length)return n.push(Ze(`${t}.approvers`,"approvers must be a non-empty list of owner, role:<name> or user:<email>")),null;if("require"!==o.effect)return n.push(Ze(`${t}.approvers`,`approvers only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;const e=[];for(let i=0;i<r.approvers.length;i++){const s=ke(r.approvers[i]);if(!s)return n.push(Ze(`${t}.approvers.${i}`,`unknown approver ${JSON.stringify(r.approvers[i])} — write owner, role:<name> or user:<email>`)),null;e.includes(s)||e.push(s)}o.approvers=e}if(void 0!==r.signatures){if("number"!=typeof r.signatures||!Number.isInteger(r.signatures)||r.signatures<1)return n.push(Ze(`${t}.signatures`,"signatures must be a whole number of signatures, at least 1")),null;if("require"!==o.effect)return n.push(Ze(`${t}.signatures`,`signatures only applies to effect: require — it does nothing on effect: ${o.effect}`)),null;if(!o.approvers)return n.push(Ze(`${t}.signatures`,"signatures needs approvers — name who may sign (owner, role:<name> or user:<email>)")),null;r.signatures>1&&(o.signatures=r.signatures)}for(const e of Object.keys(r))if(!Be.has(e))return n.push(Ze(`${t}.${e}`,`unknown key "${e}" — this substrate does not read it, and a rule it cannot read whole is not applied`)),null;if(void 0!==r.sensitive){if(!0!==r.sensitive)return n.push(Ze(`${t}.sensitive`,`sensitive must be true, got ${JSON.stringify(r.sensitive)}`)),null;o.sensitive=!0}if(void 0!==r.when){if(!Array.isArray(r.when))return n.push(Ze(`${t}.when`,"when must be a list")),null;const e=[];for(let i=0;i<r.when.length;i++){const s=Xe(r.when[i],`${t}.when.${i}`,n);if(!s)return null;e.push(s)}o.when=e}return o}function tt(e){const t=[],n=[];if(null==e)return{templates:n,problems:t};if("object"!=typeof e||Array.isArray(e))return t.push(Ze("","the policy file must be a mapping")),{templates:n,problems:t};const r=e;if(void 0!==r.version&&1!==r.version)return t.push(Ze("version",`unsupported policy file version ${JSON.stringify(r.version)} — this build reads version 1`)),{templates:n,problems:t};let i;void 0!==r.org&&("string"==typeof r.org&&""!==r.org.trim()?i=r.org.trim():t.push(Ze("org","org must be the name or id of an organisation")));const s=r.templates;if(void 0===s)return{templates:n,problems:t,...i?{org:i}:{}};if(!Array.isArray(s))return t.push(Ze("templates","templates must be a list")),{templates:n,problems:t,...i?{org:i}:{}};const o=new Set;for(let e=0;e<s.length;e++){const r=`templates.${e}`,a=s[e];if(!a||"object"!=typeof a){t.push(Ze(r,"a template must be a mapping"));continue}const c=a,l=c.name;if("string"!=typeof l||""===l.trim()){t.push(Ze(`${r}.name`,"a template needs a name"));continue}if(o.has(l)){t.push(Ze(`${r}.name`,`duplicate template name "${l}" — the later one is ignored`));continue}o.add(l);const u=c.rules,d=[];if(void 0!==u)if(Array.isArray(u))for(let e=0;e<u.length;e++){const n=et(u[e],`${r}.rules.${e}`,t);n&&d.push(n)}else t.push(Ze(`${r}.rules`,"rules must be a list"));const p={name:l,rules:d};"string"==typeof c.description&&(p.description=c.description),i&&(p.org=i),n.push(p)}return{templates:n,problems:t,...i?{org:i}:{}}}class nt extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalChainError"}}function rt(e){switch(e.type){case"single":return[e.approver];case"sequential":case"parallel":return e.approvers;case"signatures":return[]}}function it(e,t){return function(e){if("sequential"===e.type||"parallel"===e.type){if(!e.approvers||0===e.approvers.length)throw new nt("INVALID_SPEC",`${e.type} chain must have at least one approver`);const t=new Set;for(const n of e.approvers){if(t.has(n.id))throw new nt("INVALID_SPEC",`Duplicate approver id "${n.id}" in chain spec`);t.add(n.id)}if("parallel"===e.type&&void 0!==e.quorum&&(e.quorum<1||e.quorum>e.approvers.length||!Number.isInteger(e.quorum)))throw new nt("INVALID_SPEC",`parallel quorum must be an integer in [1, ${e.approvers.length}]; got ${e.quorum}`)}else if("single"===e.type){if(!e.approver?.id)throw new nt("INVALID_SPEC","single chain must declare an approver with an id")}else{if("signatures"!==e.type)throw new nt("INVALID_SPEC",`Unknown chain type: ${e.type}`);if(!Number.isInteger(e.required)||e.required<1)throw new nt("INVALID_SPEC",`signatures chain must require a whole number of signatures, at least 1; got ${e.required}`);if(!Array.isArray(e.approvers)||0===e.approvers.length)throw new nt("INVALID_SPEC","signatures chain must name who may sign (the rule's approvers)")}}(t),{chainId:e,spec:t,decisions:[],status:"pending"}}function st(e,t){if("pending"!==e.status)throw new nt("CHAIN_NOT_PENDING",`Chain ${e.chainId} is already ${e.status}; cannot accept more decisions`);const n=rt(e.spec);if(!("signatures"===e.spec.type?""!==t.approverId.trim():n.some(e=>e.id===t.approverId)))throw new nt("UNKNOWN_APPROVER","signatures"===e.spec.type?"A signature needs a name; sign in to sign this call.":`Approver "${t.approverId}" is not in chain ${e.chainId}`);if("sequential"===e.spec.type){const n=e.spec.approvers[e.decisions.length];if(n?.id!==t.approverId)throw new nt("UNKNOWN_APPROVER",`Sequential chain ${e.chainId} expects approver "${n?.id??"(end)"}" next; got "${t.approverId}"`)}if("parallel"===e.spec.type||"single"===e.spec.type||"signatures"===e.spec.type){const n=(t,n)=>"signatures"===e.spec.type?t.trim().toLowerCase()===n.trim().toLowerCase():t===n;if(e.decisions.some(e=>n(e.approverId,t.approverId)))throw new nt("DUPLICATE_DECISION","signatures"===e.spec.type?`${t.approverId} already signed this call; the next signature must come from someone else.`:`Approver "${t.approverId}" already decided on chain ${e.chainId}`)}const r=[...e.decisions,t];return{...e,decisions:r,status:ot(e.spec,r)}}function ot(e,t){const n=rt(e),r=function(e){switch(e.type){case"sequential":return e.approvers.length;case"parallel":return e.quorum??e.approvers.length;case"single":return 1;case"signatures":return e.required}}(e);let i=0,s=0;for(const e of t)"approve"===e.decision?i++:s++;switch(e.type){case"sequential":return s>0?"denied":i===n.length?"granted":"pending";case"parallel":if(i>=r)return"granted";return i+(n.length-t.length)<r?"denied":"pending";case"single":return 1===i?"granted":1===s?"denied":"pending";case"signatures":return s>0?"denied":i>=r?"granted":"pending"}}function at(){return Date.now()}function ct(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function lt(e){const t=`${e.kind}:${e.id}`;return e.argsBinding?`${t}|args=${e.argsBinding}`:t}class ut extends Error{approvers;code="APPROVER_NOT_ALLOWED";constructor(e,t,n){super(`${t?`${t} is`:"This host is"} not among the approvers this rule names (${function(e){const t=e.map(e=>{const t=Ie(e);return t?"owner"===t.kind?"the owner":"role"===t.kind?`a ${t.role}`:t.email:String(e)}).filter((e,t,n)=>n.indexOf(e)===t);return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}(e)}${n?` in ${n}`:""}); ask one of them.`),this.approvers=e,this.name="ApproverNotAllowedError"}}function dt(e,t){if(!t||0===t.length)return!0;const n=new Set(t.map(e=>ke(e)).filter(e=>!!e)),r=ke(e.decidedRole);if(r&&n.has(r))return!0;const i=e.decidedBy?.trim().toLowerCase();return!!i&&n.has(`user:${i}`)}function pt(e,t){const n=t&&t>1?t:1;return(e.signatures?e.signatures.by.length:1)>=n}function ft(e){return"once"===e?["once"]:"workspace"===e?["once","workspace"]:["once","workspace","always"]}function ht(e,t){return"workspace"===e?`workspace:${t??""}`:e}function mt(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const gt="punica.kernel.policy.v1",yt="punica.kernel.policy.v2";class wt{#v="execute";#b;#I=new Set;#k=new Map;#E=[];#S=1e3;constructor(e){this.#b=e??new Ce,this.#A()}#A(){const e=mt();if(e)try{const t=e.getItem(yt);if(t){const e=JSON.parse(t);if(e&&2===e.v)return"suggest"!==e.mode&&"execute"!==e.mode||(this.#v=e.mode),void this.#x(e.templates)}const n=e.getItem(gt);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#v=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#b.restoreAll(n),this.#w();try{e.removeItem(gt)}catch{}return}}}catch{}}#C(){const e=[];for(const[t,n]of this.#k)for(const r of n.values())e.push({scope:t,template:r});return e}#x(e){if(Array.isArray(e))for(const t of e){const e=t?.scope,n=t?.template;if("string"!=typeof e||!e)continue;if(!n||"string"!=typeof n.name)continue;let r=this.#k.get(e);r||(r=new Map,this.#k.set(e,r)),r.set(n.name,n)}}#T(e){const t=[];if(e){const n=this.#k.get(e);n&&t.push(...n.values())}const n=this.#k.get("global");return n&&t.push(...n.values()),t}#w(){const e=mt();if(e)try{let t={};try{const n=e.getItem(yt);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#v,exportedAt:at(),templates:this.#C()};e.setItem(yt,JSON.stringify(n))}catch{}}setMode(e){this.#v=e,this.#w()}getMode(){return this.#v}clearApprovals(){this.#b.clear(),this.#I.clear()}#_(e,t,n="audit",r){try{se.publishEvent({name:e,envelope:{id:se.createCorrelationId(),timestampMs:at(),source:"kernel:policy",kind:n,...r?.traceId?{traceId:r.traceId}:{},...r?.parentSpanId?{parentSpanId:r.parentSpanId}:{}},payload:r?.conversationId?{...t,conversationId:r.conversationId}:t})}catch{}}#P(e,t){return`${e}|${t}`}revokeApproval(e){const t=lt({kind:e.kind,id:e.id,argsBinding:e.argsBinding}),n="workspace"===e.scope?ht("workspace",e.workspaceId):ht(e.scope),r=this.#b.delete(t,n);return r&&(this.#N("revocation",{kind:e.kind,id:e.id,risk:"low",approval:"none"},void 0,e.scope,e.workspaceId),this.#_("approval.revoked",{kind:e.kind,id:e.id,scope:e.scope,workspaceId:e.workspaceId}),this.#I.delete(this.#P(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#b.list();if(t)return n;const r=at();return n.filter(e=>!ct(e,r))}#$(e,t){const n=[lt(e)];e.argsBinding&&e.argsBinding!==_e&&n.push(lt({...e,argsBinding:_e}));const r=[],i=at();for(const s of n){const n=this.#b.get(s,t);if(n&&(dt(n,e.approvers)&&pt(n,e.signatures))){if(!ct(n,i))return{rec:n,key:s};r.push({rec:n,key:s})}}return r[0]??null}hasApproval(e,t,n){const r="workspace"===t?n?.workspaceId?ht("workspace",n.workspaceId):null:ht(t);if(null===r)return!1;const i=this.#$(e,r);if(!i)return!1;const{rec:s,key:o}=i;if(ct(s,at())){const e=this.#P(o,r);return this.#I.has(e)||(this.#I.add(e),this.#_("approval.expired",{kind:s.kind,id:s.id,scope:s.scope,workspaceId:s.workspaceId,expiresAt:s.expiresAt,decidedBy:s.decidedBy},"warn")),!1}return!0}recordApproval(e,t,n){if("workspace"===t&&!n?.workspaceId)throw new Error("[Policy] Workspace scope requires workspaceId in context");const r=lt(e),i="workspace"===t?ht("workspace",n?.workspaceId):ht(t),s=function(e){const t=e?.decidedBy??ye(),n=Ie(e?.decidedRole);if("owner"===n?.kind)return{email:t,roles:["owner"]};if("role"===n?.kind)return{email:t,roles:[n.role]};if("user"===n?.kind)return{email:n.email,roles:[]};if(e?.decidedBy)return{email:t,roles:[]};const r=ge()?.orgs;return{email:t,roles:we(),...Array.isArray(r)?{orgs:r}:{}}}(n);let o;if(e.approvers&&e.approvers.length>0){if(o=Ee(s,e.approvers,e.org),!o)throw new ut(e.approvers,s.email,e.org)}else o=ke(n?.decidedRole);const a=e.signatures&&e.signatures>1?e.signatures:1;let c,l=n?.chainRef;if(a>1){const t=this.#P(r,i),n=this.#b.get(r,i),u=st(function(e,t,n,r){let i=it(e,{type:"signatures",required:n,approvers:r});if(t?.signatures&&t.signatures.need===n)for(const e of t.signatures.by)i=st(i,{approverId:e.by,decision:"approve",timestampMs:e.atMs,...e.role?{role:e.role}:{}});return i}(t,n?.signatures&&n.signatures.need===a&&n.signatures.by.length<a&&!ct(n,at())?n:void 0,a,e.approvers??[]),{approverId:s.email??"",decision:"approve",timestampMs:at(),...o?{role:o}:{}});c={need:a,by:u.decisions.map(e=>({by:e.approverId,...e.role?{role:e.role}:{},atMs:e.timestampMs}))},l=t}const u={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:s.email,...o?{decidedRole:o}:{},timestampMs:at(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,argsBinding:e.argsBinding,argsPreview:e.argsPreview,chainRef:l,...c?{signatures:c}:{}};return this.#b.set(r,i,u),c&&c.by.length<c.need?(this.#N("signature",e,void 0,t,n?.workspaceId),this.#_("approval.signed",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:u.decidedBy,...u.decidedRole?{decidedRole:u.decidedRole}:{},signatures:{need:c.need,have:c.by.length,by:c.by}},"audit",{traceId:n?.traceId,parentSpanId:n?.parentSpanId,conversationId:n?.conversationId}),u):(this.#N("approval",e,void 0,t,n?.workspaceId),this.#I.delete(this.#P(r,i)),this.#_("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:u.decidedBy,...u.decidedRole?{decidedRole:u.decidedRole}:{},...c?{signatures:{need:c.need,have:c.by.length,by:c.by}}:{},expiresAt:n?.expiresAt},"audit",{traceId:n?.traceId,parentSpanId:n?.parentSpanId,conversationId:n?.conversationId}),u)}declineApproval(e,t){this.#N("decline",e,void 0,void 0,t?.workspaceId),this.#_("approval.declined",{request:e,workspaceId:t?.workspaceId,decidedBy:t?.decidedBy??ye(),...ke(t?.decidedRole)?{decidedRole:ke(t?.decidedRole)}:{},reason:t?.reason},"audit",{traceId:t?.traceId,parentSpanId:t?.parentSpanId,conversationId:t?.conversationId})}#N(e,t,n,r,i){this.#E.push({timestampMs:at(),type:e,request:t,decision:n,scope:r,workspaceId:i}),this.#E.length>this.#S&&this.#E.splice(0,this.#E.length-this.#S)}evaluate(e,t){const n=n=>{const r=t,i=r?.correlationId,s=r?.traceId??i,o=r?.parentSpanId;se.publishEvent({name:"policy.evaluated",envelope:{id:se.createCorrelationId(),correlationId:i,traceId:s,...o?{parentSpanId:o}:{},timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})},r=Qe(this.#T(t?.workspaceId),{kind:e.kind,id:e.id,action:e.action,...e.egress?{egress:e.egress}:{},...e.sensitive?{sensitive:e.sensitive}:{}},t?.args,{sensitivePaths:t?.redactedPaths,argsWhollyRedacted:t?.argsWhollyRedacted,onRedactedCondition:(e,t,n)=>{console.warn(`[Policy] Rule ${e}#${t} tests "${n}", which the redactor has already replaced — the condition cannot match and the rule does not apply.`)}}),i=r?.ref;if(r&&"deny"===r.ref.effect){const s={allowed:!1,mode:"execute",requiresApproval:!1,reason:r.ref.reason??`Denied by policy rule ${r.ref.template}#${r.ref.ruleIndex}.`,policyRule:i};return this.#N("decision",e,s,void 0,t?.workspaceId),n(s),s}if(r&&"allow"===r.ref.effect){const s={allowed:!0,mode:"execute",requiresApproval:!1,reason:r.ref.reason??`Allowed by policy rule ${r.ref.template}#${r.ref.ruleIndex}.`,policyRule:i};return this.#N("decision",e,s,void 0,t?.workspaceId),n(s),s}const s=r&&"require"===r.ref.effect?r.rule.approval??"step":e.approval,o=r&&"require"===r.ref.effect?r.rule.scope:void 0,a=r&&"require"===r.ref.effect&&r.rule.approvers?.length?r.rule.approvers:void 0,c=a&&r?.ref.org?r.ref.org:void 0,l=a&&r?.ref.signatures&&r.ref.signatures>1?r.ref.signatures:void 0,u=a?{...e,approvers:a,...c?{org:c}:{},...l?{signatures:l}:{}}:e;if("suggest"===this.#v&&s===e.approval){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#N("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===s){const r={allowed:!0,mode:"execute",requiresApproval:!1,policyRule:i};return this.#N("decision",e,r,void 0,t?.workspaceId),n(r),r}if("plan"===s){const s=ft(o).some(e=>this.hasApproval(u,e,t))?{allowed:!0,mode:"execute",requiresApproval:!1,policyRule:i}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:r?.ref.reason??"Approval required (plan).",policyRule:i};return o&&(s.maxScope=o),a&&(s.approvers=a),c&&(s.org=c),l&&(s.signatures=l),this.#N("decision",e,s,void 0,t?.workspaceId),n(s),s}const d=ft(o).some(e=>this.hasApproval(u,e,t))?{allowed:!0,mode:"execute",requiresApproval:!1,policyRule:i}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:r?.ref.reason??"Approval required (step).",policyRule:i};return o&&(d.maxScope=o),a&&(d.approvers=a),c&&(d.org=c),l&&(d.signatures=l),this.#N("decision",e,d,void 0,t?.workspaceId),n(d),d}requestApproval(e,t){se.publishEvent({name:"policy.approvalRequested",envelope:{id:se.createCorrelationId(),correlationId:t?.correlationId,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,context:{workspaceId:t?.workspaceId,traceId:t?.traceId,...t?.reason?{reason:t.reason}:{}}}})}exportState(){return{version:3,exportedAt:at(),mode:this.#v,approvals:this.listApprovals({includeExpired:!0}),templates:this.#C().map(e=>({...e.template,workspaceId:e.template.workspaceId??("global"===e.scope?void 0:e.scope)}))}}importState(e,t){if(!e||"object"!=typeof e)throw new Error("[Policy] Invalid export data");if(2!==e.version&&3!==e.version)throw new Error(`[Policy] Unsupported export version: ${e.version}. Expected 2 or 3.`);const n=t?.merge??!1,r=Array.isArray(e.approvals)?e.approvals:[];"suggest"!==e.mode&&"execute"!==e.mode||(this.#v=e.mode);const i=Array.isArray(e.templates)?e.templates:[];n||this.#k.clear();for(const e of i){if(!e||"string"!=typeof e.name)continue;const t=e.workspaceId??"global",r=this.#k.get(t);if(n&&r?.has(e.name))continue;let i=r;i||(i=new Map,this.#k.set(t,i)),i.set(e.name,e)}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?ht("workspace",r):ht(n);"string"==typeof i&&i&&(this.#b.has(t,i)||(this.#b.set(t,i,e),s++))}else s=this.#b.restoreAll(r),this.#I.clear();return this.#w(),se.publishEvent({name:"policy.stateImported",envelope:{id:se.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:s,merged:n}}),s}saveTemplate(e,t,n){const r=n??"global";let i=this.#k.get(r);i||(i=new Map,this.#k.set(r,i));const s={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??at(),updatedAtMs:at()};i.set(e,s),this.#w()}getTemplate(e,t){const n=t??"global",r=this.#k.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#k.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#k.get(n);if(!r)return!1;const i=r.delete(e);return i&&this.#w(),i}exportAuditLog(e){const t=e?.format??"json";let n=[...this.#E];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:at(),version:1,count:n.length,entries:n},null,2)}}const vt=new wt(Te);var bt={manager:vt},It=Object.freeze({__proto__:null,ARGS_BINDING_ANY:_e,ApproverNotAllowedError:ut,PolicyManager:wt,canonicalDigest:Oe,computeArgsBinding:Re,default:bt,manager:vt,matchRules:Qe,scopesWithin:ft,validatePolicyTemplates:tt});async function kt(e,n,r){if(r())e.status="cancelled";else if("success"!==e.status&&"cancelled"!==e.status){e.status="running",e.startedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runStepStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=n,s=await t(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:n,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:"kernel.planExecution"},trace:{traceId:i,parentSpanId:void 0},policy:{mode:"execute"}});e.status="success",e.finishedAtMs=Date.now(),e.correlationId=r,e.resultPayload=o,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:n,step:e}})}catch(t){const r=String(t?.message??t);if(r.includes("Approval required")||r.includes("CAPABILITY_APPROVAL_REQUIRED"))throw e.status="blocked",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}}),new Error("blocked");throw e.status="failed",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:n,step:e}}),t}}}async function Et(e,t,n,r){let i=e;if(i||(i=function(){try{const e=punica.kernel.Events.manager.getRecent(200);for(let t=e.length-1;t>=0;t--){const n=e[t],r=n?.name??n?.event?.name,i=n?.payload??n?.event?.payload;if("ai.planGenerated"===r&&i?.plan?.planId)return i.plan}}catch{}return null}(),i&&r(i)),!i)throw new Error("[AI] No plan to run");return await async function(e,t,n){const r=t&&t.planId===e.planId&&!t.finishedAtMs?t:{runId:punica.kernel.Events.manager.createCorrelationId(),planId:e.planId,startedAtMs:Date.now(),steps:e.steps.map(e=>({...e,status:"pending"}))};punica.kernel.Events.manager.publishEvent({name:"ai.runStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}});for(const e of r.steps)try{await kt(e,r.runId,n)}catch(e){if("blocked"===e?.message)break;break}return r.finishedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.runId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{run:r}}),r}(i,t,n)}const St={once:0,workspace:1,always:2};function At(e,t,n,r){const i=n.get(e);if(!i)return!1;const s=i.signedScope??(o=t,(a=i.maxScope)&&St[o]>St[a]?a:o);var o,a;const c=punica.kernel.Policy.manager.recordApproval({kind:i.kind,id:i.id,risk:i.risk,approval:i.approval,reason:i.reason,argsBinding:i.argsBinding,argsPreview:i.argsPreview,...i.approvers?{approvers:i.approvers}:{},...i.org?{org:i.org}:{},...i.signatures&&i.signatures>1?{signatures:i.signatures}:{}},s,{workspaceId:i.workspaceId,...r?.decidedBy?{decidedBy:r.decidedBy}:{},...r?.decidedRole?{decidedRole:r.decidedRole}:{},...i.traceId?{traceId:i.traceId}:{},...i.correlationId?{parentSpanId:i.correlationId}:{}}),l=c?.signatures;if(l&&l.by.length<l.need){const t={...i,signed:l.by,signedScope:s};return n.set(e,t),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalSigned",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:t,scope:s,signatures:{need:l.need,have:l.by.length}}}),!0}return n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.approvalRecorded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:i,scope:s}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"approved"}}),!0}function xt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ct(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Tt(e,t,n){if(!xt(t)||!0===t.truncated)return{...n};const r={};for(const n of Object.keys(e))n in t||(r[n]=e[n]);for(const i of Object.keys(n)){const s=i in t&&i in e&&Ct(n[i],t[i]);r[i]=s?e[i]:n[i]}return r}const _t=[];function Pt(e){_t.push(e)}function Nt(){const e={};for(const t of _t)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function $t(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Mt(e){return"string"==typeof e}function Rt(e){return"string"==typeof e&&e.trim().length>0}function Ot(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const Lt=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"]),jt=new Set(["light","dark","auto"]),Dt=new Set(["compact","comfortable"]),Ft=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const Bt=new class{validate(e){const t=[];if(!$t(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)}`),$t(e.identity)?(Rt(e.identity.id)||t.push("identity.id must be a non-empty string"),Rt(e.identity.name)||t.push("identity.name must be a non-empty string"),Rt(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),$t(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys(Nt()),r=new Set([...Lt,...n]);e.shell.activeModules.forEach((e,n)=>{Mt(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&&($t(e.shell.layout)?(Rt(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),$t(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($t(e.theme)?(jt.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||Dt.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"),$t(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||Ot(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||Ot(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)=>{Mt(e)&&Ft.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 qt;function Ut(e){qt=e}function Vt(){return qt??Bt}function Wt(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 Kt{#M=new Map;#R;register(e){if(this.#M.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#M.set(e.identity.id,e),void 0===this.#R&&(this.#R=e.identity.id)}replace(e){this.#M.set(e.identity.id,e),void 0===this.#R&&(this.#R=e.identity.id)}get(e){return this.#M.get(e)}getActive(){if(void 0===this.#R||!this.#M.has(this.#R))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#M.get(this.#R)}setActive(e){if(!this.#M.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#R=e}switchProfile(e){if(!this.#M.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#R=e,Wt({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#M.has(e)}list(){return Array.from(this.#M.values())}}const Gt={manager:new class{registry=new Kt;get validator(){return Vt()}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.#O(t)}this.#O(e)}#O(e){const t=this.validator.validate(e);if(!t.valid)throw Wt({name:"shell.profile.load_failed",payload:{errors:t.errors}}),new Error(`ApplicationProfile validation failed:\n ${t.errors.join("\n ")}`);this.registry.replace(t.profile),this.registry.setActive(t.profile.identity.id),Wt({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}};function Yt(e){return!(!e||"object"!=typeof e)&&"hub-only"===e.agentVisibility}function zt(e){const t=e?.action;return Array.isArray(t)&&t.includes("ui.reveal")}function Jt(){const e=function(){try{const e=globalThis,t=e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.shell?.activeModules;return Array.isArray(t)?t:void 0}catch{return}}();if(e)return e.includes(Ht);try{const e=Gt.manager.registry.getActive()?.shell?.activeModules;return!Array.isArray(e)||e.includes(Ht)}catch{return!0}}const Ht="shell.views";const Qt={estimate:e=>Math.ceil(e.length/4)};function Zt(){return Qt}function Xt(e){const t=Zt();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 en={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 tn="[elided tool result:";function nn(e){const t=(e.content??"").length;return`${tn} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function rn(e,t){let n=0;for(let r=e.length-1;r>0;r--){const i=e[r].role;if(("assistant"===i||"user"===i)&&(n++,n>=t))return r}return 1}async function sn(e,t,n,r){const i=Xt(e);if(i<=t.maxContextTokens)return{messages:[...e],compacted:!1,strategy:"none",preTokens:i,postTokens:i,estSavedTokens:0};const s=Math.floor(.6*t.maxContextTokens),o=rn(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(tn)?{...e,content:nn(e)}:e);let c=Xt(a);if(c<=s||!t.summarizeWhenOver||!n){const e=c<i;return{messages:a,compacted:e,strategy:e?"elide":"none",preTokens:i,postTokens:c,estSavedTokens:i-c}}const l=a.slice(1,o),u=a.slice(o);try{const e="Summarize this agent conversation segment so a follow-up model call can continue the task without the originals. Keep: the user goal, decisions made, tool outcomes (names + key results), and open questions. Be dense and factual; no preamble.\n\n"+l.map(e=>`${e.role}: ${e.content??""}`).join("\n"),t=await n("llm.chat",{messages:[{role:"user",content:e}],profile:"fast"},r??{}),s=(t?.text??"").trim();if(s){const e=[a[0],{role:"assistant",content:`[conversation summary]\n${s}`},...u];return c=Xt(e),{messages:e,compacted:!0,strategy:"summarize",preTokens:i,postTokens:c,estSavedTokens:i-c}}}catch{}return{messages:a,compacted:c<i,strategy:"elide",preTokens:i,postTokens:c,estSavedTokens:i-c}}const on=Object.freeze({narrowThreshold:24,catalogTopN:100,topCategories:64,hotSetSize:40});function an(){const e=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.agent?.toolSelection}catch{return}}();if(e)return e;try{return Gt.manager.registry.getActive()?.agent?.toolSelection}catch{return}}function cn(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function ln(e,t){if(!(e&&e.calls>0))return 0;const n=Math.max(0,(t-e.last)/864e5);return Math.pow(2,-n/14)*(e.calls/(e.calls+1))*((Math.min(Math.max(e.ok,0),e.calls)+1)/(e.calls+2))}function un(e,t,n,r){return r>0?async(i,s)=>function(e,t,n,r){if(!(r>0&&t))return e;const i=e.map((e,i)=>{const s="number"==typeof e.score?e.score:0,o=ln(t[String(e.id)],n);return{r:e,i:i,score:s*(1+r*o)}});return i.sort((e,t)=>t.score-e.score||e.i-t.i),i.map(({r:e,score:t})=>({...e,score:t}))}(await e(i,s),t,n,r):e}function dn(e,t,n){return!!e&&(!n.includes(e)&&("success"===t||"failed"===t))}const pn="punica.kernel.ai.toolUsage.v1";function fn(e){const t=e;if(!t||"object"!=typeof t)return;const n=Number(t.calls),r=Number(t.ok),i=Number(t.last);return!Number.isFinite(n)||n<=0||!Number.isFinite(i)||i<=0?void 0:{calls:Math.floor(n),ok:Number.isFinite(r)?Math.min(Math.max(Math.floor(r),0),n):0,last:Math.floor(i)}}function hn(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const mn=new class{async read(){const e=hn();if(!e)return{};try{const t=e.getItem(pn);return t?function(e){const t=e,n=t?.tools;if(!n||"object"!=typeof n)return{};const r={};for(const[e,t]of Object.entries(n)){const n=fn(t);n&&e&&(r[e]=n)}return r}(JSON.parse(t)):{}}catch{return{}}}async record(e,t,n){const r=hn();var i;if(r)try{r.setItem(pn,(i=function(e,t,n,r,i=500){if(!t)return e;const s={...e},o=s[t];s[t]={calls:(o?.calls??0)+1,ok:(o?.ok??0)+(n?1:0),last:r};const a=Object.keys(s);return a.length>i&&a.sort((e,t)=>s[e].last-s[t].last||(e<t?-1:1)).slice(0,a.length-i).forEach(e=>delete s[e]),s}(await this.read(),e,t,n),JSON.stringify({v:1,tools:i},null,2)))}catch{}}async forget(){const e=hn();if(e)try{e.removeItem(pn)}catch{}}};let gn=mn;function yn(){return gn}async function wn(e,t,n){try{await yn().record(e,t,n)}catch{}}function vn(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}async function bn(e,t,n,r){try{const i=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))??[],s=new Map;let o=!1,a=0;i.forEach((e,t)=>{null!=e?.id&&s.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=vn(String(n.id)),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}(e);if(0===s.size||o&&a<=1e-9)return function(e,t){const n=[],r=[...e.values()],i=new Array(r.length).fill(0);let s=!0;for(;s&&n.length<t;){s=!1;for(let e=0;e<r.length&&n.length<t;e++){const t=i[e];t<r[e].length&&(n.push(r[e][t]),i[e]=t+1,s=!0)}}return n}(c,n.catalogTopN);const l=e=>s.has(String(e.id))?s.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=>s.has(String(e.id))).sort((e,t)=>l(e)-l(t)),r=t.filter(e=>!s.has(String(e.id)));f.push(...n,...r)}return f.slice(0,n.catalogTopN)}catch{return e}}async function In(e){const{entries:t,intent:n,budget:r,rank:i}=e,s=new Set((e.pinnedIds??[]).map(String)),o=s.size?t.filter(e=>s.has(String(e.id))):[],a=function(e){const t=e.usagePriorWeight;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:1}(r),c=un(i,e.usage??(a>0?await async function(){try{return await yn().read()??{}}catch{return{}}}():{}),e.nowMs??Date.now(),a),l=function(e,t,n,r=[]){const i=[],s=new Set,o=new Map,a=(e,t)=>{const n=String(e.id);if(i.push(e),s.add(n),t){const e=vn(n);o.set(e,(o.get(e)??0)+1)}};for(const e of r){if(i.length>=t)break;null==e?.id||s.has(String(e.id))||a(e,!1)}for(const r of e){if(i.length>=t)break;const e=String(r?.id??"");e&&!s.has(e)&&((o.get(vn(e))??0)>=n||a(r,!0))}for(const n of e){if(i.length>=t)break;const e=String(n?.id??"");e&&!s.has(e)&&a(n,!0)}return i}(await bn(t,n,r,c),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),u=new Set(l.map(e=>String(e.id)));return{hot:l,deferred:t.filter(e=>!u.has(String(e.id)))}}const kn=/<\/?(tool_call|function|parameter)\b/i;function En(e){const t=(e??"").trim();return 0===t.length||kn.test(t)&&t.replace(/<[^>]*>/g,"").trim().length<20}const Sn=["capability.search","capability.describe"];function An(e){const t=e?.code;if("CAPABILITY_APPROVAL_REQUIRED"===t)return!0;const n=String(e?.message??e);return n.includes("Approval required")||n.includes("CAPABILITY_APPROVAL_REQUIRED")}function xn(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Cn(e){const t=String(e?.message??e).trim();return""===t?"Unknown error.":t}function Tn(e,t,n){return new Promise(r=>{const i=punica.kernel.Events.manager;let s=!1;const o=e=>{if(!s){s=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=i.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed","ai.pendingApprovalEdited","ai.pendingApprovalReferred","ai.pendingApprovalSigned"],n=>{const r=n?.payload?.payload??n?.payload,i=r?.pending;if(i?.id===e&&(!i?.traceId||i.traceId===t))if("ai.pendingApprovalReferred"!==n?.name&&"ai.pendingApprovalSigned"!==n?.name){if("ai.pendingApprovalEdited"===n?.name){const e=r?.arguments;if(!e||"object"!=typeof e||Array.isArray(e))return;return void o({decision:"edited",arguments:e,preview:i?.argsPreview})}o({decision:"ai.approvalRecorded"===n?.name?"approved":"dismissed"})}else clearTimeout(l)})??void 0,c=setInterval(()=>{n()&&o({decision:"cancelled"})},250),l=setTimeout(()=>o({decision:"timeout"}),18e4)})}async function _n(e,t,n,r,i){if(!n())return"resumed";const s=Date.now();for(Pn("ai.agentPaused",e,"audit",{runId:e,...t?{sessionId:t}:{}},i);n();){if(r())return"cancelled";await new Promise(e=>setTimeout(e,100))}return Pn("ai.agentResumed",e,"audit",{runId:e,pausedMs:Date.now()-s,...t?{sessionId:t}:{}},i),"resumed"}function Pn(e,t,n,r,i){const s=punica.kernel?.Events?.manager;s&&s.publishEvent({name:e,envelope:{id:s.createCorrelationId(),correlationId:t,traceId:t,...i?.spanId?{spanId:i.spanId}:{},...i?.parentSpanId?{parentSpanId:i.parentSpanId}:{},timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}function Nn(e){const{thinking:t,...n}=e;return n}function $n(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function Mn(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function Rn(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 On(e,t,n){const r=await e("capability.schemaExport",{filter:t.toolFilter,mode:"ai-tools"},n);let i=r?.capabilities??[];if(console.log("[AgentLoop] schemaExport raw catalog",{total:i.length,byCategory:i.reduce((e,t)=>{const n=vn(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map($n).sort(Mn),deferredIndex:[]};const s=i.filter(e=>Sn.includes(String(e.id)));i=i.filter(e=>!Sn.includes(String(e.id))&&(!function(e){const t=String(e?.id??"");return!("core"!==String(e?.origin??"core")||!t.startsWith("ai.")&&(t.startsWith("capability.")?Sn.includes(t):!t.startsWith("llm.")))}(e)&&(!Yt(e)&&(!(zt(e)&&!Jt())&&(!(!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={...on};for(const n of[an(),e]){if(!n)continue;for(const e of Object.keys(t))cn(n[e])&&(t[e]=Math.floor(n[e]));for(const e of["perCategoryCap","rankLimit"])cn(n[e])&&(t[e]=Math.floor(n[e]));const e=n.usagePriorWeight;"number"==typeof e&&Number.isFinite(e)&&e>=0&&(t.usagePriorWeight=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:i.length,includeIvyNodes:!!t.includeIvyNodes,includeMcp:!!t.includeMcp,allowedMcpServers:t.allowedMcpServers??[],willTier:!1!==t.deferToolLoading&&i.length>o.narrowThreshold,narrowThreshold:o.narrowThreshold}),i.length<=o.narrowThreshold)return{hot:i.map($n).sort(Mn),deferredIndex:[]};const a=async(t,r)=>{const i=await e("capability.recommend",{intent:t,limit:r},n);return i?.recommendations??[]};if(!1===t.deferToolLoading){return{hot:(await bn(i,t.query,o,a)).map($n).sort(Mn),deferredIndex:[]}}const{hot:c,deferred:l}=await(u={entries:i,intent:t.query,budget:o,pinnedIds:t.pinnedTools,rank:a},In(u));var u;const d=new Set(c.map(e=>String(e.id))),p="none"!==t.deferredIndex,f=p?s.length===Sn.length?s.map($n):[{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}}}}]:[],h=p?l.map(e=>({id:String(e.id),line:Rn(e),category:vn(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:h.length,deferredIndex:t.deferredIndex??"full",hotSetSize:o.hotSetSize,pinned:t.pinnedTools??[],hotIds:[...d]}),{hot:[...f,...c.map($n)].sort(Mn),deferredIndex:h}}async function Ln(e,t,n,r,i){let s,o=t.arguments;const a=()=>({id:t.id,name:t.name,arguments:o,status:"success",...s?{edited:!0,editedFields:s}:{}}),c=String(n.trace?.traceId??n.sessionId??"");let l=0,u=!1;for(;;){let d;try{const r=await e(t.name,o,n);return{...a(),status:"success",resultPayload:r}}catch(e){const n=Dn(e),r=Boolean(n)&&n!==t.name;if(!An(e)||l>=jn||l>0&&!r&&!u)return{...a(),status:"failed",error:String(e?.message??e)};d=r?n:t.name,u=r}const p=await Tn(d,c,r);if("edited"===p.decision){const e=Tt(o,p.preview,p.arguments),n=Object.keys({...o,...e}).filter(t=>!Fn(o[t],e[t])),r={...s??{}};for(const e of n)e in p.arguments?r[e]=p.arguments[e]:delete r[e];o=e,s=r,i&&Pn("ai.agentArgumentsEdited",i.runId,"audit",{runId:i.runId,toolCallId:t.id,name:t.name,changedKeys:n,argsPreview:p.preview},{parentSpanId:i.parentSpanId});continue}if("approved"!==p.decision){const e="dismissed"===p.decision?"the person denied it":"cancelled"===p.decision?"the run was stopped":"nobody answered in time";return{...a(),status:"blocked",error:`tool "${t.name}" not approved: ${e}`}}l+=1}}const jn=3;function Dn(e){const t=e?.details;return"string"==typeof t?.capability?t.capability:void 0}function Fn(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}async function Bn(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${Vn(n)}\nRejected arguments:\n${Vn(r)}\nValidation errors: ${i}\nReturn ONLY a JSON object with the corrected arguments — no prose, no code fence.`;try{const t=await e("llm.chat",{messages:[{role:"user",content:o}],correlationId:s.sessionId},s);return function(e){let t=(e??"").trim();if(!t)return;const n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");e>=0&&n>e&&(t=t.slice(e,n+1))}try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch{}}(t?.text??"")}catch{return}}async function qn(e,t,n,r,i,s){let o=t.arguments,a=!1,c="";for(let l=0;l<=2;l++){const u=await Ln(e,{...t,arguments:o},r,i,s);if("failed"!==u.status||!xn(u.error))return a&&!u.edited?{...u,arguments:o,repaired:!0}:u;if(c=u.error??"",2===l||i())break;const d=await Bn(e,t.name,n,o,c,r);if(!d)break;o=d,a=!0}const l={id:t.id,name:t.name,arguments:o,status:"failed",error:c||"input validation failed"};return a&&(l.repaired=!0),l}function Un(e){return Zt().estimate(e)}function Vn(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function Wn(e,n,r,i,s=()=>!1){const o=punica.kernel.Events.manager,a=i??o.createCorrelationId(),c=e.trace?.traceId??a,l="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,u=(d=e.profile,en[d??"balanced"]);var d;const p=[],f=e.sessionId?punica.kernel?.AI?.sessions:void 0,h=[];let m=0;const g=[],y=Date.now();let w=0,v=0,b=0,I=0,k=!1,E=0,S=!1,A=0;const x=(t,n,r)=>{const i={inputTokens:w,outputTokens:v,totalTokens:b,latencyMs:Date.now()-y,steps:p.length,toolCalls:A};S&&(i.totalCost=E),k&&(i.cacheReadTokens=I);const s={runId:a,finishReason:t,steps:p,usage:i};if(void 0!==n&&(s.finalText=n),void 0!==r&&(s.error=r),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:p.length}),(t=>{if(f&&e.sessionId&&0!==m)try{const n=[{role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}},...g];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}:{}}));f.appendMessages(e.sessionId,r,{runId:a})}catch(e){console.warn("[AgentLoop] session persist failed:",e)}})(n),f&&e.sessionId&&m>0)try{f.recordUsage?.(e.sessionId,i)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Pn("ai.agentFinished",a,"audit",{runId:a,finishReason:t,finalText:n,usage:i,...void 0!==r?{error:r}:{},...e.sessionId?{sessionId:e.sessionId}:{}}),s},C="string"==typeof e.coreId&&""!==e.coreId.trim()?e.coreId.trim():void 0;Pn("ai.agentStarted",a,"audit",{runId:a,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{},...e.stance?{stance:e.stance}:{},...C?{coreId:C}:{}});const T=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!T)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),x("error",void 0,"The capability gateway is unavailable.");const _=await t(),P=function(e,t,n,r,i,s){return{sessionId:e,workspaceId:r,actor:{type:"ai",id:"ai:agent"},origin:{kind:"ai",id:"kernel.agentLoop"},trace:{traceId:t,parentSpanId:n},policy:{mode:"execute",...s?{stance:s}:{}},...i?{signal:i}:{}}}(a,c,e.trace?.parentSpanId,_,r,e.stance);let N;if(e.sessionId&&(P.conversationId=e.sessionId),"ask"===e.stance)N={hot:[],deferredIndex:[]};else try{N=await On(T,e,P)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),x("error",void 0,Cn(e))}const $=[...N.hot];console.log("[AgentLoop] tool catalog built",{hot:$.length,deferred:N.deferredIndex.length,toolFilter:e.toolFilter??null,names:$.map(e=>e.name)});const M=new Map($.map(e=>[e.name,e.parameters])),R=new Map(N.deferredIndex.map(e=>[e.id,e])),O=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!M.has(String(e.id))).map($n).sort(Mn);for(const e of n)$.push(e),M.set(e.name,e.parameters),R.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:$.length}),n.length};if(h.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 i=t.dependencies?.python;i&&n.push(`Python deps (${i.source}, ${i.count}): ${(i.names??[]).join(", ")}`);const s=t.dependencies?.node;s&&n.push(`Node deps (${s.source}, ${s.count}`+(s.dev?` + ${s.dev} dev`:"")+`): ${(s.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 T("workspace.projectContext",{},P));e&&h.push({role:"system",content:e})}catch(e){console.warn("[AgentLoop] projectContext orientation unavailable:",e)}if(N.deferredIndex.length>0&&h.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."}}(N.deferredIndex)),f&&e.sessionId)try{h.push(...f.getContextMessages(e.sessionId))}catch(e){console.warn("[AgentLoop] session seed failed; running cold:",e)}h.push({role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}}),m=h.length;let L=0,j=!1;for(let t=0;t<l;t++){if(n())return x("cancelled");if("cancelled"===await _n(a,e.sessionId,s,n))return x("cancelled");const r=punica.kernel?.Events?.manager?.createCorrelationId?.()??`${a}-step-${t}`,i={...P,trace:{traceId:c,parentSpanId:r}},o=e=>{Pn("ai.agentStep",a,"audit",{runId:a,turn:Nn(e)},{spanId:r})};let l,d=!1;if(Xt(h)>u.maxContextTokens){const e=await sn(h,u,T,i);e.compacted&&(h.splice(0,h.length,...e.messages),L=0,d=!0,Pn("ai.agentContextCompacted",a,"info",{runId:a,step:t,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const f=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:t,messageCount:h.length,toolsSent:$.length,toolChoice:"auto",toolNames:$.map(e=>e.name)});const n={stableToolsAndSystem:!0,stableMessagePrefix:L,cacheKey:a};l=await T("llm.chatStream",{messages:h,...$.length>0?{tools:$,toolChoice:"auto"}:{},correlationId:a,cacheHints:n,...e.profile?{profile:e.profile}:{},...C?{providerId:C}:{}},i),L=h.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:t,textLen:(l?.text??"").length,toolCalls:l?.toolCalls?.length??0})}catch(e){console.error("[AgentLoop] llm.chatStream call failed; aborting run:",e);const n=e?.code,r="CAPABILITY_DENIED"===n||An(e);return o({index:t,toolCalls:[],latencyMs:Date.now()-f,outcome:r?"blocked":"error",error:Cn(e)}),x(r?"blocked":"error",void 0,Cn(e))}if(n())return o({index:t,toolCalls:[],latencyMs:Date.now()-f,outcome:"cancelled"}),x("cancelled");const m=Date.now()-f,y=(l.text??"").trim(),_="string"==typeof l.thinking?l.thinking:void 0,N=l.toolCalls??[],D={index:t,assistantText:y||void 0,thinking:_,toolCalls:[],latencyMs:m},F=l.usage,B=l.meta;F?(D.usage=F,w+=F.inputTokens??0,v+=F.outputTokens??0,b+=F.totalTokens??(F.inputTokens??0)+(F.outputTokens??0),"number"==typeof F.cacheReadInputTokens&&(I+=F.cacheReadInputTokens,k=!0)):B&&(D.usage={inputTokens:B.promptTokens,outputTokens:B.completionTokens,totalTokens:B.promptTokens+B.completionTokens},w+=B.promptTokens,v+=B.completionTokens,b+=B.promptTokens+B.completionTokens),B&&"number"==typeof B.totalCost&&(E+=B.totalCost,S=!0);const q={runId:a,step:t,estToolDefTokens:Un(JSON.stringify($)),estHistoryTokens:h.filter(e=>"system"!==e.role).reduce((e,t)=>e+Un(t.content??""),0),estSystemTokens:h.filter(e=>"system"===e.role).reduce((e,t)=>e+Un(t.content??""),0),toolCount:$.length,deferredToolCount:R.size,compactionApplied:d};if(D.usage&&(q.reportedInputTokens=D.usage.inputTokens,q.reportedOutputTokens=D.usage.outputTokens,"number"==typeof D.usage.cacheReadInputTokens&&(q.cacheReadTokens=D.usage.cacheReadInputTokens)),Pn("ai.agentTurnUsage",a,"audit",{...q},{parentSpanId:r}),0===N.length){if(p.push(D),o(D),!j&&En(y)){j=!0,h.push({role:"assistant",content:y}),h.push({role:"user",content:"Your last message was empty. In one or two sentences, say what you did and what the result was, without calling any tool."});continue}return x("final",y)}p.push(D),o(D);const U=N.map(e=>`${e.name}(${Vn(e.arguments)})`).join(", "),V={role:"assistant",content:y?`${y}\n[calling tools: ${U}]`:`[calling tools: ${U}]`,toolCalls:N.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};h.push(V),g.push(V);let W=!1;for(const o of N){if(n())return x("cancelled");if("cancelled"===await _n(a,e.sessionId,s,n,{parentSpanId:r}))return x("cancelled");if(Pn("ai.agentToolCall",a,"info",{runId:a,toolCall:{id:o.id,name:o.name,arguments:o.arguments},status:"running"},{parentSpanId:r}),!M.has(o.name)&&R.has(o.name))try{O(await T("capability.describe",{ids:[o.name]},i))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const c=await qn(T,o,M.get(o.name),i,n,{runId:a,parentSpanId:r});D.toolCalls.push(c),A++,dn(c.name,c.status,Sn)&&await wn(c.name,"success"===c.status,Date.now()),"success"===c.status&&"capability.describe"===c.name&&O(c.resultPayload),console.log("[AgentLoop] tool dispatched",{step:t,name:c.name,arguments:c.arguments,status:c.status,repaired:c.repaired??!1,error:c.error,resultPreview:"success"===c.status?Vn(c.resultPayload).slice(0,300):void 0}),Pn("ai.agentToolResult",a,"result",{runId:a,toolCall:c,status:c.status},{parentSpanId:r});const l="success"===c.status?Vn(c.resultPayload,u.toolResultMaxChars):`ERROR: ${c.error??"tool failed"}`,d={role:"tool",content:c.edited?`NOTE: the person changed the arguments before this call ran. Fields changed by the person: ${Vn(c.editedFields??{})}. This is their decision; do not call the tool again with the original arguments.\n${l}`:l,name:c.name,toolCallId:c.id};h.push(d),g.push(d),"blocked"===c.status&&(W=!0)}if(W)return x("blocked")}return x("maxSteps")}function Kn(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 Gn={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",POLICY_RULES:"runtime.policyRules"},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"}},Yn={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",EDIT_PENDING:"ai.editPendingArguments",REFER_PENDING:"ai.referPending",PAUSE_RUN:"ai.pauseRun",RESUME_RUN:"ai.resumeRun",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",TOOL_USAGE_FORGET:"ai.toolUsage.forget",TOOL_USAGE_LIST:"ai.toolUsage.list"},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 zn(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 Jn(e,t,n,r,i,s,o,a){punica.kernel?.Events?.manager&&punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,traceId:r,spanId:i,parentSpanId:s,timestampMs:Date.now(),source:o,kind:t},payload:a})}function Hn(e,t,n){try{punica.kernel?.Notifications?.manager?.push({id:"",timestamp:"",level:e,title:t,message:n,source:"ai"})}catch{}}function Qn(e){const t=e.calls>0?Math.round(e.ok/e.calls*100):0,n=`${e.calls} ${1===e.calls?"call":"calls"}`;return`${e.capabilityId} (${n}, ${t}% ok, weight ${e.prior.toFixed(2)})`}function Zn(e){return`${e} ${1===e?"capability":"capabilities"}`}const Xn=["ai.cellRejected","ai.cellRestored"];function er(e,t){const n=`cell ${t.cellId} in ${t.path}`;return"ai.cellRejected"===e?"replace"===t.kind?`The person undid your change to ${n}; it holds its previous source again. Do not redo it unless they ask.`:`The person removed the cell you added (${n}). Do not add it back unless they ask.`:"ai.cellRestored"===e?"replace"===t.kind?`The person restored your change to ${n}.`:`The person put back the cell you added (${n}).`:null}function tr(e){const t=e;if(!t||"object"!=typeof t)return null;const n="string"==typeof t.name&&t.payload&&"object"==typeof t.payload?t.payload:t;return"string"!=typeof n.path||"string"!=typeof n.cellId||"insert"!==n.kind&&"replace"!==n.kind?null:n}const nr="punica.kernel.ai.sessions.index.v1",rr="punica.kernel.ai.session.",ir=".v1";function sr(e){return`${rr}${e}${ir}`}function or(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const ar=new class{readIndex(){const e=or();if(!e)return[];try{const t=e.getItem(nr);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=or();if(t)try{t.setItem(nr,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=or();if(t)try{const n=t.getItem(sr(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=or();if(t)try{t.setItem(sr(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=or();if(t)try{t.removeItem(sr(e))}catch{}}};let cr=ar;function lr(){return cr}const ur="New chat";function dr(){return Date.now()}function pr(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${dr().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function fr(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:dr(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function hr(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function mr(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 gr=new class{async list(){try{return function(e,t){return Object.entries(e).map(([e,n])=>({capabilityId:e,calls:n.calls,ok:n.ok,last:n.last,prior:ln(n,t)})).sort((e,t)=>t.prior-e.prior||(e.capabilityId<t.capabilityId?-1:1))}(await yn().read()??{},Date.now())}catch{return[]}}async forget(){await yn().forget()}setStore(e){!function(e){gn=e??mn}(e)}},yr=new class{#L=null;#j=null;#D=new Map;#F=!1;#B=new Map;initialize(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{!function(e,t){const n=e?.payload??e,r=n?.request;if(!r?.id)return;const i=e?.envelope?.correlationId,s=n?.context?.workspaceId,o=n?.context?.traceId,a=punica.kernel.Events.manager.createCorrelationId(),c={pendingId:a,kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:n?.context?.reason??r.reason,...r.argsBinding?{argsBinding:r.argsBinding}:{},...void 0!==r.argsPreview?{argsPreview:r.argsPreview}:{},...r.maxScope?{maxScope:r.maxScope}:{},...Array.isArray(r.approvers)&&r.approvers.length?{approvers:[...r.approvers]}:{},...r.org?{org:r.org}:{},..."number"==typeof r.signatures&&r.signatures>1?{signatures:r.signatures}:{},correlationId:i,...o?{traceId:o}:{},workspaceId:s,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#D)}),function(e,t){for(const n of Xn)e.subscribe(n,e=>{try{const r=tr(e);if(!r||!r.sessionId)return;const i=t();if(!i||!i.get(r.sessionId))return;const s=er(n,r);if(!s)return;i.appendMessages(r.sessionId,[{id:"",createdAtMs:0,role:"user",name:"notebook",content:s}])}catch{}})}(punica.kernel.Events.manager,()=>punica.kernel.AI?.sessions),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#L=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(Yn.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(Yn.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(Yn.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=Kn(punica.kernel.Policy.manager.exportState(),2);if(t){const e=globalThis;if(void 0===e.document||void 0===e.Blob||void 0===e.URL)return console.warn("[Policy] Download not available in this environment. Exporting to console:"),void console.log("[Policy] Export:\n"+n);const t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),i=e.document.createElement("a");i.href=r,i.download=`punica-policy-export-${Date.now()}.json`,e.document.body.appendChild(i),i.click(),e.document.body.removeChild(i),URL.revokeObjectURL(r)}else console.log("[Policy] Export:\n"+n)}}),t.registerCommand(Yn.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(Yn.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`+Kn(e,2))}}),t.registerCommand(Yn.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(Yn.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(Yn.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(Yn.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(Yn.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 i="always"===r?"always":"workspace"===r?"workspace":"once";e.approvePending(n,i)||console.warn("[AI] Failed to approve pending",n)}}),t.registerCommand(Yn.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(Yn.AI.EDIT_PENDING,{title:"AI: Edit Pending Action Arguments…",description:"Send a pending policy-gated action back with different arguments; the gate asks again.",execute:t=>{const n=t?.pendingId;n&&(e.editPending(n,t?.arguments)||console.warn("[AI] Failed to edit pending",n))}}),t.registerCommand(Yn.AI.REFER_PENDING,{title:"AI: Ask a Reviewer About a Pending Action",description:"Hand a pending policy-gated action to a named reviewer; the run waits for their answer.",execute:t=>{const n=t?.pendingId;n&&t?.to&&(e.referPending(n,t.to)||console.warn("[AI] Failed to refer pending",n))}}),t.registerCommand(Yn.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)}});const n=e=>e&&"object"==typeof e&&(e.runId||e.sessionId)?{runId:e.runId,sessionId:e.sessionId}:void 0;t.registerCommand(Yn.AI.PAUSE_RUN,{title:"AI: Pause Run",description:"Hold AI runs at their next step. Bare: every run. Pass { runId } or { sessionId } to pause one run / one conversation only.",execute:t=>{e.setPauseRequested(!0,n(t))}}),t.registerCommand(Yn.AI.RESUME_RUN,{title:"AI: Resume Run",description:"Let paused AI runs continue. Bare: every run. Pass { runId } or { sessionId } to resume one run / one conversation only.",execute:t=>{e.setPauseRequested(!1,n(t))}}),t.registerCommand(Yn.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(Yn.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(Yn.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(Yn.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(Yn.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(Yn.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"+Kn(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+Kn(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(Yn.AI.TOOL_USAGE_LIST,{title:"AI: Show What Tool Selection Learned",description:"List the capabilities this installation has called, with the ranking weight each one currently carries.",execute:async()=>{const e=await(punica.kernel?.AI?.toolUsage?.list())??[];return console.log("[AI] toolUsage\n"+Kn(e)),0===e.length?(Hn("info","Tool selection has learned nothing yet","No capability has been called on this installation, so selection is ranking on the words of your request alone."),e):(Hn("info",`Tool selection has learned from ${Zn(e.length)}`,`Carrying the most weight right now: ${e.slice(0,3).map(Qn).join(", ")}. The full list is in the developer console.`),e)}}),t.registerCommand(Yn.AI.TOOL_USAGE_FORGET,{title:"AI: Forget What Tool Selection Learned",description:"Erase the record of which capabilities this installation has called. Tool ranking returns to what a fresh install would produce.",execute:async()=>{const e=await(punica.kernel?.AI?.toolUsage?.list())??[];try{await(punica.kernel?.AI?.toolUsage?.forget())}catch(e){throw Hn("error","Could not erase what tool selection learned",`The record is still on disk. ${e instanceof Error?e.message:String(e)}`),e}Hn("info",0===e.length?"There was nothing to forget":`Forgot ${Zn(e.length)}`,0===e.length?"Tool selection had no history on this installation.":"Tool ranking is back to what a fresh install produces.")}}),t.registerCommand(Yn.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(),i=t?.__punica?.traceId??r,s=t?.__punica?.spanId??punica.kernel.Events.manager.createCorrelationId(),o=t?.__punica?.source??"kernel:ai",a=e?.source;Jn("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:zn(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();Jn("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:zn(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),Jn("ai.summaryGenerated","result",r,i,punica.kernel.Events.manager.createCorrelationId(),u,o,{summary:l,usage:c?.usage,modelId:c?.modelId,provider:c?.provider,source:a})}catch(e){Jn("ai.response","error",r,i,punica.kernel.Events.manager.createCorrelationId(),s,o,{kind:"summarize",error:String(e?.message??e)})}}})}({runLastPlan:e=>this.runLastPlan(e),runAgent:e=>this.runAgent(e),getLastPlan:()=>this.getLastPlan(),approvePending:(e,t,n)=>this.approvePending(e,t,n),dismissPending:(e,t)=>this.dismissPending(e,t),referPending:(e,t)=>this.referPending(e,t),editPending:(e,t)=>this.editPending(e,t),getPendingApprovals:()=>this.getPendingApprovals(),getLastRun:()=>this.#j,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#B){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#F=e;for(const t of this.#B.values())t.cancelRequested=e,e&&t.controller.abort()}},setPauseRequested:(e,t)=>{for(const[n,r]of this.#B){(!t?.runId&&!t?.sessionId||(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId))&&(r.pauseRequested=e)}}})}getLastPlan(){return this.#L}getPendingApprovals(){return e=this.#D,Array.from(e.values()).sort((e,t)=>e.timestampMs-t.timestampMs);var e}approvePending(e,t,n){return At(e,t,this.#D,n)}dismissPending(e,t){return function(e,t,n){const r=t.get(e);if(!r)return!1;try{punica.kernel.Policy.manager.declineApproval?.({kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason,argsBinding:r.argsBinding,argsPreview:r.argsPreview},{workspaceId:r.workspaceId,...n?.decidedBy?{decidedBy:n.decidedBy}:{},...n?.decidedRole?{decidedRole:n.decidedRole}:{},...n?.reason?{reason:n.reason}:{},...r.traceId?{traceId:r.traceId}:{},...r.correlationId?{parentSpanId:r.correlationId}:{}})}catch(e){console.warn("[AI] the decline could not be recorded:",e)}return t.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalDismissed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r}}),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:"dismissed"}}),!0}(e,this.#D,t)}referPending(e,t){return function(e,t,n){const r=n.get(e);if(!r)return!1;const i=String(t??"").trim();if(!i)return!1;const s={...r,referredTo:i};return n.set(e,s),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalReferred",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"audit",...r.traceId?{traceId:r.traceId}:{}},payload:{pending:s,to:i}}),!0}(e,t,this.#D)}editPending(e,t){return function(e,t,n){const r=n.get(e);return!!r&&!!xt(t)&&(n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalEdited",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r,arguments: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:"edited"}}),!0)}(e,t,this.#D)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#L=e);const t=await Et(this.#L,this.#j,()=>this.#F,e=>{this.#L=e});return this.#j=t,this.#F=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,pauseRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#B.set(t,n);try{return await Wn(e,()=>n.cancelRequested,n.controller.signal,t,()=>n.pauseRequested)}finally{this.#B.delete(t)}}},wr=new class{#q;constructor(){this.#U()}#U(){const e=globalThis;"function"==typeof e?.addEventListener&&e.addEventListener("storage",e=>{try{this.#V(e?.key??null)}catch{}})}#V(e){const t=lr(),n=function(e){if(!e||!e.startsWith(rr)||!e.endsWith(ir))return;return e.slice(25,-3)||void 0}(e);if(n){const e=t.readSession(n);return void(e?fr("ai.sessionUpdated",e.meta,{external:!0}):fr("ai.sessionDeleted",{sessionId:n,title:"",createdAtMs:0,updatedAtMs:0,messageCount:0},{external:!0}))}if(e===nr){const e=t.readIndex().slice().sort((e,t)=>t.updatedAtMs-e.updatedAtMs)[0];e&&fr("ai.sessionUpdated",e,{external:!0,index:!0})}}create(e){const t=lr(),n={sessionId:pr("sess"),title:e?.title?.trim()||ur,createdAtMs:dr(),updatedAtMs:dr(),messageCount:0,tokenEstimate:0};e?.workspaceId&&(n.workspaceId=e.workspaceId);const r={version:1,meta:n,transcript:[]};t.writeSession(r);const i=t.readIndex();return i.push(n),this.#W(i,n),t.writeIndex(i),fr("ai.sessionCreated",n),{...n}}list(e){const t=lr().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return lr().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#K(e,e=>{e.title=n});return!!r&&(fr("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#K(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(fr("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=lr(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[i]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),fr("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=lr(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||pr("msg"),createdAtMs:e.createdAtMs||dr(),content:e.content.length>16e3?e.content.slice(0,16e3)+"…":e.content};return n?.runId&&!t.runId&&(t.runId=n.runId),t});i.transcript.push(...s),i.transcript.length>200&&i.transcript.splice(0,i.transcript.length-200);const o=i.meta;if(o.messageCount=i.transcript.length,o.updatedAtMs=dr(),n?.runId&&(o.lastRunId=n.runId),o.tokenEstimate=i.transcript.reduce((e,t)=>{return e+(n=t.content,Math.ceil(n.length/4));var n},0),o.title===ur){const e=i.transcript.find(e=>"user"===e.role);e&&(o.title=function(e){const t=e.replace(/\s+/g," ").trim();return t?t.length>48?t.slice(0,47)+"…":t:ur}(e.content))}r.writeSession(i),this.#G(o),fr("ai.sessionUpdated",o,{appendedCount:s.length,runId:n?.runId});const a=this.#q;a?.shouldCompact(i)&&Promise.resolve().then(()=>a.compact(i)).then(t=>{const n=lr().readSession(e);n&&(n.contextView=t,lr().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=lr().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(...hr(n.messages).map(mr)),e}return hr(t.transcript.slice(-40)).map(mr)}setCompactor(e){this.#q=e}recordUsage(e,t){const n=this.#K(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=dr(),e.usage=n});return!!n&&(fr("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#K(e,t){const n=lr(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=dr(),n.writeSession(r),this.#G(r.meta),{...r.meta}}#G(e){const t=lr(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#W(e,t){const n=lr(),r=e=>e.workspaceId===t.workspaceId;let i=e.filter(r);for(;i.length>50;){const s=i.filter(e=>e.sessionId!==t.sessionId).sort((e,t)=>{const n=e.archived?0:1,r=t.archived?0:1;return n!==r?n-r:e.updatedAtMs-t.updatedAtMs})[0];if(!s)break;const o=e.findIndex(e=>e.sessionId===s.sessionId);o>=0&&e.splice(o,1),n.deleteSession(s.sessionId),fr("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};wr.setCompactor(function(){const e=en.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=rn([{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(tn)?{...e,content:nn(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());const vr=gr;var br={manager:yr,sessions:wr,toolUsage:vr},Ir=Object.freeze({__proto__:null,default:br,manager:yr,sessions:wr,toolUsage:vr});function kr(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&&"assess"!==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}const Er=new class{#Y=new Map;#z=new Map;#J=new Map;#H=new Map;#Q=new Map;#Z=new Map;#X;registerProductOriginResolver(e){this.#X=e}#ee(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.#Y.has(e.id)){const n=this.#Y.get(e.id),r=n?.originExtension||this.#J.get(e.id),i=t||e.originExtension;if(!r||!i||r!==i)throw new Error(`Instruction class ID collision: "${e.id}" is already registered by a different extension. Each product extension must use namespaced IDs (e.g., "ivy.node.generator", "ivy.agent.generator").`)}!t&&e.productId&&this.#X&&(t=this.#X(e.productId)),t&&(e.originExtension=t,this.#J.set(e.id,t)),e.capability||(e.capability=kr(e)),this.#Y.set(e.id,e),this.#z.set(e.id,e.capability)}unregister(e){this.#H.has(e)?this.removeOverride(e):(this.#Y.delete(e),this.#z.delete(e),this.#J.delete(e))}unregisterByOrigin(e){const t=[];this.#J.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>{this.#Y.delete(e),this.#z.delete(e),this.#J.delete(e)});const n=[];this.#Z.forEach((t,r)=>{t===e&&n.push(r)}),n.forEach(e=>this.removeOverride(e))}registerOverride(e,t){if(!e.id)throw new Error("Instruction class override must have an id");if(!e.role)throw new Error("Instruction class override must have a role");if(!e.systemPrompt)throw new Error("Instruction class override must have a systemPrompt");const n=t||e.originExtension;n&&(e.originExtension=n,this.#Z.set(e.id,n)),e.capability||(e.capability=kr(e)),this.#H.set(e.id,e),this.#Q.set(e.id,e.capability)}removeOverride(e){this.#H.delete(e),this.#Q.delete(e),this.#Z.delete(e)}isOverridden(e){return this.#H.has(e)}getBase(e){return this.#Y.get(e)}get(e){return this.#H.get(e)??this.#Y.get(e)}list(e=!1){const t=new Map(this.#Y);this.#H.forEach((e,n)=>t.set(n,e));const n=Array.from(t.values());return e?n.filter(e=>{const t=e.originExtension||this.#te(e.id);return!t||this.#ee(t)}):n}#te(e){return this.#H.has(e)?this.#Z.get(e):this.#J.get(e)}listSummaries(e=!1){return this.list(e).map(e=>({id:e.id,role:e.role,originExtension:e.originExtension||this.#te(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0,...this.#H.has(e.id)?{overridden:!0,overridesExtension:this.#J.get(e.id)}:{}}))}has(e){return this.#H.has(e)||this.#Y.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#te(e);return!n||this.#ee(n)}getCapability(e){return this.#Q.get(e)??this.#z.get(e)}listCapabilities(){const e=new Map(this.#z);return this.#Q.forEach((t,n)=>e.set(n,t)),Array.from(e.values())}};async function Sr(e){const{primaryModelId:t,count:n,exclude:r}=e,i=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{return await e.listInstalled()}catch{return null}}();if(!i||!Array.isArray(i.installed)||0===i.installed.length)return t?[t]:[];const s=new Set(i.installed.map(e=>e.id)),o=[],a=e=>{e&&s.has(e)&&(function(e,t){return!(!t||0===t.length)&&t.includes(e)}(e,r)||o.includes(e)||o.push(e))};if(a(t),o.length<n)for(const e of i.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function Ar(e,t){const n=e.riskLevel;let r="assess"===n?void 0:n;if(!r){const n=await async function(e,t){if("risk-assessor"===e.id)return{riskLevel:"medium"};const n=Er.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,i=[];i.push("Assess the risk level for this task:"),i.push(""),i.push(`Instruction Class: ${e.id}`),i.push(`Role: ${e.role}`),i.push(""),i.push("User Prompt:"),i.push(t.userPrompt),i.push(""),i.push("Context:"),i.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),i.push(`- File Path: ${r?.filePath??"N/A"}`),i.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),i.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),i.push(""),i.push("Consider:"),i.push("- Is this production code?"),i.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),i.push("- Is it a critical business function?"),i.push("- Does it handle sensitive data?"),i.push("- Is it a simple utility or a complex system?"),i.push(""),i.push('Respond with ONLY one word: "low", "medium", or "high".');const s=i.join("\n");try{const e=punica.runtime.capabilities?.gateway,t=e?await e.call("llm.chat",{messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20,reasoning:"none"},{sessionId:"internal",workspaceId:void 0,actor:{type:"extension",extensionName:"kernel:policy"},origin:{kind:"command",id:"risk-assessment"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat({messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20,reasoning:"none"}),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);r=n.riskLevel}if(r||(r="medium"),"high"===r){const t=e.expertModelId,n=e.expertModelIds;let i=[];return i=n&&n.length>0?n.slice():await Sr({primaryModelId:t,count:3}),{strategy:i.length>1?"multi":"single",modelIds:i.length?i:[t].filter(Boolean),riskLevel:r,reason:"High risk detected via LLM-based assessment"}}let i=e.expertModelId??null;return i||(i=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:i?[i]:[],riskLevel:r,reason:"Low/medium risk, single expert sufficient"}}function xr(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 Cr(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function Tr(){const e=globalThis;return e.punica?.runtime?.fs}function _r(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Pr={type:"ai",id:"llm:context"},Nr={kind:"ai",id:"context-builder"};async function $r(e){if(e.filePath)try{const t=Cr(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:Pr,origin:Nr,trace:{traceId:_r()},policy:{mode:"execute"}}):await(Tr()?.readFile?.(e.filePath));if(!n)return;const r=5e3,i=n.length>r?n.slice(0,r)+"\n... (truncated)":n;return`File content (${e.filePath}):\n\`\`\`\n${i}\n\`\`\``}catch{return}}async function Mr(e){try{const t=Cr(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Pr,origin:Nr,trace:{traceId:_r()},policy:{mode:"execute"}}):await(Tr()?.getFileTree?.());if(!n||!Array.isArray(n)||0===n.length)return;const r=n.filter(e=>!e.isDirectory).length,i=n.filter(e=>e.isDirectory).length;return`Workspace structure: ${r} files, ${i} directories\nTop-level items: ${n.filter(e=>{const t=String(e.path??"");return!t.includes("/")||2===t.split("/").length}).slice(0,20).map(e=>{const t=String(e.name??"");if(t)return t;return String(e.path??"").split("/").pop()??""}).join(", ")}`}catch{return}}function Rr(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Or(){return"undefined"==typeof document?void 0:document}function Lr(){const e=Or();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 jr(e){try{const t=Rr();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Lr();if(!n)return;const r=n.getSelection?.(),i=n.getModel?.();if(!r||!i||r.isEmpty())return;const s=i.getValueInRange(r),o=String(s??"").trim();if(!o)return;const a=2e3,c=o.length>a?o.slice(0,a)+"\n... (truncated)":o,l=r.startLineNumber;return`Selected code (lines ${l}-${r.endLineNumber}):\n\`\`\`\n${c}\n\`\`\``}catch{return}}function Dr(){try{const e=Rr();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=Lr();if(e){const n=e.getPosition?.(),r=e.getModel?.();if(n&&r){const e=n.lineNumber,i=n.column,s=r.getOffsetAt(n);t.push(`Cursor position: Line ${e}, Column ${i} (offset: ${s})`)}}}catch{}try{const e=Or();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 Fr(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Br={type:"ai",id:"llm:context"},qr={kind:"ai",id:"context-builder"};async function Ur(e){const t=function(){const e=globalThis;return e.punica?.runtime?.vcs}();if(!t)return;const n=[];if(t.status)try{const r=function(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}(),i=r?await r.call("vcs.status",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Br,origin:qr,trace:{traceId:Fr()},policy:{mode:"execute"}}):await t.status();if(i){const e=[];i.current&&(e.push(`Branch: ${i.current}`),i.tracking&&e.push(`Tracking: ${i.tracking}`),i.ahead&&i.ahead>0&&e.push(`Ahead: ${i.ahead}`),i.behind&&i.behind>0&&e.push(`Behind: ${i.behind}`));const t=i.modified??[],r=i.staged??[],s=i.created??[],o=i.deleted??[],a=i.renamed??[],c=(t,n,r)=>{if(0===n.length)return;const i=n.slice(0,r).join(", "),s=n.length>r?"...":"";e.push(`${t} (${n.length}): ${i}${s}`)};c("Staged",r,5),c("Modified",t,5),c("Created",s,3),c("Deleted",o,3),c("Renamed",a,3),e.length>0&&n.push(`Git Status:\n${e.join("\n")}`)}}catch{}if(t.logs&&e.filePath)try{const e=await t.logs({limit:5});if(e&&Array.isArray(e)&&e.length>0){const t=e.slice(0,5).map(e=>{const t=e.hash?e.hash.substring(0,7):"unknown",n=e.date?new Date(e.date).toLocaleDateString():"",r=e.authorName??"",i=(e.message??"").split("\n")[0].substring(0,60);return` ${t} ${n} ${r?`(${r})`:""}: ${i}${i.length>=60?"...":""}`}).join("\n");n.push(`Recent Commits:\n${t}`)}}catch{}if(t.branches)try{const e=await t.branches();if(e&&Array.isArray(e)&&e.length>0){const t=e.find(e=>e.current),r=e.filter(e=>!e.current).slice(0,5),i=[];t?.name&&i.push(`Current: ${t.name}`),r.length>0&&i.push(`Other branches: ${r.map(e=>e.name).filter(Boolean).join(", ")}`),i.length>0&&n.push(`Branches:\n${i.join("\n")}`)}}catch{}return n.length>0?n.join("\n\n"):void 0}async function Vr(){const e=function(){const e=globalThis;return e.punica?.kernel?.Tasks?.manager}();if(!e)return;const t=[];try{const n=await(e.listRuns?.({status:["running","pending"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown";return` ${e.label??e.definitionId??"Unknown"} (${t})`}).join("\n");t.push(`Active Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listDefinitions?.());if(n&&n.length>0){const e=n.slice(0,10).map(e=>{const t=e.kind??"unknown",n=e.group?` [${e.group}]`:"";return` ${e.label??e.id??"Unknown"} (${t})${n}`}).join("\n");t.push(`Available Tasks (${n.length}):\n${e}`)}}catch{}try{const n=await(e.listRuns?.({status:["success","failed","cancelled"]}));if(n&&n.length>0){const e=n.slice(0,5).map(e=>{const t=e.status??"unknown",n=e.label??e.definitionId??"Unknown",r=null!=e.exitCode?` (exit: ${e.exitCode})`:"",i=e.startedAt?new Date(e.startedAt).toLocaleDateString():"";return` ${n}: ${t}${r}${i?` (${i})`:""}`}).join("\n");t.push(`Recent Task History:\n${e}`)}}catch{}return t.length>0?t.join("\n\n"):void 0}async function Wr(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 Kr="problems.getDiagnostics";function Gr(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===Kr))return;let r;try{r=t.executeCommand?.(Kr)}catch{return}if(!r||!Array.isArray(r)||0===r.length)return;const i=e.filePath?r.filter(t=>t.file===e.filePath):r;if(0===i.length)return;const s=i.slice(0,10).map(e=>{const t=e.file?`${e.file}:${e.line??0}:${e.column??0}`:`${e.line??0}:${e.column??0}`;return` ${(e.severity??"error").toUpperCase()} ${t}${e.source?`[${e.source}]`:""}${e.code?`(${e.code})`:""}: ${e.message??""}`}).join("\n"),o=i.length;return`Diagnostics (${o} ${1===o?"issue":"issues"}):\n${s}${o>10?`\n ... and ${o-10} more`:""}`}catch{return}}function Yr(e){return{id:e.id,systemPrompt:e.systemPrompt,outputSchema:e.outputSchema??null,responseFormat:e.responseFormat??null}}const zr=new Map;function Jr(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 Hr=new class{#ne;#re=[];constructor(e){this.#ne=Math.max(1,e?.maxRecords??1e4)}record(e){this.#re.push(e),this.#re.length>this.#ne&&this.#re.splice(0,this.#re.length-this.#ne)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,i=new Map;let s=0,o=0,a=0,c=0,l=0;for(const e of this.#re){if(e.timestamp<n||e.timestamp>r)continue;const u=Jr(t,e),d=i.get(u)??{cost:0,calls:0,promptTokens:0,completionTokens:0,cachedPromptTokens:0};d.cost+=e.totalCost,d.calls+=1,d.promptTokens+=e.promptTokens,d.completionTokens+=e.completionTokens,d.cachedPromptTokens+=e.cachedPromptTokens??0,i.set(u,d),s+=e.totalCost,o+=1,a+=e.promptTokens,c+=e.completionTokens,l+=e.cachedPromptTokens??0}const u=Array.from(i.entries()).map(([e,t])=>({key:e,cost:t.cost,calls:t.calls,promptTokens:t.promptTokens,completionTokens:t.completionTokens,cachedPromptTokens:t.cachedPromptTokens})).sort((e,t)=>t.cost-e.cost);return{scope:t,totalCost:s,totalCalls:o,totalPromptTokens:a,totalCompletionTokens:c,totalCachedPromptTokens:l,byKey:u}}clear(){this.#re.length=0}};function Qr(e){return e.remaining[0]}function Zr(e,t,n,r){if(e.terminal)return e;const i=function(e,t){return"error"===e?t.onError??"fail":"timeout"===e?t.onTimeout??"fail":t.onRateLimit??"next"}(t,n),s=e.remaining[0];if(!s)return{...e,terminal:!0,lastError:r??e.lastError};if("fail"===i)return{...e,attempted:[...e.attempted,s],position:e.position+1,remaining:[],terminal:!0,pendingQueue:!1,lastError:r??e.lastError};if("queue"===i)return{...e,pendingQueue:!0,lastError:r??e.lastError};const o=e.remaining.slice(1);return{...e,position:e.position+1,attempted:[...e.attempted,s],remaining:o,terminal:0===o.length,pendingQueue:!1,lastError:r??e.lastError}}function Xr(e){return{...e,terminal:!0,pendingQueue:!1}}let ei;function ti(e){ei=e}function ni(e){return!!e&&"string"==typeof e.providerId&&""!==e.providerId.trim()}const ri={onError:"next",onTimeout:"next",onRateLimit:"next"};function ii(e){const t=e?.status??e?.statusCode;return"number"==typeof t&&(408!==t&&429!==t&&(401!==t&&403!==t&&(t>=400&&t<500)))}function si(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 oi(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}:{}}}function ai(e){const{llmRes:t,latencyMs:n,promptVersion:r,chainPosition:i,workspaceId:s}=e;try{const o=t.usage?.inputTokens??0,a=t.usage?.outputTokens??0,c=t.usage?.cacheReadInputTokens??0,l=String(t.provider??"unknown"),u=String(t.modelId??"unknown"),d=0,p={provider:l,model:u,promptTokens:o,completionTokens:a,totalCost:d,latencyMs:n,promptVersion:r,...t.meta?.cacheHit?{cacheHit:!0}:{},...void 0!==i?{fallbackChainPosition:i}:{}};Hr.record({capabilityId:e.capabilityId,provider:l,model:u,promptTokens:o,completionTokens:a,...c>0?{cachedPromptTokens:c}:{},totalCost:d,latencyMs:n,timestamp:Date.now(),workspaceId:s}),punica.kernel.Events.manager.publishEvent({name:"llm.call",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:e.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:e.capabilityId,workspaceId:s,meta:p}})}catch{}}async function ci(e,n){const r=Er;if(!r)return{ok:!1,error:"Instruction class registry not available",metadata:{instructionClass:e.instructionClass,role:"unknown"}};if(!(r.isAvailable?r.isAvailable(e.instructionClass):r.has(e.instructionClass))){const t=r.get(e.instructionClass);return t?{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_ORIGIN_EXTENSION_INACTIVE",error:`Instruction class "${e.instructionClass}" is registered but its origin extension is not active`,metadata:{instructionClass:e.instructionClass,role:t.role,originExtension:t.originExtension,productId:t.productId}}:{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}}}const i=r.get(e.instructionClass);if(!i)return{ok:!1,blocked:!0,reasonCode:"LLM_PROFILE_NOT_REGISTERED",error:`Unknown instruction class: ${e.instructionClass}`,metadata:{instructionClass:e.instructionClass,role:"unknown"}};try{const r=await async function(e){return e?(await Promise.all([Promise.resolve(xr(e)),$r(e),Promise.resolve(jr(e)),Mr(e),Ur(e),Vr(),Promise.resolve(Dr()),Wr(e),Promise.resolve(Gr(e))])).filter(e=>void 0!==e&&e.length>0).join("\n\n"):""}(e.context),s=r?`${r}\n\n${e.userPrompt}`:e.userPrompt,o=await Ar(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,reasoning:e.options?.reasoning??i.reasoning??"none",...!0===e.options?.skipCache?{skipCache:!0}:{},correlationId:n?.correlationId??punica.kernel.Events.manager.createCorrelationId()},c=!0===e.options?.stream?"llm.chatStream":"llm.chat";let l,u,d=0;const p=await t(),f=async(t,r)=>{const i=punica.kernel.Events.manager;return await punica.runtime.capabilities.gateway.call(t,{...a,...r},{sessionId:a.correlationId??i.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??i.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:i.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(ni);if(!ei)return[];try{const e=ei();return Array.isArray(e)?e.filter(ni):[]}catch{return[]}}(i);let g;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=Qr(t);if(!n)break;const r=Date.now();try{l=await f(c,oi(n)),d=Date.now()-r,g=t.position,t=Xr(t);break}catch(r){if(e=r,ii(r))break;const s=Zr(t,si(r),i.fallbackPolicy??ri,r);if(s.pendingQueue){t={...s,terminal:!0};break}const o=Qr(s);o&&h(n.providerId,o.providerId,r?.message??"unknown"),t=s}}if(!l)throw e??new Error(`No provider in the chain for "${i.id}" produced a response.`);0===d&&(d=Date.now()-n)}else if("single"===o.strategy||o.modelIds.length<=1){const t=o.modelIds[0],r=Date.now();try{const i=punica.kernel.Events.manager;l=await punica.runtime.capabilities.gateway.call(c,{...a,modelId:t},{sessionId:a.correlationId??i.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??i.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-r}catch(t){if(!(o.modelIds.length>1)||e.options?.skipFallback)throw t;{let r=t;for(const t of o.modelIds.slice(1))try{const s=Date.now(),c=punica.kernel.Events.manager;try{c.publishEvent({name:"llm.fallback",envelope:{id:c.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,fromModelId:o.modelIds[0],toModelId:t,reason:r?.message??"unknown"}})}catch{}l=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??c.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??c.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-s;break}catch(e){r=e;continue}if(!l)throw r}}}else{const t=Date.now(),r=punica.kernel.Events.manager,s=o.modelIds.map(async t=>{const s=Date.now(),o=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:n?.trace?{traceId:n.trace.traceId,parentSpanId:n.trace.parentSpanId}:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),c=Date.now()-s;let l;if(i.outputSchema&&"json_object"===i.responseFormat)try{l=JSON.parse(o.text)}catch{}return{res:o,expert:{modelId:o.modelId??t,text:o.text,structured:l,usage:o.usage,latencyMs:c}}}),c=await Promise.all(s);u=c.map(e=>e.expert);const f=function(e,t){if(!e.length)throw new Error("aggregateBestOfN called with no results");if("json_object"===t.responseFormat){const t=e.filter(e=>void 0!==e.structured);if(t.length>0)return t.reduce((e,t)=>t.latencyMs<e.latencyMs?t:e)}return e.reduce((e,t)=>{const n=e.text.length-e.latencyMs/1e3+.1*(e.usage?.outputTokens??0);return t.text.length-t.latencyMs/1e3+.1*(t.usage?.outputTokens??0)>n?t:e})}(u,i);l={text:f.text,modelId:f.modelId,provider:c.find(e=>e.expert.modelId===f.modelId)?.res.provider,usage:f.usage},d=Date.now()-t}const y=await async function(e){const t=Ne(Yr(e)),n=zr.get(t);if(n)return n;const r=await Oe(Yr(e));if(zr.size>=64){const e=zr.keys().next().value;void 0!==e&&zr.delete(e)}return zr.set(t,r),r}(i),w=l.usage?.outputTokens,v=a.maxTokens,b="number"==typeof w&&"number"==typeof v&&v>0&&w>=v,I=l.text.trim().length>0||(l.toolCalls?.length??0)>0,k={instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId,promptVersion:y,tokensUsed:l.usage?.totalTokens,inputTokens:l.usage?.inputTokens,outputTokens:w,latencyMs:d,modelId:l.modelId,provider:l.provider,...b?{truncated:!0}:{},...l.meta?.cacheHit?{cacheHit:!0}:{}};if(ai({capabilityId:i.id,llmRes:l,latencyMs:d,promptVersion:y,chainPosition:g,workspaceId:p,correlationId:a.correlationId}),!I)return{ok:!1,reasonCode:"LLM_EMPTY_ANSWER",error:b?`The model returned no answer: it reached its output budget of ${v} tokens without emitting any text. A reasoning model spends this budget on thinking, so declare \`reasoning: none\` or raise maxTokens for "${i.id}".`:"The model returned no answer: the response carried no text and no tool calls.",metadata:k};let E;if(i.outputSchema&&"json_object"===i.responseFormat)try{E=JSON.parse(l.text)}catch(e){return{ok:!1,reasonCode:"LLM_STRUCTURED_PARSE_FAILED",error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}${b?` (the answer was cut off at its ${v}-token output budget, so it is incomplete rather than malformed)`:""}`,metadata:k}}return{ok:!0,text:l.text,structured:E,metadata:k}}catch(e){return{ok:!1,error:`LLM invocation failed: ${e?.message??String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}}async function li(e){return ci({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 ui(e){return ci({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function di(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 ci({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function pi(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function fi(e,t){const n=pi(e).split("/").filter(Boolean),r=pi(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function hi(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function mi(e,t){const n=pi(e).split("/").filter(Boolean),r=pi(t).split("/").filter(Boolean);let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;const s=n.length-i,o=r.slice(i);return[...Array(s).fill(".."),...o].join("/")}async function gi(e,t){const n=[];let r=0;const i=1048576;if("0.1"!==e.specVersion)throw new Error(`Unsupported CodegenBundle version: ${e.specVersion}`);if(!e.files||!Array.isArray(e.files))throw new Error("CodegenBundle must have a files array");if(0===e.files.length)throw new Error("CodegenBundle files array cannot be empty");if(e.files.length>50)throw new Error(`CodegenBundle exceeds max files limit: ${e.files.length} > 50`);let s=0;const o=/^(?!\/)(?!.*\.\.)([a-zA-Z0-9._-]+\/)*[a-zA-Z0-9._-]+$/;for(const r of e.files){if(!o.test(r.path)){n.push({path:r.path,error:"Invalid path: must be relative, no absolute paths, no .."});continue}if("delete"===r.action){if(void 0!==r.content){n.push({path:r.path,error:"Delete action cannot have content"});continue}}else if("create"===r.action||"update"===r.action){if(!r.content){n.push({path:r.path,error:`${r.action} action requires content`});continue}s+=r.content.length}const e=mi(t,fi(t,pi(r.path)));(e.startsWith("..")||hi(e))&&n.push({path:r.path,error:"Path traversal detected"})}if(s>i)throw new Error(`CodegenBundle exceeds max total size: ${s} > 1048576 bytes`);for(const t of e.files)if(!n.some(e=>e.path===t.path))try{const e=pi(t.path);if("create"===t.action){const n=e.split("/");if(n.length>1){const e=n.slice(0,-1).join("/");try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFolder(e)}catch{}}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.createFileWithContent(e,t.content),r++}else if("update"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{n.push({path:t.path,error:"File does not exist for update"});continue}const i=punica.runtime.capabilities?.gateway;i?await i.call("fs.writeFile",{path:e,content:t.content},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.updateFileContent(e,t.content),r++}else if("delete"===t.action){try{const t=punica.runtime.capabilities?.gateway;t?await t.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:void 0,actor:{type:"ai",id:"codegen"},origin:{kind:"ai",id:"codegen-bundle"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.fs.readFile(e)}catch{continue}await punica.runtime.fs.deleteFile(e),r++}}catch(e){n.push({path:t.path,error:e?.message??String(e)})}return{applied:r,errors:n}}const yi={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 wi=new class{api;constructor(){this.api={instructionClassRegistry:Er,invoke:ci,plan:li,generateCode:ui,editWorkflow:di,listInstructionClasses:e=>Er.listSummaries(e),setDefaultProviderChainResolver:ti}}};var vi={manager:wi};const bi={Commands:g,History:w,TimeServer:v,Tasks:S,Events:ue,Notifications:he,Policy:It,AI:Ir,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:yi,applyCodegenBundle:gi,default:vi,manager:wi})};function Ii(e,t){switch(e.mode){case"extension":return function(e,t){const n=t.path.split(".").pop();return!(!n||!1===t.path.endsWith(`.${n}`))&&n.toLowerCase()===e.toLowerCase()}(e.pattern,t);case"mime":return function(e,t){if(!t.mimeType)return!1;const n=e.toLowerCase(),r=t.mimeType.toLowerCase();if(n.endsWith("/*")){const e=n.slice(0,-2);return r.startsWith(e+"/")}return r===n}(e.pattern,t);case"glob":return function(e,t){const n="__DOUBLE_STAR_PLACEHOLDER__",r="__SINGLE_STAR_PLACEHOLDER__",i=e.replace(/\*\*/g,n).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),".*").replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"[^/]*");return new RegExp(`^${i}$`,"i").test(t.path)}(e.pattern,t);default:return!1}}const ki=new class{#ie=[];register(e){this.#ie=this.#ie.filter(t=>t.id!==e.id),this.#ie.push({priority:0,...e}),this.#ie.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#ie=this.#ie.filter(t=>t.id!==e)}clear(){this.#ie=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#ie){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>Ii(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.#ie.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>Ii(t,e))}).map(e=>({opener:e,command:e.command}))}};function Ei(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 Si="runtime:fileOperations";function Ai(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function xi(e){return"object"==typeof e&&null!==e&&!0===e.veto}const Ci=new class{#se=new Map;#oe=new Set;#ae(){const e=globalThis.punica?.runtime?.fs;if(!e)throw new Error("[Runtime.fileOperations] No FileSystem provider is available.");return e}registerParticipant(e){const{id:t}=e;if(!t)throw new Error("[Runtime.fileOperations] A participant must declare an id.");return this.#se.set(t,e),{dispose:()=>{this.#se.get(t)===e&&this.#se.delete(t)}}}setDirty(e,t){t?this.#oe.add(e):this.#oe.delete(e)}isDirty(e){return this.#oe.has(e)}getDirtyPaths(e){const t=Array.from(this.#oe);return void 0===e?t:t.filter(t=>{return(r=t)===(n=e)||r.startsWith(`${n}/`);var n,r})}async rename(e,t,n){if(!e||!t)throw new Error("[Runtime.fileOperations] rename requires both oldPath and newPath.");if(e===t)return;const r=await this.#ce(e,n?.isDirectory),i={oldPath:e,newPath:t,isDirectory:r};await this.#le("rename",e=>e.willRename?.(i));const s=this.#ae();r?await s.renameFolder(e,t):await s.renameFile(e,t);for(const n of this.getDirtyPaths(e))this.#oe.delete(n),this.#oe.add(Ai(n,e,t));await this.#ue("rename",e=>e.didRename?.(i)),Ei({name:"workspace.files.didRename",source:Si,payload:{oldPath:e,newPath:t,isDirectory:r}})}async delete(e,t){if(!e)throw new Error("[Runtime.fileOperations] delete requires a path.");const n=await this.#ce(e,t?.isDirectory),r={path:e,isDirectory:n};await this.#le("delete",e=>e.willDelete?.(r));const i=this.#ae();n?await i.deleteFolder(e):await i.deleteFile(e,t?.ifExists?{ifExists:!0}:void 0);for(const t of this.getDirtyPaths(e))this.#oe.delete(t);await this.#ue("delete",e=>e.didDelete?.(r)),Ei({name:"workspace.files.didDelete",source:Si,payload:{path:e,isDirectory:n}})}async#ce(e,t){if("boolean"==typeof t)return t;const n=this.#ae().stat;if("function"!=typeof n)return!1;try{return(await n(e)).isDirectory}catch{return!1}}async#le(e,t){for(const n of this.#se.values()){const r=await t(n);if(xi(r))throw new Error(r.reason??`The ${e} was cancelled by "${n.id}".`)}}async#ue(e,t){for(const n of this.#se.values())try{await t(n)}catch(t){console.error(`[Runtime.fileOperations] participant "${n.id}" failed after ${e}`,t),Ei({name:"workspace.files.participantFailed",source:Si,kind:"error",payload:{participantId:n.id,operation:e,error:t instanceof Error?t.message:String(t)}})}}};function Ti(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}}}}const _i=Ti({label:"Runtime.resources",noProviderMessage:"[Runtime.resources] No Resources provider registered. This host keeps no resource registry; a host that does calls punica.runtime.setResourcesProvider() (or attaches punica.runtime.resources before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.resources;if(void 0!==t&&!Ni(t))return t}});function Pi(e){_i.set(e)}function Ni(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedResourcesFacade}const $i=Ti({label:"Runtime.search",noProviderMessage:"[Runtime.search] No Search provider registered. This host indexes no workspace; a host that does calls punica.runtime.setSearchProvider() (or attaches punica.runtime.search before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.search;if(void 0!==t&&!Ri(t))return t}});function Mi(e){$i.set(e)}function Ri(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedSearchFacade}const Oi=Ti({label:"Runtime.tasks",noProviderMessage:"[Runtime.tasks] No Tasks provider registered. This host runs no local processes; a host that does calls punica.runtime.setTasksProvider() (or attaches punica.runtime.tasks before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.tasks;if(void 0!==t&&!ji(t))return t}});function Li(e){Oi.set(e)}function ji(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedTasksFacade}const Di=Ti({label:"Runtime.terminals",noProviderMessage:"[Runtime.terminals] No Terminal provider registered. This host opens no terminal; a host that does calls punica.runtime.setTerminalProvider() (or attaches punica.runtime.terminals before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.terminals;if(void 0!==t&&!Bi(t))return t}});function Fi(e){Di.set(e)}function Bi(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedTerminalFacade}let qi;function Ui(){if(qi)return qi;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}const Vi=Ti({label:"Runtime.vcs",noProviderMessage:"[Runtime.vcs] No Vcs provider registered. This host reads no repository; a host that does calls punica.runtime.setVcsProvider() (or attaches punica.runtime.vcs before the substrate boots).",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.vcs;if(void 0!==t&&!Ki(t))return t}});function Wi(e){Vi.set(e)}function Ki(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedVcsFacade}const Gi=Ti({label:"Runtime.workspace",noProviderMessage:"[Runtime.workspace] No Workspace provider registered. Host must attach punica.runtime.workspace",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.workspace;if(!Ji(t))return t}});function Yi(){return Gi.get()}function zi(e){Gi.set(e),e&&Ei({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Ji(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedWorkspaceFacade}function Hi(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}}function Qi(e){return!!e&&"local"!==Zi(e)}function Zi(e){if(!e)return;const t=String(e).trim().toLowerCase();return""!==t?t.startsWith("local:")||"local"===t||"mock"===t||"ollama"===t||t.startsWith("ollama-")||"llama.cpp"===t||"llamacpp"===t?"local":"remote":void 0}async function Xi(e,t){if("remote"===e?.route)return"remote";if("local"===e?.route)return"local";const n=Zi(e?.providerId);if("remote"===n||"local"===n){const t=String(e?.providerId??"").trim().toLowerCase();if(t.startsWith("remote:")||t.startsWith("local:")||"local"===t)return n}const r=t?.describeDestination;if("function"==typeof r)try{const n=await r.call(t,e);if("local"===n||"remote"===n)return n}catch{}const i=t?.id;return"string"==typeof i&&""!==i?Qi(i)?"remote":"local":"unknown"}let es;function ts(){return es}function ns(e){const t=e.response;return{...t,usage:{inputTokens:0,outputTokens:0,totalTokens:0},meta:{...t.meta??{provider:String(t.provider??"unknown"),model:String(t.modelId??"unknown"),promptTokens:0,completionTokens:0,totalCost:0,latencyMs:0},promptTokens:0,completionTokens:0,totalCost:0,cacheHit:!0}}}const rs=Symbol("punica.llm.gatewayGovernedAi");let is,ss,os;function as(){if(is)return is;const e=punica.runtime.llm;if(!e||"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedLlmFacade)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");var t;return is=e,is}function cs(e){if(is=e,ss=void 0,os=void 0,!e)return;const t=e;Hi("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class ls{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 us=null;function ds(){return us||(us=new ls),us}class ps{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 fs{providerSession;id;providerId;language;kernelspec;languageRuntime;constructor(e,t,n,r,i,s){this.providerSession=e,this.id=t,this.providerId=n,this.language=r,this.kernelspec=i,this.languageRuntime=s}run(e,t){const n=t?.runId??function(e="id"){const t=globalThis;if(t.crypto?.randomUUID)return`${e}_${t.crypto.randomUUID()}`;const n=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${n}`}("run"),r={id:this.id,providerId:this.providerId,language:this.language,kernelspec:this.kernelspec},i=this.languageRuntime.prepare(e,r);return this.providerSession.run(i,n,t)}async interrupt(){return this.providerSession.interrupt()}async restart(){return this.providerSession.restart()}async close(){return this.providerSession.close()}}const hs={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}}},ms={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}}},gs={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},ys={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},ws={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 vs(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 bs{registry;router;constructor(e,t){this.registry=e,this.router=t}async open(e){const t=this.router.selectProvider(e),n=this.router.selectLanguageRuntime(e.language),r=this.router.resolveKernelSpec(e,n),i=await t.openSession({...e,kernelspec:r}),s=vs("session");return new fs(i,s,t.id,e.language,r,n)}}class Is{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 ks=null;function Es(){return ks||(ks=new Is),ks}class Ss{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 As{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 xs=null;function Cs(){return xs||(xs=new As),xs}class Ts{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 _s{#de=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#de.set(e.id,e)}get(e){return this.#de.get(e)}list(){return Array.from(this.#de.values())}select(e){return this.list().find(t=>t.canRun(e))}}let Ps=null;function Ns(){return Ps||(Ps=new _s),Ps}function $s(e,t){const n=Math.min(e.length,t.length);let r=0,i=0,s=0;for(let o=0;o<n;o++)r+=e[o]*t[o],i+=e[o]*e[o],s+=t[o]*t[o];return 0===i||0===s?0:r/(Math.sqrt(i)*Math.sqrt(s))}const Ms="default";class Rs{#pe=new Map;#fe(e){const t=e||Ms;let n=this.#pe.get(t);return n||(n=new Map,this.#pe.set(t,n)),n}upsert(e,t=Ms){const n=this.#fe(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=Ms){const r=this.#fe(n),i=[];for(const t of r.values())i.push({id:t.id,score:$s(e,t.vector),text:t.text,metadata:t.metadata});return i.sort((e,t)=>t.score-e.score),i.slice(0,Math.max(0,t))}delete(e,t=Ms){const n=this.#fe(t);for(const t of e)n.delete(t)}clear(e=Ms){this.#pe.delete(e||Ms)}count(e=Ms){return this.#fe(e).size}export(e=Ms){return Array.from(this.#fe(e).values())}import(e,t=Ms){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#pe.set(t||Ms,n)}}const Os=".punica/vectors";class Ls{#b=new Rs;#he=new Set;#ae(){try{return punica.runtime?.fs}catch{return}}#me(e){return`${Os}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#ge(e){const t=e||"default";if(this.#he.has(t))return;this.#he.add(t);const n=this.#ae();if(n?.readFile)try{const e=await n.readFile(this.#me(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#b.import(r.records,t)}catch{}}async#ye(e){const t=this.#ae();if(t)try{if(t.mkdir)try{await t.mkdir(Os)}catch{}const n={version:1,records:this.#b.export(e)},r=this.#me(e),i=JSON.stringify(n);try{await t.updateFileContent(r,i)}catch{await t.createFileWithContent(r,i)}}catch(e){console.warn("[Runtime.vectors] Failed to persist collection:",e)}}async upsert(e,t){const n=t?.collection??"default";await this.#ge(n),this.#b.upsert(e,n),await this.#ye(n)}async query(e){const t=e.collection??"default";return await this.#ge(t),this.#b.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#ge(n),this.#b.delete(e,n),await this.#ye(n)}async clear(e){const t=e?.collection??"default";await this.#ge(t),this.#b.clear(t),await this.#ye(t)}async count(e){const t=e?.collection??"default";return await this.#ge(t),this.#b.count(t)}}let js,Ds,Fs;function Bs(){return js||(Ds||(Ds=new Ls),Ds)}function qs(){if(!Fs)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 Fs}var Us;!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"}(Us||(Us={}));class Vs extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const Ws=new class{#we=new Map;#ve=new Map;registerCapability(e){if(!e.name)throw new Vs(Us.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new Vs(Us.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 Vs(Us.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.#we.has(e.name))throw new Vs(Us.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 Vs(Us.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 Vs(Us.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.#be(t,e.name);if(n)throw new Vs(Us.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#we.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{}}#be(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#we.get(e);if(!r?.requires)return null;for(const i of r.requires){const r=this.#be(i,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#we.has(e.name))throw new Vs(Us.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ve.set(e.name,e)}getSpec(e){return this.#we.get(e)}getProvider(e){return this.#ve.get(e)}hasCapability(e){return this.#we.has(e)}hasProvider(e){return this.#ve.has(e)}listCapabilities(){return Array.from(this.#we.keys())}getAllSpecs(){return Array.from(this.#we.values())}clear(){this.#we.clear(),this.#ve.clear()}};function Ks(e){const t={id:e.name,title:e.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 e.description&&(t.description=e.description),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.action&&e.action.length>0&&(t.action=[...e.action]),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),e.dataClassification&&(t["x-dataClassification"]=e.dataClassification),t}function Gs(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:Hs(e.sideEffects),risk:e.policy?.risk??"low",permissions:n,inputSchema:e.inputs?.schema,outputSchema:e.outputs?.schema};e.title&&e.title!==e.id&&(r.title=e.title),e.description&&(r.description=e.description),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);const i=t["x-dataClassification"]??t.dataClassification;return"public"!==i&&"internal"!==i&&"sensitive"!==i||(r.dataClassification=i),e.deprecated&&(r.deprecated={...e.deprecated}),Array.isArray(e.requires)&&e.requires.length>0&&(r.requires=[...e.requires]),Array.isArray(e.action)&&e.action.length>0&&(r.action=[...e.action]),e.policy&&(r.policy={...e.policy}),r}const Ys=["write","delete","remove","modify","destroy","create","update","install","publish","process","spawn","exec","run"],zs=["network","http","fetch","request","upload","download"],Js=["read","list","get","query","inspect","search"];function Hs(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":Ys.some(t=>e.includes(t))?"write":zs.some(t=>e.includes(t))?"network":Js.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 Qs=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function Zs(){const e=globalThis;return e.punica?.extensions?.manager}function Xs(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function eo(){const e=globalThis;return e.punica?.flow?.registry}function to(e){const t=Array.isArray(e.action)?e.action:[];return t.includes("process.exec")?e:{...e,action:[...t,"process.exec"]}}function no(){const e=globalThis;return e.punica?.flow?.agents}function ro(e,t){const n=(t?.graph?.nodes??[]).filter(e=>"flowInput"!==e?.ref?.kind&&"flowOutput"!==e?.ref?.kind),r=n.filter(e=>"ivy.agent.turn"===e?.ref?.id).length,i=[...Array.isArray(e.action)?e.action:[]];i.includes("process.exec")||i.push("process.exec"),r>0&&!i.includes("model.invoke")&&i.push("model.invoke");const s=e.execution,o="number"==typeof s?.timeoutMs?s.timeoutMs:Math.max(12e4,3e4*(n.length-r)+6e5*r);return{...e,action:i,execution:{...s??{},timeoutMs:o}}}function io(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const so={core:function(e){const t=Ws.getSpec(e);if(t)return{origin:"core",definition:Ks(t)}},extension:function(e){const t=Zs();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=Xs();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=eo();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-node",definition:to(r),metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},"ivy-agent":function(e){const t=no();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-agent",definition:ro(r,n.manifest),metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},mcp:function(e){const t=io();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},oo={core:function(){return Ws.getAllSpecs().map(e=>({origin:"core",definition:Ks(e)}))},extension:function(){const e=Zs();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=Xs();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=eo();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-node",definition:to(e),metadata:{packageRoot:n.manifestPath}})}return t},"ivy-agent":function(){const e=no();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-agent",definition:ro(e,n.manifest),metadata:{packageRoot:n.manifestPath}})}return t},mcp:function(){const e=io();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},ao={getCapability(e){for(const t of Qs){const n=so[t](e);if(n)return n}},listCapabilities(e){const t=(n=e?.origin,void 0===n?void 0:new Set(Array.isArray(n)?n:[n]));var n;const r=new Set,i=[];for(const e of Qs)if(!t||t.has(e))for(const t of oo[e]()){const e=t.definition.id;r.has(e)||(r.add(e),i.push(t))}return i},hasCapability(e){return void 0!==this.getCapability(e)}};function co(e){return!!e&&"object"==typeof e&&!Array.isArray(e)&&1===Object.keys(e).length&&"string"==typeof e.$secret}function lo(e){return!!co(e)||(Array.isArray(e)?e.some(lo):!(!e||"object"!=typeof e)&&Object.values(e).some(lo))}async function uo(e,t,n){if(!lo(e))return e;const r=globalThis.punica?.runtime?.capabilities?.gateway;if(!r?.call)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`${n} names a stored secret, and this host has no gateway to read it through.`,{capability:n});const i=new Map,s=async e=>{if(co(e))return(async e=>{const s=i.get(e);if(void 0!==s)return s;const o=await r.call("secrets.get",{name:e},{...t??{},invocationId:t?.invocationId});if("string"!=typeof o||0===o.length)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`${n} needs the secret "${e}", and no secret by that name is stored. Add it in Secrets and run again.`,{capability:n,secret:e});return i.set(e,o),o})(e.$secret);if(Array.isArray(e))return Promise.all(e.map(s));if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=await s(r);return t}return e};return s(e)}function po(e,t,n){switch(e){case"mcp":return function(e,t){const{mcpServerId:n,mcpToolName:r}=t;return{name:e.id,async execute(t,i){const s=globalThis.punica?.runtime?.mcp;if(!s?.callTool)throw new Vs(Us.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 Vs(Us.CAPABILITY_PROVIDER_MISSING,`MCP capability "${e.id}" is missing serverId or toolName metadata`,{capability:e.id,origin:"mcp"});return await s.callTool(n,r,t??{})}}}(t,n??{});case"instruction-class":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.kernel?.llm?.api;if(!r?.invokeLlmCapability)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`LLM kernel API is not initialized — cannot invoke instruction-class capability "${e.id}".`,{capability:e.id,origin:"instruction-class"});const i=null!==t&&"object"==typeof t?t:{},s="string"==typeof i.instructionClass?i.instructionClass:e.id,o="string"==typeof i.userPrompt?i.userPrompt:"string"==typeof i.prompt?i.prompt:JSON.stringify(t);return await r.invokeLlmCapability({instructionClass:s,userPrompt:o,context:i.context??{}})}}}(t);case"ivy-node":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.flow?.runner;if(!r?.run)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Flow runner is not initialized — cannot invoke ivy-node capability "${e.id}". Ensure the flow module has started before calling IvyNode capabilities.`,{capability:e.id,origin:"ivy-node"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await uo(t??{},n,e.id),o=await r.run(e.id,{input:s,timeoutMs:i,scopeId:n?.trace?.traceId});return o?.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 Vs(Us.CAPABILITY_PROVIDER_MISSING,`Agent registry is not initialized — cannot invoke ivy-agent capability "${e.id}". Ensure the flow module has started before calling IvyAgent capabilities.`,{capability:e.id,origin:"ivy-agent"});const i="number"==typeof e.execution?.timeoutMs?e.execution.timeoutMs:3e4,s=await r.run(e.id,{input:t??{},timeoutMs:i,workspaceId:n?.workspaceId,..."user"===n?.actor?.type?{waitForApproval:!0}:{}});return s?.output??null}}}(t);case"extension":return function(e){return{name:e.id,async execute(t,n){const r=globalThis.punica?.extensions?.manager;if(!r?.executeCapability)throw new Vs(Us.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 Vs(Us.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}const fo={recordSpan:()=>{}};let ho=fo;function mo(){return ho}function go(e){try{mo().recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function yo(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,o={capability:i,"actor.type":s.actor.type,"origin.kind":s.origin.kind};s.actor.extensionName&&(o["actor.extension"]=s.actor.extensionName),s.origin.extension&&(o["origin.extension"]=s.origin.extension),s.workspaceId&&(o["workspace.id"]=s.workspaceId),r.tags={...r.tags,...o};try{const e=await t();return r.durationMs=Date.now()-r.startTimeMs,go({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"success",attributes:{...r.tags}}),e}catch(e){r.error=e instanceof Error?e:new Error(String(e)),r.durationMs=Date.now()-r.startTimeMs;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.failed",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,spanId:s.trace.parentSpanId??n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"error"},payload:{invocationId:n.invocationId,capability:i,error:r.error.message,durationMs:r.durationMs}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.failed event:",e)}throw go({invocationId:n.invocationId,capability:i,traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId,startTimeMs:r.startTimeMs,durationMs:r.durationMs,status:"error",errorCode:e instanceof Vs?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function wo(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(wo);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=wo(r);return t}return e}const vo=new WeakMap;function bo(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s}=n;if(!0===r.spec.secretBearing||i.startsWith("secrets."))r.redactedInput=wo(s);else{const e=function(e){const t=vo.get(e);if(t)return t;const n=u(e.inputSchema);return vo.set(e,n),n}(r.spec);r.redactedInput=e.length>0?f(s,e):s}return await t()}}function Io(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function ko(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===Io(t))}const Eo=new class{validate(e,t){const n=[];if(!e||"object"!=typeof e)return{ok:!0,errors:n};const r=e,i=r.type;if(i&&(ko(i,t)||n.push(`Expected type "${i}", got "${Io(t)}"`)),"object"===i&&t&&"object"==typeof t&&!Array.isArray(t)){const e=t,i=r.required,s=r.properties;if(Array.isArray(i))for(const t of i)t in e&&void 0!==e[t]||n.push(`Missing required field: "${t}"`);if(s)for(const[t,r]of Object.entries(e)){if(void 0===r)continue;const e=s[t];if(!e)continue;const i=e.type;i&&(ko(i,r)||n.push(`Field "${t}": expected type "${i}", got "${Io(r)}"`))}}return{ok:0===n.length,errors:n}}};let So=Eo;function Ao(){return So}function xo(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=Ao().validate(s,i);if(!o.ok)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const Co=Ti({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function To(){return Co.get()}const _o=["path","oldPath","newPath","src","dst","target","linkPath"];function Po(e,t){if(e.includes("\0"))return{ok:!1,reason:"null byte in path"};if(/(%2e|\.)(?:%2e|\.)/i.test(e)&&/%2e/i.test(e))return{ok:!1,reason:"URL-encoded traversal segment"};if(/^[A-Za-z]:[\\/]?/.test(e))return{ok:!1,reason:"drive-relative path"};if(e.startsWith("\\\\"))return{ok:!1,reason:"UNC path"};const n=e.replace(/\\/g,"/"),r=n.startsWith("/"),i=n.split("/").filter(e=>""!==e&&"."!==e),s=[];for(const e of i)if(".."===e){if(0===s.length)return{ok:!1,reason:"traversal above root"};s.pop()}else s.push(e);let o=(r?"/":"")+s.join("/");if(""===o&&(o=r?"/":"."),t&&r){const e=function(e){let t=e.replace(/\\/g,"/");t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1));return t}(t);if("/"===e);else if(o!==e&&!o.startsWith(`${e}/`))return{ok:!1,reason:"path is outside the workspace root"}}return{ok:!0,canonical:o}}function No(){try{return To().cwd}catch{return}}function $o(){return async(e,t)=>{const{input:n}=e.req;if("object"!=typeof n||null===n)return await t();const r=n;let i,s=!1;for(const e of _o){const t=r[e];if("string"!=typeof t)continue;s||(i=No(),s=!0);const n=Po(t,i);if(!n.ok)throw new Vs(Us.CAPABILITY_PATH_TRAVERSAL_DENIED,`Path traversal denied on field "${e}": ${n.reason}`,{field:e,reason:n.reason,value:t,...void 0!==i?{cwd:i}:{}})}return await t()}}const Mo="encrypted-at-rest";function Ro(){return async(e,t)=>{const n=e.state.spec;if("sensitive"!==(n.dataClassification??"internal"))return t();if(!(r=n.name).startsWith("fs.")&&!r.startsWith("workspace."))return t();var r;const i=function(){try{return To()}catch{return}}();if(!i)throw new Vs(Us.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:Mo,reason:"provider not registered"});if(!i.capabilities?.has(Mo))throw new Vs(Us.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${Mo}" capability flag`,{capability:n.name,required:Mo,reason:"capability not advertised"});return Ei({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:Mo}}),t()}}const Oo=new Map;function Lo(e,t,n=0){if(n>=t.length)return null!=e&&""!==e;const r=t[n];return"*"===r?Array.isArray(e)&&e.some(e=>Lo(e,t,n+1)):!(!e||"object"!=typeof e||Array.isArray(e))&&Lo(e[r],t,n+1)}function jo(e,t){if("sensitive"===e.dataClassification)return!0;const n=e.inputSchema;if(!n)return!1;let r;try{r=u(n)}catch{return!1}return r.some(e=>Lo(t,e))}function Do(){return async(e,t)=>{const n=e.state.spec,r=e.req.ctx?.trace?.traceId,i=jo(n,e.req.input);i?e.state.sensitive="declared":function(e){if(e)return Oo.get(e.trim())}(r)&&(e.state.sensitive="taint");const s=()=>{i&&r&&function(e,t,n=Date.now()){const r=e.trim();if(r)for(Oo.has(r)&&Oo.delete(r),Oo.set(r,{atMs:n,by:t});Oo.size>4096;){const e=Oo.keys().next().value;if(void 0===e)break;Oo.delete(e)}}(r,n.name)},o=async()=>{const e=await t();return s(),e},a=n.egress??(Fe(n)?.includes("net.request")?"remote":"none");if("none"===a)return o();if("remote"===a)return e.state.egress="remote",o();const c=await Xi(e.req.input,function(){try{return as()}catch{return}}());return e.state.egress="local"===c?"local":"remote",o()}}function Fo(){const e=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()}catch{return}}();if(e)return e;try{return Gt.manager.registry.getActive()}catch{return}}function Bo(e,t,n,r,i){try{const s=globalThis.punica?.kernel?.Events?.manager;if(!s||"function"!=typeof s.publishEvent)return;s.publishEvent({name:"capability.denied_by_profile",source:"runtime:capabilities:middleware:profileBudget",kind:"warn",correlationId:i,payload:{invocationId:i,capability:e,profile:t,reason:n,origin:r??"unknown"}})}catch{}}function qo(){return async(e,t)=>{const n=Fo();if(!n)return t();const{allowedIds:r,deniedIds:i,allowedOrigins:s}=n.capabilities;if("*"===r&&!i?.length&&!s?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(s&&s.length>0){const e=ao.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw Bo(o,c,"origin-not-allowed",t,a),new Vs(Us.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" origin "${t??"unknown"}" is not in profile "${c}" allowedOrigins`,{capability:o,profile:c,reason:"origin-not-allowed",origin:t??"unknown"})}if(i&&i.includes(o))throw Bo(o,c,"in-denylist",void 0,a),new Vs(Us.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 Bo(o,c,"not-in-allowlist",void 0,a),new Vs(Us.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const Uo={alg:"HS256",typ:"PUNICA-APPROVAL"};class Vo extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function Wo(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 Ko(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 Go(e){return(new TextEncoder).encode(e)}function Yo(e){return Wo(Go(JSON.stringify(e)))}function zo(e){return JSON.parse((t=Ko(e),(new TextDecoder).decode(t)));var t}function Jo(){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 Ho(){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 Qo{#Ie;#ke;constructor(e){e?.secret instanceof Uint8Array?this.#Ie=e.secret:this.#Ie="string"==typeof e?.secret?Go(e.secret):Ho()}async sign(e){const t=await this.#Ee(),n=Yo(Uo),r=Yo(e),i=Go(`${n}.${r}`),s=await Jo().sign("HMAC",t,i);return`${n}.${r}.${Wo(new Uint8Array(s))}`}getSecret(){return this.#Ie}async#Ee(){return this.#ke||(this.#ke=await Jo().importKey("raw",this.#Ie,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#ke}}class Zo{#Ie;#ke;#Se=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#Ie=e.secret:this.#Ie="string"==typeof e?.secret?Go(e.secret):Ho()}async verify(e){const t=e.split(".");if(3!==t.length)throw new Vo("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=zo(n)}catch{throw new Vo("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new Vo("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=zo(r)}catch{throw new Vo("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#Ee(),c=Go(`${n}.${r}`);let l;try{l=Ko(i)}catch{throw new Vo("MALFORMED","Token signature is not valid base64url")}const u=Jo();if(!await u.verify("HMAC",a,l,c))throw new Vo("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new Vo("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new Vo("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#Se.add(e)}isRevoked(e){return this.#Se.has(e)}async#Ee(){return this.#ke||(this.#ke=await Jo().importKey("raw",this.#Ie,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#ke}}let Xo,ea,ta;function na(){return Xo||(Xo=function(){const e=new Qo,t=new Zo({secret:e.getSecret()});return{signer:e,verifier:t}}()),Xo}function ra(e){ea=e}function ia(){return ta??na().verifier}function sa(e){ta=e}const oa=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";let aa;function ca(){return aa??oa}function la(e){aa=e}const ua=new WeakMap;function da(e){const t=ua.get(e);if(t)return t;const n=function(e){return d(e,"policyKey")}(e.inputSchema);return ua.set(e,n),n}const pa=new WeakMap;function fa(e){const t=pa.get(e);if(t)return t;const n=u(e.inputSchema);return pa.set(e,n),n}function ha(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=globalThis.punica?.kernel?.Policy?.manager;if(!a){const e=o.policy??{},a=e.risk??o.risk??"low",c=e.approval??"none",l="high"===a||"step"===c||"plan"===c,u=!0===globalThis.punica?.kernel?.Policy?.failClosed,d=u&&l;try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"policy.manager.missing",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:d?"error":"warning"},payload:{capability:i,risk:a,approval:c,actor:s.actor,decision:d?"deny":"allow",failClosed:u}})}catch{}if(console.warn(`[CapabilityGateway] Policy manager not available for "${i}" (risk=${a}, approval=${c}); `+(d?"DENYING (fail-closed)":"allowing (fail-open)")+"."),d)throw new Vs(Us.CAPABILITY_DENIED,`Policy manager unavailable and capability "${i}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:i,reason:"policy-manager-missing",risk:a,approval:c});return r.policyDecision={allowed:!0,requiresApproval:!1,reason:"policy-manager-missing (fail-open)"},await t()}const c=o.policy??{},l=c.risk??o.risk??"low",u=c.approval??"none";let d=!1,p="";const f=s.policy?.stance;let h;if("ai"===s.actor.type&&"auto"!==f){"approval"===ca()({capabilityId:i,risk:o.risk,sideEffect:o.sideEffect})&&(d=!0,p=`agent-mode policy: ${o.sideEffect}/${o.risk}`,"observe"===f&&(h=`Observe refuses ${i} because it `+("high"===o.risk?"is high risk":"writes")+"; switch to Assist to be asked before it runs."))}"high"===o.risk&&(d=!0,p="High risk capability"),"step"!==u&&"plan"!==u||(d=!0,p=`Capability requires ${u} approval`);const{binding:m,preview:g}=await Re(r.redactedInput,{policyKeyPaths:da(o)}),y={kind:"capability",id:i,risk:l,approval:u,reason:o.description??o.title??`Capability: ${i}`,argsBinding:m,argsPreview:g},w=Fe(o);w&&(y.action=w),"remote"===r.egress&&(y.egress="remote"),r.sensitive&&(y.sensitive=r.sensitive);const v=!0===o.secretBearing||i.startsWith("secrets."),b=a.evaluate(y,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId,parentSpanId:n.invocationId,args:r.redactedInput,redactedPaths:fa(o),argsWhollyRedacted:v});r.policyDecision={allowed:b.allowed,requiresApproval:b.requiresApproval||d,approvalToken:s.policy.approvalToken,reason:b.reason||p,argsBinding:m};const I=b.policyRule;I&&(r.policyDecision.policyRule=I),b.maxScope&&(y.maxScope=b.maxScope),b.approvers&&(y.approvers=b.approvers),b.org&&(y.org=b.org),b.signatures&&(y.signatures=b.signatures);const k=ft(b.maxScope);if("deny"===I?.effect)throw new Vs(Us.CAPABILITY_DENIED,b.reason??"Policy denied execution",{capability:i,decision:b,policyRule:I});if(!h&&"observe"===f&&"ai"===s.actor.type&&(b.requiresApproval||d)&&function(e,t){return"high"===e.risk||("write"===e.sideEffect||(t??[]).some(e=>"process.exec"===e||e.endsWith(".write")||e.endsWith(".delete")||e.endsWith(".send")))}(o,w)&&(h=`Observe refuses ${i} because it `+("high"===o.risk?"is high risk":"writes")+"; switch to Assist to be asked before it runs."),h)throw r.policyDecision.allowed=!1,r.policyDecision.requiresApproval=!1,r.policyDecision.reason=h,new Vs(Us.CAPABILITY_DENIED,h,{capability:i,stance:f,decision:b});if("allow"===I?.effect&&(d=!1,r.policyDecision.requiresApproval=!1),d||b.requiresApproval)if(s.policy.approvalToken)try{await ia().verify(s.policy.approvalToken)}catch(e){if(e instanceof Vo){try{const t=globalThis.punica?.kernel?.Events?.manager;t&&t.publishEvent({name:"token.invalid",envelope:{id:n.invocationId,correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:policyGate",kind:"error"},payload:{capability:i,tokenError:e.code,actor:s.actor}})}catch{}throw new Vs(Us.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:i,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!k.some(e=>a.hasApproval(y,e,{workspaceId:s.workspaceId}))){a.requestApproval(y,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId,...b.reason?{reason:b.reason}:{}});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:i,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}const e=b.reason||p;throw new Vs(Us.CAPABILITY_APPROVAL_REQUIRED,b.reason?b.reason:p?`Approval required: ${p}`:"Approval required.",{capability:i,reason:e})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:s.workspaceId};if(!k.filter(e=>"once"!==e).some(t=>a.hasApproval(y,t,e))&&"function"==typeof a.revokeApproval){const e=[y.argsBinding];y.argsBinding&&e.push("any");for(const t of e)try{a.revokeApproval({kind:y.kind,id:y.id,scope:"once",argsBinding:t})}catch{}}}}if(!b.allowed&&!d&&"suggest"!==b.mode)throw new Vs(Us.CAPABILITY_DENIED,b.reason??"Policy denied execution",{capability:i,decision:b});return r.policyDecision&&"suggest"===b.mode&&!b.allowed&&(r.policyDecision.allowed=!0,r.policyDecision.mode="suggest",r.policyDecision.reason="Policy mode is suggest; advisory at the gate, so the call ran."),await t()}}const ma=new class{#g=new Map;#Ae;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#Ae=t<=0?1:t}get(e,t){const n=this.#xe(e,t),r=this.#g.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#g.delete(n),this.#g.set(n,r),r;this.#g.delete(n)}}set(e){const t=this.#xe(e.capabilityId,e.key);for(this.#g.delete(t),this.#g.set(t,e);this.#g.size>this.#Ae;){const e=this.#g.keys().next().value;if(void 0===e)break;this.#g.delete(e)}}delete(e,t){return this.#g.delete(this.#xe(e,t))}clear(){this.#g.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#g)r.expiresAtMs<=e&&(this.#g.delete(n),t++);return t}size(){return this.#g.size}#xe(e,t){return`${e}|${t}`}};let ga=ma;function ya(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,input:s,idempotencyKey:o}=n,a=r.spec.defaults?.idempotency??"none";if("none"===a)return t();if("required"===a&&!o)throw new Vs(Us.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=ga,l=function(e){const t=JSON.stringify(e??null);let n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}(s),u=c.get(i,o);if(u){if(u.inputHash!==l)throw function(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}({name:"idempotency.replay_blocked",envelope:{id:n.invocationId,correlationId:n.invocationId,timestampMs:Date.now(),source:"runtime:capabilities:middleware:idempotency",kind:"error"},payload:{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs,actor:n.ctx.actor}}),new Vs(Us.CAPABILITY_IDEMPOTENCY_REPLAY_BLOCKED,`Capability "${i}" idempotencyKey "${o}" was previously used with a different input`,{capability:i,idempotencyKey:o,cachedAtMs:u.createdAtMs});return r.output=u.response,r.tags["idempotency.hit"]="true",u.response}const d=await t(),p=Date.now();return c.set({key:o,capabilityId:i,inputHash:l,response:d,createdAtMs:p,expiresAtMs:p+864e5}),r.tags["idempotency.cached"]="true",d}}const wa=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(),i=(r-n.lastRefillMs)/1e3*t;return n.tokens=Math.min(n.maxTokens,n.tokens+i),n.lastRefillMs=r,n.tokens>=1&&(n.tokens-=1,!0)}};function va(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a=o.defaults?.rateLimit;if(!a||!a.perSecond)return await t();const c=function(e,t,n){const r=[e,t];return n&&r.push(n),r.join(":")}(i,s.actor.type,s.actor.extensionName??s.origin.extension);if(!wa.consumeToken(c,a.perSecond))throw new Vs(Us.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const ba=new class{#Te=new Map;getSemaphore(e,t){let n=this.#Te.get(e);return n||(n={count:0,max:t,queue:[]},this.#Te.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.#Te.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function Ia(){return async(e,t)=>{const{req:n,state:r}=e,{ctx:i}=n,{spec:s}=r,o=s.defaults?.concurrency;if(!o||!o.key||!o.max)return await t();const a=function(e,t){let n=e;return n=n.replace(/\{workspaceId\}/g,t.workspaceId??""),n=n.replace(/\{tenantId\}/g,t.tenantId??""),n=n.replace(/\{extension\}/g,t.extension??""),n=n.replace(/\{actorType\}/g,t.actorType??""),n}(o.key,{workspaceId:i.workspaceId,tenantId:i.tenantId,extension:i.actor.extensionName??i.origin.extension,actorType:i.actor.type});try{await ba.acquire(a,o.max)}catch(e){throw new Vs(Us.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{ba.release(a)}}}const ka=new class{#_e=new Map;getBreaker(e){let t=this.#_e.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#_e.set(e,t)),t}};function Ea(){return async(e,t)=>{const{req:n,state:r}=e,{name:i}=n,s=r.spec.defaults?.circuitBreaker;if(!s)return await t();const o=s.failureThreshold??3,a=s.cooldownMs??6e4,c=ka.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new Vs(Us.CAPABILITY_CIRCUIT_OPEN,`Circuit breaker open for "${i}"`,{capability:i,openedAtMs:c.openedAtMs,cooldownMs:a,remainingMs:a-(l-c.openedAtMs)});try{const e=await t();return c.consecutiveFailures=0,c.status="closed",e}catch(e){c.consecutiveFailures++;throw("half-open"===c.status||c.consecutiveFailures>=o)&&(c.status="open",c.openedAtMs=l),e}}}function Sa(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 Aa(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new Vs(Us.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),s])}finally{void 0!==i&&clearTimeout(i)}}const xa=["dataset","file","model","prompt","collection","artifact"],Ca={subjects:[],digests:[]};function Ta(e){if(!e||"object"!=typeof e)return Ca;const t=[];for(const n of p(e,"subject")){if("string"!=typeof n.value)continue;const e=n.value.trim();0!==e.length&&t.push({path:n.path,kind:e})}return 0===t.length?Ca:{subjects:t,digests:d(e,"subjectDigest")}}function _a(e,t){let n=[{path:[],value:e}];for(const e of t){const t=[];for(const r of n){if("*"===e){if(!Array.isArray(r.value))continue;r.value.forEach((e,n)=>{t.push({path:[...r.path,String(n)],value:e})});continue}if(!r.value||"object"!=typeof r.value)continue;if(Array.isArray(r.value))continue;const n=r.value;e in n&&t.push({path:[...r.path,e],value:n[e]})}if(n=t,0===n.length)return[]}return n}const Pa=new Set(["[REDACTED]","***"]);function Na(e){let t;if("string"==typeof e)t=e;else{if("number"!=typeof e||!Number.isFinite(e))return;t=String(e)}const n=t.trim();if(0!==n.length&&!(n.length>1024||Pa.has(n)))return n}function $a(e){return e.slice(0,-1).join(" ")}function Ma(e,t,n,r){const i=Ta(e);if(0===i.subjects.length)return;const s=[],o=new Map;for(const e of i.subjects)for(const r of _a(t,e.path)){const t=Na(r.value);if(void 0===t)continue;const i=$a(r.path);o.set(i,(o.get(i)??0)+1),s.push({subject:{kind:e.kind,id:t,from:n},parent:i})}if(0===s.length)return;const a=function(e,t,n){const r=new Map;for(const n of t.digests)for(const t of _a(e,n)){const e=Na(t.value);if(void 0===e)continue;const n=$a(t.path),i=r.get(n);i?i.push(e):r.set(n,[e])}const i=new Map;for(const[e,t]of r)1===t.length&&1===n.get(e)&&i.set(e,t[0]);return i}(t,i,o);for(const e of s){const t=a.get(e.parent);r.push(void 0===t?e.subject:{...e.subject,digest:t})}}function Ra(e){return{invocationId:e.invocationId,runId:e.trace?.traceId,conversationId:e.conversationId,spanId:e.trace?.spanId??e.invocationId,parentSpanId:e.trace?.parentSpanId,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,argsBinding:e.policyDecision.argsBinding,policyRule:e.policyDecision.policyRule}:void 0,input:e.redactedInput,output:e.redactedOutput,egress:e.egress,subjects:e.subjects?.length?e.subjects:void 0,subjectsOmitted:e.subjectsOmitted,sensitive:e.sensitive,duration:e.durationMs,error:e.error?{message:e.error.message,name:e.error.name,code:e.error.code}:void 0,timestamp:e.timestamp}}async function Oa(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,traceId:e.trace?.traceId,spanId:e.trace?.spanId??e.invocationId,parentSpanId:e.trace?.parentSpanId,timestampMs:e.timestamp,source:"runtime:capabilities:gateway",kind:"audit"},payload:Ra(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(Ra(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=To()}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(Ra(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 La=new WeakMap;const ja=new WeakMap;function Da(e,t,n){const r=ja.get(e);if(r)return r;const i=function(e,t,n){if(!0===e.secretBearing)return{subjects:[]};const r=[];if(Ma(e.inputSchema,t,"input",r),Ma(e.outputSchema,n,"output",r),0===r.length)return{subjects:[]};const i=new Set,s=[];for(const e of r){const t=[e.kind,e.id,e.digest??"",e.from].join(" ");i.has(t)||(i.add(t),s.push(e))}return s.length<=64?{subjects:s}:{subjects:s.slice(0,64),omitted:s.length-64}}(e,t,n);return 0!==i.subjects.length||function(e){return Ta(e.inputSchema).subjects.length>0||Ta(e.outputSchema).subjects.length>0}(e)||ja.set(e,i),i}function Fa(e,t){if(!0===t.secretBearing)return Ba(e);const n=function(e){const t=La.get(e);if(t)return t;const n=u(e.outputSchema);return La.set(e,n),n}(t);return n.length>0?f(e,n):e}function Ba(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Ba);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Ba(r);return t}return e}function qa(){return async(e,t)=>{const{req:n,state:r}=e,{name:i,ctx:s}=n,{spec:o}=r,a="object"==typeof n.input&&null!==n.input&&"path"in n.input&&"string"==typeof n.input.path&&/^\.punica\/audit\//.test(n.input.path);let c,l;try{c=await t(),r.output=c}catch(e){throw l=e instanceof Error?e:new Error(String(e)),r.error=l,e}finally{const e=globalThis.punica?.runtime,t=!e||"bootstrapping"===e.lifecyclePhase||"noWorkspace"===e.lifecyclePhase;if(!a&&!t){const e=Fa(r.output,o),t=Da(o,r.redactedInput,e);await Oa({invocationId:n.invocationId,capability:i,actor:s.actor,origin:s.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:s.workspaceId,conversationId:s.conversationId,trace:s.trace?{traceId:s.trace.traceId,spanId:n.invocationId,parentSpanId:s.trace.parentSpanId}:void 0,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,egress:r.egress,sensitive:r.sensitive,subjects:t.subjects,subjectsOmitted:t.omitted,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Ua=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","egressGuard","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Va(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const Wa=new class{async call(e,t,n,r){const i="user"!==n.actor.type||n.actor.id?n:{...n,actor:{...n.actor,id:ye()}},s=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let o=Ws.getSpec(e),a=o?Ws.getProvider(e):void 0,c="core";if(!o){const t=ao.getCapability(e);if(!t)throw Va({name:"capability.unknown_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:i.actor}}),new Vs(Us.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);c=t.origin,o=Gs(t.definition),a=po(t.origin,t.definition,t.metadata)}if(!a)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(o.requires)for(const t of o.requires)if(!Ws.hasCapability(t))throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});o.deprecated&&Va({name:"capability.deprecated_called",envelope:{id:s,correlationId:s,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:c,since:o.deprecated.since,reason:o.deprecated.reason,replacement:o.deprecated.replacement,actor:i.actor}});const l={req:{invocationId:s,name:e,input:t,ctx:{...i,invocationId:s},idempotencyKey:r},state:{spec:o,capabilityOrigin:c,startTimeMs:Date.now(),tags:{}}},u=this.#Pe(a);try{return await this.#Ne(u,l)}catch(e){if(e instanceof Vs)throw e;const t=e instanceof Error&&e.message?e.message:`Provider execution failed: ${String(e)}`;throw new Vs(Us.CAPABILITY_PROVIDER_ERROR,t,{originalError:String(e),errorName:e instanceof Error?e.name:void 0})}}#Pe(e){const t={auditTrail:qa,traceMetrics:yo,redaction:bo,validateInput:xo,pathTraversalGuard:$o,encryptionRouting:Ro,egressGuard:Do,profileBudget:qo,policyGate:ha,idempotency:ya,rateLimit:va,concurrency:Ia,circuitBreaker:Ea,timeoutRetry:()=>function(e){return async(t,n)=>{const{req:r,state:i}=t,{input:s,idempotencyKey:o}=r,{spec:a}=i,c=a.defaults?.timeoutMs??3e4,l=a.defaults?.retries??0,u=a.defaults?.retryBackoffMs??1e3,d="write"!==a.sideEffect||Boolean(o);let p=null,f=0;for(;f<=l;){f++;try{const n=await Aa(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),f<=l&&d&&Sa(p)){const e=u*Math.pow(2,f-1);await new Promise(t=>setTimeout(t,e));continue}throw i.error=p,p}}throw i.error=p??new Error("Execution failed"),i.error}}(e)};return Ua.map(e=>t[e]())}#Ne(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const i=e[n];return n++,await i(t,r)};return r()}};function Ka(e,t){const n=To(),r=n[t];if("function"!=typeof r)throw new Vs(Us.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 Ga(e,t,n){const r=To();if(!r.capabilities?.has(n))throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires the FileSystemProvider to advertise the "${n}" capability flag, but it does not`,{capability:e,method:String(t),requiredProviderCapability:n});const i=r[t];if("function"!=typeof i)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires FileSystemProvider.${String(t)}() but the registered provider does not expose it`,{capability:e,method:String(t),requiredProviderCapability:n});return i.bind(r)}class Ya{name="fs.readFile";async execute(e,t){const n=To(),r=await n.readFile(e.path);if(null==r)throw new Error(`No such file: ${e.path}`);return r}}class za{name="fs.writeFile";async execute(e,t){const n=To();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}const Ja=89478485;class Ha{name="fs.writeBytes";async execute(e,t){if(e.base64.length>Ja)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Capability "fs.writeBytes" received a ${e.base64.length}-character base64 payload, over the 89478485 limit`,{capability:"fs.writeBytes",limit:Ja});let n;try{n=function(e){if("undefined"!=typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}const t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t).buffer}(e.base64)}catch{throw new Vs(Us.CAPABILITY_INPUT_INVALID,'Capability "fs.writeBytes" received a malformed base64 payload',{capability:"fs.writeBytes"})}await Ka("fs.writeBytes","writeBytes")(e.path,n)}}class Qa{name="fs.listFiles";async execute(e,t){const n=To();return await n.getFileTree()}}class Za{name="fs.stat";async execute(e,t){return await Ka("fs.stat","stat")(e.path)}}class Xa{name="fs.exists";async execute(e,t){return await Ka("fs.exists","exists")(e.path)}}class ec{name="fs.copy";async execute(e,t){await Ka("fs.copy","copy")(e.src,e.dst)}}class tc{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Ka("fs.mkdir","mkdir")(e.path,n)}}class nc{name="fs.history";async execute(e,t){return await Ga("fs.history","history","versioning")(e.path)}}class rc{name="fs.readAtVersion";async execute(e,t){return await Ga("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class ic{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Ka("fs.list","list")(e.path,n)}}const sc=Ti({label:"Runtime.secrets",noProviderMessage:"[Runtime.secrets] No Secrets provider registered. Host must call punica.runtime.setSecretsProvider() before using Secrets API",resolveHostFallback:()=>{const e=globalThis,t=e.punica?.runtime?.secrets;return void 0===t||cc(t)?function(){const e=new Map,t=new Map;return{set(n,r){const i=String(n??"").trim();if(!i)throw new Error("[Runtime.secrets] Secret name is required");const s=Date.now();if(t.has(i)){const e=t.get(i);t.set(i,{...e,updatedAtMs:s})}else t.set(i,{createdAtMs:s,updatedAtMs:s});e.set(i,String(r??""))},get(t){const n=String(t??"").trim();return n&&e.has(n)?e.get(n):null},delete(n){const r=String(n??"").trim();return!!r&&(t.delete(r),e.delete(r))},list(){const e=[];for(const[n,r]of t.entries())e.push({name:n,createdAtMs:r.createdAtMs,updatedAtMs:r.updatedAtMs});return e.sort((e,t)=>e.name.localeCompare(t.name)),e}}}():t}});function oc(){return sc.get()}function ac(e){sc.set(e),e&&Ei({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}function cc(e){return"object"==typeof e&&null!==e&&!0===e.__punicaWrappedSecretsFacade}class lc{name="secrets.get";async execute(e,t){return oc().get(e.name)}}class uc{name="secrets.set";async execute(e,t){oc().set(e.name,e.value)}}function dc(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[rs]=!0,n}class pc{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=dc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class fc{name="llm.chatStream";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=globalThis.punica?.kernel?.Events?.manager,i=t.sessionId??t.trace?.traceId,s=e=>{if(r)try{r.publishEvent({name:"llm.chunk",envelope:{id:r.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"progress"},payload:{capabilityId:this.name,chunk:e}})}catch{}},o=dc(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);if("function"!=typeof n.chatStream){const e=await n.chat(o);return s({type:"done",response:e}),e}let a="",c="";const l=[];let u;for await(const e of n.chatStream(o)){if(t.signal?.aborted)break;switch(s(e),e.type){case"content":a+=e.text;break;case"thinking":c+=e.text;break;case"tool_call":l.push(e.toolCall);break;case"done":u=e.response;break;case"error":throw new Error(`[llm.chatStream] ${e.error.code}: ${e.error.message}`)}}const d={text:a||u?.text||"",modelId:u?.modelId,provider:u?.provider,usage:u?.usage,meta:u?.meta};return l.length>0&&(d.toolCalls=l),c&&(d.thinking=c),d}}class hc{name="llm.invoke";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.invoke(e,{correlationId:t.sessionId??t.trace?.traceId,...t.trace?.traceId?{trace:{traceId:t.trace.traceId,...t.invocationId?{parentSpanId:t.invocationId}:t.trace.parentSpanId?{parentSpanId:t.trace.parentSpanId}:{}}}:{}})}}class mc{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 gc{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 yc{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 wc{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 vc{name="workspace.readFile";async execute(e,t){const n=To();return await n.readFile(e.path)}}class bc{name="workspace.writeFile";async execute(e,t){const n=To();await n.createFileWithContent(e.path,e.content)}}class Ic{name="workspace.listFiles";async execute(e,t){const n=To(),r=await n.getFileTree(),i=[],s=e=>{for(const t of e??[])i.push({path:t.path,name:t.name,isDirectory:t.isDirectory}),t.isDirectory&&Array.isArray(t.children)&&t.children.length&&s(t.children)};return s(r??[]),{entries:i}}}const kc=[".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"],Ec=["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 Sc(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("/"),i=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),s=new RegExp(`^${r||n?"":"(?:.*/)?"}${i}(?:/.*)?$`);return e=>s.test(e)}const Ac={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"},xc=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 Cc(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 Tc(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function _c(e,t,n){const r=new Map;for(const t of e){if(t.endsWith("/"))continue;const e=Ac[Tc(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 Pc(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(xc.has(e)&&n.add(t),n.size>=8)break}return[...n].slice(0,8)}function Nc(e){const t={};let n,r;if(e.packageJson)try{const i=JSON.parse(e.packageJson),s=Object.keys(i.dependencies??{}),o=Object.keys(i.devDependencies??{});if(t.node={source:"package.json",count:s.length,dev:o.length,names:[...s,...o].slice(0,60)},i.scripts&&Object.keys(i.scripts).length){n={};for(const[e,t]of Object.entries(i.scripts).slice(0,30))n[e]=t}"string"==typeof i.main&&(r=i.main)}catch{t.node={source:"package.json",count:0,dev:0,names:[]}}const i=e.requirementsTxt?function(e){const t=[];for(const n of e.split(/\r?\n/)){const e=Cc(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,i=-1;for(let t=n;t<e.length;t++)if("["===e[t])r++;else if("]"===e[t]&&0===--r){i=t;break}if(i<0)return[];const s=[];for(const t of e.slice(n+1,i).match(/["']([^"']+)["']/g)??[]){const e=Cc(t.replace(/["']/g,""));e&&s.push(e)}return s}(e.pyproject):null;i&&(t.python={source:e.requirementsTxt?"requirements.txt":"pyproject.toml",count:i.length,names:i.slice(0,60)});const s={workspace:e.workspace,stack:_c(e.layout,!!t.node,!!t.python),dependencies:t,entrypoints:Pc(e.layout,r),layout:e.layout.slice(0,250),truncated:e.layoutTruncated||e.layout.length>250};if(n&&(s.scripts=n),e.readme&&(s.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);s.vcs={branch:t.current??null,...null!=t.ahead?{ahead:t.ahead}:{},...null!=t.behind?{behind:t.behind}:{},dirtyFiles:n}}return s}const $c=["readme.md","readme.rst","readme.txt","readme"];async function Mc(e,t){try{return await e.readFile(t)}catch{return}}async function Rc(){const e=To(),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(kc),n=new Set(Ec),r=(e.gitignore??"").split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")&&!e.startsWith("!")),i=r.map(Sc).filter(e=>null!=e),s=[],o=new Set,a=e=>{o.has(e)||(o.add(e),s.push(e))};for(const e of kc)a(`${e}/`);for(const e of Ec)a(`*.${e}`);for(const e of r)a(e);return{patterns:s,isNoise:e=>{const r=String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"");if(!r)return!1;const s=r.split("/");for(const e of s)if(t.has(e))return!0;const o=s[s.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 i)if(e(r))return!0;return!1}}}({gitignore:n.has(".gitignore")?await Mc(e,n.get(".gitignore")):void 0}),{layout:i,truncated:s}=function(e,t){const n=[];let r=!1;const i=(e,s)=>{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&&s<2&&i(o.children,s+1)}}};return i(e??[],0),{layout:n,truncated:r}}(t,r.isNoise),o=t=>n.has(t)?Mc(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 $c)if(n.has(t)&&(u=await Mc(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:Nc({workspace:d,layout:i,layoutTruncated:s,packageJson:a,requirementsTxt:c,pyproject:l,readme:u,vcs:p}),noisePatterns:r.patterns}}class Oc{name="workspace.projectContext";async execute(e,t){const{context:n}=await Rc();return n}}async function Lc(e,t,n){try{await e.updateFileContent(t,n)}catch{await e.createFileWithContent(t,n)}}class jc{name="workspace.writeOrientation";async execute(e,t){const n=!1!==e?.claudeMd,r=!1!==e?.claudeignore,i=To(),{context:s,noisePatterns:o}=await Rc(),a=[];if(n&&(await Lc(i,"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,i=e.dependencies.node;if((r||i)&&(t.push("## Dependencies",""),r&&t.push(`**Python** (\`${r.source}\`, ${r.count}): ${r.names.join(", ")}`,""),i&&t.push(`**Node** (\`${i.source}\`, ${i.count} + ${i.dev} dev): ${i.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")}(s)),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 Lc(i,".claudeignore",e),a.push(".claudeignore")}return{written:a}}}const Dc=".punica/facts",Fc=`${Dc}/facts.json`;async function Bc(e){let t;try{t=await e.readFile(Fc)}catch{return{}}try{const e=JSON.parse(t);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}class qc{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=To(),i=await Bc(r);return i[n]=e.value??null,await async function(e,t){const n=`${JSON.stringify(t,null,2)}\n`;try{await e.updateFileContent(Fc,n)}catch{try{await e.createFolder(".punica")}catch{}try{await e.createFolder(Dc)}catch{}await e.createFileWithContent(Fc,n)}}(r,i),{key:n,count:Object.keys(i).length}}}class Uc{name="context.recall";async execute(e,t){const n=To(),r=await Bc(n),i=e?.key?String(e.key).trim():"";if(i){const e=Object.prototype.hasOwnProperty.call(r,i);return{key:i,value:e?r[i]:null,found:e}}const s=Object.keys(r),o={};for(const e of s.slice(0,200))o[e]=r[e];return{facts:o,count:s.length,truncated:s.length>200}}}class Vc{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 Wc{name="terminals.send";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");const r=e.text??"";n.write(e.id,/[\r\n]$/.test(r)?r:`${r}\n`)}}class Kc{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)}}const Gc={name:"ECDSA",namedCurve:"P-256"},Yc={name:"ECDSA",hash:"SHA-256"};function zc(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("[Runtime.packageSigner] No WebCrypto available; cannot sign or verify a package.");return e.subtle}function Jc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t.padEnd(4*Math.ceil(t.length/4),"=")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}async function Hc(e){const t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y}),n=await zc().digest("SHA-256",(new TextEncoder).encode(t));return function(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(new Uint8Array(n))}async function Qc(e,t){try{if("ES256"!==t?.alg)return!1;const n=await zc().importKey("jwk",t.publicKeyJwk,Gc,!1,["verify"]);return await Hc(t.publicKeyJwk)===t.keyId&&await zc().verify(Yc,n,Jc(t.signature),function(e){const t=(new TextEncoder).encode("PUNICA-PACKAGE-v1\0"),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}(e))}catch{return!1}}const Zc=Ti({label:"Runtime.packageSigner",noProviderMessage:"[Runtime.packageSigner] No package signer registered. A host installs one with punica.runtime.setPackageSigner() during bootstrap; without it a package cannot be signed, and the substrate does not substitute a key nobody can verify against."});function Xc(){return Zc.get()}function el(){return Zc.hasProvider()}function tl(){return new Vs(Us.CAPABILITY_PROVIDER_MISSING,"No package signer is installed on this host, so nothing can be signed here.",{capability:"signing.sign",reason:"no-package-signer"})}class nl{name="signing.sign";async execute(e,t){if(!el())throw tl();return Xc().sign(Jc(e.bytes))}}class rl{name="signing.verify";async execute(e,t){return{valid:await Qc(Jc(e.bytes),e.signature)}}}class il{name="signing.publicKey";async execute(e,t){if(!el())throw tl();return Xc().publicKey()}}class sl{name="flow.migrate";async execute(e,t){const n=globalThis.punica,r=n?.flow?.primitives?.migrations;if(!r||"function"!=typeof r.migrate)throw new Error("[FlowMigrateProvider] Migration registry is not available — substrate bootstrap incomplete");return r.migrate(e)}}class ol{name="flow.runSubflow";async execute(e,t){const n=globalThis.punica,r=n?.flow?.engine?.manager;if(!r||"function"!=typeof r.runSubflow)throw new Error("[FlowRunSubflowProvider] Flow engine is not available — substrate bootstrap incomplete");const i={...e,workspaceId:e.workspaceId??t.workspaceId,parentTraceId:e.parentTraceId??t.trace?.traceId};return r.runSubflow(i)}}const al="capability.catalog";class cl{name=al;async execute(e,t){const n=e??{},r=ao.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>ll(e,n));return{capabilities:r,count:r.length}}}function ll(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=ul(t.risk);if(0===n.length)return!1;const r=e.definition.policy?.risk;if(!r||!n.includes(r))return!1}if(void 0!==t.tags){const n=ul(t.tags);if(0===n.length)return!1;const r=e.definition.tags;if(!Array.isArray(r)||0===r.length)return!1;if(!n.some(e=>r.includes(e)))return!1}if(void 0!==t.sideEffects){const n=ul(t.sideEffects);if(0===n.length)return!1;const r=e.definition.sideEffects;if(!Array.isArray(r)||0===r.length)return!1;if(!n.some(e=>r.includes(e)))return!1}return!0}function ul(e){return Array.isArray(e)?e:[e]}const dl=["examples","$comment","default","title"];function pl(e,t){let n=String(e??"");if(n=n.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[`*_#>]/g,"").replace(/\s+/g," ").trim(),!n)return n;const r=n.match(/^.{12,}?[.!?](?=\s|$)/)?.[0];return r&&(n=r),n.length>t&&(n=n.slice(0,t-1).trimEnd()+"…"),n}const fl=["properties","patternProperties","definitions","$defs"];function hl(e){if(Array.isArray(e))return e.map(e=>hl(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!dl.includes(n))if("description"!==n||"string"!=typeof r){if(fl.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=hl(n);t[n]=e;continue}t[n]=hl(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const ml="capability.schemaExport";class gl{name=ml;async execute(e,t){const n=e??{},r=n.filter??{},i=ao.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>ll(e,r)),s=n.mode??"full",o=i.map(e=>{const t=function(e){const t=e.definition,n={id:t.id,origin:e.origin,version:t.version,title:t.title};void 0!==t.description&&(n.description=t.description);void 0!==t.inputs?.schema&&(n.inputSchema=t.inputs.schema);void 0!==t.outputs?.schema&&(n.outputSchema=t.outputs.schema);t.policy&&(n.policy={risk:t.policy.risk,approval:t.policy.approval});t.tags&&t.tags.length>0&&(n.tags=[...t.tags]);Yt(t)&&(n.agentVisibility="hub-only");const r=t.action;Array.isArray(r)&&r.length>0&&(n.action=r.map(String));t.sideEffects&&t.sideEffects.length>0&&(n.sideEffects=[...t.sideEffects]);const i=t.requires;i&&i.length>0&&(n.requires=[...i]);t.deprecated&&(n.deprecated={...t.deprecated});if(e.metadata){const t={};for(const[n,r]of Object.entries(e.metadata))void 0!==r&&(t[n]=r);Object.keys(t).length>0&&(n.metadata=t)}return n}(e);return"ai-tools"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=pl(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=hl(e.inputSchema));e.policy&&(t.policy={...e.policy});e.agentVisibility&&(t.agentVisibility=e.agentVisibility);e.action&&e.action.length>0&&(t.action=[...e.action]);return t}(t):"summary"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=pl(e.description??e.title,100);n&&(t.description=n);return t}(t):t});return{schemaVersion:"v1",generatedAt:Date.now(),capabilities:o,count:o.length}}}const yl={"ı":"i","ø":"o","đ":"d","ł":"l","ß":"ss","æ":"ae","œ":"oe"};function wl(e){return e.length<4||!e.endsWith("s")||/(?:ss|us|is)$/.test(e)?e:e.slice(0,-1)}function vl(e){return function(e){let t="";for(const n of e)t+=yl[n]??n;return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}(e.toLowerCase()).split(/[^a-z0-9]+/).filter(e=>e.length>=2).map(wl)}function bl(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function Il(e,t){if(0===e.size||0===t.size)return 0;let n=0,r=0,i=0;for(const[,t]of e)r+=t*t;for(const[,e]of t)i+=e*e;for(const[r,i]of e){const e=t.get(r);void 0!==e&&(n+=i*e)}const s=Math.sqrt(r)*Math.sqrt(i);return 0===s?0:n/s}function kl(e,t){const n=bl(vl(e));return t.map(e=>({...e,score:Il(n,bl(vl(e.text)))}))}const El={tr:{roots:{ac:"open",kapat:"close",kaydet:"save",sil:"delete remove",olustur:"create new build",yarat:"create new",ekle:"add insert",oku:"read",yaz:"write",bul:"find search",ara:"search find",degis:"change replace modify diff",liste:"list",goster:"show display view",calis:"run execute working",calisiy:"running active",calisan:"running active",basla:"start begin run",durdur:"stop",dur:"stop",durum:"status state",yukle:"upload install load",indir:"download",kur:"install setup",gonder:"push send",cek:"pull fetch",birlestir:"merge",adlandir:"rename name",tasi:"move",kopyala:"copy",yapistir:"paste",kes:"cut",bicim:"format",ozet:"summary summarize",sec:"select",secim:"selection select",isaretle:"mark toggle",bagla:"connect",baglan:"connect",sorgu:"query",derle:"build compile",ayikla:"debug",guncelle:"update upgrade",kaldir:"remove uninstall",yenile:"refresh reload",gec:"switch",koy:"set place",koyu:"dark",calistir:"run execute",onizle:"preview",dene:"try test",onar:"fix repair",duzelt:"fix format",bekle:"wait",iptal:"cancel abort",onayla:"confirm approve",paylas:"share",disari:"export",ice:"import",dosya:"file",klasor:"folder directory",dizin:"directory folder",proje:"project workspace",depo:"repository repo",depolama:"storage",dal:"branch",islem:"commit operation",satir:"line",sutun:"column",kesme:"breakpoint break",nokta:"point",terminal:"terminal shell",ucbirim:"terminal shell",kabuk:"shell",komut:"command",ayar:"settings preferences configuration",secenek:"option",tercih:"preferences",konteyner:"container",kapsayici:"container",imaj:"image",gunluk:"log",kova:"bucket",ortam:"environment",sanal:"virtual",paket:"package pack",betik:"script",gorev:"task job",veritaban:"database",tablo:"table",gezgin:"explorer browser",duzenleyici:"editor",editor:"editor",pencere:"window panel",sekme:"tab",panel:"panel",kenar:"sidebar side",icerik:"content contents",icerig:"content contents",metin:"text",yol:"path",uzanti:"extension",islev:"function",fonksiyon:"function",sinif:"class",degisken:"variable",hata:"error bug debug",uyari:"warning",cikti:"output",girdi:"input",tema:"theme",boyut:"size",sunucu:"server",uzak:"remote",yerel:"local",yeni:"new",konsol:"console terminal",taban:"base",alan:"area workspace field",imlec:"cursor",resim:"image",anahtar:"key",gizli:"secret hidden",sifre:"password",belge:"document",sayfa:"page",baglanti:"link connection",kod:"code",surec:"process",bellek:"memory",klavye:"keyboard",kisayol:"shortcut",yorum:"comment",isim:"name",tur:"type",deger:"value",yigin:"stack",onbellek:"cache",yedek:"backup",gunce:"log",veri:"data",set:"set dataset",model:"model",aktif:"active current",indeks:"index",anlamsal:"semantic",profil:"profile",nesne:"object",bilgi:"knowledge information",kesf:"discover collect list",politika:"policy rule",kural:"rule policy",onay:"approval approve",bekleyen:"pending waiting",kanit:"evidence",disa:"export",aktar:"export transfer",soy:"lineage",grafik:"graph",agac:"tree graph",hiperparametre:"hyperparameter sweep",tara:"sweep scan",kursl:"course",kursu:"course",dugum:"node",katalog:"catalog list",kosu:"run",hucre:"cell",defter:"notebook",deney:"experiment",motor:"engine",izi:"trace",izle:"watch follow",gecerli:"apply effective valid",test:"test",kayit:"record log registry",kuyruk:"queue",dagit:"deploy",boru:"pipeline",asama:"stage step",kapi:"gate",surum:"version"},stopWords:["bu","su","bir","ve","veya","ile","icin","gibi","kadar","daha","cok","az","olan","olarak","her","hep","tum","butun","ben","sen","biz","siz","benim","senin","bizim","kendi","mi","mu","de","da","ki","ama","fakat","ancak","yine","yeniden","hangi","ne","nasil","neden","nicin","nerede","nereye","nereden","neler","kim","yok","degil","evet","hayir","sey","cunku","sonra","once","simdi","artik","bile","ise","eger","hem"]}},Sl=new Map,Al=new Set;for(const e of Object.values(El)){for(const[t,n]of Object.entries(e.roots)){const e=vl(t).join("");e.length>0&&Sl.set(e,vl(n))}for(const t of e.stopWords){const e=vl(t).join("");e.length>0&&Al.add(e)}}const xl=[...Sl.keys()].sort((e,t)=>t.length-e.length);function Cl(e){let t=0;for(const n of e)n.score>t&&(t=n.score);return t}const Tl=new WeakMap;async function _l(e,t,n){const r=kl(e,t);let i={scores:r,score:Cl(r),path:"text-similarity"};const s=vl(e),o=function(e,t){const n=[];for(const r of e){if(Al.has(r))continue;if(t?.has(r)){n.push(r);continue}const e=xl.find(e=>r.startsWith(e));e?n.push(r,...Sl.get(e).filter(e=>e!==r)):n.push(r)}return n}(s,function(e){let t=Tl.get(e);if(!t){t=new Set;for(const n of e)for(const e of vl(n.text))t.add(e);Tl.set(e,t)}return t}(t)),a=o.join(" ");if(a.length>0&&o.join("\0")!==s.join("\0")){const e=kl(a,t);i={scores:e,score:Cl(e),path:"lexicon",text:a}}return i.score,"text-similarity"!==(c=i).path&&Hi("llm.normalizeIntent",{intent:e,path:c.path,normalizedAs:c.text,topScore:c.score}),{scores:c.scores,path:c.path,...void 0===c.text?{}:{normalizedAs:c.text}};var c}async function Pl(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return{recommendations:[],path:"text-similarity"};const i=ao.listCapabilities();if(0===i.length)return{recommendations:[],path:"text-similarity"};const s=i.map(e=>({id:e.definition.id,description:e.definition.description,text:Nl(e.definition)}));let o,a,c;{const e=await _l(r,s);o=e.path,a=e.normalizedAs,c=e.scores}const l=c.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 Hi("llm.recommendIntent",{intent:r,limit:n,path:o,normalizedAs:a,topIds:l.map(e=>e.id),topScore:l[0]?.score??0}),{recommendations:l,path:o,...void 0===a?{}:{normalizedAs:a}}}function Nl(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(" ")}const $l="capability.recommend";class Ml{name=$l;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await Pl(r,"number"==typeof n.limit?{limit:n.limit}:void 0);return{recommendations:i.recommendations.map(e=>({id:e.id,score:e.score,description:e.description})),path:i.path,count:i.recommendations.length,...void 0===i.normalizedAs?{}:{normalizedAs:i.normalizedAs}}}}const Rl="capability.describe",Ol="capability.search";function Ll(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class jl{name=Rl;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new gl).execute({mode:"ai-tools"},t)).capabilities.filter(e=>r.has(String(e.id))),s=new Set(i.map(e=>String(e.id)));return{tools:i,missing:n.filter(e=>!s.has(e))}}}class Dl{name=Ol;async execute(e,t){const n=e??{},r=String(n.query??"").trim(),i=Math.min(Math.max(1,Math.floor(n.limit??16)),50);if(!r)return{results:[],count:0};const s=ao.listCapabilities().filter(e=>!(Yt(e.definition)||zt(e.definition)&&!Jt())),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await async function(e,t){return(await Pl(e,t)).recommendations}(r,{limit:i});e.reduce((e,t)=>"number"==typeof t.score&&t.score>e?t.score:e,0)>1e-9&&(a=e.map(e=>String(e.id)).filter(e=>o.has(e)))}catch{}if(0===a.length){const e=r.toLowerCase().split(/\s+/).filter(Boolean);a=s.filter(t=>{const n=`${t.definition.id} ${t.definition.title??""} ${t.definition.description??""}`.toLowerCase();return e.some(e=>n.includes(e))}).map(e=>String(e.definition.id))}const c=a.slice(0,i).map(e=>{const t=o.get(e);return{id:e,description:pl(t?.description??t?.title??e,100),category:Ll(e)}});return{results:c,count:c.length}}}function Fl(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Bl(e,t){return{name:e,title:t.title,description:t.description,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 ql{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Fl().create(n)}}}class Ul{name="ai.session.list";async execute(e,t){const n=Fl().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Vl{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Fl().get(n)}}}class Wl{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Fl().rename(String(n?.sessionId??""),String(n?.title??""))}}}class Kl{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Fl().archive(String(n?.sessionId??""),n?.archived)}}}class Gl{name="ai.session.delete";async execute(e,t){return{ok:Fl().delete(String(e?.sessionId??""))}}}const Yl={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"}]}},zl={id:"weak-description",severity:"warning",check(e){const t=e.description,n="string"==typeof t?t.trim():"";if(n.length>=20)return[];const r=0===n.length?"has no description":`has a very short description ("${n}")`;return[{ruleId:"weak-description",severity:"warning",message:`Capability "${e.id}" ${r} — the agent reads this to decide when to call the tool; write 1-2 sentences (what it does, when to pick it, side effects)`,capabilityId:String(e.id),path:"description",code:"CAP_WEAK_DESC"}]}},Jl=new Set(["low","medium","high"]),Hl={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&Jl.has(t.risk)?[]:[{ruleId:"invalid-risk",severity:"error",message:`Capability "${e.id}" declares policy.risk "${String(t.risk)}" — must be one of low | medium | high`,capabilityId:String(e.id),path:"policy.risk",code:"CAP_BAD_RISK"}]:[]}},Ql=new Set(["none","plan","step"]),Zl={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Ql.has(t.approval)?[]:[{ruleId:"invalid-approval",severity:"error",message:`Capability "${e.id}" declares policy.approval "${String(t.approval)}" — must be one of none | plan | step`,capabilityId:String(e.id),path:"policy.approval",code:"CAP_BAD_APPROVAL"}]:[]}};const Xl={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"}]:[]}},eu=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,tu={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&eu.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"}]}},nu=new Set(["low","medium","high"]),ru=["write","delete","remove","modify","destroy"],iu={id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!nu.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&&ru.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 su={id:"policy-key-on-sensitive",severity:"error",check(e){const t=function(e){const t=e.inputs;if(t&&"object"==typeof t)return t.schema}(e);if(!t||"object"!=typeof t)return[];const n=d(t,"policyKey");if(0===n.length)return[];const r=new Set(d(t,"sensitive").map(e=>e.join("."))),i=[];for(const t of n){const n=t.join(".");r.has(n)&&i.push({ruleId:"policy-key-on-sensitive",severity:"error",message:`Capability "${e.id}" marks input field "${n}" as both sensitive and policyKey — the binding is computed from the redacted input, so this field cannot narrow an approval; remove one of the two annotations`,capabilityId:String(e.id),path:`inputs.schema.${n}`,code:"CAP_POLICY_KEY_ON_SENSITIVE"})}return i}},ou=new Set(xa);const au={id:"subject-declaration",severity:"error",check(e){const t=[],n=String(e.id);for(const r of function(e){const t=[];for(const n of["inputs","outputs"]){const r=e[n];if(!r||"object"!=typeof r)continue;const i=r.schema;i&&"object"==typeof i&&t.push({prefix:`${n}.schema`,schema:i})}return t}(e)){const e=p(r.schema,"subject"),i=d(r.schema,"subjectDigest");if(0===e.length&&0===i.length)continue;const s=new Set(d(r.schema,"sensitive").map(e=>e.join(".")));let o=0;for(const i of e){const e=i.path.join("."),a=`${r.prefix}.${e}`;if("string"!=typeof i.value||""===i.value.trim()){t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" marks field "${e}" as a subject without naming a kind — the audit record labels every subject, so this field is dropped instead of recorded; set subject to one of ${xa.join(", ")}`,capabilityId:n,path:a,code:"CAP_SUBJECT_WITHOUT_KIND"});continue}const c=i.value.trim();ou.has(c)?s.has(e)?t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" marks field "${e}" as both sensitive and subject — subjects are read from the redacted payload, so this field's value is always [REDACTED] and no subject is recorded; remove one of the two annotations`,capabilityId:n,path:a,code:"CAP_SUBJECT_ON_SENSITIVE"}):o+=1:t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" declares field "${e}" as subject kind "${c}", which is not one of ${xa.join(", ")} — the vocabulary is closed so a reader can compare two evidence packages`,capabilityId:n,path:a,code:"CAP_SUBJECT_UNKNOWN_KIND"})}i.length>0&&0===o&&t.push({ruleId:"subject-declaration",severity:"error",message:`Capability "${n}" declares subjectDigest in ${r.prefix} with no usable subject beside it — a digest is recorded only as a property of a subject, so this one is dropped`,capabilityId:n,path:`${r.prefix}.${i[0].join(".")}`,code:"CAP_SUBJECT_DIGEST_ORPHAN"})}return t}},cu=[Yl,zl,Hl,Zl,Xl,tu,iu,su,au,{id:"action-declaration",severity:"warning",check(e){const t=[],n=e?.id??"(unknown)",r=e?.action;if(void 0!==r&&!Array.isArray(r))return t.push({ruleId:"action-declaration",severity:"error",message:`Capability "${n}" declares action as ${typeof r} — it must be a list, e.g. action: [file.read]`,capabilityId:n,path:"action",code:"CAP_ACTION_NOT_A_LIST"}),t;const i=Array.isArray(r)?r:[];for(let e=0;e<i.length;e++){const r=i[e];De(r)||t.push({ruleId:"action-declaration",severity:"error",message:`Capability "${n}" declares action ${JSON.stringify(r)}, which is not one of ${Le.join(", ")} — a policy rule written against it matches nothing`,capabilityId:n,path:`action.${e}`,code:"CAP_ACTION_UNKNOWN"})}const s=Array.isArray(e?.sideEffects)?e.sideEffects:[];return 0===i.length&&s.length>0&&t.push({ruleId:"action-declaration",severity:"warning",message:`Capability "${n}" declares side effects (${s.join(", ")}) and no action — no policy rule addressing an action can reach it, so a rule denying that action leaves this id open`,capabilityId:n,path:"action",code:"CAP_ACTION_UNDECLARED"}),t}}];const lu=new class{#$e=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#$e.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.#$e.set(e.id,e)}unregister(e){return this.#$e.delete(e)}list(){return Array.from(this.#$e.keys())}reset(){this.#$e.clear();for(const e of cu)this.#$e.set(e.id,e)}},uu="capability.lint";class du{name=uu;async execute(e,t){const n=e??{},r=ao.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=lu.lintAll(r).map(e=>({id:e.id,ok:e.ok,issues:e.issues}));return{results:i,ok:i.every(e=>e.ok),count:i.length}}}const pu={type:"object"};function fu(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function hu(e){let t;return t=function(e){if(e instanceof Vs)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:fu(e),{content:[{type:"text",text:t}],isError:!0}}const mu="capability.serveList",gu="capability.serveCall",yu=new Set([mu,gu]);class wu{name=mu;async execute(e,t){const n=(e??{}).filter??{},r=ao.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!yu.has(e.definition.id)).filter(e=>ll(e,n)).map(e=>function(e,t){const n=t??e.id,r=e.sideEffects??[];return{name:n,description:e.description??e.title??n,inputSchema:e.inputs?.schema??pu,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class vu{name=gu;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||yu.has(r)||!ao.getCapability(r))return hu(new Error(`unknown tool: ${r||"(empty)"}`));try{const e=t.trace?.traceId?{...t,trace:{...t.trace,...t.invocationId?{parentSpanId:t.invocationId}:{}}}:t;return function(e){return{content:[{type:"text",text:fu(e)}],isError:!1}}(await Wa.call(r,n.arguments??{},e))}catch(e){return hu(e)}}}const bu="shell.revealView",Iu="shell.hideView",ku="shell.listViews",Eu="shell.toggleView",Su="shell.toggleSlot",Au="shell.moveView";function xu(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new Vs(Us.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:bu});return e}function Cu(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 Tu{name=bu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=xu();if(!i.getPlacement(n))throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:bu,viewId:n});return await i.reveal(n,Cu(t),{focus:r}),{viewId:n,revealed:!0}}}class _u{name=Iu;async execute(e,t){const{viewId:n}=e??{};return xu().hide(n,Cu(t)),{viewId:n,hidden:!0}}}class Pu{name=ku;async execute(e,t){return{views:xu().listViews()}}}class Nu{name=Eu;async execute(e,t){const{viewId:n,focus:r}=e??{},i=xu();if(!i.getPlacement(n))throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:Eu,viewId:n});return"visible"===i.getState(n)?(i.hide(n,Cu(t)),{viewId:n,visible:!1}):(await i.reveal(n,Cu(t),{focus:r}),{viewId:n,visible:!0})}}const $u=new Map;class Mu{name=Su;async execute(e,t){const{slot:n,focus:r}=e??{},i=xu(),s=function(){const e=globalThis.punica?.shell?.Layout?.manager;return e&&"function"==typeof e.setSlotCollapsed?e:void 0}();if(s?.isSlotCollapsed?.(n)){s.setSlotCollapsed?.(n,!1);const e=i.getVisibleView(n);if(e)return{slot:n,visible:!0,viewId:e}}else{const e=i.getVisibleView(n);if(e)return $u.set(n,e),s?.setSlotCollapsed?.(n,!0),s?.isSlotCollapsed?.(n)||i.hide(e,Cu(t)),{slot:n,visible:!1,viewId:e}}const o=$u.get(n);let a=o&&i.getPlacement(o)?o:void 0;return a||(a=i.listViews().find(e=>e.slot===n)?.viewId),a?(await i.reveal(a,Cu(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}class Ru{name=Au;async execute(e,t){const{viewId:n,slot:r}=e??{},i=xu(),s=i.getPlacement(n);if(!s)throw new Vs(Us.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover movable views.`,{capability:Au,viewId:n});const o=s.allowedSlots??[];if(!o.includes(r))throw new Vs(Us.CAPABILITY_INPUT_INVALID,`View "${n}" cannot be moved to slot "${r}". Allowed slots: ${o.length?o.join(", "):"(none)"}.`,{capability:Au,viewId:n,slot:r});return await i.moveView(n,r,Cu(t)),{viewId:n,slot:r,moved:!0}}}function Ou(e){try{Ws.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function Lu(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 ju(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 Du(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=ao.getCapability(e.id);return t?void ju(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=ao.listCapabilities(n),i=r.map(Lu);if(console.log("[Punica] Trinity capability catalog",{count:i.length}),i.length>0){if(console.table(i),e?.verbose){console.log("[Punica] Full definitions (same fields as .punica/capabilities.yaml):");for(const e of r)ju(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Fu(e){return Du({...e,verbose:!0})}function Bu(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 qu(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,i=t.policy?.risk??"—",s=function(e){const t=e.indexOf("\n");return(-1===t?e:e.slice(0,t)).trim()}(t.description??t.title??"")||"—";return`| ${n} | ${r} | ${i} | ${o=s,o.replace(/\|/g,"\\|")} |`;var o}function Uu(e){return JSON.stringify(e,null,2)}const Vu=new class{#Me=new Map;get(e){return this.#Me.get(e)}list(){return[...this.#Me.values()]}register(e,t){for(const e of t)this.#Me.set(e.definition.id,e),this.#Re(e.definition.id)}unregister(e){for(const[t,n]of this.#Me)n.serverId===e&&(this.#Me.delete(t),this.#Oe(t))}hasServer(e){for(const t of this.#Me.values())if(t.serverId===e)return!0;return!1}#Re(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{}}#Oe(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{}}},Wu=16384,Ku="runtime:mcp:client";function Gu(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Yu(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 Yu(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=>Yu(e,t+1));return e.length>50&&n.push(`…[${e.length-50} more items truncated]`),n}if(e&&"object"==typeof e){if(t>=12)return"…[truncated]";const n={};for(const[r,i]of Object.entries(e))n[r]=Yu(i,t+1);return n}return e}function zu(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=Wu)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Yu(e,0),null,2)??"null";if(r.length<=Wu)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,Wu)+"\n… [truncated]",bytes:n,truncated:!0}}function Ju(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}function Hu(e,t){let n=e;const r=()=>(n===e&&(n={...e}),n);for(const e of t){const t=e.split(".").filter(e=>e.length>0);if(0===t.length)continue;let n=r();for(let e=0;e<t.length&&n;e++){const r=t[e],i="*"===r?n.items:n.properties?.[r];if(!i||"object"!=typeof i){n=void 0;break}const s={...i};"*"===r?n.items=s:n.properties={...n.properties,[r]:s},n=s}n&&(n.policyKey=!0)}return n}const Qu=new class{#Le=new Map;async connect(e){if(this.#Le.has(e.id))return this.#Le.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return sd}),r=e.toolOverrides??await t(e.id),i="stdio"===e.kind?await n(e.env):e.env,s="streamable-http"===e.kind||"sse"===e.kind?await n(e.headers):e.headers,o={...e,env:i,headers:s,toolOverrides:r&&Object.keys(r).length?r:void 0},a=function(e,t){const n=(t,n,r)=>({direction:"outbound",serverId:e.serverId,serverName:e.serverName,transport:e.transport,method:n,toolName:Ju(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Gu(),s=zu(r??{});Ei({name:"mcp.request",source:Ku,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:Zt().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Gu(),s=Date.now(),o=zu(r??{});Ei({name:"mcp.request",source:Ku,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:Zt().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=zu(o??null);return Ei({name:"mcp.response",source:Ku,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:Zt().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw Ei({name:"mcp.response",source:Ku,correlationId:i,kind:"error",payload:{...n(i,e,r),kind:"request",isError:!0,durationMs:Date.now()-s,errorMessage:t instanceof Error?t.message:String(t)}}),t}}}}({serverId:o.id,serverName:o.name,transport:o.kind},await async function(e){if("stdio"===e.kind){if(!e.command)throw new Error(`MCP server "${e.id}": stdio transport requires 'command'`);const{StdioTransport:t}=await Promise.resolve().then(function(){return Gv});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 Yv});return new t(e.url,e.headers??{})}throw new Error(`MCP server "${e.id}": unknown transport kind "${e.kind}"`)}(o));await a.connect(),await a.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"punica-editor",version:"1.0.0"}}),a.notify("notifications/initialized",{});const c=await a.request("tools/list",{}),l=c?.tools??[],u=l.map(e=>{const t=o.toolOverrides?.[e.name]??{},n=function(e,t,n={}){const r=t._meta?.punica??{},i={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},s=n.policy?.keyPaths??r.policy?.keyPaths??[],o={timeoutMs:n.executionDefaults?.timeoutMs??r.executionDefaults?.timeoutMs??3e4,idempotency:n.executionDefaults?.idempotency??r.executionDefaults?.idempotency??"none"},a=["mcp",e],c=r.tags??[],l=n.tags??[],u=[...new Set([...a,...c,...l])],d=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:Hu(t.inputSchema??{type:"object"},s)},outputs:{schema:{type:"object",properties:{content:{type:"array",items:{type:"object",properties:{type:{type:"string"},text:{type:"string"}}}},isError:{type:"boolean"}}},kind:"direct"},policy:i,sideEffects:d,executionDefaults:o,tags:u}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});Vu.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(),Vu.unregister(e.id),this.#Le.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#Le.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#Le.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#Le.values()].map(e=>e.handle)}listTools(e){return e?this.#Le.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#Le.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},Zu=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/,Xu=/^\$\{secret\.([A-Za-z0-9_.-]+)\}$/;async function ed(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 td(e){if(!e)return{};const t={},n=function(){const e=globalThis.process,t=e?.env;return t&&"object"==typeof t?t:void 0}(),r=void 0!==n;for(const[i,s]of Object.entries(e)){if("string"!=typeof s){t[i]=s;continue}const e=s.match(Xu);if(e){const n=e[1],r=await ed(n);void 0!==r?t[i]=r:console.warn(`[Punica] MCP secret placeholder \${secret.${n}} — not found in Secret Manager`);continue}const o=s.match(Zu);if(o){const e=o[1];if(!r){console.warn(`[Punica] MCP env placeholder \${env.${e}} skipped — not in Node/Electron`);continue}const s=n[e];void 0!==s?t[i]=s:console.warn(`[Punica] MCP env placeholder \${env.${e}} — variable unset`)}else t[i]=s}return t}async function nd(e){try{const t=globalThis,n=t.punica?.runtime?.fs,r=n?.readFile,i=n?.exists;if(!r)return{};if(i){const t=`.punica/mcp/${e}.yaml`;if(!await i(t))return{}}let s;try{s=await r(`.punica/mcp/${e}.yaml`,{encoding:"utf8"})}catch{return{}}if("string"!=typeof s||""===s.trim())return{};const{parse:o}=await Promise.resolve().then(function(){return am}),a=o(s);return a?.tools&&"object"==typeof a.tools?a.tools:{}}catch(t){return console.warn(`[Punica] MCP overrides for "${e}" failed:`,t?.message??t),{}}}async function rd(){try{const e=globalThis,t=e.punica?.runtime?.fs,n=t?.readFile,r=t?.exists;if(!n)return[];if(r){if(!await r(".punica/mcp.yaml"))return[]}let i;try{i=await n(".punica/mcp.yaml",{encoding:"utf8"})}catch{return[]}const{parseYamlMcpConfig:s}=await Promise.resolve().then(function(){return zv}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await nd(e.id),n="stdio"===e.kind?await td(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?await td(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 id(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 sd=Object.freeze({__proto__:null,loadMcpConfig:rd,loadServerOverrides:nd,parseStaticConfig:id,resolveEnvPlaceholders:td});class od{name=Gn.RUNTIME.MCP;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.RUNTIME.FS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){this.#je=e.BOOTSTRAPPING;const n=await rd();this.#De(n),this.#je=e.BOOTSTRAPPED}async#De(e){for(const t of e)try{await Qu.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#je=e.STARTING,this.#je=e.STARTED,console.log(`[Punica] MCP module started — ${Vu.list().length} capability(ies) active`)}}const ad=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const cd={get capabilities(){return Co.hasProvider()?Co.get().capabilities:void 0},get cwd(){return Co.hasProvider()?Co.get().cwd:void 0},hasProvider:()=>Co.hasProvider(),getFileTree:()=>Co.get().getFileTree(),readFile:e=>Co.get().readFile(e),get readBytes(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.readBytes?e.readBytes.bind(e):void 0},get writeBytes(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.writeBytes?e.writeBytes.bind(e):void 0},updateFileContent:(e,t)=>Co.get().updateFileContent(e,t),createFolder:e=>Co.get().createFolder(e),deleteFolder:e=>Co.get().deleteFolder(e),deleteFile:(e,t)=>Co.get().deleteFile(e,t),renameFile:(e,t)=>Co.get().renameFile(e,t),renameFolder:(e,t)=>Co.get().renameFolder(e,t),get revealInOS(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.revealInOS?e.revealInOS.bind(e):void 0},createFileWithContent:(e,t)=>Co.get().createFileWithContent(e,t),get list(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.list?e.list.bind(e):void 0},get stat(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.stat?e.stat.bind(e):void 0},get mkdir(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.mkdir?e.mkdir.bind(e):void 0},get copy(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.copy?e.copy.bind(e):void 0},get exists(){if(!Co.hasProvider())return;const e=Co.get();return"function"==typeof e.exists?e.exists.bind(e):void 0},__punicaWrappedFsFacade:!0},ld=function(e){return Ri(e)?e:(void 0!==e&&Mi(e),{__punicaWrappedSearchFacade:!0,query:e=>$i.get().query(e),startIndex:e=>{const t=$i.get();return t.startIndex?t.startIndex(e):Promise.resolve()}})}(ad?.search),ud=function(e){return Ki(e)?e:(void 0!==e&&Wi(e),{__punicaWrappedVcsFacade:!0,status:()=>Vi.get().status(),branches:()=>Vi.get().branches(),logs:e=>Vi.get().logs(e),init:e=>Vi.get().init(e),clone:e=>Vi.get().clone(e),commit:e=>Vi.get().commit(e),stage:e=>Vi.get().stage(e),unstage:e=>Vi.get().unstage(e),discard:e=>Vi.get().discard(e),reset:e=>Vi.get().reset(e),switchBranch:e=>Vi.get().switchBranch(e),createBranch:(e,t)=>Vi.get().createBranch(e,t),fetch:e=>Vi.get().fetch(e),pull:e=>Vi.get().pull(e),push:e=>Vi.get().push(e)})}(ad?.vcs),dd=function(e){return Bi(e)?e:(void 0!==e&&Fi(e),{__punicaWrappedTerminalFacade:!0,create:e=>Di.get().create(e),write:(e,t)=>Di.get().write(e,t),resize:(e,t,n)=>Di.get().resize(e,t,n),close:e=>Di.get().close(e),onData:(e,t)=>Di.get().onData(e,t),onExit:(e,t)=>Di.get().onExit(e,t),list:()=>Di.get().list()})}(ad?.terminals),pd=function(e){return e||{start:e=>Ui().start(e),send:(e,t)=>Ui().send(e,t),onMessage:(e,t)=>Ui().onMessage(e,t),onStderr:(e,t)=>Ui().onStderr(e,t),onExit:(e,t)=>Ui().onExit(e,t),stop:e=>Ui().stop(e),list:()=>Ui().list()}}(ad?.debug),fd=function(e){return ji(e)?e:(void 0!==e&&Li(e),{__punicaWrappedTasksFacade:!0,run:e=>Oi.get().run(e)})}(ad?.tasks),hd=function(e){return Ji(e)?e:(void 0!==e&&zi(e),{getCurrent:()=>Gi.get().getCurrent(),list:()=>Gi.get().list(),open:e=>Gi.get().open(e),setEnvironment:(e,t)=>Gi.get().setEnvironment(e,t),onDidChange:e=>Gi.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0})}(ad?.workspace),md=function(e){return Ni(e)?e:(void 0!==e&&Pi(e),{__punicaWrappedResourcesFacade:!0,list:e=>_i.get().list(e),get:e=>_i.get().get(e),register:e=>_i.get().register(e),unregister:e=>_i.get().unregister(e),onDidChange:e=>_i.get().onDidChange(e)})}(ad?.resources),gd=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&cs(e),t)return e;async function n(e,t){return"local"!==await Xi(e,t)}async function r(e,t,n){!function(e,t){(ss&&ss!==e||os&&t&&os!==t)&&se.publishEvent({name:"llm.providerChanged",envelope:{id:se.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:ss,newProviderId:e,previousEndpoint:os,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),ss=e,t&&(os=t)}(t,n);const r=await i(),s=e?.correlationId??se.createCorrelationId(),o=vt.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!o.allowed)throw o.requiresApproval&&vt.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:s}),se.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:se.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(o.reason??"[Policy] Remote LLM request denied");return se.publishEvent({name:"llm.remoteRequestSent",envelope:{id:se.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}}async function i(){try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch(e){return void console.error("[LLM Facade] Error accessing punica.runtime.workspace:",e?.message??e)}}async function s(e){const t=ts();if(!t)return{cache:void 0,cacheKey:void 0,cached:void 0};try{const n=await i(),r=await async function(e){try{const t=globalThis.crypto?.subtle;if(!t)return;const n=(new TextEncoder).encode(Ne(function(e){return{workspaceId:e.workspaceId??null,userId:e.userId??null,messages:e.messages??null,profile:e.profile??null,temperature:e.temperature??null,maxTokens:e.maxTokens??null,route:e.route??null,providerId:e.providerId??null,responseFormat:e.responseFormat??null,modelId:e.modelId??null,modelIds:e.modelIds??null,tools:e.tools??null,toolChoice:e.toolChoice??null,reasoning:e.reasoning??null}}(e))),r=await t.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{return}}(function(e,t){return{workspaceId:t,userId:ge()?.email,messages:e.messages,profile:e.profile,temperature:e.temperature,maxTokens:e.maxTokens,route:e.route,providerId:e.providerId,responseFormat:e.responseFormat,modelId:e.modelId,modelIds:e.modelIds,tools:e.tools,toolChoice:e.toolChoice,reasoning:e.reasoning}}(e,n));return r?!0===e?.skipCache?{cache:t,cacheKey:r,cached:void 0}:{cache:t,cacheKey:r,cached:await t.get(r)??void 0}:{cache:void 0,cacheKey:void 0,cached:void 0}}catch(e){return console.warn("[LLM Facade] Response cache lookup failed; calling the model:",e?.message??e),{cache:void 0,cacheKey:void 0,cached:void 0}}}function o(e,t,n){if(e&&t&&function(e){return!!e&&("string"==typeof e.text&&e.text.trim().length>0||(e.toolCalls?.length??0)>0)}(n))try{const r=e.set(t,{response:n,storedAtMs:Date.now()});r&&"function"==typeof r.catch&&r.catch(()=>{})}catch{}}const a={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",a=e?.providerId??"remote",c=as(),l=!0===e?.[rs],{cache:u,cacheKey:d,cached:p}=await s(e);if(!l&&("remote"===t||await n(e,c))){const t=e?.endpoint,n=await r(e,a,t);if(p)return ns(p);const i=await c.chat(n);return o(u,d,i),i}const f=p?ns(p):await c.chat(e);if(!f)throw new Error("[LLM Facade] No response returned from LLM provider");const h=f?.provider;if(!l&&Qi(h)){const n=h&&"remote"!==h?h:a,r=await i(),s=e?.correlationId??se.createCorrelationId(),o=vt.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw se.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:se.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"error"},payload:{providerId:n,route:t,workspaceId:r,messageCount:e.messages?.length??0,reason:p?"Policy denies this provider; a cached answer is refused for the same reason a fresh one would be":"Policy gate bypassed via auto route",...p?{cacheHit:!0}:{}}}),o.requiresApproval&&vt.requestApproval({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r,correlationId:s}),new Error(o.reason??"[Policy] Remote LLM request denied (auto route bypass detected)");p||se.publishEvent({name:"llm.remoteRequestSent",envelope:{id:se.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:n,workspaceId:r,messageCount:e.messages?.length??0,retroactive:!0,route:t}})}return p||o(u,d,f),f},chatStream:async function*(e){if(e?.signal?.aborted)return;const t=e?.route??"auto",i=e?.providerId??"remote",a=as();let c=e;if(!(!0===e?.[rs])&&("remote"===t||await n(e,a))){const t=e?.endpoint;c=await r(e,i,t)}const{cache:l,cacheKey:u,cached:d}=await s(c);if(d){const e=ns(d);if(c?.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})}if("function"!=typeof a.chatStream){const e=await a.chat(c);if(!e)throw new Error("[LLM Facade] No response returned from LLM provider");if(o(l,u,e),c?.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 a.chatStream(c)){if(c?.signal?.aborted)return;"done"===e?.type&&o(l,u,e.response),yield e}},__punicaWrappedLlmFacade:!0};return a.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?.())}}}(),a}(ad?.llm),yd=function(e){if(e)return e;const t=ds(),n=new ps(t),r=new bs(t,n);t.registerLanguageRuntime(hs),t.registerLanguageRuntime(ms),t.registerLanguageRuntime(gs),t.registerLanguageRuntime(ys),t.registerLanguageRuntime(ws);const i=new Map;return{async*run(e,t){const n=t?.runId??vs("run"),s=await r.open({language:e.language,provider:e.metadata?.provider,kernelspec:e.metadata?.kernelspec,env:e.env,cwd:e.cwd,resources:e.resources,metadata:e.metadata});i.set(n,s);try{for await(const n of s.run(e,t))yield n}finally{i.delete(n),await s.close()}},async cancel(e){const t=i.get(e);t&&(await t.interrupt(),i.delete(e))},session:r,registry:t}}(ad?.compute),wd=function(e){if(e)return e;const t=Es(),n=new Ss(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],i=t.getProvider(r);if(!i)throw new Error(`Dataset provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Dataset provider not found: ${e.provider}`);return n.list({query:e.query,tags:e.tags})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({query:e?.query,tags:e?.tags});r.push(...n)}catch(e){console.warn(`Failed to list datasets from provider ${t.id}:`,e)}return r},registry:t}}(ad?.datasets),vd=function(e){if(e)return e;const t=Cs(),n=new Ts(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],i=t.getProvider(r);if(!i)throw new Error(`Model provider not found: ${r}`);return i.unmount(e)},async list(e){if(e?.provider){const n=t.getProvider(e.provider);if(!n)throw new Error(`Model provider not found: ${e.provider}`);return n.list({task:e.task,query:e.query})}const n=t.listProviders(),r=[];for(const t of n)try{const n=await t.list({task:e?.task,query:e?.query});r.push(...n)}catch(e){console.warn(`Failed to list models from provider ${t.id}:`,e)}return r},registry:t}}(ad?.models),bd=function(e){if(e)return e;const t=Ns();return{registry:t,async start(e){const n=function(e){if(e.format&&"unknown"!==e.format)return e.format;const t=e.filePath?.trim().toLowerCase();if(t){if(t.endsWith(".gguf"))return"gguf";if(t.endsWith(".safetensors"))return"safetensors";if(t.endsWith(".onnx"))return"onnx"}return"unknown"}(e),r=n!==e.format?{...e,format:n}:e,i=t.select(r);if(!i){const e=t.list().map(e=>e.id);throw new Error(`No model runtime can run record "${r.id}" (format=${r.format??"unknown"}). Registered runtimes: [${e.join(", ")||"none"}].`)}return i.start(r)},async stop(e){const n=t.get(e.runtimeId);if(!n)throw new Error(`No model runtime registered for handle runtimeId="${e.runtimeId}".`);await n.stop(e)}}}(ad?.modelRuntimes),Id=function(e){if(e)return e;const t=Ns();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}.`);const i=e.handle?.tasks??r.tasks;if(e.task&&i&&!i.includes(e.task)){const t=e.handle?.tasks?"this handle":`runtime "${n}"`;throw new Error(`Task "${e.task}" is not served by ${t}. Declared: [${i.join(", ")||"none"}].`)}return r.infer(e)}}}(ad?.inference),kd=function(e){return e||{upsert:(e,t)=>Bs().upsert(e,t),query:e=>Bs().query(e),delete:(e,t)=>Bs().delete(e,t),clear:e=>Bs().clear(e),count:e=>Bs().count(e)}}(ad?.vectors),Ed=function(e){if(e)return e;function t(){const e=qs().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=qs().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=qs().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 i={start:e=>r().start(e),stop:()=>r().stop(),status:()=>r().status(),onRequest:e=>r().onRequest(e),reply:(e,t)=>r().reply(e,t)},s={info:e=>{const t=qs().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:()=>qs().dataDir(),dataFs:{list:(e,t)=>qs().dataFs.list(e,t),readFile:e=>qs().dataFs.readFile(e),stat:e=>qs().dataFs.stat(e),mkdir:(e,t)=>qs().dataFs.mkdir(e,t),deleteFile:e=>qs().dataFs.deleteFile(e),deleteFolder:e=>qs().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=qs().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=qs().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=Fs?.http?.download;if(e)return e=>n().download(e)},get onDownloadProgress(){const e=Fs?.http?.onDownloadProgress;if(e)return e=>n().onDownloadProgress(e)}},get mcpServer(){return Fs?.mcpServer?i:void 0},get system(){return Fs?.system?s:void 0}}}(ad?.host),Sd=function(e){return cc(e)?e:(void 0!==e&&ac(e),{set:(e,t)=>sc.get().set(e,t),get:e=>sc.get().get(e),delete:e=>sc.get().delete(e),list:()=>sc.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:sc.get().get(`secret-manager.${e}`)},__punicaWrappedSecretsFacade:!0})}(ad?.secrets);console.log("[Runtime] Facades created"),function(){Ou({name:"fs.readFile",title:"Read a file",description:"Read a file's full text content from disk by path. The usual first step before changing a file: look at what it says.",version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",subject:"file"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Ya),Ou({name:"fs.writeFile",title:"Write a file",description:"Write text to a file, creating it when it does not exist and replacing its contents when it does. The canonical way to save, edit, or generate a file.",version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string",subject:"file"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),Ws.registerProvider(new za),Ou({name:"fs.writeBytes",title:"Write binary file content",description:"Write raw bytes to a file, creating it when it does not exist and replacing its contents when it does. The binary counterpart to fs.writeFile, which encodes as UTF-8 and would corrupt an image or any other non-text payload. Bytes travel base64-encoded because capability inputs are JSON.",version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","base64"],properties:{path:{type:"string",subject:"file"},base64:{type:"string",sensitive:!0,maxLength:89478485}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),Ws.registerProvider(new Ha),Ou({name:"fs.listFiles",title:"List the whole file tree",description:"List every file and folder in the workspace as a nested tree, showing the whole project layout rather than the contents of one directory.",version:"1.0.0",sideEffect:"read",action:["file.list"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Qa),Ou({name:"fs.stat",title:"File size and dates",description:"Get a path's size, modification time, and whether it is a directory, without reading its contents.",version:"1.0.0",sideEffect:"read",action:["file.stat"],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}}),Ws.registerProvider(new Za),Ou({name:"fs.exists",title:"Check a path exists",description:"Check whether a file or folder exists at a path, before reading it or overwriting it.",version:"1.0.0",sideEffect:"read",action:["file.stat"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"boolean"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Xa),Ou({name:"fs.copy",title:"Copy a file",description:"Copy a file or folder to another path, leaving the original in place.",version:"1.0.0",sideEffect:"write",action:["file.read","file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["src","dst"],properties:{src:{type:"string",subject:"file"},dst:{type:"string",subject:"file"}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),Ws.registerProvider(new ec),Ou({name:"fs.mkdir",title:"Create a folder",description:"Create a folder, optionally creating the missing parent folders above it.",version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),Ws.registerProvider(new tc),Ou({name:"fs.list",title:"List one folder",description:"List the files and folders directly inside one directory, optionally recursing into subfolders.",version:"1.0.0",sideEffect:"read",action:["file.list"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new ic),Ou({name:"fs.history",title:"File version history",description:"List the earlier saved versions of one file, so a change can be reviewed or rolled back.",version:"1.0.0",sideEffect:"read",action:["file.stat"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new nc),Ou({name:"fs.readAtVersion",title:"Read an earlier version",description:"Read a file's contents as they were at one of its earlier saved versions.",version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path","versionId"],properties:{path:{type:"string",subject:"file"},versionId:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new rc),Ou({name:"secrets.get",title:"Read a stored secret",description:"Read a stored credential — an API key, token, or password — from the host's secret store by name; the result is the secret itself, so it must never be written to a file, a log, or a message.",version:"1.0.0",sideEffect:"read",action:["secret.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"}}},outputSchema:{type:["string","null"]},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3}}),Ws.registerProvider(new lc),Ou({name:"secrets.set",title:"Store a secret",description:"Store a credential — an API key, token, or password — in the host's secret store under a name, so other capabilities can use it without the value being written anywhere else.",version:"1.0.0",sideEffect:"write",action:["secret.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"}}),Ws.registerProvider(new uc),Ou({name:"llm.chat",title:"Chat with a model",description:"Send a conversation to a language model and get the reply back as text.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],egress:"dynamic",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",subject:"model"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),Ws.registerProvider(new pc),Ou({name:"llm.chatStream",title:"Stream a model reply",description:"Send a conversation to a language model and stream the reply as it is generated. Same contract as llm.chat, with live tokens delivered as events.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],egress:"dynamic",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",subject:"model"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),Ws.registerProvider(new fc),Ou({name:"llm.plan",title:"Plan a workflow",description:"Turn a request written in plain language into a runnable workflow plan.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],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}}}),Ws.registerProvider(new mc),Ou({name:"llm.invoke",title:"Run an instruction class",description:"Run one named instruction class — planner, code generator, validator — against a prompt, using the model and the provider chain that class is configured with.",version:"1.0.0",sideEffect:"network",action:["model.invoke"],egress:"dynamic",risk:"low",permissions:[],inputSchema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",subject:"prompt"},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"},text:{type:"string"},structured:{},metadata:{type:"object",properties:{instructionClass:{type:"string"},modelId:{type:"string",subject:"model"},provider:{type:"string"},tokensUsed:{type:"number"},cacheHit:{type:"boolean"}}}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),Ws.registerProvider(new hc),Ou({name:"search.query",title:"Search across all files",description:"Search the text of every file in the workspace and return the matching files with their matching lines and line numbers. This is how to answer where something is, which files mention a word, or where a function is defined.",version:"1.0.0",sideEffect:"read",action:["file.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}}),Ws.registerProvider(new gc),Ou({name:"vcs.status",title:"Uncommitted changes",description:"Show what has changed in the repository: which files have uncommitted changes — modified, added, deleted, and untracked.",version:"1.0.0",sideEffect:"read",action:["vcs.read"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new yc),Ou({name:"vcs.commit",title:"Commit changes",description:"Commit the current changes to version control with a message.",version:"1.0.0",sideEffect:"write",action:["vcs.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["message"],properties:{message:{type:"string"},all:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),Ws.registerProvider(new wc),Ou({name:"workspace.readFile",title:"Read a workspace file",description:"Read a file's text from the workspace — the same operation as fs.readFile, kept for compatibility, and fs.readFile is the one to prefer.",deprecated:{since:"1.37.0",reason:"Duplicates fs.readFile exactly; kept so older flows and manifests keep working.",replacement:"fs.readFile"},version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string",subject:"file"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new vc),Ou({name:"workspace.writeFile",title:"Write a workspace file",description:"Create a workspace file with the given text, kept for compatibility; prefer fs.writeFile, which also updates a file that already exists.",deprecated:{since:"1.37.0",reason:"Creates only; fs.writeFile also updates a file that already exists.",replacement:"fs.writeFile"},version:"1.0.0",sideEffect:"write",action:["file.write"],risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string",subject:"file"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),Ws.registerProvider(new bc),Ou({name:"workspace.listFiles",title:"Flat list of workspace files",description:"List every file in the workspace as one flat list of paths, without the folder structure that fs.listFiles returns.",version:"1.0.0",sideEffect:"read",action:["file.list"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object"}}}},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Ic),Ou({name:"workspace.projectContext",title:"What this project is",description:"Summarize the project in a single read: language and stack, dependencies, the scripts it can run, version control state, a digest of the README, and the meaningful parts of the folder layout. The fastest way to get oriented in an unfamiliar project.",version:"1.0.0",sideEffect:"read",action:["file.read"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),Ws.registerProvider(new Oc),Ou({name:"workspace.writeOrientation",title:"Write the project summary to files",description:"Write the project summary into the workspace as CLAUDE.md and .claudeignore, so a terminal agent gets oriented from a file read.",version:"1.0.0",sideEffect:"write",action:["file.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"}}),Ws.registerProvider(new jc),Ou({name:"context.remember",title:"Remember a fact",description:"Save a durable fact about this project under a key so it survives across sessions and is not rediscovered every time.",version:"1.0.0",sideEffect:"write",action:["memory.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"}}),Ws.registerProvider(new qc),Ou({name:"context.recall",title:"Recall saved facts",description:"Read back the facts saved for this project — all of them, or the one under a key.",version:"1.0.0",sideEffect:"read",action:["memory.read"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{key:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Uc),Ou({name:"terminals.create",title:"Open a terminal",description:"Open a new terminal in the app and return its id.",version:"1.0.0",sideEffect:"write",action:["process.exec"],risk:"low",permissions:[],inputSchema:{type:"object",properties:{title:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),Ws.registerProvider(new Vc),Ou({name:"terminals.send",title:"Run a line in an open terminal",description:"Type a line into an already open terminal and run it, using the terminal id returned by terminals.create.",version:"1.0.0",sideEffect:"write",action:["process.exec"],risk:"low",permissions:[],inputSchema:{type:"object",required:["id","text"],properties:{id:{type:"string"},text:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:5e3,idempotency:"optional"}}),Ws.registerProvider(new Wc),Ou({name:"tasks.runCommand",title:"Run a shell command",description:"Run a shell command or program and return its exit code together with everything it printed. This is how tests, builds, installs, and any other command-line work get done.",version:"1.0.0",sideEffect:"write",action:["process.exec"],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"}}),Ws.registerProvider(new Kc),Ou({name:"signing.sign",title:"Sign bytes with this workstation key",description:"Sign the given bytes with the host's package-signing key and return a detached signature carrying the public half, so a later reader can check the bytes were not altered without holding any secret.",version:"1.0.0",sideEffect:"read",risk:"medium",permissions:[],inputSchema:{type:"object",required:["bytes"],properties:{bytes:{type:"string",description:"base64url-encoded payload"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new nl),Ou({name:"signing.verify",title:"Verify a signature",description:"Check a detached signature against the given bytes and report whether they were altered since signing; this needs no key and works on a machine that did not produce them.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["bytes","signature"],properties:{bytes:{type:"string",description:"base64url-encoded payload"},signature:{type:"object"}}},outputSchema:{type:"object",required:["valid"],properties:{valid:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new rl),Ou({name:"signing.publicKey",title:"Read the signing public key",description:"Read the public half of the host's package-signing key, so a package can name the key in its header before its bytes are signed.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new il),Ou({name:"flow.migrate",title:"Migrate a workflow document",description:"Bring a saved workflow document up to a newer schema version, or report what migrating it would change. Reads only; nothing runs.",version:"1.0.0",sideEffect:"read",action:["flow.run"],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}}),Ws.registerProvider(new sl),Ou({name:"flow.runSubflow",title:"Run a subflow",description:"Run another workflow as a child of the current one and return its result.",version:"1.0.0",sideEffect:"write",action:["flow.run"],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"}}),Ws.registerProvider(new ol),Ou({name:al,title:"Browse the capability catalog",description:"List the capabilities available on this installation, filtered by where they came from, which extension declared them, their tags, their risk, or their side effects.",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}}),Ws.registerProvider(new cl),Ou({name:ml,title:"Export capability schemas",description:"Export the installed capabilities as machine-readable tool schemas, in the format a model provider expects.",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}}),Ws.registerProvider(new gl),Ou({name:$l,title:"Find capabilities for a goal",description:"Rank the installed capabilities against a goal written in plain language and return the closest ones. The way to find a tool when its name is not known.",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"},normalizedAs:{type:"string"}}},defaults:{timeoutMs:5e3}}),Ws.registerProvider(new Ml),Ou({name:Ol,title:"Search for a capability",description:"Search the installed capabilities by keyword and return the matches with a one-line summary each. Use it when the right tool is not in the list already at hand.",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}}),Ws.registerProvider(new Dl),Ou({name:Rl,title:"Describe a capability",description:"Return one capability in full: what it does, the exact arguments it takes, what it returns, and whether calling it needs approval. Read this before calling a capability that is not already described.",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}}),Ws.registerProvider(new jl);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Bl("ai.session.create",{title:"Start a new chat session",description:"Create a new persistent assistant conversation in a workspace and return it.",properties:{workspaceId:{type:"string"},title:{type:"string"}},outputProperties:{session:{type:"object"}}}),Bl("ai.session.list",{title:"List chat sessions",description:"List the saved assistant conversations, optionally limited to one workspace.",properties:{workspaceId:{type:"string"}},outputProperties:{sessions:{type:"array"},count:{type:"number"}}}),Bl("ai.session.get",{title:"Read one chat session",description:"Read one saved assistant conversation, including its messages.",required:["sessionId"],properties:e,outputProperties:{session:{type:"object"}}}),Bl("ai.session.rename",{title:"Rename a chat session",description:"Give a saved assistant conversation a different title.",required:["sessionId","title"],properties:{...e,title:{type:"string"}},outputProperties:{ok:{type:"boolean"}}}),Bl("ai.session.archive",{title:"Archive a chat session",description:"Move a saved assistant conversation out of the active list without deleting it.",required:["sessionId"],properties:{...e,archived:{type:"boolean"}},outputProperties:{ok:{type:"boolean"}}}),Bl("ai.session.delete",{title:"Delete a chat session",description:"Delete a saved assistant conversation and its whole message history. Cannot be undone.",risk:"medium",required:["sessionId"],properties:e,outputProperties:{ok:{type:"boolean"}}})]}())Ou(e);for(const e of[new ql,new Ul,new Vl,new Wl,new Kl,new Gl])Ws.registerProvider(e);Ou({name:uu,title:"Check capability declarations",description:"Check the installed capability declarations against the substrate conventions and report what is missing or malformed.",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}}),Ws.registerProvider(new du),Ou({name:mu,title:"List capabilities offered to remote callers",description:"List the capabilities this installation exposes to a remote caller, with the schema each one accepts.",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}}),Ws.registerProvider(new wu),Ou({name:gu,title:"Call a capability on behalf of a remote caller",description:"Run one capability for a remote caller through the full policy, approval, and audit pipeline.",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}}),Ws.registerProvider(new vu),Ou({name:bu,action:["ui.reveal"],title:"Show a panel",description:"Open a named panel such as settings, source control, the file explorer or the terminal, and focus it.",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string",description:"Id of the panel to open, as `shell.listViews` reports it."},focus:{type:"boolean",description:"Also move keyboard focus into the panel."}}},outputSchema:{type:"object",required:["viewId","revealed"],properties:{viewId:{type:"string"},revealed:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),Ws.registerProvider(new Tu),Ou({name:Iu,title:"Hide a panel",description:"Hide a panel, sidebar, or editor view.",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}}),Ws.registerProvider(new _u),Ou({name:ku,title:"List the panels",description:"List the panels, sidebars, and editor views this window has, and which of them are currently visible.",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}}),Ws.registerProvider(new Pu),Ou({name:Eu,action:["ui.reveal"],title:"Toggle a panel",description:"Show a panel if it is hidden, hide it if it is showing.",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}}),Ws.registerProvider(new Nu),Ou({name:Su,action:["ui.reveal"],title:"Toggle a whole area of the window",description:"Show or hide one whole area of the window — the left sidebar, the right sidebar, or the bottom panel — rather than a single view inside it.",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}}),Ws.registerProvider(new Mu),Ou({name:Au,title:"Move a panel somewhere else",description:"Move a view into a different area of the window, for example from the bottom panel into the right sidebar.",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}}),Ws.registerProvider(new Ru)}(),console.log("[Runtime] Capabilities registered");const Ad={lifecyclePhase:ad?.lifecyclePhase??"bootstrapping",fs:cd,fileOpeners:ad?.fileOpeners??ki,fileOperations:ad?.fileOperations??Ci,search:ld,vcs:ud,terminals:dd,debug:pd,tasks:fd,workspace:hd,resources:md,secrets:Sd,llm:gd,compute:yd,datasets:wd,models:vd,modelRuntimes:bd,inference:Id,vectors:kd,host:Ed,capabilities:{gateway:Wa,unifiedRegistry:ao,logTrinityCatalog:Du,docs:{formatCapabilityMarkdown:function(e){const t=e.definition,n=[];n.push(`# \`${t.id}\``),n.push(""),n.push(function(e){const t=e.definition,n=[];n.push(`**Origin:** ${e.origin}`),n.push(`**Version:** ${t.version}`);const r=t.policy?.risk??"—",i=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${i}`);const s=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";n.push(`**Side effects:** ${s}`);const o=Array.isArray(t.action)&&t.action.length>0?t.action.join(", "):"—";return n.push(`**Action:** ${o}`),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(Uu(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Uu(t.outputs.schema)),n.push("```"),n.push("")),t.tags&&t.tags.length>0&&(n.push("## Tags"),n.push(""),n.push(t.tags.join(", ")),n.push(""));const i=t.requires;if(i&&i.length>0){n.push("## Requires"),n.push("");for(const e of i)n.push(`- \`${e}\``);n.push("")}if(t.deprecated){n.push("## Deprecated"),n.push("");const e=[];e.push(`**Since:** ${t.deprecated.since}`),t.deprecated.reason&&e.push(`— ${t.deprecated.reason}`),n.push(e.join(" ")),t.deprecated.replacement&&(n.push(""),n.push(`**Replacement:** \`${t.deprecated.replacement}\``)),n.push("")}const s=function(e){const t=e.metadata;if(!t)return;const n=[];t.extensionName&&n.push(`- Extension: \`${t.extensionName}\``);t.productId&&n.push(`- Product: \`${t.productId}\``);t.packageRoot&&n.push(`- Manifest: \`${t.packageRoot}\``);return n.length>0?n.join("\n"):void 0}(e);for(s&&(n.push("## Source"),n.push(""),n.push(s),n.push(""));n.length>1&&""===n[n.length-1];)n.pop();return n.join("\n")+"\n"},formatCapabilitiesIndex:function(e){const t=[];t.push("# Capability Reference"),t.push(""),t.push("Auto-generated from the substrate's unified capability registry."),t.push("Run `npm run docs:capabilities` to regenerate — CI gates drift."),t.push("");const n=function(e){const t=new Map;for(const n of e){const e=t.get(n.origin)??[];e.push(n),t.set(n.origin,e)}for(const e of t.values())e.sort((e,t)=>e.definition.id.localeCompare(t.definition.id));return t}(e),r=["core","extension","instruction-class","ivy-node"];for(const e of r){const r=n.get(e);if(r&&0!==r.length){t.push(`## ${Bu(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(qu(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:Vu,connect:e=>Qu.connect(e),disconnect:e=>Qu.disconnect(e),listServers:()=>Qu.listServers(),listTools:e=>Qu.listTools(e),callTool:(e,t,n)=>Qu.callTool(e,t,n)},setFsProvider:function(e){Co.set(e),e&&Ei({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:cs,setComputeProvider:function(e){ds().registerProvider(e)},setComputeRuntime:function(e){ds().registerLanguageRuntime(e)},setDatasetProvider:function(e){Es().registerProvider(e)},setModelProvider:function(e){Cs().registerProvider(e)},setModelRuntime:function(e){Ns().register(e)},setHostProvider:function(e){Fs=e},setVectorsProvider:function(e){js=e},setSearchProvider:Mi,setWorkspaceProvider:zi,setTerminalProvider:Fi,setDebugProvider:function(e){qi=e},setVcsProvider:Wi,setResourcesProvider:Pi,setTasksProvider:Li,setSecretsProvider:ac,installDefaultApprovalTokenPair:e=>{!function(e){const t=new Qo({secret:e}),n=new Zo({secret:t.getSecret()});ra(t),sa(n)}(e)},setApprovalTokenSigner:ra,setApprovalTokenVerifier:sa,getApprovalTokenSigner:function(){return ea??na().signer},getApprovalTokenVerifier:ia,setHostIdentity:function(e){me=e},getHostIdentity:ge,setPackageSigner:function(e){Zc.set(e),e&&Ei({name:"packageSigner.providerRegistered",source:"runtime:packageSigner",payload:{}})},hasPackageSigner:el,verifyPackageSignature:Qc,setCapabilityTelemetryExporter:function(e){ho=e??fo},getCapabilityTelemetryExporter:mo,setEventTelemetryExporter:function(e){H=e??J},getEventTelemetryExporter:Q,setLlmResponseCache:function(e){es=e},getLlmResponseCache:ts,InMemoryLlmResponseCache:class{#Ae;#Fe;#Me=new Map;#Be=0;#qe=0;#Ue=0;#Ve=0;constructor(e){this.#Ae=Math.max(1,e?.maxEntries??200),this.#Fe=Math.max(0,e?.ttlMs??36e5)}get(e){const t=this.#Me.get(e);if(t)return this.#Fe>0&&Date.now()-t.storedAtMs>this.#Fe?(this.#Me.delete(e),void(this.#qe+=1)):(this.#Me.delete(e),this.#Me.set(e,t),this.#Be+=1,this.#Ve+=t.response.usage?.totalTokens??0,t);this.#qe+=1}set(e,t){for(this.#Me.delete(e),this.#Me.set(e,t),this.#Ue+=1;this.#Me.size>this.#Ae;){const e=this.#Me.keys().next().value;if(void 0===e)break;this.#Me.delete(e)}}clear(){this.#Me.clear()}stats(){return{entries:this.#Me.size,hits:this.#Be,misses:this.#qe,stores:this.#Ue,tokensSaved:this.#Ve}}}};class xd{#We;constructor(e){this.#We=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#We);n?e(n):t(new Error("Extension not found"))})}}let Cd=class{#Ke;constructor(e){this.#Ke=e}async execute(){return await this.#Ke.execute()}},Td=class extends Cd{constructor(e){super(e)}async execute(){return await super.execute()}},_d=class extends Cd{constructor(e){super(e)}async execute(){try{const e=await super.execute(),t=`${e.moduleURL}${e.main}`,n=(await import(/* webpackIgnore: true */`${t}`)).default;return e.module=n,e}catch(e){if(e instanceof Error)throw e;throw new Error(String(e))}}},Pd=class extends Cd{constructor(e){super(e)}async execute(){return await super.execute()}};const Nd=Symbol.for("yaml.alias"),$d=Symbol.for("yaml.document"),Md=Symbol.for("yaml.map"),Rd=Symbol.for("yaml.pair"),Od=Symbol.for("yaml.scalar"),Ld=Symbol.for("yaml.seq"),jd=Symbol.for("yaml.node.type"),Dd=e=>!!e&&"object"==typeof e&&e[jd]===Nd,Fd=e=>!!e&&"object"==typeof e&&e[jd]===$d,Bd=e=>!!e&&"object"==typeof e&&e[jd]===Md,qd=e=>!!e&&"object"==typeof e&&e[jd]===Rd,Ud=e=>!!e&&"object"==typeof e&&e[jd]===Od,Vd=e=>!!e&&"object"==typeof e&&e[jd]===Ld;function Wd(e){if(e&&"object"==typeof e)switch(e[jd]){case Md:case Ld:return!0}return!1}function Kd(e){if(e&&"object"==typeof e)switch(e[jd]){case Nd:case Md:case Od:case Ld:return!0}return!1}const Gd=Symbol("break visit"),Yd=Symbol("skip children"),zd=Symbol("remove node");function Jd(e,t){const n=Xd(t);if(Fd(e)){Hd(null,e.contents,n,Object.freeze([e]))===zd&&(e.contents=null)}else Hd(null,e,n,Object.freeze([]))}function Hd(e,t,n,r){const i=ep(e,t,n,r);if(Kd(i)||qd(i))return tp(e,r,i),Hd(e,i,n,r);if("symbol"!=typeof i)if(Wd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Hd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Gd)return Gd;i===zd&&(t.items.splice(e,1),e-=1)}}}else if(qd(t)){r=Object.freeze(r.concat(t));const e=Hd("key",t.key,n,r);if(e===Gd)return Gd;e===zd&&(t.key=null);const i=Hd("value",t.value,n,r);if(i===Gd)return Gd;i===zd&&(t.value=null)}return i}async function Qd(e,t){const n=Xd(t);if(Fd(e)){await Zd(null,e.contents,n,Object.freeze([e]))===zd&&(e.contents=null)}else await Zd(null,e,n,Object.freeze([]))}async function Zd(e,t,n,r){const i=await ep(e,t,n,r);if(Kd(i)||qd(i))return tp(e,r,i),Zd(e,i,n,r);if("symbol"!=typeof i)if(Wd(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await Zd(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Gd)return Gd;i===zd&&(t.items.splice(e,1),e-=1)}}}else if(qd(t)){r=Object.freeze(r.concat(t));const e=await Zd("key",t.key,n,r);if(e===Gd)return Gd;e===zd&&(t.key=null);const i=await Zd("value",t.value,n,r);if(i===Gd)return Gd;i===zd&&(t.value=null)}return i}function Xd(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 ep(e,t,n,r){return"function"==typeof n?n(e,t,r):Bd(t)?n.Map?.(e,t,r):Vd(t)?n.Seq?.(e,t,r):qd(t)?n.Pair?.(e,t,r):Ud(t)?n.Scalar?.(e,t,r):Dd(t)?n.Alias?.(e,t,r):void 0}function tp(e,t,n){const r=t[t.length-1];if(Wd(r))r.items[e]=n;else if(qd(r))"key"===e?r.key=n:r.value=n;else{if(!Fd(r)){const e=Dd(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Jd.BREAK=Gd,Jd.SKIP=Yd,Jd.REMOVE=zd,Qd.BREAK=Gd,Qd.SKIP=Yd,Qd.REMOVE=zd;const np={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},rp=e=>e.replace(/[!,[\]{}]/g,e=>np[e]);class ip{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},ip.defaultYaml,e),this.tags=Object.assign({},ip.defaultTags,t)}clone(){const e=new ip(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new ip(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:ip.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},ip.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:ip.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},ip.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(2!==n.length&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[e,r]=n;return this.tags[e]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==n.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=n;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const n=e.slice(2,-1);return"!"===n||"!!"===n?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),n)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return"!"===n?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+rp(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&&Kd(e.contents)){const t={};Jd(e.contents,(e,n)=>{Kd(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(const[i,s]of n)"!!"===i&&"tag:yaml.org,2002:"===s||e&&!r.some(e=>e.startsWith(s))||t.push(`%TAG ${i} ${s}`);return t.join("\n")}}function sp(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 op(e){const t=new Set;return Jd(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function ap(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function cp(e,t,n,r){if(r&&"object"==typeof r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){const n=r[t],i=cp(e,r,String(t),n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),i=cp(e,r,t,n);void 0===i?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(const t of Array.from(r)){const n=cp(e,r,t,t);void 0===n?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(const[t,n]of Object.entries(r)){const i=cp(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function lp(e,t,n){if(Array.isArray(e))return e.map((e,t)=>lp(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Ud(r=e)&&!Wd(r)||!r.anchor))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=e=>{i.res=e,delete n.onCreate};const s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}var r;return"bigint"!=typeof e||n?.keep?e:Number(e)}ip.defaultYaml={explicit:!1,version:"1.2"},ip.defaultTags={"!!":"tag:yaml.org,2002:"};class up{constructor(e){Object.defineProperty(this,jd,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Fd(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=lp(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?cp(i,{"":o},"",o):o}}class dp extends up{constructor(e){super(Nd),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Jd(e,{Node:(e,n)=>{if(n===this)return Jd.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,s=this.resolve(r);if(!s){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(s);if(o||(lp(s,null,t),o=n.get(s)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(i>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=pp(r,s,n)),o.count*o.aliasCount>i)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return o.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(sp(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 pp(e,t,n){if(Dd(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Wd(t)){let r=0;for(const i of t.items){const t=pp(e,i,n);t>r&&(r=t)}return r}if(qd(t)){const r=pp(e,t.key,n),i=pp(e,t.value,n);return Math.max(r,i)}return 1}const fp=e=>!e||"function"!=typeof e&&"object"!=typeof e;class hp extends up{constructor(e){super(Od),this.value=e}toJSON(e,t){return t?.keep?this.value:lp(this.value,e,t)}toString(){return String(this.value)}}hp.BLOCK_FOLDED="BLOCK_FOLDED",hp.BLOCK_LITERAL="BLOCK_LITERAL",hp.PLAIN="PLAIN",hp.QUOTE_DOUBLE="QUOTE_DOUBLE",hp.QUOTE_SINGLE="QUOTE_SINGLE";function mp(e,t,n){if(Fd(e)&&(e=e.contents),Kd(e))return e;if(qd(e)){const t=n.schema[Md].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||"undefined"!=typeof BigInt&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n;let c;if(r&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=i(e)),new dp(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 hp(e);return c&&(c.node=t),t}l=e instanceof Map?o[Md]:Symbol.iterator in Object(e)?o[Ld]:o[Md]}s&&(s(l),delete n.onTagObj);const u=l?.createNode?l.createNode(n.schema,e,n):"function"==typeof l?.nodeClass?.from?l.nodeClass.from(n.schema,e,n):new hp(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function gp(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 mp(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 yp=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class wp extends up{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=>Kd(t)||qd(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(yp(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Wd(i))i.addIn(r,t);else{if(void 0!==i||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`);this.set(n,gp(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(Wd(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return 0===r.length?!t&&Ud(i)?i.value:i:Wd(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!qd(t))return!1;const n=t.value;return null==n||e&&Ud(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!!Wd(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(Wd(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,gp(this.schema,r,t))}}}}wp.maxFlowStringSingleLineLength=60;const vp=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function bp(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Ip=(e,t,n)=>e.endsWith("\n")?bp(n,t):n.includes("\n")?"\n"+bp(n,t):(e.endsWith(" ")?"":" ")+n,kp="flow",Ep="block",Sp="quoted";function Ap(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let d,p,f=i-t.length;"number"==typeof r&&(r>i-Math.max(2,s)?l.push(0):f=i-r);let h=!1,m=-1,g=-1,y=-1;n===Ep&&(m=xp(e,m,t.length),-1!==m&&(f=m+c));for(let r;r=e[m+=1];){if(n===Sp&&"\\"===r){switch(g=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if("\n"===r)n===Ep&&(m=xp(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===Sp){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 i=l[r],s=l[r+1]||e.length;0===i?w=`\n${t}${e.slice(0,s)}`:(n===Sp&&u[i]&&(w+=`${e[i]}\\`),w+=`\n${t}${e.slice(i+1,s)}`)}return w}function xp(e,t,n){let r=t,i=t+1,s=e[i];for(;" "===s||"\t"===s;)if(t<i+n)s=e[++t];else{do{s=e[++t]}while(s&&"\n"!==s);r=t,i=t+1,s=e[i]}return r}const Cp=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Tp=e=>/^(%|---|\.\.\.)/m.test(e);function _p(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(Tp(e)?" ":"");let o="",a=0;for(let e=0,t=n[e];t;t=n[++e])if(" "===t&&"\\"===n[e+1]&&"n"===n[e+2]&&(o+=n.slice(a,e)+"\\ ",e+=1,a=e,t="\\"),"\\"===t)switch(n[e+1]){case"u":{o+=n.slice(a,e);const t=n.substr(e+2,4);switch(t){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===t.substr(0,2)?o+="\\x"+t.substr(2):o+=n.substr(e,6)}e+=5,a=e+1}break;case"n":if(r||'"'===n[e+2]||n.length<i)e+=1;else{for(o+=n.slice(a,e)+"\n\n";"\\"===n[e+2]&&"n"===n[e+3]&&'"'!==n[e+4];)o+="\n",e+=2;o+=s," "===n[e+2]&&(o+="\\"),e+=1,a=e+1}break;default:e+=1}return o=a?o+n.slice(a):n,r?o:Ap(o,s,Sp,Cp(t,!1))}function Pp(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return _p(e,t);const n=t.indent||(Tp(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:Ap(r,n,kp,Cp(t,!1))}function Np(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=_p;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?Pp:i&&!t?_p:n?Pp:_p}return r(e,t)}let $p;try{$p=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{$p=/\n+(?!\n|$)/g}function Mp({comment:e,type:t,value:n},r,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return Np(n,r);const l=r.indent||(r.forceBlockIndent||Tp(n)?" ":""),u="literal"===o||"folded"!==o&&t!==hp.BLOCK_FOLDED&&(t===hp.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}(n,c,l.length));if(!n)return u?"|\n":">\n";let d,p;for(p=n.length;p>0;--p){const e=n[p-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let f=n.substring(p);const h=f.indexOf("\n");-1===h?d="-":n===f||h!==f.length-1?(d="+",s&&s()):d="",f&&(n=n.slice(0,-f.length),"\n"===f[f.length-1]&&(f=f.slice(0,-1)),f=f.replace($p,`$&${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," ")),i&&i()),u)return`${v}\n${l}${w}${n=n.replace(/\n+/g,`$&${l}`)}${f}`;return`${v}\n${l}${Ap(`${w}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${f}`,l,Ep,Cp(r,!0))}`}function Rp(e,t,n,r){const{implicitKey:i,inFlow:s}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==hp.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=hp.QUOTE_DOUBLE);const c=e=>{switch(e){case hp.BLOCK_FOLDED:case hp.BLOCK_LITERAL:return i||s?Np(o.value,t):Mp(o,t,n,r);case hp.QUOTE_DOUBLE:return _p(o.value,t);case hp.QUOTE_SINGLE:return Pp(o.value,t);case hp.PLAIN:return function(e,t,n,r){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&s.includes("\n")||u&&/[[\]{},]/.test(s))return Np(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?Np(s,t):Mp(e,t,n,r);if(!a&&!u&&i!==hp.PLAIN&&s.includes("\n"))return Mp(e,t,n,r);if(Tp(s)){if(""===c)return t.forceBlockIndent=!0,Mp(e,t,n,r);if(a&&c===l)return Np(s,t)}const d=s.replace(/\n+/g,`$&\n${c}`);if(o){const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return Np(s,t)}return a?d:Ap(d,c,kp,Cp(t,!1))}(o,t,n,r);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}function Op(e,t){const n=Object.assign({blockQuote:!0,commentString:vp,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 Lp(e,t,n,r){if(qd(e))return e.toString(t,n,r);if(Dd(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=Kd(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i||(i=function(e,t){if(t.tag){const n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(Ud(t)){r=t.value;const i=e.filter(e=>e.identify?.(r));n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n)throw new Error(`Tag not resolved for ${r?.constructor?.name??typeof r} value`);return n}(t.doc.schema.tags,s));const o=function(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const i=[],s=(Ud(e)||Wd(e))&&e.anchor;s&&sp(s)&&(n.add(s),i.push(`&${s}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&i.push(r.directives.tagString(o)),i.join(" ")}(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof i.stringify?i.stringify(s,t,n,r):Ud(s)?Rp(s,t,n,r):s.toString(t,n,r);return o?Ud(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function jp(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function Dp(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&Fp(n))if(r=Dd(r)?r.resolve(e.doc):r,Vd(r))for(const n of r.items)Bp(e,t,n);else if(Array.isArray(r))for(const n of r)Bp(e,t,n);else Bp(e,t,r);else{const i=lp(n,"",e);if(t instanceof Map)t.set(i,lp(r,i,e));else if(t instanceof Set)t.add(i);else{const s=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(Kd(e)&&n?.doc){const t=Op(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)+'..."'),jp(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}(n,i,e),o=lp(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const Fp=e=>"<<"===e||Ud(e)&&"<<"===e.value&&(!e.type||e.type===hp.PLAIN);function Bp(e,t,n){const r=e&&Dd(n)?n.resolve(e.doc):n;if(!Bd(r))throw new Error("Merge sources must be maps or map aliases");const i=r.toJSON(null,e,Map);for(const[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function qp(e,t,n){const r=mp(e,void 0,n),i=mp(t,void 0,n);return new Up(r,i)}class Up{constructor(e,t=null){Object.defineProperty(this,jd,{value:Rd}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Kd(t)&&(t=t.clone(e)),Kd(n)&&(n=n.clone(e)),new Up(t,n)}toJSON(e,t){return Dp(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,r,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n;let p=Kd(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Wd(e)||!Kd(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||Wd(e)||(Ud(e)?e.type===hp.BLOCK_FOLDED||e.type===hp.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!f&&(d||!s),indent:a+c});let h,m,g,y=!1,w=!1,v=Lp(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(s||null==t)return y&&r&&r(),""===v?"?":f?`? ${v}`:v}else if(s&&!d||null==t&&f)return v=`? ${v}`,p&&!y?v+=Ip(v,n.indent,l(p)):w&&i&&i(),v;y&&(p=null),f?(p&&(v+=Ip(v,n.indent,l(p))),v=`? ${v}\n${a}:`):(v=`${v}:`,p&&(v+=Ip(v,n.indent,l(p)))),Kd(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||!Ud(t)||(n.indentAtStart=v.length+1),w=!1,u||!(c.length>=2)||n.inFlow||f||!Vd(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let b=!1;const I=Lp(t,n,()=>b=!0,()=>w=!0);let k=" ";if(p||h||m)k=h?"\n":"",m&&(k+=`\n${bp(l(m),n.indent)}`),""!==I||n.inFlow?k+=`\n${n.indent}`:"\n"===k&&(k="\n\n");else if(!f&&Wd(t)){const e=I[0],r=I.indexOf("\n"),i=-1!==r,s=n.inFlow??t.flow??0===t.items.length;if(i||!s){let t=!1;if(i&&("&"===e||"!"===e)){let n=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+=Ip(v,n.indent,l(g)):w&&i&&i(),v}(this,e,t,n):JSON.stringify(this)}}function Vp(e,t,n){return(t.inFlow??e.flow?Kp:Wp)(e,t,n)}function Wp({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null});let d=!1;const p=[];for(let e=0;e<t.length;++e){const i=t[e];let o=null;if(Kd(i))!d&&i.spaceBefore&&p.push(""),Gp(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(qd(i)){const e=Kd(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),Gp(n,p,e.commentBefore,d))}d=!1;let a=Lp(i,u,()=>o=null,()=>d=!0);o&&(a+=Ip(a,s,l(o))),d&&o&&(d=!1),p.push(r+a)}let f;if(0===p.length)f=i.start+i.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"+bp(l(e),c),a&&a()):d&&o&&o(),f}function Kp({items:e},t,{flowChars:n,itemIndent:r}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;r+=s;const c=Object.assign({},t,{indent:r,inFlow:!0,type:null});let l=!1,u=0;const d=[];for(let n=0;n<e.length;++n){const i=e[n];let s=null;if(Kd(i))i.spaceBefore&&d.push(""),Gp(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(qd(i)){const e=Kd(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),Gp(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Kd(i.value)?i.value:null;n?(n.comment&&(s=n.comment),n.commentBefore&&(l=!0)):null==i.value&&e?.comment&&(s=e.comment)}s&&(l=!0);let o=Lp(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=Ip(o,r,a(s))),!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${s}${i}${t}`:"\n";return`${e}\n${i}${f}`}return`${p}${o}${d.join(" ")}${o}${f}`}function Gp({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=bp(t(r),e);n.push(i.trimStart())}}function Yp(e,t){const n=Ud(t)?t.value:t;for(const r of e)if(qd(r)){if(r.key===t||r.key===n)return r;if(Ud(r.key)&&r.key.value===n)return r}}class zp extends wp{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Md,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:i}=n,s=new this(e),o=(e,o)=>{if("function"==typeof i)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(void 0!==o||r)&&s.items.push(qp(e,o,n))};if(t instanceof Map)for(const[e,n]of t)o(e,n);else if(t&&"object"==typeof t)for(const e of Object.keys(t))o(e,t[e]);return"function"==typeof e.sortMapEntries&&s.items.sort(e.sortMapEntries),s}add(e,t){let n;n=qd(e)?e:e&&"object"==typeof e&&"key"in e?new Up(e.key,e.value):new Up(e,e?.value);const r=Yp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Ud(r.value)&&fp(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const e=this.items.findIndex(e=>i(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=Yp(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=Yp(this.items,e),r=n?.value;return(!t&&Ud(r)?r.value:r)??void 0}has(e){return!!Yp(this.items,e)}set(e,t){this.add(new Up(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)Dp(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!qd(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})),Vp(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Jp={collection:"map",default:!0,nodeClass:zp,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(Bd(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>zp.from(e,t,n)};class Hp extends wp{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ld,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Qp(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Qp(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Ud(r)?r.value:r}has(e){const t=Qp(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Qp(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Ud(r)&&fp(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(lp(e,String(r++),t));return n}toString(e,t,n){return e?Vp(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let s of t){if("function"==typeof r){const n=t instanceof Set?s:String(e++);s=r.call(t,n,s)}i.items.push(mp(s,void 0,n))}}return i}}function Qp(e){let t=Ud(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const Zp={collection:"seq",default:!0,nodeClass:Hp,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Vd(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Hp.from(e,t,n)},Xp={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>Rp(e,t=Object.assign({actualString:!0},t),n,r)},ef={identify:e=>null==e,createNode:()=>new hp(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new hp(null),stringify:({source:e},t)=>"string"==typeof e&&ef.test.test(e)?e:t.options.nullStr},tf={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new hp("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&tf.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function nf({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const i="number"==typeof r?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(s)){let e=s.indexOf(".");e<0&&(e=s.length,s+=".");let n=t-(s.length-e-1);for(;n-- >0;)s+="0"}return s}const rf={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:nf},sf={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():nf(e)}},of={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 hp(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:nf},af=e=>"bigint"==typeof e||Number.isInteger(e),cf=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function lf(e,t,n){const{value:r}=e;return af(r)&&r>=0?n+r.toString(t):nf(e)}const uf={identify:e=>af(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>cf(e,2,8,n),stringify:e=>lf(e,8,"0o")},df={identify:af,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>cf(e,0,10,n),stringify:nf},pf={identify:e=>af(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>cf(e,2,16,n),stringify:e=>lf(e,16,"0x")},ff=[Jp,Zp,Xp,ef,tf,uf,df,pf,rf,sf,of];function hf(e){return"bigint"==typeof e||Number.isInteger(e)}const mf=({value:e})=>JSON.stringify(e),gf=[Jp,Zp].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:mf},{identify:e=>null==e,createNode:()=>new hp(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:mf},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:mf},{identify:hf,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})=>hf(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:mf}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),yf={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if("function"==typeof Buffer)return Buffer.from(e,"base64");if("function"==typeof atob){const t=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,i,s){const o=n;let a;if("function"==typeof Buffer)a=o instanceof Buffer?o.toString("base64"):Buffer.from(o.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);a=btoa(e)}}if(t||(t=hp.BLOCK_LITERAL),t!==hp.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(a.length/e),i=new Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=a.substr(r,e);a=i.join(t===hp.BLOCK_LITERAL?"\n":" ")}return Rp({comment:e,type:t,value:a},r,i,s)}};function wf(e,t){if(Vd(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!qd(r)){if(Bd(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Up(new hp(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]=qd(r)?r:new Up(r)}}else t("Expected a sequence for this tag");return e}function vf(e,t,n){const{replacer:r}=n,i=new Hp(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){let o,a;if("function"==typeof r&&(e=r.call(t,String(s++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);o=e[0],a=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);o=t[0],a=e[o]}else o=e;i.items.push(qp(o,a,n))}return i}const bf={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:wf,createNode:vf};class If extends Hp{constructor(){super(),this.add=zp.prototype.add.bind(this),this.delete=zp.prototype.delete.bind(this),this.get=zp.prototype.get.bind(this),this.has=zp.prototype.has.bind(this),this.set=zp.prototype.set.bind(this),this.tag=If.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const e of this.items){let r,i;if(qd(e)?(r=lp(e.key,"",t),i=lp(e.value,r,t)):r=lp(e,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,i)}return n}static from(e,t,n){const r=vf(e,t,n),i=new this;return i.items=r.items,i}}If.tag="tag:yaml.org,2002:omap";const kf={collection:"seq",identify:e=>e instanceof Map,nodeClass:If,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=wf(e,t),r=[];for(const{key:e}of n.items)Ud(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new If,n)},createNode:(e,t,n)=>If.from(e,t,n)};function Ef({value:e,source:t},n){return t&&(e?Sf:Af).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const Sf={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 hp(!0),stringify:Ef},Af={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 hp(!1),stringify:Ef},xf={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:nf},Cf={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():nf(e)}},Tf={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 hp(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:nf},_f=e=>"bigint"==typeof e||Number.isInteger(e);function Pf(e,t,n,{intAsBigInt:r}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const s=parseInt(e,n);return"-"===i?-1*s:s}function Nf(e,t,n){const{value:r}=e;if(_f(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return nf(e)}const $f={identify:_f,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Pf(e,2,2,n),stringify:e=>Nf(e,2,"0b")},Mf={identify:_f,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Pf(e,1,8,n),stringify:e=>Nf(e,8,"0")},Rf={identify:_f,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Pf(e,0,10,n),stringify:nf},Of={identify:_f,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Pf(e,2,16,n),stringify:e=>Nf(e,16,"0x")};class Lf extends zp{constructor(e){super(e),this.tag=Lf.tag}add(e){let t;t=qd(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Up(e.key,null):new Up(e,null);Yp(this.items,t.key)||this.items.push(t)}get(e,t){const n=Yp(this.items,e);return!t&&qd(n)?Ud(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=Yp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Up(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof r&&(e=r.call(t,e,e)),i.items.push(qp(e,null,n));return i}}Lf.tag="tag:yaml.org,2002:set";const jf={collection:"map",identify:e=>e instanceof Set,nodeClass:Lf,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Lf.from(e,t,n),resolve(e,t){if(Bd(e)){if(e.hasAllNullValues(!0))return Object.assign(new Lf,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function Df(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,i=e=>t?BigInt(e):Number(e),s=r.replace(/_/g,"").split(":").reduce((e,t)=>e*i(60)+i(t),i(0));return"-"===n?i(-1)*s:s}function Ff(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return nf(e);let r="";t<0&&(r="-",t*=n(-1));const i=n(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),r+s.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const Bf={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})=>Df(e,n),stringify:Ff},qf={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=>Df(e,!1),stringify:Ff},Uf={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(Uf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,i,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=Df(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$/,"")},Vf=[Jp,Zp,Xp,ef,Sf,Af,$f,Mf,Rf,Of,xf,Cf,Tf,yf,kf,bf,jf,Bf,qf,Uf],Wf=new Map([["core",ff],["failsafe",[Jp,Zp,Xp]],["json",gf],["yaml11",Vf],["yaml-1.1",Vf]]),Kf={binary:yf,bool:tf,float:of,floatExp:sf,floatNaN:rf,floatTime:qf,int:df,intHex:pf,intOct:uf,intTime:Bf,map:Jp,null:ef,omap:kf,pairs:bf,seq:Zp,set:jf,timestamp:Uf},Gf={"tag:yaml.org,2002:binary":yf,"tag:yaml.org,2002:omap":kf,"tag:yaml.org,2002:pairs":bf,"tag:yaml.org,2002:set":jf,"tag:yaml.org,2002:timestamp":Uf};function Yf(e,t){let n=Wf.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(Wf.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=Kf[e];if(t)return t;const n=Object.keys(Kf).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const zf=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Jf{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?Yf(e,"compat"):e?Yf(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Gf:{},this.tags=Yf(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,Md,{value:Jp}),Object.defineProperty(this,Od,{value:Xp}),Object.defineProperty(this,Ld,{value:Zp}),this.sortMapEntries="function"==typeof s?s:!0===s?zf:null}clone(){const e=Object.create(Jf.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Hf{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,jd,{value:$d});let r=null;"function"==typeof t||Array.isArray(t)?r=t:void 0===n&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:s}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new ip({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Hf.prototype,{[jd]:{value:$d}});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=Kd(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Qf(this.contents)&&this.contents.add(e)}addIn(e,t){Qf(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=op(this);e.anchor=!t||n.has(t)?ap(t||"a",n):t}return new dp(e.anchor)}createNode(e,t,n){let r;if("function"==typeof t)e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,n=t.filter(e).map(String);n.length>0&&(t=t.concat(n)),r=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:s,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=function(e,t){const n=[],r=new Map;let i=null;return{onAnchor:r=>{n.push(r),i||(i=op(e));const s=ap(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Ud(t.node)&&!Wd(t.node)){const t=new Error("Failed to resolve repeated object (this should not happen)");throw t.source=e,t}t.node.anchor=t.anchor}},sourceObjects:r}}(this,s||"a"),f=mp(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&Wd(f)&&(f.flow=!0),d(),f}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Up(r,i)}delete(e){return!!Qf(this.contents)&&this.contents.delete(e)}deleteIn(e){return yp(e)?null!=this.contents&&(this.contents=null,!0):!!Qf(this.contents)&&this.contents.deleteIn(e)}get(e,t){return Wd(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return yp(e)?!t&&Ud(this.contents)?this.contents.value:this.contents:Wd(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!Wd(this.contents)&&this.contents.has(e)}hasIn(e){return yp(e)?void 0!==this.contents:!!Wd(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=gp(this.schema,[e],t):Qf(this.contents)&&this.contents.set(e,t)}setIn(e,t){yp(e)?this.contents=t:null==this.contents?this.contents=gp(this.schema,Array.from(e),t):Qf(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 ip({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 ip({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 Jf(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},a=lp(this.contents,t??"",o);if("function"==typeof i)for(const{count:e,res:t}of o.anchors.values())i(t,e);return"function"==typeof s?cp(s,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return function(e,t){const n=[];let r=!0===t.directives;if(!1!==t.directives&&e.directives){const t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");const i=Op(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(bp(t,""))}let o=!1,a=null;if(e.contents){if(Kd(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(bp(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=Lp(e.contents,i,()=>a=null,t);a&&(c+=Ip(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(Lp(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(bp(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(bp(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Qf(e){if(Wd(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Zf extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Xf extends Zf{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class eh extends Zf{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const th=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){const e=Math.min(s-39,o.length-79);o="…"+o.substring(e),s-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+"…\n"),o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];t&&t.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-s)));const a=" ".repeat(s)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function nh(e,{flow:t,indicator:n,next:r,offset:i,onError:s,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 i of e)switch(m&&("space"!==i.type&&"newline"!==i.type&&"comma"!==i.type&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&"comment"!==i.type&&"newline"!==i.type&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),i.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!i.source.includes("\t")||(g=i),u=!0;break;case"comment":{u||s(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=i.source.substring(1)||" ";d?d+=p+e:d=e,p="",l=!1;break}case"newline":l?d?d+=i.source:c=!0:p+=i.source,l=!0,f=!0,(y||w)&&(h=!0),u=!0;break;case"anchor":y&&s(i,"MULTIPLE_ANCHORS","A node can have at most one anchor"),i.source.endsWith(":")&&s(i.offset+i.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=i,null===I&&(I=i.offset),l=!1,u=!1,m=!0;break;case"tag":w&&s(i,"MULTIPLE_TAGS","A node can have at most one tag"),w=i,null===I&&(I=i.offset),l=!1,u=!1,m=!0;break;case n:(y||w)&&s(i,"BAD_PROP_ORDER",`Anchors and tags must be after the ${i.source} indicator`),b&&s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.source} in ${t??"collection"}`),b=i,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){v&&s(i,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),v=i,l=!1,u=!1;break}default:s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.type} token`),l=!1,u=!1}const k=e[e.length-1],E=k?k.offset+k.source.length:i;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||"block-map"===r?.type||"block-seq"===r?.type)&&s(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:b,spaceBefore:c,comment:d,hasNewline:f,hasNewlineAfterProp:h,anchor:y,tag:w,end:E,start:I??E}}function rh(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(rh(t.key)||rh(t.value))return!0}return!1;default:return!0}}function ih(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&rh(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function sh(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Ud(t)&&Ud(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const oh="All mapping items must start at the same column";function ah(e,t,n,r){let i="";if(e){let s=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}const ch="Block collections are not allowed within flow collections",lh=e=>e&&("block-map"===e.type||"block-seq"===e.type);function uh(e,t,n,r,i,s){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??zp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const s of r.items){const{start:l,key:u,sep:d,value:p}=s,f=nh(l,{indicator:"explicit-key-ind",next:u??d?.[0],offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0}),h=!f.found;if(h){if(u&&("block-seq"===u.type?i(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&i(a,"BAD_INDENT",oh)),!f.anchor&&!f.tag&&!d){c=f.end,f.comment&&(o.comment?o.comment+="\n"+f.comment:o.comment=f.comment);continue}(f.hasNewlineAfterProp||rh(u))&&i(u??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==r.indent&&i(a,"BAD_INDENT",oh);const m=f.end,g=u?e(n,u,f,i):t(n,m,l,null,f,i);n.schema.compat&&ih(r.indent,u,i),sh(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=nh(d??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){h&&("block-map"!==p?.type||y.hasNewline||i(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&f.start<y.found.offset-1024&&i(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const c=p?e(n,p,y,i):t(n,a,d,null,y,i);n.schema.compat&&ih(r.indent,p,i),a=c.range[2];const l=new Up(g,c);n.options.keepSourceTokens&&(l.srcToken=s),o.items.push(l)}else{h&&i(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const e=new Up(g);n.options.keepSourceTokens&&(e.srcToken=s),o.items.push(e)}}return c&&c<a&&i(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[r.offset,a,c??a],o}(e,t,n,r,s):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o=new(s?.nodeClass??Hp)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=nh(s,{indicator:"seq-item-ind",next:l,offset:a,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(!(u.anchor||u.tag||l)){c=u.end,u.comment&&(o.comment=u.comment);continue}l&&"block-seq"===l.type?i(u.end,"BAD_INDENT","All sequence items must start at the same column"):i(a,"MISSING_CHAR","Sequence item without - indicator")}const d=l?e(n,l,u,i):t(n,u.end,s,null,u,i);n.schema.compat&&ih(r.indent,l,i),a=d.range[2],o.items.push(d)}return o.range=[r.offset,a,c??a],o}(e,t,n,r,s):function({composeNode:e,composeEmptyNode:t},n,r,i,s){const o="{"===r.start.source,a=o?"flow map":"flow sequence",c=new(s?.nodeClass??(o?zp:Hp))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1);let u=r.offset+r.start.source.length;for(let s=0;s<r.items.length;++s){const l=r.items[s],{start:d,key:p,sep:f,value:h}=l,m=nh(d,{flow:a,indicator:"explicit-key-ind",next:p??f?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!m.found){if(!(m.anchor||m.tag||f||h)){0===s&&m.comma?i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):s<r.items.length-1&&i(m.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),m.comment&&(c.comment?c.comment+="\n"+m.comment:c.comment=m.comment),u=m.end;continue}!o&&n.options.strict&&rh(p)&&i(p,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===s)m.comma&&i(m.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m.comma||i(m.start,"MISSING_CHAR",`Missing , between ${a} items`),m.comment){let e="";e:for(const t of d)switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}if(e){let t=c.items[c.items.length-1];qd(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 s=m.end,g=p?e(n,p,m,i):t(n,s,d,null,m,i);lh(p)&&i(g.range,"BLOCK_IN_FLOW",ch);const y=nh(f??[],{flow:a,indicator:"map-value-ind",next:h,offset:g.range[2],onError:i,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){i(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}m.start<y.found.offset-1024&&i(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else h&&("source"in h&&h.source&&":"===h.source[0]?i(h,"MISSING_CHAR",`Missing space after : in ${a}`):i(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const w=h?e(n,h,y,i):y.found?t(n,y.end,f,null,y,i):null;w?lh(h)&&i(w.range,"BLOCK_IN_FLOW",ch):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const v=new Up(g,w);if(n.options.keepSourceTokens&&(v.srcToken=l),o){const e=c;sh(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(v)}else{const e=new zp(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,i):t(n,m.end,f,null,m,i);c.items.push(r),u=r.range[2],lh(h)&&i(r.range,"BLOCK_IN_FLOW",ch)}}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);i(u,l?"MISSING_CHAR":"BAD_INDENT",l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`),p&&1!==p.source.length&&f.unshift(p)}if(f.length>0){const e=ah(f,h,n.options.strict,i);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,s),a=o.constructor;return"!"===i||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function dh(e,t,n){const r=t.offset,i=function({offset:e,props:t},n,r){if("block-scalar-header"!==t[0].type)return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=t[0],s=i[0];let o=0,a="",c=-1;for(let t=1;t<i.length;++t){const n=i[t];if(a||"-"!==n&&"+"!==n){const r=Number(n);!o&&r?o=r:-1===c&&(c=e+t)}else a=n}-1!==c&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":l=!0;case"newline":d+=i.source.length;break;case"comment":if(n&&!l){r(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=i.source.length,u=i.source.substring(1);break;case"error":r(i,"UNEXPECTED_TOKEN",i.message),d+=i.source.length;break;default:{r(i,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${i.type}`);const e=i.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:s,indent:o,chomp:a,comment:u,length:d}}(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};const s=">"===i.mode?hp.BLOCK_FOLDED:hp.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}(t.source):[];let a=o.length;for(let e=o.length-1;e>=0;--e){const t=o[e][1];if(""!==t&&"\r"!==t)break;a=e}if(0===a){const e="+"===i.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:s,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<a;++t){const[r,s]=o[t];if(""!==s&&"\r"!==s){if(r.length<c){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+r.length,"MISSING_CHAR",e)}if(0===i.indent&&(c=r.length),u=t,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===i.indent&&r.length>c&&(c=r.length),l+=r.length+s.length+1}for(let e=o.length-1;e>=a;--e)o[e][0].length>c&&(a=e+1);let d="",p="",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 ${i.indent?"explicit indentation indicator":"first line"}`;n(l-r.length-(a?2:1),"BAD_INDENT",e),t=""}s===hp.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(i.chomp){case"-":break;case"+":for(let e=a;e<o.length;++e)d+="\n"+o[e][0].slice(c);"\n"!==d[d.length-1]&&(d+="\n");break;default:d+="\n"}const h=r+i.length+t.source.length;return{value:d,type:s,comment:i.comment,range:[r,h,h]}}function ph(e,t,n){const{offset:r,type:i,source:s,end:o}=e;let a,c;const l=(e,t,i)=>n(r+e,t,i);switch(i){case"scalar":a=hp.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 fh(e)}(s,l);break;case"single-quoted-scalar":a=hp.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return fh(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=hp.QUOTE_DOUBLE,c=function(e,t){let n="";for(let r=1;r<e.length-1;++r){const i=e[r];if("\r"!==i||"\n"!==e[r+1])if("\n"===i){const{fold:t,offset:i}=hh(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=mh[i];if(s)n+=s;else if("\n"===i)for(i=e[r+1];" "===i||"\t"===i;)i=e[1+ ++r];else if("\r"===i&&"\n"===e[r+1])for(i=e[1+ ++r];" "===i||"\t"===i;)i=e[1+ ++r];else if("x"===i||"u"===i||"U"===i){const s={x:2,u:4,U:8}[i];n+=gh(e,r+1,s,t),r+=s}else{const i=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),n+=i}}else if(" "===i||"\t"===i){const t=r;let s=e[r+1];for(;" "===s||"\t"===s;)s=e[1+ ++r];"\n"===s||"\r"===s&&"\n"===e[r+2]||(n+=r>t?e.slice(t,r+1):i)}else n+=i}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}const u=r+s.length,d=ah(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function fh(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch(e){t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],s=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)""===r[1]?"\n"===s?i+=s:s="\n":(i+=s+r[1],s=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,r=a.exec(e),i+s+(r?.[1]??"")}function hh(e,t){let n="",r=e[t+1];for(;!(" "!==r&&"\t"!==r&&"\n"!==r&&"\r"!==r||"\r"===r&&"\n"!==e[t+2]);)"\n"===r&&(n+="\n"),r=e[(t+=1)+1];return n||(n=" "),{fold:n,offset:t}}const mh={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function gh(e,t,n,r){const i=e.substr(t,n),s=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(s)){const i=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}return String.fromCodePoint(s)}function yh(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?dh(e,t,r):ph(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,"TAG_RESOLVE_FAILED",e)):null,l=n&&c?function(e,t,n,r,i){if("!"===n)return e[Od];const s=[];for(const t of e.tags)if(!t.collection&&t.tag===n){if(!t.default||!t.test)return t;s.push(t)}for(const e of s)if(e.test?.test(t))return e;const o=e.knownTags[n];if(o&&!o.collection)return e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o;return i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[Od]}(e.schema,i,c,n,r):"scalar"===t.type?function({directives:e,schema:t},n,r,i){const s=t.tags.find(e=>e.default&&e.test?.test(n))||t[Od];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[Od];if(s.tag!==o.tag){i(r,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${e.tagString(s.tag)} or ${e.tagString(o.tag)}`,!0)}}return s}(e,i,t,r):e.schema[Od];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Ud(s)?s:new hp(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new hp(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function wh(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 vh={composeNode:bh,composeEmptyNode:Ih};function bh(e,t,n,r){const{spaceBefore:i,comment:s,anchor:o,tag:a}=n;let c,l=!0;switch(t.type){case"alias":c=function({options:e},{offset:t,source:n,end:r},i){const s=new dp(n.substring(1));""===s.source&&i(t,"BAD_ALIAS","Alias cannot be an empty string");s.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=ah(r,o,e.strict,i);s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment);return s}(e,t,r),(o||a)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=yh(e,t,a,r),o&&(c.anchor=o.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":c=function(e,t,n,r,i){const s=r?t.directives.tagName(r.source,e=>i(r,"TAG_RESOLVE_FAILED",e)):null,o="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!s||"!"===s||s===zp.tagName&&"map"===o||s===Hp.tagName&&"seq"===o||!o)return uh(e,t,n,i,s);let a=t.schema.tags.find(e=>e.tag===s&&e.collection===o);if(!a){const c=t.schema.knownTags[s];if(!c||c.collection!==o)return c?.collection?i(r,"BAD_COLLECTION_TYPE",`${c.tag} used for ${o} collection, but expects ${c.collection}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),uh(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=uh(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Kd(l)?l:new hp(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(vh,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=Ih(e,t.offset,void 0,null,n,r),l=!1}return o&&""===c.anchor&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),i&&(c.spaceBefore=!0),s&&("scalar"===t.type&&""===t.source?c.comment=s:c.commentBefore=s),e.options.keepSourceTokens&&l&&(c.srcToken=t),c}function Ih(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=yh(e,{type:"scalar",offset:wh(t,n,r),indent:-1,source:""},a,l);return o&&(u.anchor=o.source.substring(1),""===u.anchor&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function kh(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 Eh(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){const s=e[i];switch(s[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(s.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[i+1]?.[0]&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}class Sh{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=kh(e);r?this.warnings.push(new eh(i,t,n)):this.errors.push(new Xf(i,t,n))},this.directives=new ip({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Eh(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Wd(i)&&!i.flow&&i.items.length>0){let e=i.items[0];qd(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Eh(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=kh(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=function(e,t,{offset:n,start:r,value:i,end:s},o){const a=Object.assign({_directives:t},e),c=new Hf(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=nh(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!i||"block-map"!==i.type&&"block-seq"!==i.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?bh(l,i,u,o):Ih(l,u.end,r,null,u,o);const d=c.contents.range[2],p=ah(s,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[n,d,p.offset],c}(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Xf(kh(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 Xf(kh(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=ah(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 Xf(kh(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 Hf(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 Ah(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 xh(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{const r=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{const r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{const r="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}function Ch(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=Ch(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=Th(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=Th(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=Th(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 Th({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=Ch(t)),n)for(const e of n)i+=e.source;return r&&(i+=Ch(r)),i}const _h=Symbol("break visit"),Ph=Symbol("skip children"),Nh=Symbol("remove item");function $h(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),Mh(Object.freeze([]),e,t)}function Mh(e,t,n){let r=n(t,e);if("symbol"==typeof r)return r;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let t=0;t<s.items.length;++t){const r=Mh(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===_h)return _h;r===Nh&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}$h.BREAK=_h,$h.SKIP=Ph,$h.REMOVE=Nh,$h.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},$h.parentCollection=(e,t)=>{const n=$h.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};const Rh="\ufeff",Oh="",Lh="",jh="";function Dh(e){switch(e){case Rh:return"byte-order-mark";case Oh:return"doc-mode";case Lh:return"flow-error-end";case jh: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 Fh=Object.freeze({__proto__:null,BOM:Rh,DOCUMENT:Oh,FLOW_END:Lh,SCALAR:jh,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=Rp({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:"\n"}];switch(a[0]){case"|":case">":{const e=a.indexOf("\n"),t=a.substring(0,e),n=a.substring(e+1)+"\n",i=[{type:"block-scalar-header",offset:s,indent:r,source:t}];return Ah(i,c)||i.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:s,indent:r,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:c};default:return{type:"scalar",offset:s,indent:r,source:a,end:c}}},isCollection:e=>!!e&&"items"in e,isScalar:e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),prettyToken:function(e){switch(e){case Rh:return"<BOM>";case Oh:return"<DOC>";case Lh:return"<FLOW_END>";case jh:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const r=(e,t,r)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new Xf([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ph(e,t,r);case"block-scalar":return dh({options:{strict:t}},e,r)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(r&&"number"==typeof a&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");o=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=Rp({type:o,value:t},{implicitKey:i||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),i=t.substring(n+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=r,e.source=i}else{const{offset:t}=e,n="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:t,indent:n,source:r}];Ah(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:s,source:i})}}(e,c);break;case'"':xh(e,c,"double-quoted-scalar");break;case"'":xh(e,c,"single-quoted-scalar");break;default:xh(e,c,"scalar")}},stringify:e=>"type"in e?Ch(e):Th(e),tokenType:Dh,visit:$h});function Bh(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const qh=new Set("0123456789ABCDEFabcdef"),Uh=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Vh=new Set(",[]{}"),Wh=new Set(" ,[]{}\n\r\t"),Kh=e=>!e||Wh.has(e);class Gh{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)&&Bh(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]===Rh&&(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 Oh,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&&Bh(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&Bh(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Bh(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)&&Bh(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(Kh),"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("..."))&&Bh(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield Lh,yield*this.parseLineStart()}let i=0;for(;","===r[i];)i+=(yield*this.pushCount(1)),i+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(i+=(yield*this.pushIndicators()),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Kh),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Bh(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=>Bh(e)||"#"===e)}*parseBlockScalar(){let e,t=this.pos-1,n=0;e:for(let r=this.pos;e=this.buffer[r];++r)switch(e){case" ":n+=1;break;case"\n":t=r,n=0;break;case"\r":{const e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if("\n"===e)break}default:break e}if(!e&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(t+1);if(-1===e)break;t=this.buffer.indexOf("\n",e)}while(-1!==t);if(-1===t){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(e=this.buffer[r];" "===e;)e=this.buffer[++r];if("\t"===e){for(;"\t"===e||" "===e||"\r"===e||"\n"===e;)e=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)for(;;){let e=t-1,r=this.buffer[e];"\r"===r&&(r=this.buffer[--e]);const i=e;for(;" "===r;)r=this.buffer[--e];if(!("\n"===r&&e>=this.pos&&e+1+n>i))break;t=e}return yield jh,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(Bh(t)||e&&Vh.has(t))break;n=r}else if(Bh(t)){let i=this.buffer[r+1];if("\r"===t&&("\n"===i?(r+=1,t="\n",i=this.buffer[r+1]):n=r),"#"===i||e&&Vh.has(i))break;if("\n"===t){const e=this.continueScalar(r+1);if(-1===e)break;r=Math.max(r,e-2)}}else{if(e&&Vh.has(t))break;n=r}return t||this.atEnd?(yield jh,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(Kh))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Bh(t)||e&&Vh.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(;!Bh(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(Uh.has(t))t=this.buffer[++e];else{if("%"!==t||!qh.has(this.buffer[e+1])||!qh.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 Yh{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 zh(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Jh(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 Hh(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 Qh(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 Zh(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 Xh(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||zh(t.start,"explicit-key-ind")||zh(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Hh(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 em{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 Gh,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=Dh(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&&Xh(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===Jh(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!==Jh(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=Zh(Qh(this.peek(2)));let n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let i=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const i=t.sep[r];switch(i.type){case"newline":n.push(r);break;case"space":break;case"comment":i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(zh(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Hh(t.key)&&!zh(t.sep,"newline")){const e=Zh(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(zh(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Zh(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):zh(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0))}default:{const t=this.startBlockValue(e);if(t)return n&&"block-seq"!==t.type&&e.items.push({start:i}),void this.stack.push(t)}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||zh(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=Zh(Qh(t));Xh(e);const r=e.end.splice(1,e.end.length);r.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=Zh(Qh(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=Zh(Qh(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 tm(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new Yh||null,prettyErrors:t}}function nm(e,t={}){const{lineCounter:n,prettyErrors:r}=tm(t),i=new em(n?.addNewLine),s=new Sh(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(th(e,n)),t.warnings.forEach(th(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function rm(e,t={}){const{lineCounter:n,prettyErrors:r}=tm(t),i=new em(n?.addNewLine),s=new Sh(t);let o=null;for(const t of s.compose(i.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new Xf(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(th(e,n)),o.warnings.forEach(th(e,n))),o}function im(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=rm(e,n);if(!i)return null;if(i.warnings.forEach(e=>jp(i.options.logLevel,e)),i.errors.length>0){if("silent"!==i.options.logLevel)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function sm(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 Hf(e,r,n).toString(n)}var om=Object.freeze({__proto__:null,Alias:dp,CST:Fh,Composer:Sh,Document:Hf,Lexer:Gh,LineCounter:Yh,Pair:Up,Parser:em,Scalar:hp,Schema:Jf,YAMLError:Zf,YAMLMap:zp,YAMLParseError:Xf,YAMLSeq:Hp,YAMLWarning:eh,isAlias:Dd,isCollection:Wd,isDocument:Fd,isMap:Bd,isNode:Kd,isPair:qd,isScalar:Ud,isSeq:Vd,parse:im,parseAllDocuments:nm,parseDocument:rm,stringify:sm,visit:Jd,visitAsync:Qd}),am=Object.freeze({__proto__:null,Alias:dp,CST:Fh,Composer:Sh,Document:Hf,Lexer:Gh,LineCounter:Yh,Pair:Up,Parser:em,Scalar:hp,Schema:Jf,YAMLError:Zf,YAMLMap:zp,YAMLParseError:Xf,YAMLSeq:Hp,YAMLWarning:eh,default:om,isAlias:Dd,isCollection:Wd,isDocument:Fd,isMap:Bd,isNode:Kd,isPair:qd,isScalar:Ud,isSeq:Vd,parse:im,parseAllDocuments:nm,parseDocument:rm,stringify:sm,visit:Jd,visitAsync:Qd});class cm{#Ge;constructor(e){this.#Ge=e}execute(){return new Promise((e,t)=>{const n=`${this.#Ge}.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=om.parse(t);if(n.moduleURL=this.#Ge,n.hasCapabilities){const e=`${this.#Ge}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=om.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.#Ge}.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 om.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class lm{#Ke;constructor(e){this.#Ke=e}async execute(){return await this.#Ke.execute()}}class um{#n;#Ye;constructor(){this.#n=new Map,this.#Ye=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#Ye.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#Ye.has(t)||console.warn(`Unknown event type: ${t}`)}}class dm{}class pm extends dm{#ze;constructor(e){super(),this.#ze=e}execute(){}}let fm=class extends lm{#Je;constructor(e){super(e),this.#Je=new um,this.#Je.register("onExtension",pm),this.#Je.markKnown("onCommand"),this.#Je.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Je.handleEvent(e)),e}},hm=class extends lm{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t,activationEvents:n}=e,r=e.capabilities,i=[];if(r&&"object"==typeof r)for(const[e,t]of Object.entries(r)){if(!e)continue;const n="string"==typeof t?.title?t.title:e,r="string"==typeof t?.description?t.description:void 0;i.push({id:e,title:n,description:r})}return i.length&&i.forEach(({id:t,title:i,description:s})=>{if(!t)return;const o=punica.kernel.Commands.manager,a=punica.extensions.manager,c=punica.kernel.Events.manager;if(n?.some(e=>e===`onCommand:${t}`||"onCommand"===e)??!1)return;const l=r?.[t],u=l?.outputs?.resultEvent,d=l?.outputs?.errorEvent;o.registerCommand(t,{title:i??t,description:s,execute:(...n)=>{const r=n.length?n[n.length-1]:void 0,i=r?.__punica?.correlationId;a.activate(e.name,{reason:"command",trigger:t}).then(()=>{u&&c.publishEvent({name:u,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"result"},payload:{ok:!0,dispatched:!0,capabilityId:t,activatedExtension:e.name}})}).catch(n=>{d&&c.publishEvent({name:d,envelope:{id:c.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:`extensions:stub:${e.name}`,kind:"error"},payload:{ok:!1,capabilityId:t,activatedExtension:e.name,error:String(n?.message??n)}})})}})}),e}};function mm(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}function gm(e,t=mm()){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 ym=class extends lm{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(t){const{keybindings:e}=t,n=globalThis.punica?.shell?.KeyboardShortcuts?.manager;e&&n&&e.forEach(e=>{if(!e.capability)return void console.warn(`[Keybindings] Missing capability for keybinding: ${e.key}`);const t=e.capability,r=e.key,i=e.when;n.registerShortcut({command:t,keys:[gm(r)],when:i})})}return e}},wm=class extends lm{constructor(e){super(e)}async execute(){return await super.execute()}};class vm extends lm{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=Ad.fileOpeners;e.forEach((e,t)=>{if(!e.capability)return void console.warn(`[FileOpeners] Missing capability for file opener: ${e.id??t}`);const i=e.capability,s=e.id??`${n}:${i||"opener"}:${t.toString(10)}`;r.register({id:s,label:e.label,command:i,priority:e.priority,matches:e.matches})})}return e}}const bm={"shell.activityBar":["activityBar","primarySidebar","contentSidebar"],"shell.statusbar":["statusbar"]},Im=["content"];function km(e,t){if(e&&"object"==typeof e)if("slot"!==e.type){if(Array.isArray(e.children))for(const n of e.children)km(n,t)}else"string"==typeof e.id&&e.id.length>0&&t.add(e.id)}function Em(e){const t=new Set,n=e?.shell?.layout?.root;if(n)km(n,t);else for(const e of Im)t.add(e);for(const n of e?.shell?.activeModules??[])for(const e of bm[n]??[])t.add(e);return t}function Sm(e){try{const t=globalThis.punica?.shell?.Profile?.manager?.registry,n=t?.getActive?.();if(!n)return;return Em(n).has(e)}catch{return}}function Am(e){if(!function(){const e=globalThis,t=e.punica?.shell;return!!t&&Object.keys(t).length>0}())return;const{integrations:t}=e;if(!t)return;const{views:n}=t;if(!n)return;const{activityBar:r,statusBar:i,primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c}=n;if(r&&!1!==Sm("activityBar")){const e={...r};e.capability&&(e.command=e.capability),s&&!e.viewId&&(e.viewId=s.id),punica.shell.ActivityBar.manager.addItem(e)}if(i){const e={...i};e.capability&&(e.command=e.capability),punica.shell.Statusbar.manager.addItem(e)}!function(e,t){const n=punica.shell?.Views?.manager;if(!n?.registerPlacement)return;const{primarySidebar:r,secondarySidebar:i,contentSidebar:s,panel:o,activityBar:a}=t;if(r?.id){const t=Tm(r.id),i=t??Cm("primarySidebar");n.registerPlacement({viewId:r.id,slot:i,homeSlot:"primarySidebar",allowedSlots:t?["primarySidebar",t]:[i],extensionName:e.name,title:r.title??r.name,icon:r.icon,onDemand:"content"===i,fallbackCommand:r.capability??a?.capability??a?.command})}if(s?.id){const t=Tm(s.id),r=t??Cm("contentSidebar");n.registerPlacement({viewId:s.id,slot:r,homeSlot:"contentSidebar",allowedSlots:t?["contentSidebar",t]:[r],extensionName:e.name,title:s.title??s.name,icon:s.icon,onDemand:"content"===r,fallbackCommand:s.capability})}if(o?.id){const t=Array.isArray(o.toolbar)?o.toolbar:void 0;xm(e,o,"panel",{order:o.order,panelToolbar:t})}i?.id&&xm(e,i,"secondarySidebar",{})}(e,{primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r})}function xm(e,t,n,r){const i=punica.shell?.Views?.manager;if(!i?.registerPlacement)return;const s=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=Tm(t.id);l&&!c.includes(l)&&c.push(l);const u=s?.getSlotOverride?.(t.id),d=u&&c.includes(u)?u:l??n,p=Cm(d),f=p!==d,h=!1===t.showOnStartup||f;if(i.registerPlacement({viewId:t.id,slot:p,homeSlot:n,allowedSlots:f?["content"]:c,extensionName:e.name,title:t.title??t.name,icon:t.icon,order:r.order,fallbackCommand:t.capability,onDemand:h,panelToolbar:r.panelToolbar}),!h){const e=o?.forSlot?.(p)??("panel"===p?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})}}function Cm(e){return"content"===e?e:!1===Sm(e)?"content":e}function Tm(e){try{const t=punica.shell?.Profile?.manager?.registry,n=t?.getActive?.(),r=n?.shell?.viewDefaults?.slotOverrides,i=r?.[e];return"string"==typeof i&&i.length>0?i:void 0}catch{return}}let _m=0;function Pm(){_m++}function Nm(){_m>0&&_m--}function $m(){return _m>0}async function Mm(e){Pm();try{return await e()}finally{Nm()}}const Rm=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#He(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#He(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}#He(e){const t=e.integrations?.configuration?{title:e.integrations.configuration.title,properties:Object.freeze(Object.fromEntries(Object.entries(e.integrations.configuration.properties??{}).map(([e,t])=>{const n=t,r={type:n.type,default:n.default,description:n.description};let i;return"string"===n.type&&"enum"in n&&Array.isArray(n.enum)&&(i=Object.freeze([...n.enum])),[e,Object.freeze({...r,enum:i})]})))}:void 0;return Object.freeze({name:e.name,displayName:e.displayName,description:e.description,version:e.version,configuration:t?Object.freeze(t):void 0,capabilities:this.getExtensionCapabilities(e.name)})}};const Om=new class{#Qe=".punica/settings.json";#Ze;#Xe=null;#et=null;#tt=new Map;#nt=null;#he=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Ze=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Ze="localStorage:punica.settings":this.#Ze="settings.json"}async load(){this.#he||(await this.#rt(),await this.#it(),this.#he=!0)}async#rt(){try{if(this.#Ze.startsWith("localStorage:")){const e=this.#Ze.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#et=await this.#st(e)}else this.#et={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Ze),t=JSON.parse(e);this.#et=await this.#st(t)}catch{this.#et={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#et={version:"1.0",extensions:{},system:{}}}}async#it(){try{const e=await punica.runtime.fs.readFile(this.#Qe),t=JSON.parse(e);this.#Xe=await this.#st(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Xe=null}}async save(e="project"){this.#nt&&clearTimeout(this.#nt),this.#nt=window.setTimeout(async()=>{"global"===e?await this.#ot():await this.#at(),this.#nt=null},500)}async#ot(){if(this.#et)if(this.#Ze.startsWith("localStorage:")){const e=this.#Ze.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#et,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Ze,JSON.stringify(this.#et,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#at(){this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Qe,JSON.stringify(this.#Xe,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#he)return void this.load();if("system"===e){const e=this.#Xe?.system?.[t];if(void 0!==e)return e;const n=this.#et?.system?.[t];return void 0!==n?n:void 0}const n=this.#Xe?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#et?.extensions?.[e]?.[t];if(void 0!==r)return r;const i=punica.extensions.metadata.manager.getExtension(e);return i?.configuration?.properties?.[t]?.default}async set(e,t,n,r="project"){if(this.#he||await this.load(),"system"===e){const i=this.get(e,t);return"global"===r?(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.system||(this.#et.system={}),this.#et.system[t]=n,await this.save("global")):(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.system||(this.#Xe.system={}),this.#Xe.system[t]=n,await this.save("project")),void this.#ct(e,t,n,i)}const i=this.validate(e,t,n);if(!i.ok)throw new Error(`Invalid setting value: ${i.errors?.join(", ")}`);const s=this.get(e,t);"global"===r?(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.extensions[e]||(this.#et.extensions[e]={}),this.#et.extensions[e][t]=n,await this.save("global")):(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.extensions[e]||(this.#Xe.extensions[e]={}),this.#Xe.extensions[e][t]=n,await this.save("project")),this.#ct(e,t,n,s)}getAll(e){if(!this.#he)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#et?.extensions?.[e]??{},i=this.#Xe?.extensions?.[e]??{},s={};for(const[e,t]of Object.entries(n)){const n=t;s[e]=n.default}return{...s,...r,...i}}validate(e,t,n){const r=punica.extensions.metadata.manager.getExtension(e),i=r?.configuration?.properties?.[t];if(!i)return{ok:!1,errors:[`Setting "${t}" not found in extension "${e}"`]};const s=[];switch(i.type){case"boolean":"boolean"!=typeof n&&s.push(`Setting "${t}" must be a boolean`);break;case"string":"string"!=typeof n?s.push(`Setting "${t}" must be a string`):i.enum&&!i.enum.includes(n)&&s.push(`Setting "${t}" must be one of: ${i.enum.join(", ")}`);break;case"number":("number"!=typeof n||isNaN(n))&&s.push(`Setting "${t}" must be a number`)}return{ok:0===s.length,errors:s.length>0?s:void 0}}getTyped(e,t,n){const r=this.get(e,t);if(void 0!==r&&typeof r===n)return r}async reset(e,t){if("system"===e){const n=this.get(e,t),r=void 0!==this.#Xe?.system?.[t],i=void 0!==this.#et?.system?.[t];if(!r&&!i)return;return r&&delete this.#Xe.system[t],i&&delete this.#et.system[t],r&&await this.#at(),i&&await this.#ot(),void this.#ct(e,t,void 0,n)}const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Xe?.extensions?.[e]&&(delete this.#Xe.extensions[e][t],await this.save("project")),this.#et?.extensions?.[e]&&(delete this.#et.extensions[e][t],await this.save("global"))):await this.set(e,t,r,"project")}async resetExtension(e){const t=punica.extensions.metadata.manager.getExtension(e);if(t?.configuration?.properties)for(const n of Object.keys(t.configuration.properties))await this.reset(e,n)}getScope(e,t){return this.#he?"system"===e?void 0!==this.#Xe?.system?.[t]?"project":void 0!==this.#et?.system?.[t]?"global":"default":void 0!==this.#Xe?.extensions?.[e]?.[t]?"project":void 0!==this.#et?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#tt.has(e)||this.#tt.set(e,new Set),this.#tt.get(e).add(t),()=>{this.#tt.get(e)?.delete(t)}}async export(e){this.#he||await this.load();const t=e?.scope??"merged",n={version:this.#et?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Xe?.system:"global"===t?this.#et?.system:{...this.#et?.system,...this.#Xe?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#et?.extensions??{}),...Object.keys(this.#Xe?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Xe?.extensions?.[e]??{}:"global"===t?this.#et?.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.#Xe:this.#et)||("project"===r?this.#Xe={version:"1.0",extensions:{},system:{}}:this.#et={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Xe:this.#et;for(const[r,i]of Object.entries(n.extensions??{}))t.extensions&&!t.extensions.includes(r)||(e.extensions[r]={...e.extensions[r],...i});n.system&&(e.system={...e.system,...n.system})}else{if(t?.extensions)for(const e of t.extensions)n.extensions[e]&&("project"===r?(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.extensions[e]=n.extensions[e]):(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.extensions[e]=n.extensions[e]));else"project"===r?this.#Xe={...this.#Xe,...n,version:this.#Xe?.version??"1.0"}:this.#et={...this.#et,...n,version:this.#et?.version??"1.0"};n.system&&("project"===r?(this.#Xe||(this.#Xe={version:"1.0",extensions:{},system:{}}),this.#Xe.system=n.system):(this.#et||(this.#et={version:"1.0",extensions:{},system:{}}),this.#et.system=n.system))}await this.save(r)}async#st(e){return e.version,e}#ct(e,t,n,r){const i=this.#tt.get(e);i&&i.forEach(e=>e(t,n,r)),punica.kernel.Events.manager&&punica.kernel.Events.manager.publishEvent({name:"settings.changed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),timestampMs:Date.now(),source:"extension-settings",kind:"info"},payload:{extensionName:e,key:t,newValue:n,oldValue:r}})}},Lm="system",jm="ui.language",Dm="en";const Fm=new class{#lt=new Map;#tt=new Set;#ut=null;#dt=new Set;#pt=new Map;getLocale(){return this.#ut??=this.#ft(),this.#ut}supportedLocales(){const e=this.#ht()?.supported;return Array.isArray(e)&&e.length?e:[Dm]}async setLocale(e){const t=String(e||"").trim();if(t&&t!==this.getLocale()){try{await punica.extensions.settings.manager.set(Lm,jm,t,"global")}catch(e){throw e instanceof Error?e:new Error(String(e))}this.#ut=t,this.#mt(t)}}onDidChange(e){return this.#tt.add(e),()=>{this.#tt.delete(e)}}#mt(e){for(const t of[...this.#tt])try{t(e)}catch{}}#ht(){try{return punica.shell?.Profile?.manager?.registry?.getActive?.()?.localization}catch{return}}#ft(){const e=this.supportedLocales();try{const t=punica.extensions?.settings?.manager?.get?.(Lm,jm);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.#ht()?.default;return t&&e.includes(t)?t:e.includes(Dm)?Dm:e[0]}refresh(){const e=this.#ft();e!==this.#ut&&(this.#ut=e,this.#mt(e))}register(e,t){e&&t&&this.#lt.set(e,t)}t(e,t,n){const r=this.#gt(e,t,n?.count);return void 0===r?(this.#yt(`${e}:${t}`,e,t),t):n?r.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):r}#gt(e,t,n){const r=this.#lt.get(e);if(!r)return;const i=[],s=e=>{e&&!i.includes(e)&&i.push(e)};s(this.getLocale()),s(this.#ht()?.default),s(Dm);const o=[];"number"==typeof n&&Number.isFinite(n)&&o.push(`${t}.${this.#wt(this.getLocale(),n)}`,`${t}.other`),o.push(t);for(const e of i){const t=r[e];if(t)for(const e of o){const n=t[e];if("string"==typeof n)return n}}}#wt(e,t){let n=this.#pt.get(e);if(!n){try{n=new Intl.PluralRules(e)}catch{n=new Intl.PluralRules(Dm)}this.#pt.set(e,n)}return n.select(t)}#yt(e,t,n){this.#dt.has(e)||(this.#dt.add(e),console.warn(`[i18n] missing message "${n}" for ${t} (${this.getLocale()})`))}resetForTesting(){this.#lt.clear(),this.#tt.clear(),this.#ut=null,this.#dt.clear(),this.#pt.clear()}};const Bm=new Set;function qm(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 Um=new Map;function Vm(){return"undefined"!=typeof document&&!!document}function Wm(e){if(!Vm())return void Um.delete(e);const t=Um.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),Um.delete(e)}const Km={register(e,t,n){if(!Vm())return{id:e,dispose(){}};const r=n?.target??document.head,i=Um.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),Um.set(e,i),{id:e,dispose(){Wm(e)}};const s=document.createElement("style");if(s.id=e,n?.attrs)for(const[e,t]of Object.entries(n.attrs))s.setAttribute(e,t);return s.textContent=t,r.appendChild(s),Um.set(e,s),{id:e,dispose(){Wm(e)}}},unregister(e){Wm(e)},has:e=>!!Um.has(e)||!!Vm()&&!!document.getElementById(e)};const Gm={manager:new class{#vt;#bt;#It;#kt;#Et;#St;#At;#xt;#Ct;constructor(){this.#vt=new Map,this.#bt=new Map,this.#It=new Map,this.#kt=new Map,this.#Et=new Set,this.#St=new Set,this.#At=new Map,this.#xt=new Map,this.#Ct=new Map}getRuntimeState(e){return this.#bt.get(e)}registerBuiltinCapabilities(e){const t=Array.isArray(e)?e:[];for(const e of t){const t=String(e?.id??""),n=String(e?.extensionName??""),r=e?.definition??{};if(!t)throw new Error("[Extensions] registerBuiltinCapabilities: Missing id");if(!n)throw new Error(`[Extensions] registerBuiltinCapabilities: Missing extensionName (id="${t}")`);const i=this.#xt.get(t);if(i&&i.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${i.extensionName}" and "${n}".`);this.#xt.set(t,{id:t,extensionName:n,definition:r})}}#Tt(e){const t=e,n=t?.capabilities;if(n&&"object"==typeof n){for(const[t,r]of Object.entries(n)){if(!t)continue;const n=r??{};n.id||(n.id=t);const i={id:t,extensionName:e.name,definition:n},s=this.#xt.get(t);s&&s.extensionName!==e.name&&console.warn(`[Extensions] Capability id collision "${t}" between "${s.extensionName}" and "${e.name}". Keeping the last loaded.`),this.#xt.set(t,i)}this.#_t(e,n)}}#_t(e,t){const n=lu.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`)}#Pt(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 cm(e),n=new hm(t),r=new ym(n),i=new wm(r),s=new vm(i);return new fm(s)})(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.#vt.set(r.name,r),this.#bt.set(r.name,"loaded"),this.#Tt(r),this.#Pt(r);try{Am(r)}catch(e){console.error(`[Extensions] view registration failed for ${r.name}:`,e)}const i=r.activationEvents??[];(i.includes("onStartup")||i.includes("onStartup:begin"))&&this.#Et.add(r.name),i.includes("onStartup:finish")&&this.#St.add(r.name),i.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#At.get(t);n||(n=new Set,this.#At.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#bt.get(e))return;const n=this.#It.get(e);if(n)return n;if(!this.#vt.get(e))return void console.error(`Extension "${e}" not found.`);const r=function(e){const t=e?.reason??"host",n=e?.presentation??("capability"===t||"extension"===t?"headless":"interactive");return{reason:t,trigger:e?.trigger,presentation:n}}(t),i=this.#Nt(e,r);this.#It.set(e,i);try{await i}finally{this.#It.delete(e)}}async#Nt(e,t){this.#bt.set(e,"activating"),qm("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new xd(e),n=new _d(t),r=new Pd(n);return new Td(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.#$t(e,t),i="startup:begin"===t.reason||"startup:finish"===t.reason;i&&Bm.add(e);try{"headless"===t.presentation?await Mm(()=>r.module.activate(n)):await r.module.activate(n)}finally{i&&Bm.delete(e)}const s=this.#kt.get(e);s&&(s.module=r.module),this.#bt.set(e,"active"),qm("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#bt.set(e,"failed"),qm("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}}#$t(e,t){const n=[];this.#kt.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.#Ct.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const i=globalThis.punica?.shell?.Views?.manager;if(!i?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const s=i.registerProvider(t,r,e);return n.push(s),s},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway,s=r.punica?.shell?.Views?.manager?.getPlacement?.(e);if(function(e,t){return t&&function(e){return!!e&&"content"===e.slot&&"string"==typeof e.homeSlot&&"content"!==e.homeSlot}(e)}(s,Bm.has(t)))return void Wt({name:"shell.view.revealBlocked",source:"extensions:activation",payload:{viewId:e,extensionName:t,reason:"no-home-slot-at-startup",homeSlot:s?.homeSlot}});if(i?.call){const s=r.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await i.call("shell.revealView",{viewId:e,focus:n?.focus??!1},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:o},policy:{mode:"execute"}})}const o=r.punica?.shell?.Views?.manager;if(!o?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await o.reveal(e,{kind:"extension",id:t})}(t,e,n)},hide:async t=>{await async function(e,t){const n=globalThis,r=n.punica?.runtime?.capabilities?.gateway;if(r?.call){const i=n.punica?.kernel?.Events?.manager,s=i?.createCorrelationId?.()??`ext-hide-${Date.now()}`;return void await r.call("shell.hideView",{viewId:e},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:s},policy:{mode:"execute"}})}const i=n.punica?.shell?.Views?.manager;if(!i?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);i.hide(e,{kind:"extension",id:t})}(t,e)},setViewStatus:(t,n)=>{const r=globalThis.punica?.shell?.Views?.manager;r?.setViewStatus?r.setViewStatus(t,n,e):console.warn(`[Extensions] shell.Views unavailable — view status for "${t}" not published (${e}).`)}}};return r}async startupBegin(){await this.#Mt(this.#Et,"startup:begin")}async startupFinish(){await this.#Mt(this.#St,"startup:finish")}async#Mt(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.#vt.get(e)}getAllExtensions(){return Array.from(this.#vt.values())}getCapability(e){return this.#xt.get(e)?.definition}listCapabilities(){return Array.from(this.#xt.values())}validateCapabilityInput(e,t){const n=this.getCapability(e);if(!n)return{ok:!0};const r=n.inputs?.schema;if(!r)return{ok:!0};const i=Ao().validate(r,t);return i.ok?{ok:!0}:{ok:!1,errors:i.errors}}registerCapabilityHandler(e,t){this.#Ct.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#xt.get(e);if(!r)throw new Vs(Us.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#bt.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new Vs(Us.EXTENSION_ACTIVATION_FAILED,`Extension "${r.extensionName}" failed to activate for capability "${e}": `+(t instanceof Error?t.message:String(t)),{capability:e,extensionName:r.extensionName})}const i=this.#Ct.get(e);if(!i)throw new Vs(Us.CAPABILITY_HANDLER_MISSING,`Extension "${r.extensionName}" declared capability "${e}" but did not register a handler. Call context.capabilities.registerHandler("${e}", handler) inside activate().`,{capability:e,extensionName:r.extensionName});return await i.fn(t,n)}async deactivate(e){if("active"!==this.#bt.get(e))return;const t=this.#vt.get(e);this.#bt.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.#kt.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#kt.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.#kt.delete(e)}for(const[t,n]of this.#Ct)n.extensionName===e&&this.#Ct.delete(t)}finally{this.#bt.set(e,"loaded"),qm("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#bt.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.#xt)n.extensionName===e&&this.#xt.delete(t);for(const[t,n]of this.#At)n.delete(e)&&0===n.size&&this.#At.delete(t);const n=this.#vt.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.#Et.delete(e),this.#St.delete(e),this.#It.delete(e),this.#kt.delete(e),this.#vt.delete(e),this.#bt.delete(e),qm("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.#bt.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.#At.get(e);return t?Array.from(t):[]}},Styles:Km,metadata:{manager:Rm},settings:{manager:Om},i18n:{manager:Fm}};function Ym(e){return!!e&&"object"==typeof e&&"handle"===e["x-ivy-kind"]}function zm(e,t=""){return function(e){return!!e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.$handle}(e)?[t||"(input)"]:Array.isArray(e)?e.flatMap((e,n)=>zm(e,t?`${t}.${n}`:String(n))):e&&"object"==typeof e?Object.entries(e).flatMap(([e,n])=>zm(n,t?`${t}.${e}`:e)):[]}const Jm='\nif \'__ivy_handles__\' not in globals():\n __ivy_handles__ = {}\ndef __ivy_resolve_handles__(value):\n if isinstance(value, dict):\n if isinstance(value.get("$handle"), str) and set(value.keys()) <= {"$handle", "pythonType"}:\n token = value["$handle"]\n if token not in __ivy_handles__:\n raise ValueError("handle " + token + " is not in this run; it was made by a node in another run or the run has ended")\n return __ivy_handles__[token]\n return {k: __ivy_resolve_handles__(v) for k, v in value.items()}\n if isinstance(value, list):\n return [__ivy_resolve_handles__(v) for v in value]\n return value\n';const Hm=new Map,Qm=new Map;function Zm(e){let t=e;for(let e=0;e<32;e++){const e=Qm.get(t);if(!e)return t;t=e}return t}function Xm(e){!e||Hm.has(e)||Qm.has(e)||Hm.set(e,{session:null,tail:Promise.resolve()})}function eg(e){return!!e&&Hm.has(Zm(e))}async function tg(e,t){const n=Zm(e),r=Hm.get(n);if(!r)throw new Error(`No session scope is open for ${e}`);return r.session||(r.session=t(),r.session.catch(()=>{Hm.get(n)===r&&(r.session=null)})),r.session}async function ng(e){if(!e)return;if(Qm.delete(e))return;const t=Hm.get(e);if(t){Hm.delete(e);for(const[t,n]of Qm)n===e&&Qm.delete(t);if(t.session)try{const e=await t.session;await e.close()}catch{}}}function rg(e,t){const n=[Jm];for(const[r,i]of Object.entries(e)){const e=`${t}/${r}`;n.push(`\n__ivy_src = ${JSON.stringify(i.python)}\ntry:\n __ivy_val = eval(compile(__ivy_src, ${JSON.stringify(`<fixture ${r}>`)}, "eval"), globals())\nexcept SyntaxError:\n __ivy_ns = dict(globals())\n exec(compile(__ivy_src, ${JSON.stringify(`<fixture ${r}>`)}, "exec"), __ivy_ns)\n if "value" not in __ivy_ns:\n raise ValueError(${JSON.stringify(`fixture ${r} is a block, and a block must assign value`)})\n __ivy_val = __ivy_ns["value"]\n__ivy_handles__[${JSON.stringify(e)}] = __ivy_val\n`)}return n.join("\n")}function ig(e){if(void 0===e)return{ok:!0,fixture:{}};if(!e||"object"!=typeof e||Array.isArray(e))return{ok:!1,why:"fixture must be an object keyed by input field"};const t={};for(const[n,r]of Object.entries(e)){const e=r?.python;if("string"!=typeof e||!e.trim())return{ok:!1,why:`fixture ${n} needs a python string`};t[n]={python:e}}return{ok:!0,fixture:t}}async function sg(e,t,n,r){const i=Object.keys(n);if(0===i.length)return t;const s=globalThis.punica?.runtime?.compute;if(!s)throw new Error("A fixture runs Python, and this host has no compute provider.");const o=await tg(e,()=>s.session.open({language:"python"}));let a=null,c="";for await(const t of o.run({id:"test-fixture",language:"python",code:rg(n,e),resources:{timeoutMs:r}},{runId:`${e}:fixture`})){const e=t;"error"===e.type?a=`${e.name?`${e.name}: `:""}${e.message??"fixture failed"}`:"stderr"===e.type&&"string"==typeof e.text&&(c+=e.text)}if(a)throw new Error(`The case's fixture failed before the node ran: ${a}${c.trim()?` (${c.trim()})`:""}`);const l=t&&"object"==typeof t&&!Array.isArray(t)?{...t}:{};for(const t of i)l[t]={$handle:`${e}/${t}`};return l}function og(e){if(null==e)return!1;if(Array.isArray(e))return e.some(og);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(og)}return!1}function ag(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=lg(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=lg(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(t.push(...cg(r.inputs?.schema,"capability.inputs.schema"),...cg(r.outputs?.schema,"capability.outputs.schema")),n.program&&"object"==typeof n.program){if("cells"!==n.program.format&&t.push({path:"program.format",message:'program.format must be "cells"',code:"INVALID_PROGRAM_FORMAT",severity:"error"}),Array.isArray(n.program.cells)){n.program.cells.forEach((e,n)=>{e&&"object"==typeof e?(e.id&&"string"==typeof e.id||t.push({path:`program.cells[${n}].id`,message:"Cell id is required and must be a string",code:"MISSING_CELL_ID",severity:"error"}),e.cell_type&&["code","markdown","raw"].includes(e.cell_type)||t.push({path:`program.cells[${n}].cell_type`,message:'Cell cell_type must be "code", "markdown", or "raw"',code:"INVALID_CELL_TYPE",severity:"error"}),void 0===e.source&&t.push({path:`program.cells[${n}].source`,message:"Cell source is required",code:"MISSING_CELL_SOURCE",severity:"error"})):t.push({path:`program.cells[${n}]`,message:"Cell must be an object",code:"INVALID_CELL_TYPE",severity:"error"})});const e=n.program;if(e?.roles){if(e.roles.inputCellId||t.push({path:"program.roles.inputCellId",message:"program.roles.inputCellId is required",code:"MISSING_INPUT_CELL_ID",severity:"error"}),e.roles.outputCellId||t.push({path:"program.roles.outputCellId",message:"program.roles.outputCellId is required",code:"MISSING_OUTPUT_CELL_ID",severity:"error"}),e.roles.inputCellId){if(e.cells.some(t=>t.id===e.roles.inputCellId)){const n=e.cells.find(t=>t.id===e.roles.inputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["input"]')||r.includes("['input']"));r.includes("__ivy_input__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_input__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["input"].',code:"LEGACY_INPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Input cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["input"] protocol.',code:"INVALID_INPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.inputCellId",message:`Input cell id "${e.roles.inputCellId}" not found in cells`,code:"INVALID_INPUT_CELL_ID",severity:"error"})}if(e.roles.outputCellId){if(e.cells.some(t=>t.id===e.roles.outputCellId)){const n=e.cells.find(t=>t.id===e.roles.outputCellId);if(n&&"code"===n.cell_type){const r=Array.isArray(n.source)?n.source.join(""):String(n.source||""),i=r.includes("__ivy_ctx__")&&r.includes("__ivy_node_id__")&&(r.includes('["output"]')||r.includes("['output']"));r.includes("__ivy_output__")?t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Legacy __ivy_output__ protocol is not supported. Use __ivy_ctx__["nodes"][__ivy_node_id__]["output"].',code:"LEGACY_OUTPUT_PROTOCOL_NOT_SUPPORTED",severity:"error"}):i||t.push({path:`program.cells[${e.cells.indexOf(n)}].source`,message:'Output cell must use __ivy_ctx__["nodes"][__ivy_node_id__]["output"] protocol.',code:"INVALID_OUTPUT_CELL_FORMAT",severity:"error"})}}else t.push({path:"program.roles.outputCellId",message:`Output cell id "${e.roles.outputCellId}" not found in cells`,code:"INVALID_OUTPUT_CELL_ID",severity:"error"})}}else t.push({path:"program.roles",message:"program.roles is required for ivy.node/v0.2 (inputCellId/outputCellId)",code:"MISSING_PROGRAM_ROLES",severity:"error"})}else t.push({path:"program.cells",message:"program.cells is required and must be an array",code:"MISSING_PROGRAM_CELLS",severity:"error"});n.program.language&&"string"==typeof n.program.language||t.push({path:"program.language",message:"program.language is required and must be a string",code:"MISSING_PROGRAM_LANGUAGE",severity:"error"})}else t.push({path:"program",message:"program is required and must be an object",code:"MISSING_PROGRAM",severity:"error"});if(r.policy){const e=["low","medium","high"];r.policy.risk&&e.includes(r.policy.risk)||t.push({path:"capability.policy.risk",message:`capability.policy.risk must be one of: ${e.join(", ")}`,code:"INVALID_POLICY_RISK",severity:"error"});const n=["none","plan","step"];r.policy.approval&&n.includes(r.policy.approval)||t.push({path:"capability.policy.approval",message:`capability.policy.approval must be one of: ${n.join(", ")}`,code:"INVALID_POLICY_APPROVAL",severity:"error"})}else t.push({path:"capability.policy",message:"capability.policy is required",code:"MISSING_POLICY",severity:"error"});if(void 0!==n.runtime&&"object"!=typeof n.runtime&&t.push({path:"runtime",message:"runtime must be an object",code:"INVALID_RUNTIME_TYPE",severity:"error"}),void 0!==n.tests)if("object"!=typeof n.tests)t.push({path:"tests",message:"tests must be an object",code:"INVALID_TESTS_TYPE",severity:"error"});else{const e=["draft","verified","certified"];n.tests.tier&&e.includes(n.tests.tier)||t.push({path:"tests.tier",message:`tests.tier must be one of: ${e.join(", ")}`,code:"INVALID_TESTS_TIER",severity:"error"}),n.tests.cases&&!Array.isArray(n.tests.cases)?t.push({path:"tests.cases",message:"tests.cases must be an array",code:"INVALID_TESTS_CASES",severity:"error"}):Array.isArray(n.tests.cases)&&n.tests.cases.forEach((e,n)=>{if(!e||"object"!=typeof e)return void t.push({path:`tests.cases[${n}]`,message:"Test case must be an object",code:"INVALID_TEST_CASE",severity:"error"});"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"});const r=ig(e.fixture);r.ok||t.push({path:`tests.cases[${n}].fixture`,message:`${r.why}, so THIS CASE cannot run. The node itself is unaffected.`,code:"INVALID_TEST_FIXTURE",severity:"warning"}),"input"in e?og(e.input)&&t.push({path:`tests.cases[${n}].input`,message:'Test case input contains a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }), which an isolated runner test cannot resolve, so THIS CASE cannot run. The node itself is unaffected. Give the case a literal value, or — when the input is an object another node hands over — a fixture that builds it ("fixture": { "<field>": { "python": "<expression>" } }). (Domain $ref strings, e.g. inside a Swagger/JSON-Schema document, are fine.)',code:"TEST_INPUT_REF_NOT_ALLOWED",severity:"warning"}):t.push({path:`tests.cases[${n}].input`,message:"Test case input is required",code:"MISSING_TEST_CASE_INPUT",severity:"error"})})}return{ok:0===t.filter(e=>"error"===e.severity).length,issues:t}}function cg(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return[];const r=[];for(const[e,i]of Object.entries(n)){if(!Ym(i))continue;const n=i.type;void 0!==n&&"object"!==n&&r.push({path:`${t}.properties.${e}`,message:`${e} is a handle, which travels as a token rather than a ${String(n)}; drop its type`,code:"HANDLE_DECLARES_TYPE",severity:"warning"})}return r}function lg(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 ug{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{let e;try{e=await Yi().getCurrent()}catch{return void console.warn("[NodeRegistry] No workspace provider — nothing to discover")}if(!e)return void console.warn("[NodeRegistry] No workspace available");const t=To();let n;try{n=await t.getFileTree()}catch(e){return void console.warn("[NodeRegistry] Failed to get file tree:",e)}const r=function(e){const t=[];return dg(e,t),t}(n);await Promise.all(r.map(e=>this.loadManifest(t,e)))}catch(e){console.error("[NodeRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n),i=ag(r);if(!i.ok)return void console.warn(`[NodeRegistry] Invalid manifest at ${t}:`,i.issues);const s=r,o=s.capability;if(!o||"object"!=typeof o||!("id"in o))return void console.warn(`[NodeRegistry] Missing capability.id in ${t}`);const a=t.lastIndexOf("/"),c=a>=0?t.slice(0,a):"";this.packages.set(o.id,{packageRoot:c,manifestPath:t,manifest:s})}catch(e){console.warn(`[NodeRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.runtime&&(t=t.filter(t=>t.manifest.runtime?.kind===e.runtime)),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}setTestReport(e,t){this.testReports.set(e,t)}getLatestTestReport(e){return this.testReports.get(e)}clear(){this.packages.clear(),this.testReports.clear()}}function dg(e,t){for(const n of e)n.isDirectory?n.children&&dg(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let pg;function fg(){return pg||(pg=new ug),pg}function hg(e,t,n,r=!1){if("code"!==e.cell_type)throw new Error("Cell must be a code cell");let i=Array.isArray(e.source)?e.source.join(""):String(e.source||"");const s=JSON.stringify(t);return i=i.replace(/__ivy_node_id__/g,s),i}async function mg(e,t,n,r){let i={};for await(const s of e.run({id:"ivy-snapshot",language:"python",code:"import json as __ivy_json\ndef __ivy_snapshot__():\n out = {}\n __ivy_skip = ('In', 'Out', 'get_ipython', 'exit', 'quit', 'json')\n for __ivy_k in list(globals().keys()):\n if __ivy_k.startswith('_'):\n continue\n if __ivy_k in __ivy_skip:\n continue\n try:\n __ivy_v = globals()[__ivy_k]\n except Exception:\n continue\n if callable(__ivy_v):\n continue\n __ivy_tn = type(__ivy_v).__name__\n __ivy_m = getattr(type(__ivy_v), '__module__', '') or ''\n if __ivy_tn == 'module':\n continue\n try:\n if __ivy_tn in ('DataFrame', 'Series') and 'pandas' in __ivy_m:\n __ivy_shape = getattr(__ivy_v, 'shape', None)\n out[__ivy_k] = {'__type__': __ivy_tn, 'shape': list(__ivy_shape) if __ivy_shape is not None else None}\n elif __ivy_tn == 'ndarray' and 'numpy' in __ivy_m:\n out[__ivy_k] = {'__type__': 'ndarray', 'shape': list(__ivy_v.shape), 'dtype': str(__ivy_v.dtype)}\n else:\n try:\n __ivy_enc = __ivy_json.dumps(__ivy_v)\n if len(__ivy_enc) > 2000:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n else:\n out[__ivy_k] = __ivy_v\n except Exception:\n __ivy_s = repr(__ivy_v)\n out[__ivy_k] = __ivy_s[:500] + ('…' if len(__ivy_s) > 500 else '')\n except Exception:\n try:\n out[__ivy_k] = repr(__ivy_v)[:500]\n except Exception:\n out[__ivy_k] = '<unrepr>'\n return out\nprint(__ivy_json.dumps(__ivy_snapshot__(), default=lambda o: repr(o)[:500]))\n",resources:r?{timeoutMs:r}:void 0},{runId:`${t}:snapshot:${n}`}))if("stdout"===s.type&&"text"in s){const e=s.text;try{const t=JSON.parse(e.trim());t&&"object"==typeof t&&(i=t)}catch{}}return i}function gg(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 yg=/token|secret|key|password|passwd|api[_-]?key/i;function wg(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=yg.test(i)?"[REDACTED]":e[i],o=i.length+JSON.stringify(s??null).length;n+o>16e3?r=!0:(n+=o,t[i]=s)}return r&&(t.__truncated__=!0),t}let vg=0;function bg(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Ig(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function kg(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Eg(e,t){const n=e.value;switch(e.type){case"isType":return{passed:Ig(t)===String(n??""),expected:String(n??""),actual:Ig(t)};case"equals":return{passed:kg(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=>kg(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:Ig(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:Ig(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):Ig(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:Ig(t)}}}function Sg(e,t,n=""){const r=e.assertions||{},i={},s=[];if(void 0!==r.schema){const e=!0===r.schema;i.schema={passed:e},s.push(!e)}if(void 0!==r.expectsError){const e=!1===r.expectsError;i.error={passed:e},s.push(!e)}if(r.errorPattern&&r.expectsError){const e=new RegExp(r.errorPattern).test(n);i.error={passed:e,expected:r.errorPattern,actual:n||void 0},s.push(!e)}if(r.properties&&"object"==typeof r.properties){const e={};for(const[n,i]of Object.entries(r.properties)){if(!i||"object"!=typeof i)continue;const r=bg(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=Eg(a,r);else if("string"==typeof a)o=Eg({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=Eg({type:"equals",value:i.expected},r)}e[n]=o,s.push(!o.passed)}Object.keys(e).length&&(i.properties=e)}return{status:s.some(Boolean)?"fail":"pass",assertions:Object.keys(i).length>0?i:void 0}}function Ag(e,t,n){const r=!0===e.assertions?.expectsError,i=e.assertions?.errorPattern;let s;return s=r?i?new RegExp(i).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:s,error:t,assertions:{error:{passed:"pass"===s,expected:i,actual:t}}}}function xg(e){const{capabilityId:t,version:n,tier:r,results:i,startedAtMs:s}=e,o=i.filter(e=>"pass"===e.status).length,a=i.filter(e=>"fail"===e.status).length,c=i.filter(e=>"skip"===e.status).length,l=i.filter(e=>"error"===e.status).length;return{reportId:`report-${t}-${n}-${Date.now()}`,capabilityId:t,capabilityVersion:n,specVersion:"v0.1",timestampMs:Date.now(),runner:{version:"0.1.0",environment:"punica-editor"},summary:{tier:r,status:0===a&&0===l?"pass":a>0?"fail":"flaky",totalCases:i.length,passedCases:o,failedCases:a,skippedCases:c,durationMs:Date.now()-s},cases:i}}function Cg(){return Date.now()}function Tg(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function _g(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function Pg(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Ng(){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 $g(){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 Mg(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 Rg(e){try{const n=Ng();if(!n)throw new Error("[FlowEngine] Capability gateway not available. Gateway is mandatory for all FS operations.");{const r=await t();await n.call("fs.writeFile",{path:`${e}/.keep`,content:""},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}}catch{}}async function Og(e,n){const r=Ng();if(!r)throw new Error("[FlowEngine] writeTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");const i=await t();await r.call("fs.writeFile",{path:e,content:n},{sessionId:"internal",workspaceId:i,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}function Lg(e,t,n,r,i){const s=i?.traceId??t;punica.kernel.Events.manager.publishEvent({name:e,envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:t,traceId:s,spanId:i?.spanId,parentSpanId:i?.parentSpanId,timestampMs:Cg(),source:i?.source??"flow:engine",kind:n},payload:r})}const jg=new Set(["sensitive","secret"]);function Dg(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function Fg(e,t,n,r){if(!function(e,t,n){return!(!n||!jg.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:Dg(e)}}const Bg=new class{#Rt=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#Rt.set(e,(this.#Rt.get(e)??0)+r),!0;const i=this.#Rt.get(e)??0;return!(i+r>n)&&(this.#Rt.set(e,i+r),!0)}used(e){return this.#Rt.get(e)??0}release(e){this.#Rt.delete(e)}reset(){this.#Rt.clear()}};class qg{async ensureBase(){await Rg(".punica"),await Rg(Pg(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await Rg(Pg(".punica","workflow-runs",e)),await Rg(Pg(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=Cg();await this.ensureRunDirs(e);const s=n.surface??"output",o=n.payload,a=n.text;let c,l=o,u=a;if(n.redactionPolicy||n.capabilityClassification){const e=Fg(o??a,n.redactionPolicy,s,n.capabilityClassification);e&&"object"==typeof e&&!0===e.redacted&&(c=e,l=c,u=void 0)}const d="string"==typeof u,p=Pg(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let f;f=d?String(u??""):Tg(l??{},2);const h=n.sizeBudget?.maxBytes;if(c||"number"!=typeof h)"number"==typeof h&&Bg.acquire(e,f.length,h);else{Bg.acquire(e,f.length,h)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,f.length),f=Tg(c,2),Bg.acquire(e,f.length,h))}await Og(p,f);const m=f.length,g=_g(d?String(u??""):Tg(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs:i,name:n.name,mimeType:n.mimeType,uri:p,preview:g,sizeBytes:m,meta:c?{...n.meta??{source:"flow:engine"},redacted:c}:n.meta??{source:"flow:engine"}};return Lg("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function Ug(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 Vg(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function Wg(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 Kg(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 Gg(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 Yg(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function zg(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 Jg(e,t,n){const r=zg(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 Hg(e,t){const n=zg(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 Qg(e,t){const n=zg(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 Zg(e,t=".punica"){const n=Yg(t,"workflow-runs",e.runId),r=Yg(n,"checkpoint.json"),i=Yg(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await Hg("writeCheckpoint",n),await Jg("writeCheckpoint",i,s);try{await async function(e,t,n){const r=zg(e);await r.call("fs.rename",{from:t,to:n},{sessionId:"internal",actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},policy:{mode:"execute"}})}("writeCheckpoint",i,r)}catch{try{await Qg("writeCheckpoint",r)}catch{}await Jg("writeCheckpoint",r,s);try{await Qg("writeCheckpoint",i)}catch{}}}async function Xg(e,t=".punica"){const n=Yg(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=zg(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 ey(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 ty{runs;runIdToSession;artifactStore;constructor(e,t,n){this.runs=e,this.runIdToSession=t,this.artifactStore=n}async startRun(e){const t=e?.spec,n=e?.workspaceId,r=e?.filePathOrUri,i=e?.input??null;if(!t||"ivy.workflow/v0.1"!==t.apiVersion||"Workflow"!==t.kind)throw new Error('Invalid WorkflowDocument: must have apiVersion="ivy.workflow/v0.1" and kind="Workflow"');if(!t.graph||!t.graph.nodes||!t.graph.edges)throw new Error("Invalid WorkflowDocument: missing graph.nodes or graph.edges");if(!t.graph.entryNodeId)throw new Error("Invalid WorkflowDocument: missing graph.entryNodeId");if(!t.graph.nodes.some(e=>e.id===t.graph.entryNodeId))throw new Error(`Invalid WorkflowDocument: entryNodeId "${t.graph.entryNodeId}" not found in graph.nodes`);const s=t,o=function(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=e.graph.edges.filter(e=>n.has(e.fromId)&&n.has(e.toId)),i=new Map,s=new Map;t.forEach(e=>{i.set(e.id,0),s.set(e.id,[])}),r.forEach(e=>{s.get(e.fromId).push(e.toId),i.set(e.toId,(i.get(e.toId)??0)+1)});const o=[];for(const[e,t]of i.entries())0===t&&o.push(e);const a=[];for(;o.length;){const e=o.shift();a.push(e);for(const t of s.get(e)??[])i.set(t,(i.get(t)??0)-1),0===(i.get(t)??0)&&o.push(t)}if(a.length!==t.length)throw new Error("Workflow graph is not a DAG (cycle detected).");return a}(s),a=punica.kernel.Events.manager.createCorrelationId(),c=a,l=punica.kernel.Events.manager.createCorrelationId(),u={runId:a,specVersion:"0.1",status:"QUEUED",createdAtMs:Cg(),startedAtMs:Cg(),traceId:c,entryNodeId:s.graph.entryNodeId,metadata:{title:s.title,tags:s.tags},steps:[]};for(const e of o){const t=s.graph.nodes.find(t=>t.id===e);if(!t)continue;const n="ivyNode"===t.ref.kind?"capability.call":"workflow"===t.ref.kind?"workflow.run":"flowInput"===t.ref.kind?"flow.input":"flowOutput"===t.ref.kind?"flow.output":"primitive"===t.ref.kind?`primitive.${t.ref.primitive}`:"unknown",r={stepId:t.id,nodeId:t.id,nodeType:n,attempt:0,status:t.disabled?"SKIPPED":"PENDING",cellId:void 0};u.steps.push(r)}u.status="RUNNING";const d=Wg(s),p=s.graph.runBudget?.maxInFlight;return this.runs.set(a,{run:u,spec:s,order:o,cursor:0,paused:!1,cancelled:!1,rootSpanId:l,filePathOrUri:r,dependencyGraph:d,inFlightNodes:new Set,maxInFlight:p,nodeOutputs:new Map,input:i}),Lg("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),ey({name:"flow.run.started",correlationId:a,traceId:c,payload:{runId:a,flowId:s.id,workspaceId:n,startedAtMs:u.startedAtMs??u.createdAtMs,entryNodeId:u.entryNodeId}}),await this.persistRun(a),await this.persistIndex(),{runId:a,workspaceId:n}}async pauseRun(e){const t=this.runs.get(e);return!!t&&(t.paused=!0,t.run.status="PAUSED",Lg("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 Xg(e);if(!n)return!1;{const r=n.dependencyGraphState?Wg(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"),Lg("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=Cg();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 Lg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Lg("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=Pg(".punica","workflow-runs",e,"run.json");await Og(n,Tg({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=Pg(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Og(e,Tg({version:1,updatedAtMs:Cg(),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 Zg(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=Pg(".punica","workflow-runs","index.json"),n=await async function(e){const n=Ng();if(!n)throw new Error("[FlowEngine] readTextFile: capability gateway is mandatory — substrate refuses to fall back to runtime.fs (would bypass audit + policy + traversal middleware).");try{const r=await t();return await n.call("fs.readFile",{path:e},{sessionId:"internal",workspaceId:r,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}})}catch{return null}}(e);if(n)try{const e=JSON.parse(n);Lg("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class ny{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,i,s){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=i,this.resumeRunLoop=s}setupApprovalSubscription(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{const t=e?.event?.payload?e.event:e,n=t?.envelope?.correlationId;if(!n)return;const r=t?.payload??{},i=r?.request??{},s=r?.context??{};let o=this.pendingToRunStep.get(n);if(!o){if(o=this.#Ot(s?.traceId,String(i?.id??"")),!o)return;this.pendingToRunStep.set(n,o)}const 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,argsBinding:"string"==typeof i?.argsBinding?i.argsBinding:void 0,argsPreview:i?.argsPreview,workspaceId:"string"==typeof s?.workspaceId?s.workspaceId:void 0,timestampMs:Cg()};this.pendingByCorrelation.set(n,c);const l=this.runs.get(o.runId);if(l){const e=l.run.steps.find(e=>e.stepId===o.stepId);e&&(e.status="WAITING_APPROVAL",e.approval={pendingId:a,required:!0,requestedAtMs:Cg(),resolved:!1},Lg("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",Lg("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}),Lg("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:o.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),ey({name:"flow.approval.requested",correlationId:l.run.runId,traceId:l.run.traceId,payload:{runId:l.run.runId,stepId:o.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)}})}#Ot(e,t){if("string"!=typeof e||!e||!t)return;const n=[];for(const[r,i]of this.runs){if(i.run.traceId!==e)continue;const s=i.spec.graph?.nodes??[];for(const e of i.run.steps){if("RUNNING"!==e.status)continue;const i=s.find(t=>t.id===e.nodeId),o=i?.data,a=i?.ref;("string"==typeof o?.capabilityId?o.capabilityId:"ivyNode"===a?.kind?String(a.id??""):"")===t&&n.push({runId:r,stepId:e.stepId})}}return 1===n.length?n[0]:void 0}approvePending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=e?.scope??"once",r=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!r)return!1;const i=this.pendingToRunStep.get(r.attemptCorrelationId);if(!i)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id,argsBinding:r.argsBinding,argsPreview:r.argsPreview},n,{workspaceId:r.workspaceId})}catch{}Lg("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:Cg()},{traceId:i.runId}),ey({name:"flow.approval.granted",correlationId:i.runId,traceId:i.runId,payload:{runId:i.runId,stepId:i.stepId,pendingId:t,scope:n,capability:{kind:r.kind,id:r.id}}}),this.pendingByCorrelation.delete(r.attemptCorrelationId);const s=this.runs.get(i.runId);if(s){const e=s.run.steps.find(e=>e.stepId===i.stepId);e?.approval&&(e.approval.resolved=!0,e.approval.decision="approved"),s.run.status="RUNNING",Lg("workflow.runUpdated",s.run.runId,"info",{runId:s.run.runId,patch:{status:"RUNNING"}},{traceId:s.run.traceId,spanId:s.rootSpanId}),this.persistRun(s.run.runId),this.resumeRunLoop(s.run.runId)}return!0}rejectPending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!n)return!1;const r=this.pendingToRunStep.get(n.attemptCorrelationId);if(!r)return!1;Lg("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:Cg()},{traceId:r.runId}),ey({name:"flow.approval.rejected",kind:"warn",correlationId:r.runId,traceId:r.runId,payload:{runId:r.runId,stepId:r.stepId,pendingId:t,capability:{kind:n.kind,id:n.id}}}),this.pendingByCorrelation.delete(n.attemptCorrelationId);const i=this.runs.get(r.runId);return i&&(i.run.status="FAILED",i.run.endedAtMs=Cg(),Lg("workflow.runUpdated",i.run.runId,"error",{runId:i.run.runId,patch:{status:"FAILED",endedAtMs:i.run.endedAtMs,error:{message:"Approval rejected",nodeId:r.stepId}}},{traceId:i.run.traceId,spanId:i.rootSpanId}),Lg("workflow.runFinished",i.run.runId,"error",{runId:i.run.runId,status:"FAILED",endedAtMs:i.run.endedAtMs},{traceId:i.run.traceId,spanId:i.rootSpanId}),this.persistRun(i.run.runId),this.persistIndex()),!0}}const ry=3e4,iy={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const sy=new class{#Te=new Map;getSemaphore(e,t){let n=this.#Te.get(e);return n||(n={count:0,max:t,queue:[]},this.#Te.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.#Te.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function oy(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function ay(e,t){if(!t.retry)return 0;const n=t.retry.initialDelayMs??1e3,r=t.retry.maxDelayMs??3e4,i=t.retry.backoffMultiplier??2,s=t.retry.jitter??"none";return function(e,t){if("none"===t)return e;if("full"===t)return Math.floor(Math.random()*e);if("decorrelated"===t){const t=e/2;return Math.floor(t+Math.random()*t)}return e}(Math.min(n*Math.pow(i,e-1),r),s)}const cy=new class{#Lt=new Map;register(e,t){this.#Lt.set(e,t)}get(e){return this.#Lt.get(e)}resolveOrThrow(e){const t=this.#Lt.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.#Lt.clear()}};function ly(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 uy(e,t){if(!e||"object"!=typeof e)return{ok:!1,reason:"invalid-ref"};if("literal"===e.kind)return{ok:!0,value:e.value};if("path"===e.kind){const n=String(e.path??"").split(".").filter(e=>e.length>0);if(0===n.length)return{ok:!1,reason:"invalid-ref"};const[r,...i]=n;if(!t.has(r))return{ok:!1,reason:"missing-node"};const s=t.get(r);if(0===i.length)return{ok:!0,value:s??null};const o=ly(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function dy(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 py(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fy(e){return String(e??"").split(".").filter(e=>e.length>0)}function hy(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];py(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function my(e,t,n){const r=t.filter(t=>t.toId===e.id&&(void 0!==t.fromPath||void 0!==t.toPath)),i=e.data?.input;if(0===r.length)return void 0!==i?i:void 0!==e.defaults?e.defaults:void 0;const s={...py(e.defaults)?e.defaults:{},...py(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?fy(e.fromPath):[],i=r.length?ly(t,r):t;if(void 0===i)continue;const o=e.toPath?fy(e.toPath):[];o.length?hy(s,o,i):py(i)?Object.assign(s,i):s[e.fromId]=i}return s}class gy 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 yy(e,t){if(function(e){return!0===e.cancelled}(e))throw new gy(e.run?.runId,t)}function wy(e,t){const n=e?.code;return"CAPABILITY_APPROVAL_REQUIRED"===n||t.includes("Approval required")}class vy{runs;pendingToRunStep;runIdToSession;artifactStore;persistRun;persistCheckpoint;persistIndex;notifyTerminal;constructor(e,t,n,r,i,s,o,a){this.runs=e,this.pendingToRunStep=t,this.runIdToSession=n,this.artifactStore=r,this.persistRun=i,this.persistCheckpoint=s,this.persistIndex=o,this.notifyTerminal=a}async executeSequential(e,t){const n=this.runs.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;if(!n.notebook&&n.filePathOrUri)try{const e=Ng();if(!e)throw new Error("[FlowEngine] notebook lazy-load: capability gateway is mandatory — substrate refuses to fall back to runtime.fs.");const r=await e.call("fs.readFile",{path:n.filePathOrUri},{sessionId:"internal",workspaceId:t?.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:"internal"},trace:{traceId:n.run.traceId,parentSpanId:n.rootSpanId},policy:{mode:"execute"}});n.notebook=JSON.parse(r)}catch{}const r=n.run.traceId,i=n.rootSpanId;for(;n.cursor<n.order.length;){if(n.cancelled)return;if(n.paused)return;const s=n.order[n.cursor];n.run.currentNodeId=s;const o=n.spec.graph.nodes.find(e=>e.id===s),a=n.run.steps.find(e=>e.stepId===s);if(!o||!a){n.cursor++;continue}if(o.disabled){a.status="SKIPPED",n.cursor++;continue}if(this.#jt(e,n,o,a)){n.cursor++;continue}const c=o.data?.breakpoint;if(c&&"PAUSED"!==n.run.status)return n.paused=!0,n.run.status="PAUSED",Lg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"PAUSED",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const l=this.prepareNodeExecutionConfig(o,n),u=l.retry,d=u?.maxAttempts??0,p=u?.retryOnTimeout??!1,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=Cg(),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}),Lg("workflow.stepStarted",e,"info",{runId:e,step:{stepId:a.stepId,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,status:"RUNNING",startedAtMs:a.startedAtMs,cellId:a.cellId,attemptCorrelationId:c,spanId:u,inputsPreview:a.inputsPreview}},{traceId:r,spanId:u,parentSpanId:i}),ey({name:"flow.node.started",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,nodeType:a.nodeType,attempt:a.attempt,attemptCorrelationId:c,spanId:u}});try{const s=await this.executeNodeAttempt(o,a,l,{attemptCorrelationId:c,spanId:u,rootSpanId:i,traceId:r,workspaceId:t?.workspaceId,filePathOrUri:n.filePathOrUri,notebook:n.notebook,timeoutMs:f,nodeOutputs:n.nodeOutputs,runBudget:n.spec.graph.runBudget,runInput:n.input,resolvedInput:my(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),Lg("workflow.stepFinished",e,"result",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"SUCCESS",endedAtMs:a.endedAtMs,outputsPreview:a.outputsPreview,artifactIds:a.artifactIds}},{traceId:r,spanId:u,parentSpanId:i}),ey({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",Lg("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",Lg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:s}},{traceId:r,spanId:i}),await this.persistRun(e),void await this.persistIndex();const 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=Cg(),a.error={message:o},Lg("workflow.stepFinished",e,"error",{runId:e,step:{stepId:a.stepId,attempt:a.attempt,status:"FAILED",endedAtMs:a.endedAtMs,error:{message:o},artifactIds:a.artifactIds??[]}},{traceId:r,spanId:u,parentSpanId:i}),ey({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=Cg(),n.run.error={message:o,nodeId:s,correlationId:c},Lg("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),Lg("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),ey({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=ay(h,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Lg("workflow.stepRetry",e,"info",{runId:e,stepId:a.stepId,attempt:h,maxAttempts:d,delayMs:m,error:o},{traceId:r,spanId:u,parentSpanId:i}),await new Promise(e=>setTimeout(e,m))}}}"RUNNING"!==n.run.status&&"PAUSED"!==n.run.status&&console.warn(`[FlowEngine] Invalid state transition to COMPLETED from ${n.run.status}`),n.run.status="COMPLETED",n.run.endedAtMs=Cg(),Lg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),Lg("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),ey({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=Yg(n,"workflow-runs",e.runId),i=Yg(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await Hg("writeRunHistory",r),await Jg("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=Yg(t,"workflow-runs",e,"checkpoint.json");try{await Qg("deleteCheckpoint",n)}catch{}}(e);const s=this.runIdToSession.get(e);if(s){try{await s.close()}catch(t){console.warn(`[FlowEngine] Error closing session for run ${e}:`,t)}this.runIdToSession.delete(e)}this.notifyTerminal?.(e,"COMPLETED")}async executeParallel(e,t,n,r){const i=r.run.traceId,s=r.rootSpanId,o=r.maxInFlight??1/0,a=!!(c=r.spec.graph.runBudget)&&!0===c.failFast;for(var c;!Vg(n);){if(r.cancelled)return;if(r.paused)return;if("WAITING_APPROVAL"===r.run.status)break;const c=o-(r.inFlightNodes?.size??0),l=Ug(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=>{Gg(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 Kg(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void Kg(o,!0,n);if(this.#jt(e,r,c,l))return r.inFlightNodes?.delete(o),void Kg(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,m=!1;for(;f<=d&&!h&&!m;){yy(r),f++,l.attempt=f,l.status="RUNNING",l.startedAtMs=Cg();const n=punica.kernel.Events.manager.createCorrelationId(),u=punica.kernel.Events.manager.createCorrelationId();l.attemptCorrelationId=n,l.spanId=u,Lg("workflow.stepStarted",e,"info",{runId:e,step:{stepId:l.stepId,nodeId:l.nodeId,nodeType:l.nodeType,attempt:l.attempt,status:"RUNNING",startedAtMs:l.startedAtMs,attemptCorrelationId:n,spanId:u}},{traceId:i,spanId:u,parentSpanId:s});try{const o=await this.executeNodeAttempt(c,l,a,{attemptCorrelationId:n,spanId:u,rootSpanId:s,traceId:i,workspaceId:t?.workspaceId,filePathOrUri:r.filePathOrUri,notebook:r.notebook,timeoutMs:p,nodeOutputs:r.nodeOutputs,runBudget:r.spec.graph.runBudget,runInput:r.input,resolvedInput:my(c,r.spec.graph.edges,r.nodeOutputs??new Map)});void 0!==o.output&&r.nodeOutputs&&r.nodeOutputs.set(c.id,o.output),h=!0,Lg("workflow.stepFinished",e,"result",{runId:e,step:{stepId:l.stepId,attempt:l.attempt,status:"SUCCESS",endedAtMs:l.endedAtMs,outputsPreview:l.outputsPreview,artifactIds:l.artifactIds??[]}},{traceId:i,spanId:u,parentSpanId:s})}catch(t){if(t instanceof gy)throw l.status="CANCELLED",l.endedAtMs=Cg(),t;const n=String(t?.message??t);if(wy(t,n)){m=!0,this.#Dt(e,r,l,o);break}if(f<=d){const e=ay(f,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=Cg(),l.error={message:n},Lg("workflow.stepFinished",e,"error",{runId:e,step:{stepId:l.stepId,attempt:l.attempt,status:"FAILED",endedAtMs:l.endedAtMs,error:{message:n},artifactIds:l.artifactIds??[]}},{traceId:i,spanId:u,parentSpanId:s}),t}}if(m){const t=n.nodes.get(o);t&&(t.status="ready"),n.readyNodes.add(o),l.attempt=0,await this.persistRun(e),await this.persistIndex()}else h&&(Kg(o,!0,n),await this.persistRun(e))}catch(t){Kg(o,!1,n),t instanceof gy||(r.run.status="FAILED",r.run.endedAtMs=Cg(),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)}"WAITING_APPROVAL"!==r.run.status&&("RUNNING"===r.run.status?(r.run.status="COMPLETED",r.run.endedAtMs=Cg(),Lg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),Lg("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),ey({name:"flow.run.completed",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs}}),await this.persistRun(e),await this.persistIndex(),this.notifyTerminal?.(e,"COMPLETED")):"FAILED"===r.run.status&&(ey({name:"flow.run.failed",kind:"error",correlationId:e,traceId:i,payload:{runId:e,endedAtMs:r.run.endedAtMs,error:r.run.error}}),this.notifyTerminal?.(e,"FAILED")))}prepareNodeExecutionConfig(e,t){const n=cy.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:ry,retry:{...iy},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)}#Dt(e,t,n,r){n.status="WAITING_APPROVAL",Lg("workflow.stepUpdated",e,"info",{runId:e,stepId:n.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),t.run.status="WAITING_APPROVAL",Lg("workflow.runUpdated",e,"info",{runId:e,patch:{status:"WAITING_APPROVAL",currentNodeId:r}},{traceId:t.run.traceId,spanId:t.rootSpanId})}#jt(e,t,n,r){const i=t.spec;return!!function(e,t,n,r){const i=t.graph.nodes,s=i.find(t=>t.id===e);if(!s||"flowOutput"===s.ref?.kind)return!1;const o=t.graph.edges.filter(t=>t.toId===e);return 0!==o.length&&o.every(e=>{if("SKIPPED"===n(e.fromId))return!0;const t=function(e){const t=e.metadata?.branch;return"then"===t||"else"===t?t:void 0}(e);if(!t)return!1;if(!function(e,t){return!!e&&"primitive"===e.ref?.kind&&e.ref.primitive===t}(i.find(t=>t.id===e.fromId),"if"))return!1;const s=r?.get(e.fromId)?.taken;return("then"===s||"else"===s)&&s!==t})}(n.id,i,e=>t.run.steps.find(t=>t.stepId===e)?.status,t.nodeOutputs)&&(r.status="SKIPPED",Lg("workflow.stepUpdated",e,"info",{runId:e,stepId:r.stepId,patch:{status:"SKIPPED",reason:"branch-not-taken"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),!0)}async executeNodeAttempt(e,t,n,r){const i=cy.get(e.ref.kind);let s;try{s=await(i?.acquireResources?.(e,n,{workspaceId:r.workspaceId}))}catch(e){throw new Error(`Concurrency limit reached: ${e?.message??String(e)}`)}try{const n=this.executeNode(e,r),i=r.timeoutMs?await async function(e,t){return Promise.race([e,oy(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=Cg(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return cy.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class by 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 Iy(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new by(e??0,t);return n}const ky="__default__";class Ey{workspaceId;#Ft=new Map;#Bt=new Map;#qt=new Map;#Ut=new qg;#Vt=!1;#Wt=new Map;#Kt;#Gt;#Yt;constructor(e=ky){this.workspaceId=e,this.#Kt=new ty(this.#Ft,this.#Wt,this.#Ut),this.#Gt=new ny(this.#Ft,this.#Bt,this.#qt,e=>this.#Kt.persistRun(e),()=>this.#Kt.persistIndex(),e=>this.#zt(e)),this.#Yt=new vy(this.#Ft,this.#qt,this.#Wt,this.#Ut,e=>this.#Kt.persistRun(e),e=>this.#Kt.persistCheckpoint(e),()=>this.#Kt.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#Vt||(this.#Vt=!0,this.#Gt.setupApprovalSubscription(),this.#Kt.loadIndex())}async startRun(e){const t=await this.#Kt.startRun(e),n=this.#Ft.get(t.runId)?.run.traceId;return n&&Xm(n),this.#zt(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#Kt.pauseRun(e)}async resumeRun(e){const t=await this.#Kt.resumeRun(e);return t&&this.#zt(e,{}),t}async cancelRun(e,t){const n=await this.#Kt.cancelRun(e,t);return n&&this.#Jt(e),n}#Jt(e){const t=this.#Ft.get(e)?.run.traceId;t&&ng(t)}getRun(e){return this.#Kt.getRun(e)}listRuns(e){return this.#Kt.listRuns(e)}approvePending(e){return this.#Gt.approvePending(e)}rejectPending(e){return this.#Gt.rejectPending(e)}hasRun(e){return this.#Ft.has(e)}getNodeOutput(e,t){const n=this.#Ft.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=Iy(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#Kt.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId,r=this.#Ft.get(n)?.run.traceId;var i,s;r&&e.parentTraceId&&(i=r,s=e.parentTraceId,i&&s&&i!==s&&eg(s)&&Qm.set(i,Zm(s))),ey({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 o=new Promise(e=>{const t=this.#Ht.get(n);if(t)return this.#Ht.delete(n),void e(t);this.#Qt.set(n,e)});this.#zt(n,{workspaceId:this.workspaceId});const a=await o,c=this.getRun(n),l=this.getNodeOutput(n,"flow-output");return{runId:n,parentRunId:e.parentRunId,depth:t,status:a,output:l,startedAtMs:c?.startedAtMs,endedAtMs:c?.endedAtMs,error:c?.error}}notifyTerminal(e,t){this.#Jt(e);const n=this.#Qt.get(e);if(n)return this.#Qt.delete(e),void n(t);this.#Ht.set(e,t)}#Qt=new Map;#Ht=new Map;hasPending(e){for(const t of this.#Bt.values())if(t.pendingId===e)return!0;return!1}async#zt(e,t){const n=this.#Ft.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;const r=void 0!==n.dependencyGraph,i=n.dependencyGraph;r&&i?await this.#Yt.executeParallel(e,t,i,n):await this.#Yt.executeSequential(e,t)}}const Sy=new Map,Ay=new Map,xy=new Map;function Cy(e){const t=e??ky;let n=Sy.get(t);return n||(n=new Ey(t),Sy.set(t,n)),n}let Ty=!1;const _y=new class{initialize(){if(Ty)return;Ty=!0;const e=punica.kernel.Commands.manager;e.registerCommand(Yn.WORKFLOW.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(Yn.WORKFLOW.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(Yn.WORKFLOW.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(Yn.WORKFLOW.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(Yn.WORKFLOW.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(Yn.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:ky}(e),n=Cy(t);n.initialize();const r=await n.startRun(e);return Ay.set(r.runId,t),r}async pauseRun(e){const t=this.#Zt(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#Zt(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#Zt(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#Zt(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#Zt(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of Sy.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.#Xt(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#Xt(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(Iy(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=Cy(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Ay.set(n.runId,t.workspaceId),n}#Zt(e){const t=Ay.get(e);if(t)return Sy.get(t);for(const[t,n]of Sy.entries())if(n.hasRun(e))return Ay.set(e,t),n}#Xt(e){const t=xy.get(e);if(t)return Sy.get(t);for(const[t,n]of Sy.entries())if(n.hasPending(e))return xy.set(e,t),n}};function Py(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 Ny(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class $y{packages=new Map;async discover(){this.packages.clear();try{let e;try{e=await Yi().getCurrent()}catch{return void console.warn("[AgentRegistry] No workspace provider — nothing to discover")}if(!e)return void console.warn("[AgentRegistry] No workspace available");const t=To();let n;try{n=await t.getFileTree()}catch(e){return void console.warn("[AgentRegistry] Failed to get file tree:",e)}const r=function(e){const t=[];return My(e,t),t}(n);await Promise.all(r.map(e=>this.loadManifest(t,e)))}catch(e){console.error("[AgentRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n);if(!Ny(r))return void console.warn(`[AgentRegistry] Not an IvyAgent manifest: ${t}`);const i=r,s=i.capability;if(!s||"object"!=typeof s||!("id"in s))return void console.warn(`[AgentRegistry] Missing capability.id in ${t}`);const o=t.lastIndexOf("/"),a=o>=0?t.slice(0,o):"";this.packages.set(s.id,{packageRoot:a,manifestPath:t,manifest:i})}catch(e){console.warn(`[AgentRegistry] Failed to load ${t}:`,e)}}get(e){return this.packages.get(e)}list(){return Array.from(this.packages.values())}search(e){let t=this.list();if(e.tags&&e.tags.length>0&&(t=t.filter(t=>{const n=t.manifest.capability,r=n&&"object"==typeof n&&"tags"in n&&n.tags||[];return e.tags.some(e=>r.includes(e))})),e.text){const n=e.text.toLowerCase();t=t.filter(e=>{const t=e.manifest.capability,r=t&&"title"in t?String(t.title||"").toLowerCase():"",i=t&&"description"in t?String(t.description||"").toLowerCase():"",s=t&&"id"in t?String(t.id||"").toLowerCase():"";return r.includes(n)||i.includes(n)||s.includes(n)})}return t}unregister(e){return this.packages.delete(e)}clear(){this.packages.clear()}}function My(e,t){for(const n of e)n.isDirectory?n.children&&My(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let Ry;function Oy(){return Ry||(Ry=new $y),Ry}const Ly=new Set(["COMPLETED","FAILED","CANCELLED"]);function jy(e){return new Promise(t=>setTimeout(t,e))}async function Dy(e,t,n,r){const i=Date.now()+n;let s=e.getRun(t);for(;Date.now()<i;){s=e.getRun(t);const n=s?.status;if(n&&Ly.has(n))return{record:s,timedOut:!1};if("WAITING_APPROVAL"===n&&!r?.waitForApproval)return{record:s,timedOut:!1};await jy(250)}return{record:s,timedOut:!0}}async function Fy(e,t,n,r,i){const s=Date.now(),o=(e,t)=>({caseId:n.id,status:e.status,durationMs:Date.now()-s,...void 0!==t?{output:t}:{},...void 0!==e.error?{error:e.error}:{},...e.assertions?{assertions:e.assertions}:{}});let a;try{const r=await e.startRun({spec:t,workspaceId:i,input:n.input});if(a=r?.runId,!a)throw new Error("Engine did not return a runId")}catch(e){const t=e instanceof Error?e.message:String(e);return o(Ag(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await Dy(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(Ag(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(Ag(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(Sg(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(Ag(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}async function By(e,t,n,r=`test-${e}-${Date.now()}`){const i=globalThis,s=i.punica?.runtime?.capabilities?.gateway;if(!s?.call)throw new Error(`Capability gateway is not initialized — cannot test "${e}".`);const o=[];let a;try{const e=i.punica?.kernel?.Events?.manager?.subscribe?.("ivy.node.cell.failed",e=>{const t=e?.payload,n=t?.message??e?.message;"string"==typeof n&&n&&o.push(n)});a="function"==typeof e?e:e?.dispose?.bind(e)}catch{}try{return{output:await s.call(e,t??{},{sessionId:`test-${e}`,workspaceId:void 0,actor:{type:"system",id:"flow.test"},origin:{kind:"command",id:"flow.test.run"},trace:{traceId:r,spanId:"case"},policy:{},timeoutMs:n}),errorText:o.join(" ")}}finally{try{a?.()}catch{}}}async function qy(e,t){const n=fg(),r=n.get(e);if(!r){if(t?.manifest){if(Ny(t.manifest))return async function(e,t){const n=e,r=String(n?.capability?.id??n?.id??"");if(!r)throw new Error("Agent manifest has no capability id — cannot run tests.");const i=n?.tests;if(!i||!Array.isArray(i.cases)||!i.cases.length)throw new Error(`No test specification found for agent: ${r}`);const s=_y,o=Py(n),a=Date.now(),c=[];for(const e of i.cases){if(e.skip){c.push({caseId:e.id,status:"skip",durationMs:0,error:"string"==typeof e.skip?e.skip:void 0});continue}const n=e.timeoutMs??i.timeoutMs??3e4;c.push(await Fy(s,o,e,n,t?.workspaceId))}const l=xg({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{fg().setTestReport(r,l)}catch{}return l}(t.manifest);throw new Error(`Manifest for ${e} is not a testable IvyAgent (expected kind 'IvyAgent' with a graph).`)}throw new Error(`IvyNode not found: ${e}`)}const i=r.manifest,s=i.tests;if(!s)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of s.cases||[]){if(t.skip){a.push({caseId:t.id,status:"skip",durationMs:0,error:"string"==typeof t.skip?t.skip:void 0});continue}const n=Date.now();let r;const i=ig(t.fixture),o=i.ok&&Object.keys(i.fixture).length>0,c=`test-${e}-${n}-${a.length}`;o&&Xm(c);try{if(!i.ok)throw new Error(`The case cannot run: ${i.why}.`);const a=s.timeoutMs||3e4,l=o?await sg(c,t.input,i.fixture,a):t.input,{output:u,errorText:d}=await By(e,l,a,c),p=Sg(t,u,d);r={caseId:t.id,status:p.status,durationMs:Date.now()-n,output:u,assertions:p.assertions}}catch(e){const i=Ag(t,e instanceof Error?e.message:String(e));r={caseId:t.id,status:"error"===i.status?"fail":i.status,durationMs:Date.now()-n,error:i.error,assertions:i.assertions}}finally{o&&await ng(c)}a.push(r)}const c=i.capability,l=xg({capabilityId:e,version:c&&"object"==typeof c&&"version"in c?String(c.version||"0.0.0"):"0.0.0",tier:s.tier,results:a,startedAtMs:o});return n.setTestReport(e,l),l}function Uy(e){return(e.split(/(?<=\.)\s/)[0]??e).replace(/[\s.;:]+$/,"")}function Vy(e){const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:""}function Wy(){return globalThis.punica?.runtime?.capabilities?.gateway??null}function Ky(e){return{sessionId:"flow.test.verify",actor:{type:"system",id:"flow.test"},origin:{kind:"command",id:e},trace:{traceId:`verify-${Date.now()}-${Math.random().toString(36).slice(2,8)}`},policy:{mode:"execute"}}}const Gy={validator:{validate:ag},registry:{discover:()=>fg().discover(),get:e=>fg().get(e),list:()=>fg().list(),search:e=>fg().search(e),setTestReport:(e,t)=>fg().setTestReport(e,t),getLatestTestReport:e=>fg().getLatestTestReport(e)},runner:{run:async function(e,t){const n=Date.now(),r=fg().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=ag(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(og(t.input))throw new Error('Input contains a node-output wiring reference ({ "$ref": "node-output:<nodeId>#<key>" }). punica.ivy.runner.run executes a single node in isolation and cannot resolve references. Resolve inputs before calling runner, or execute inside the workflow engine.');const o=s.capability;if(!o||"object"!=typeof o||!("inputs"in o))throw new Error("Manifest missing capability.inputs");const a=o.inputs;if(!a.schema)throw new Error("Manifest missing capability.inputs.schema");const c=function(e,t){const n=[];if("object"===t.type&&"object"!=typeof e)return n.push("Input must be an object"),{valid:!1,errors:n};if(t.required&&Array.isArray(t.required)&&"object"==typeof e&&null!==e&&!Array.isArray(e)){const r=e;for(const e of t.required)e in r||n.push(`Missing required property: ${e}`)}return{valid:0===n.length,errors:n}}(t.input,a.schema);if(!c.valid)throw new Error(`Input validation failed: ${c.errors.join(", ")}`);const l=eg(t.scopeId);if(!l){const e=zm(t.input);if(e.length>0)throw new Error(`Input ${e.join(", ")} is a handle from another node, and a handle exists only inside the run that made it. Run this node from an agent, or give its test case a fixture that builds the value.`)}if(!s.program)throw new Error("Manifest missing program");const u=s.program,d=u.cells,p=u.roles?.inputCellId,f=u.roles?.outputCellId;if(!p)throw new Error("Program missing roles.inputCellId");if(!f)throw new Error("Program missing roles.outputCellId");const h=d.find(e=>e.id===p),m=d.find(e=>e.id===f);if(!h)throw new Error(`Input cell with id "${p}" not found in program.cells`);if(!m)throw new Error(`Output cell with id "${f}" not found in program.cells`);const g=function(){if(!punica.runtime?.compute)throw new Error("[IvyNodeRunner] Runtime compute API not available. Ensure compute provider is registered.");return punica.runtime.compute}(),y=[],w=u.language||(s.runtime,"python"),v=t.runId??`ivynode-${e}-${n}`,b=(e,t)=>{try{punica.kernel.Events.manager.publish(e,t)}catch{}},I=(e,t)=>{const n=Array.isArray(e.source)?e.source[0]:e.source;return String(n??"").replace(/^#+\s*/,"").trim().slice(0,50)||`Cell ${t+1}`},k=e=>{const t=e;return"stdout"!==t.type&&"stderr"!==t.type||"string"!=typeof t.text?"":t.text},E=()=>g.session.open({language:w}),S=async()=>{const r=l?await tg(t.scopeId,E):await E(),i=t.runId||`ivynode-${e}-${Date.now()}-${++vg}`;let s={};try{const p=["# IvyNode runner context init (v0.2)","import json",l?'if not isinstance(globals().get("__ivy_ctx__"), dict) or "nodes" not in __ivy_ctx__:\n __ivy_ctx__ = {"nodes": {}}':'__ivy_ctx__ = {"nodes": {}}',Jm,`__ivy_ctx__["nodes"][${JSON.stringify(e)}] = {"input": __ivy_resolve_handles__(json.loads(${JSON.stringify(JSON.stringify(t.input))})), "output": {}}`].join("\n");let f=null;for await(const e of r.run({id:"init-ivy-ctx",language:"python",code:p,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${i}:init`})){y.push({type:e.type,data:e});const t=e;"error"===t.type&&(f=`${t.name?`${t.name}: `:""}${t.message??"context init failed"}`)}if(f)throw new Error(f);if(l)try{s=await mg(r,i,"init",t.timeoutMs)}catch{}for(let n=0;n<d.length;n++){const o=d[n];if("code"!==o.cell_type)continue;const a=hg(o,e),c=o.id||`cell-${n}`,l=I(o,n),u=Date.now();let p,f="";b("ivy.node.cell.started",{runId:v,nodeId:e,cellId:c,index:n,label:l,startedAtMs:u});try{let e=null;for await(const n of r.run({id:c,language:w,code:a,resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${i}:cell:${c}`})){y.push({type:n.type,data:n}),f+=k(n);const t=n;if("error"===t.type){e=`${t.name?`${t.name}: `:""}${t.message??"cell execution error"}`.trim()}else if("finished"===t.type&&!1===t.ok){const n=null!=t.exitCode?` (exit code ${t.exitCode})`:"",r=f.trim()?`:\n${f.trim()}`:"";e=e??`Cell execution failed${n}${r}`}}if(e)throw new Error(e)}catch(t){throw b("ivy.node.cell.failed",{runId:v,nodeId:e,cellId:c,index:n,label:l,durationMs:Date.now()-u,error:t instanceof Error?t.message:String(t),logs:f}),t}try{const e=await mg(r,i,c,t.timeoutMs),n=wg(gg(s,e));Object.keys(n).length&&(p=n),s=e}catch{}b("ivy.node.cell.finished",{runId:v,nodeId:e,cellId:c,index:n,label:l,durationMs:Date.now()-u,logs:f,...p?{variables:p}:{}})}const h=function(e){const t=e?.properties;return t&&"object"==typeof t?Object.keys(t).filter(e=>Ym(t[e])):[]}(o.outputs?.schema);if(h.length>0){let n=null;for await(const s of r.run({id:"stash-handles",language:"python",code:(a=e,c=h,u=i,`\n__ivy_out = __ivy_ctx__["nodes"][${JSON.stringify(a)}]["output"]\nfor __ivy_f in ${JSON.stringify(c)}:\n if __ivy_f in __ivy_out and not (isinstance(__ivy_out[__ivy_f], dict) and "$handle" in __ivy_out[__ivy_f]):\n __ivy_tok = ${JSON.stringify(u)} + "/" + __ivy_f\n __ivy_handles__[__ivy_tok] = __ivy_out[__ivy_f]\n __ivy_out[__ivy_f] = {"$handle": __ivy_tok, "pythonType": type(__ivy_handles__[__ivy_tok]).__name__}\n`),resources:t.timeoutMs?{timeoutMs:t.timeoutMs}:void 0},{runId:`${i}:stash-handles`})){const e=s;"error"===e.type&&(n=`${e.name?`${e.name}: `:""}${e.message??"handle stash failed"}`)}if(n)throw new Error(n)}const m=await async function(e,t,n,r){const i=JSON.stringify(t),s=`\nimport json\ntry:\n if '__ivy_ctx__' in globals() and isinstance(__ivy_ctx__, dict):\n if "nodes" in __ivy_ctx__ and ${i} in __ivy_ctx__["nodes"]:\n node_data = __ivy_ctx__["nodes"][${i}]\n if "output" in node_data:\n print(json.dumps(node_data["output"]))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\n else:\n print(json.dumps({}))\nexcept Exception as e:\n print(json.dumps({"error": str(e)}))\n`;for await(const t of e.run({id:"extract-output",language:"python",code:s,resources:r?{timeoutMs:r}:void 0},{runId:`${n}:extract-output`}))if("stdout"===t.type&&"text"in t){const e=t.text;try{const t=JSON.parse(e.trim());if(t&&"object"==typeof t)return t}catch(e){}}throw new Error("Failed to extract output from execution context")}(r,e,i,t.timeoutMs),g=o.outputs;if(!g?.schema)throw new Error("Manifest missing capability.outputs.schema");const E=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}}(m,g.schema);if(!E.valid)throw new Error(`Output validation failed: ${E.errors.join(", ")}`);const S=Date.now()-n;return{output:m,events:y,durationMs:S}}finally{l||await r.close()}var a,c,u};return l?async function(e,t){const n=Hm.get(Zm(e));if(!n)return t();const r=n.tail;let i;n.tail=new Promise(e=>i=e),await r;try{return await t()}finally{i()}}(t.scopeId,S):S()}},test:{run:qy,verify:async function(e,t={}){const n=t.producedBy??"flow.test.verify",r=function(e,t){const n=fg().get(e);if(n)return{manifest:n.manifest,path:n.manifestPath??null,isAgent:!1};const r=Oy().get(e);return r?{manifest:r.manifest,path:r.manifestPath??null,isAgent:!0}:t?{manifest:t,path:null,isAgent:!0}:null}(e,t.manifest);if(!r)throw new Error(`Nothing to verify: ${e} is not a registered node or agent.`);const i=await qy(e,r.isAgent?{manifest:r.manifest}:void 0),s=i?.cases??[],o=Array.isArray(r.manifest?.tests?.cases)?r.manifest.tests.cases:[],a=function(e,t={}){const n=e.filter(e=>"skip"===e.status).length,r=e.filter(e=>"skip"!==e.status),i=r.filter(e=>"pass"===e.status).length,s={ran:r.length,passed:i,skipped:n};if(0===e.length)return{...s,color:"yellow",verified:!1,reason:"no test cases, so nothing proves it"};if(0===r.length)return{...s,color:"yellow",verified:!1,reason:`all ${n} cases are skipped, so nothing proves it`};const o=r.filter(e=>"pass"!==e.status);if(0===o.length)return{...s,color:"green",verified:!0,reason:`${i} of ${r.length} cases passed${n?`, ${n} skipped`:""}`};const a=o.find(e=>{return t=Vy(e),/\b(compute provider|provider|runtime|kernel|interpreter)\b[^.]*not (found|available)|Failed to fetch|has no compute provider/i.test(t);var t});if(a)return{...s,color:"yellow",verified:!1,reason:`not run here: ${Uy(Vy(a))}`};const c=o[0],l=Uy(Vy(c))||`status ${c.status}`;return t.syntheticOnly?{...s,color:"yellow",verified:!1,reason:`failed under placeholder input (${l}); give it a real test case to verify`}:{...s,color:"red",verified:!1,reason:`${o.length} of ${r.length} cases failed; ${c.caseId??c.id??"a case"}: ${l}`}}(s,{syntheticOnly:o.length>0&&o.every(e=>!0===e?.synthetic)}),c=r.path?(l=r.path,/\/ivy\.agent\.json$/.test(l)?l.replace(/ivy\.agent\.json$/,"verification.json"):l.replace(/\.ivy\.(node|agent)$/,"")+".verification.json"):null;var l;let u=null;if(a.verified){const t=await async function(e){try{const t=await(Wy()?.call("kernels.jupyter.server.status",{},Ky(e))),n=Array.isArray(t?.servers)?t.servers.find(e=>e?.running):t?.server??t;return{kernel:n?.envLabel??null,port:n?.port??null}}catch{return{kernel:null,port:null}}}(n),i={};for(const e of o)e?.id&&(i[e.id]=e.input);u={capabilityId:(d={capabilityId:String(e),manifestVersion:String(r.manifest?.capability?.version??"0.0.0"),cases:s,inputs:i,kernel:t.kernel,kernelPort:t.port,nowMs:Date.now(),producedBy:n}).capabilityId,manifestVersion:d.manifestVersion,verifiedAtMs:d.nowMs,kernel:d.kernel??null,kernelPort:d.kernelPort??null,host:"IVYX Studio",producedBy:d.producedBy,cases:d.cases.map(e=>{const t=e.caseId??e.id??"";return{id:t,status:e.status,durationMs:e.durationMs,input:d.inputs[t],..."pass"===e.status?{output:e.output}:{error:Vy(e)||void 0}}})}}var d;const p=Wy();if(c&&p)if(u)await p.call("fs.writeFile",{path:c,content:JSON.stringify(u,null,2)+"\n"},Ky(n));else if("red"===a.color)try{await p.call("fs.deleteFile",{path:c},Ky(n))}catch{}return{...a,record:u,path:c}}}},Yy={discover:()=>Oy().discover(),get:e=>Oy().get(e),list:()=>Oy().list(),search:e=>Oy().search(e),unregister:e=>Oy().unregister(e),run:(e,t)=>async function(e,t){const n=Oy().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??_y,i=t?.timeoutMs??3e4,s=Py(n.manifest),o=Date.now(),a=await r.startRun({spec:s,workspaceId:t?.workspaceId,input:t?.input??{}}),c=a?.runId;if(!c)throw new Error(`Engine did not return a runId for agent ${e}`);const{record:l,timedOut:u}=await Dy(r,c,i,{waitForApproval:t?.waitForApproval});if(u){try{await r.cancelRun(c)}catch{}throw new Error("WAITING_APPROVAL"===l?.status?`Agent ${e} waited ${Math.round(i/1e3)} s for a person to answer a step, and nobody did`:`Agent ${e} did not complete in ${i}ms (status ${l?.status??"unknown"})`)}const d=l?.status;if("WAITING_APPROVAL"===d){try{await r.cancelRun(c)}catch{}throw new Error(`Agent ${e} requires approval — approve the workflow run or lower the capability's approval policy`)}if("COMPLETED"===d){let e;try{e=r.getNodeOutput(c,"flow-output")}catch{e=void 0}return{output:e,runId:c,durationMs:Date.now()-o}}const p=l?.steps?.find(e=>"FAILED"===e.status);throw new Error(`Agent ${e} failed: ${l?.error?.message??p?.error?.message??`Run ended with status ${d??"unknown"}`}`)}(e,t),envelope:Py,isAgentManifest:Ny},zy=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",[]]]),Jy=new Set(["COMPLETED","FAILED","CANCELLED"]);const Hy=new class{canTransitionTo(e,t){if(e===t)return!1;const n=zy.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 zy.get(e)??[]}isTerminal(e){return Jy.has(e)}},Qy=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],Zy={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const Xy={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function ew(e){return{x:Xy.marginX+e%6*240,y:Xy.marginY+120*Math.floor(e/6)}}function tw(e){const t=Math.max(0,e.inputCount??0),n=Math.max(0,e.outputCount??0),r=22*(t+n),i=t>0&&n>0?9:0;return 60+Math.max(56,16+r+i)}function nw(e,t){const n={...Xy,...t??{}},r=e.nodes??[],i={};if(!r.length)return i;const s=new Map;r.forEach((e,t)=>s.set(e.id,t));const o=(e.edges??[]).filter(e=>e.source!==e.target&&s.has(e.source)&&s.has(e.target));if(1===r.length)return i[r[0].id]={x:n.marginX,y:n.marginY},i;const a=new Map,c=new Map;for(const e of r)a.set(e.id,[]),c.set(e.id,[]);for(const e of o)a.get(e.source).push(e.target),c.get(e.target).push(e.source);const l=new Map;for(const e of r)l.set(e.id,c.get(e.id).length);const u=r.filter(e=>0===l.get(e.id)).map(e=>e.id),d=[];for(;u.length;){const e=u.shift();d.push(e);for(const t of a.get(e)){const e=l.get(t)-1;l.set(t,e),0===e&&u.push(t)}}if(d.length<r.length)return r.forEach((e,t)=>{i[e.id]=ew(t)}),i;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)=>{i[e.id]=ew(t)}),i;const m=new Map;for(const e of d){if(!p(e))continue;const t=c.get(e),n=t.length?Math.max(...t.map(e=>m.get(e)??0))+1:0;m.set(e,n)}const g=Math.max(...Array.from(m.values())),y=Array.from({length:g+1},()=>[]);for(const e of 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,tw(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 s=S-k(e)/2;for(const t of e)i[t]={x:r,y:s},s+=I.get(t)+n.verticalGap});const A=n.marginY+E+2*n.verticalGap;return f.forEach((e,t)=>{i[e.id]={x:n.marginX+t*(n.cardWidth+n.horizontalGap/2),y:A}}),i}let rw;function iw(e){if(!rw)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 rw}function sw(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");rw=e}function ow(){rw=void 0}function aw(){return rw}function cw(e){return iw("createFlowRenderer").createRenderer(e)}function lw(e){return iw("createViewportController").createViewportController(e)}function uw(e,t){return iw("attachZoomControl").attachZoomControl(e,t)}function dw(e,t){return iw("attachMinimap").attachMinimap(e,t)}function pw(e,t){const n={...e,metadata:{...e.metadata??{}}},r=n.metadata,i=r.ivy=r.ivy?{...r.ivy}:{},s=i.view??{},o={x:t.viewport?.x??s.viewport?.x??0,y:t.viewport?.y??s.viewport?.y??0,zoom:t.viewport?.zoom??s.viewport?.zoom??1},a={...s.nodes??{}};return t.nodes.forEach(e=>{e&&e.id&&(a[e.id]={x:e.x,y:e.y})}),i.view={...s,viewport:o,nodes:a},n}var fw={setRendererProvider:sw,resetRendererProvider:ow,getRendererProvider:aw,createFlowRenderer:cw,createViewportController:lw,attachZoomControl:uw,attachMinimap:dw,mergeViewSnapshotIntoNotebook:pw,computeFlowLayout:nw,gridFallbackPosition:ew,get rendererProvider(){return rw}},hw=Object.freeze({__proto__:null,attachMinimap:dw,attachZoomControl:uw,computeFlowLayout:nw,createFlowRenderer:cw,createViewportController:lw,default:fw,getRendererProvider:aw,gridFallbackPosition:ew,mergeViewSnapshotIntoNotebook:pw,resetRendererProvider:ow,setRendererProvider:sw});function mw(e,t,n){return{path:e,message:t,severity:"error",code:n}}function gw(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const yw="WF_INVALID_VERSION",ww="WF_INVALID_EDGE_REF",vw=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function bw(e){return"string"==typeof e&&vw.test(e)}const Iw=new class{#en=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.#en.set(e,t)}unregister(e){return this.#en.delete(e)}get(e){return this.#en.get(e)}list(){return Array.from(this.#en.keys())}clear(){this.#en.clear()}},kw={id:"capability-not-declared",severity:"error",check(e,t){const n=t.hasCapability??(e=>!!t.getCapability?.(e));if(!t.hasCapability&&!t.getCapability)return[];const r=[];for(let t=0;t<e.graph.nodes.length;t++){const i=e.graph.nodes[t];if(i.disabled)continue;const s=i.ref;if("ivyNode"!==s.kind&&"workflow"!==s.kind)continue;const o=s.id;"string"==typeof o&&0!==o.length&&(n(o)||r.push({ruleId:"capability-not-declared",severity:"error",message:`Capability "${o}" is not declared in the unified registry — flow refs must exist in at least one origin (extension / instruction-class / ivy-node)`,path:`graph.nodes[${t}].ref.id`,nodeId:i.id,code:"WF_UNKNOWN_CAPABILITY"}))}return r}},Ew={id:"unreachable-node",severity:"warning",check(e){const t=[],n=e.graph.nodes.filter(e=>!e.disabled),r=new Set(n.map(e=>e.id)),i=e.graph.entryNodeId;if(!i||!r.has(i))return t;const s=new Map;for(const e of r)s.set(e,[]);for(const t of e.graph.edges)r.has(t.fromId)&&r.has(t.toId)&&s.get(t.fromId).push(t.toId);const o=new Set([i]),a=[i];for(;a.length>0;){const e=a.shift();for(const t of s.get(e)??[])o.has(t)||(o.add(t),a.push(t))}for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];r.disabled||(o.has(r.id)||t.push({ruleId:"unreachable-node",severity:"warning",message:`Node "${r.id}" is unreachable from entry node "${i}"`,path:`graph.nodes[${n}].id`,nodeId:r.id,code:"WF_UNREACHABLE_NODE"}))}return t}},Sw={id:"dep-cycle",severity:"error",check(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=new Map,i=new Map;for(const e of t)r.set(e.id,0),i.set(e.id,[]);for(const t of e.graph.edges)n.has(t.fromId)&&n.has(t.toId)&&(i.get(t.fromId).push(t.toId),r.set(t.toId,(r.get(t.toId)??0)+1));const s=[];for(const[e,t]of r.entries())0===t&&s.push(e);let o=0;const a=new Set;for(;s.length>0;){const e=s.shift();a.add(e),o++;for(const t of i.get(e)??[])r.set(t,(r.get(t)??0)-1),0===(r.get(t)??0)&&s.push(t)}if(o===t.length)return[];const c=[],l=[];for(const e of t)a.has(e.id)||l.push(e.id);return c.push({ruleId:"dep-cycle",severity:"error",message:`Workflow graph contains a cycle among enabled nodes: ${l.join(", ")}`,path:"graph.edges",code:"WF_CYCLE"}),c}},Aw={id:"idempotency-required-but-no-key",severity:"error",check(e,t){if(!t.getCapability)return[];const n=[];for(let r=0;r<e.graph.nodes.length;r++){const i=e.graph.nodes[r];if(i.disabled)continue;if("ivyNode"!==i.ref.kind)continue;const s=i.ref.id;if("string"!=typeof s||0===s.length)continue;const o=t.getCapability(s);if(!o)continue;const a=o.defaults;if(!("required"===a?.execution?.idempotency))continue;const c=i.executionOverride;("none"===c?.idempotency||!0===i.data?.skipIdempotencyKey)&&n.push({ruleId:"idempotency-required-but-no-key",severity:"error",message:`Capability "${s}" declares idempotency: 'required' but node "${i.id}" opts out of key derivation — write/retry semantics will double-execute on a network retry`,path:`graph.nodes[${r}]`,nodeId:i.id,code:"WF_IDEMPOTENCY_REQUIRED"})}return n}};function xw(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function Cw(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 Tw={id:"schema-mismatch",severity:"warning",check(e,t){if(!t.getCapability)return[];const n=[],r=new Map(e.graph.nodes.map(e=>[e.id,e]));for(let i=0;i<e.graph.edges.length;i++){const s=e.graph.edges[i],o=r.get(s.fromId),a=r.get(s.toId);if(!o||!a)continue;if(o.disabled||a.disabled)continue;const c=xw(o.ref),l=xw(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=Cw(p,s.fromPath),m=Cw(f,s.toPath);h&&m&&(h.type&&m.type&&h.type!==m.type&&n.push({ruleId:"schema-mismatch",severity:"warning",message:`Edge ${s.fromId} → ${s.toId} type mismatch: upstream emits "${h.type}" but downstream expects "${m.type}"`,path:`graph.edges[${i}]`,code:"WF_SCHEMA_MISMATCH"}))}return n}},_w=["while","forEach"],Pw={id:"infinite-loop",severity:"error",check(e){const t=[];for(let n=0;n<e.graph.nodes.length;n++){const r=e.graph.nodes[n];if(r.disabled)continue;if("primitive"!==r.ref.kind)continue;const i=r.ref.primitive;if(!_w.includes(i))continue;const s=r.data,o=s?.maxIterations;"number"==typeof o?o<=0&&t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" has maxIterations=${o} — loops with zero or negative caps never execute the body`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"}):t.push({ruleId:"infinite-loop",severity:"error",message:`${i} primitive on node "${r.id}" is missing maxIterations — substrate refuses to ship unbounded loops`,path:`graph.nodes[${n}].data.maxIterations`,nodeId:r.id,code:"WF_INFINITE_LOOP"})}return t}};function Nw(e,t,n){let r=0;for(const i of e.graph.nodes){if(i.disabled)continue;if("workflow"!==i.ref.kind)continue;const e=i.ref,s=e.id??"<unnamed>";if(n.has(s))return t+1;if(!e.inline)continue;const o=new Set(n);o.add(s);const a=1+Nw(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const $w={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Nw(e,n,new Set([i]));return s<=n||r.push({ruleId:"subflow-depth-exceeded",severity:"error",message:`Flow "${i}" has a statically-derivable inline subflow chain of depth ${s} — exceeds cap (${n}). Direct cycles count as depth > cap.`,path:"graph",code:"WF_SUBFLOW_DEPTH_EXCEEDED"}),r}},Mw=[kw,Ew,Sw,Aw,Tw,Pw,$w];const Rw=new class{#$e=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#$e.values())try{const i=t.check(e,r);i&&i.length>0&&n.push(...i)}catch(e){n.push({ruleId:t.id,severity:"info",message:`Lint rule "${t.id}" threw during analysis: ${String(e?.message??e)}`,code:"WF_LINT_RULE_ERROR"})}return{ok:!n.some(e=>"error"===e.severity),issues:n}}register(e){if(!e||"function"!=typeof e.check)throw new Error("FlowLinter.register: rule must have a check(spec, ctx) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("FlowLinter.register: rule.id must be a non-empty string");this.#$e.set(e.id,e)}unregister(e){return this.#$e.delete(e)}list(){return Array.from(this.#$e.keys())}reset(){this.#$e.clear();for(const e of Mw)this.#$e.set(e.id,e)}};function Ow(e,t,n){if(t===n)return[];const r=new Map;for(const t of e.values()){const e=r.get(t.from)??[];e.push(t),r.set(t.from,e)}const i=new Set([t]),s=new Map,o=[t];for(;o.length>0;){const e=o.shift();if(e===n)break;for(const t of r.get(e)??[])if(!i.has(t.to)){if(i.add(t.to),s.set(t.to,t),t.to===n){o.length=0;break}o.push(t.to)}}if(!i.has(n))return;const a=[];let c=n;for(;c!==t;){const e=s.get(c);if(!e)return;a.unshift(e),c=e.from}return a}function Lw(e){return e.map(e=>`${e.from}=>${e.to}`)}function jw(e,t){return`${e}=>${t}`}const Dw=new class{#tn=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.#tn.set(jw(e.from,e.to),e)}unregister(e,t){return this.#tn.delete(jw(e,t))}find(e,t){return this.#tn.get(jw(e,t))}list(){return Array.from(this.#tn.values())}clear(){this.#tn.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,i=e.targetVersion;if(!bw(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(!bw(i))return{ok:!1,reason:"invalid-result",message:`targetVersion "${String(i)}" is not a valid semver — substrate refuses to migrate to an unrecognized version.`,appliedTransformers:[]};if(r===i)return{ok:!0,document:e.document,appliedTransformers:[],fromVersion:r,toVersion:i};if("reject"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'reject'. Re-invoke with 'auto-migrate' to apply registered transformers.`,appliedTransformers:[]};if("warn"===n)return{ok:!1,reason:"no-migrate-policy",message:`Version mismatch ${r} → ${i} and policy is 'warn'. Substrate did not migrate; downstream consumers may see a stale IR.`,partialDocument:e.document,appliedTransformers:[]};const s=("function"==typeof t.__plan?t.__plan.bind(t):(e,n)=>Ow(new Map(t.list().map(e=>[`${e.from}=>${e.to}`,e])),e,n))(r,i);if(!s||0===s.length)return{ok:!1,reason:"no-path",message:`No transformer chain from ${r} to ${i}. Register transformers via punica.flow.primitives.migrations.register(...).`,appliedTransformers:[]};let o=e.document;const a=[];for(const e of s)try{const t=e.transform(o);if(!t||"object"!=typeof t)return{ok:!1,reason:"invalid-result",message:`Transformer ${e.from}=>${e.to} returned a non-object — substrate refuses to thread an invalid document through the chain.`,partialDocument:o,appliedTransformers:Lw(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:Lw(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:Lw(a)}}return{ok:!0,document:o,appliedTransformers:Lw(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Ow(this.#tn,e,t)}};function Fw(){return Date.now()}class Bw{#Me=new Map;#tt=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.#Me.set(e.id,n),this.#mt({type:"registered",triggerId:e.id,kind:e.kind,ts:Fw()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#Me.get(e.id)===n&&(this.#Me.delete(e.id),this.#mt({type:"unregistered",triggerId:e.id,ts:Fw()}))}}}unregister(e){const t=this.#Me.get(e);return!!t&&(t.unsubscribed=!0,this.#Me.delete(e),this.#mt({type:"unregistered",triggerId:e,ts:Fw()}),!0)}list(){return Array.from(this.#Me.values()).map(e=>e.trigger)}subscribe(e){return this.#tt.add(e),()=>{this.#tt.delete(e)}}async fire(e,t){const n=this.#Me.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Fw()}-${Math.floor(1e6*Math.random())}`,i=Fw();this.#mt({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),ey({name:"flow.trigger.fired",source:"flow:triggers",correlationId:r,payload:{triggerId:e,kind:n.trigger.kind,flowId:n.trigger.flowId,firedAtMs:i,payload:t??null}});try{return await n.callback({triggerId:e,firedAtMs:i,payload:t,correlationId:r}),!0}catch(t){return this.#mt({type:"error",triggerId:e,ts:Fw(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#Me.values())e.unsubscribed=!0;this.#Me.clear(),this.#tt.clear()}#mt(e){for(const t of this.#tt)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const qw=new Bw;let Uw=qw;const Vw={get manager(){return Uw},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()");Uw!==e&&Uw instanceof Bw&&Uw.clear(),Uw=e},resetProvider(){Uw instanceof Bw&&Uw.clear(),Uw=qw}};function Ww(e,t){return`${e}=>${t}`}const Kw={migrators:new class{#nn=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.#nn.set(Ww(e.from,e.to),e)}unregister(e,t){return this.#nn.delete(Ww(e,t))}find(e,t){return this.#nn.get(Ww(e,t))}list(){return Array.from(this.#nn.values())}clear(){this.#nn.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}},Gw={...Gy,agents:Yy,engine:{manager:_y,statusStateMachine:Hy,subscribeNodeStatuses:function(e,t){const n=new Set(e.nodeIds);let r=null;const i=(e,i,s)=>{const o=String(e??"");if(!o||!n.has(o))return;const a=String(i??"").toUpperCase(),c=Zy[a];if(!c)return;const l=s?String(s):null,u=null!==l&&l!==r;u&&(r=l),t({nodeId:o,status:c,runId:l,isNewRun:u,stepStatus:a})},s=e=>{const t=e?.payload?.payload??e?.payload??{};switch(e?.name){case"workflow.stepStarted":return i(t?.step?.stepId,t?.step?.status??"RUNNING",t?.runId);case"workflow.stepUpdated":return i(t?.stepId,t?.patch?.status,t?.runId);case"workflow.stepFinished":return i(t?.step?.stepId,t?.step?.status,t?.runId);default:return}};let o=null;try{o=punica.kernel.Events.manager.subscribeMany(Qy,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:hw,validateWorkflowDocument:function(e,t){const n=[],r=[],i=t?.mode??"best-effort",s=t?.hasCapability;if(!e||"ivy.workflow/v0.1"!==e.apiVersion)return n.push(mw("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',yw)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(mw("kind",'kind must equal "Workflow"',yw)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!bw(o)){const e=mw("version","version must be a semver string (major.minor.patch[-prerelease][+build]); got "+("string"==typeof o?`"${o}"`:typeof o),"WF_INVALID_SEMVER");"strict"===i?n.push(e):r.push({...e,severity:"warning"})}if(!e.graph||"object"!=typeof e.graph)return n.push(mw("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(mw("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(mw("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(mw(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(mw(`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(mw(`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(mw(`graph.nodes[${t}].ref.id`,"ref.id is required for ivyNode/workflow refs")),"primitive"===r.kind){const e=["if","else","forEach","while","try","catch","finally","lambda"],i=r.primitive;"string"==typeof i&&e.includes(i)||n.push(mw(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(mw(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(mw(`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(mw("graph.nodes","flow-input node is required when edges reference it")),f&&!d&&n.push(mw("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(mw("graph.entryNodeId",`entryNodeId "${e.graph.entryNodeId}" must reference an existing node`,"WF_INVALID_ENTRY")),c.forEach((e,t)=>{const r=String(e?.fromId??""),i=String(e?.toId??"");r||n.push(mw(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(mw(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(mw(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,ww)),i&&!l.has(i)&&n.push(mw(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,ww))}),"strict"===i&&function(e,t,n){const r=e.filter(e=>!e.disabled),i=new Set(r.map(e=>e.id)),s=t.filter(e=>i.has(e.fromId)&&i.has(e.toId)),o=new Map,a=new Map;for(const e of r)o.set(e.id,0),a.set(e.id,[]);for(const e of s)a.get(e.fromId).push(e.toId),o.set(e.toId,(o.get(e.toId)??0)+1);const c=[];for(const[e,t]of o.entries())0===t&&c.push(e);let l=0;for(;c.length;){const e=c.shift();l++;for(const t of a.get(e)??[])o.set(t,(o.get(t)??0)-1),0===(o.get(t)??0)&&c.push(t)}l!==r.length&&n.push(mw("edges","Workflow graph is not a DAG (cycle detected among enabled nodes).","WF_CYCLE"))}(a,c,n),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)&&function(e,t,n,r){const i=e.filter(e=>!e.disabled),s=new Set(i.map(e=>e.id));if(!s.has(n))return;const o=t.filter(e=>s.has(e.fromId)&&s.has(e.toId)),a=new Set,c=[n];for(a.add(n);c.length>0;){const e=c.shift();for(const t of o)t.fromId!==e||a.has(t.toId)||(a.add(t.toId),c.push(t.toId))}for(const t of i)if(!a.has(t.id)){const i=e.indexOf(t);r.push(gw(`graph.nodes[${i}].id`,`Node "${t.id}" is unreachable from entry node "${n}"`,"WF_UNREACHABLE_NODE"))}}(a,c,e.graph.entryNodeId,r),s&&a.forEach((e,t)=>{if(e.disabled)return;const o=e.ref;if(!o||"ivyNode"!==o.kind&&"workflow"!==o.kind)return;const a=o.id;if("string"!=typeof a||0===a.length)return;if(s(a))return;("strict"===i?n:r).push(("strict"===i?mw:gw)(`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:Iw,linter:Rw,migrations:Dw,checkpoints:Kw},triggers:Vw};class Yw{name=Gn.EXTENSIONS.MANAGER;version="1.0.0";dependencies=[Gn.KERNEL.COMMANDS,Gn.KERNEL.EVENTS,Gn.RUNTIME.WORKSPACE];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.COMMANDS),s=r.getState(Gn.KERNEL.EVENTS),o=r.getState(Gn.RUNTIME.WORKSPACE),a=r.getState(Gn.SHELL.LAYOUT);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before extensions.manager");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before extensions.manager");if(o!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before extensions.manager");if(void 0!==a&&a!==e.BOOTSTRAPPED)throw new Error("shell.layout must be bootstrapped before extensions.manager");if(!n.extensions?.manager)throw new Error("Extensions manager not available")}async start(e){}}class zw{name=Gn.FLOW.VALIDATOR;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}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 Jw(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 Hw{prepareExecutionConfig(e){const t=Jw(e);if(!t)return{};const n=$g(),r=n?.getSpec?.(t);return{capabilityDefaults:Mg(r)}}async acquireResources(e,t,n){const r=Jw(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 sy.acquire(n,e.concurrency.max),()=>{sy.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=Jw(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Ng();if(!o)throw new Error("[FlowEngine] Capability gateway not available");const a=function(e,t){return`${e.attemptCorrelationId}::${t}`}(t,e.id),c=await o.call(i,s,{sessionId:t.workspaceId??"default",workspaceId:t.workspaceId,actor:{type:"extension",extensionName:"flow:engine"},origin:{kind:"workflow",id:t.traceId},trace:{traceId:t.traceId,parentSpanId:t.rootSpanId},policy:{mode:"execute"}},a),l=$g(),u=l?.getSpec?.(i),d=u?.defaults?.dataClassification,p=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`${i}.result`,payload:c,meta:{source:"capability.call",capabilityId:i},redactionPolicy:e.redactionPolicy,surface:"output",capabilityClassification:d,sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:_g(Tg(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Qw(e){return e.data??{}}function Zw(e){return e.nodeOutputs??new Map}async function Xw(e,t,n,r,i){const s=await e.artifactStore.writeArtifact(t.traceId,n.id,{type:"json",name:`primitive.${r}.decision`,payload:i,meta:{source:"primitive",primitive:r},redactionPolicy:n.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:_g(Tg(i,0),320),artifactIds:[s.id]}}async function ev(e,t,n){const r=Qw(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&&!r.bodyCapabilityId)throw new Error(`[primitive:forEach] bodyFlowId or bodyCapabilityId is required on node "${e.id}"`);const i=uy(r.collection,Zw(t));if(!i.ok&&"missing-node"!==i.reason)throw new Error(`[primitive:forEach] collection did not resolve (${i.reason}) on node "${e.id}"`);const s=i.ok?i.value:null,o=Array.isArray(s)?s:[],a=o.length>r.maxIterations,c=Math.min(o.length,r.maxIterations);if(r.bodyCapabilityId)return async function(e,t,n,r,i,s){const o=Ng();if(!o)throw new Error("[primitive:forEach] Capability gateway not available");const a=r.itemBinding??"item",c=r.bodyInput&&"object"==typeof r.bodyInput?r.bodyInput:{},l=[];for(let n=0;n<i.length;n++){let s;try{s=await o.call(r.bodyCapabilityId,{...c,[a]:i[n]},{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.spanId},policy:{mode:"execute"}},`${t.attemptCorrelationId}::${e.id}::${n}`)}catch(e){const t=e instanceof Error?e.message:String(e),s=e?.code;if("CAPABILITY_APPROVAL_REQUIRED"===s)throw new Error(`[primitive:forEach] item ${n+1} of ${i.length} needs a person to approve ${r.bodyCapabilityId}, and a for-each step cannot wait for one; allow it with a policy rule or move it out of the loop`);throw new Error(`[primitive:forEach] item ${n+1} of ${i.length} failed in ${r.bodyCapabilityId}: ${t}`)}l.push(s??null)}const u={results:l,count:l.length,truncated:s,bodyCapabilityId:r.bodyCapabilityId},d=await Xw(n,t,e,"forEach",u);return{...d,output:u}}(e,t,n,r,o.slice(0,c),a);const l={bodyFlowId:r.bodyFlowId,itemBinding:r.itemBinding??"item",maxIterations:r.maxIterations,plannedIterations:c,sourceLength:o.length,truncated:a};return{...await Xw(n,t,e,"forEach",l),output:l}}class tv{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=Qw(e),i=uy(r.predicate,Zw(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:dy(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Xw(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Xw(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return ev(e,t,n);case"while":return async function(e,t,n){const r=Qw(e);if("number"!=typeof r.maxIterations||r.maxIterations<0)throw new Error(`[primitive:while] maxIterations is required (>= 0) on node "${e.id}"`);if(!r.bodyFlowId)throw new Error(`[primitive:while] bodyFlowId is required on node "${e.id}"`);const i=uy(r.predicate,Zw(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=dy(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Xw(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Qw(e);if(!r.tryBodyFlowId)throw new Error(`[primitive:try] tryBodyFlowId is required on node "${e.id}"`);const i={tryBodyFlowId:r.tryBodyFlowId,catchBodyFlowId:r.catchBodyFlowId??null,finallyBodyFlowId:r.finallyBodyFlowId??null};return{...await Xw(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Xw(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Xw(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Qw(e),i=r.lambdaId??"";if("string"!=typeof i||0===i.length)throw new Error(`[primitive:lambda] lambdaId is required on node "${e.id}"`);const s=Iw.get(i);if(!s)throw new Error(`[primitive:lambda] lambdaId "${i}" is not registered (node "${e.id}")`);let o=null;if(void 0!==r.input){const n=uy(r.input,Zw(t));if(!n.ok)throw new Error(`[primitive:lambda] input did not resolve (${n.reason}) on node "${e.id}"`);o=n.value}const a=await s(o,{nodeId:e.id,attemptCorrelationId:t.attemptCorrelationId,traceId:t.traceId}),c=await n.artifactStore.writeArtifact(t.traceId,e.id,{type:"json",name:`primitive.lambda.${i}.result`,payload:a,meta:{source:"primitive",primitive:"lambda",lambdaId:i},redactionPolicy:e.redactionPolicy,surface:"output",sizeBudget:t.runBudget?.artifactBudget});return{outputsPreview:_g(Tg(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 nv{async execute(e,t){return{output:t.runInput??null}}}class rv{async execute(e,t){return{output:t.resolvedInput??null}}}let iv=!1;class sv{name=Gn.FLOW.ENGINE;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.KERNEL.POLICY,Gn.KERNEL.COMMANDS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.EVENTS),s=r.getState(Gn.KERNEL.POLICY),o=r.getState(Gn.KERNEL.COMMANDS);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before flow.engine");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before flow.engine");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.commands must be bootstrapped before flow.engine");if(iv||(cy.register("ivyNode",new Hw),cy.register("primitive",new tv),cy.register("flowInput",new nv),cy.register("flowOutput",new rv),iv=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class ov{name=Gn.FLOW.SHELL;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before shell.flow");if(!n.flow?.shell)throw new Error("Flow shell API not available")}async start(e){}}class av{name=Gn.KERNEL.EVENTS;version="1.0.0";dependencies=[];#je=e.CREATED;#l=null;get state(){return this.#je}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 cv{name=Gn.KERNEL.COMMANDS;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class lv{name=Gn.KERNEL.POLICY;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.policy");if(!n.kernel?.Policy?.manager)throw new Error("Policy manager not available")}async start(e){}}class uv{name=Gn.KERNEL.HISTORY;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class dv{name=Gn.KERNEL.TIME_SERVER;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class pv{name=Gn.KERNEL.TASKS;version="1.0.0";dependencies=[Gn.RUNTIME.TERMINALS,Gn.RUNTIME.WORKSPACE];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.RUNTIME.TERMINALS),s=r.getState(Gn.RUNTIME.WORKSPACE);if(i!==e.BOOTSTRAPPED)throw new Error("runtime.terminals must be bootstrapped before kernel.tasks");if(s!==e.BOOTSTRAPPED)throw new Error("runtime.workspace must be bootstrapped before kernel.tasks");if(!n.kernel?.Tasks)throw new Error("Tasks API not available")}async start(e){}}class fv{name=Gn.KERNEL.NOTIFICATIONS;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class hv{name=Gn.KERNEL.AI;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.KERNEL.POLICY,Gn.KERNEL.LLM];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.EVENTS),s=r.getState(Gn.KERNEL.POLICY),o=r.getState(Gn.KERNEL.LLM);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.ai");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.ai");if(o!==e.BOOTSTRAPPED)throw new Error("kernel.llm must be bootstrapped before kernel.ai");if(!n.kernel?.AI?.manager?.initialize)throw new Error("AI manager not available");n.kernel.AI.manager.initialize()}async start(e){}}let mv=class{name=Gn.KERNEL.LLM;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS,Gn.KERNEL.POLICY];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(Gn.KERNEL.EVENTS),s=r.getState(Gn.KERNEL.POLICY);if(i!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before kernel.llm");if(s!==e.BOOTSTRAPPED)throw new Error("kernel.policy must be bootstrapped before kernel.llm");if(!n.kernel?.llm?.manager)throw new Error("LLM manager not available");const o=n;if(o.kernel||(o.kernel={}),o.kernel.llm||(o.kernel.llm={}),!Object.prototype.hasOwnProperty.call(o.kernel.llm,"CodegenBundleV0_1Schema"))try{Object.defineProperty(o.kernel.llm,"CodegenBundleV0_1Schema",{value:yi,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class gv{name=Gn.RUNTIME.FS;version="1.0.0";dependencies=[];#je=e.CREATED;get state(){return this.#je}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class yv{name=Gn.RUNTIME.SEARCH;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.search");if(!n.runtime?.search)throw new Error("Search facade not available")}async start(e){}}class wv{name=Gn.RUNTIME.VCS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.vcs");if(!n.runtime?.vcs)throw new Error("VCS facade not available")}async start(e){}}class vv{name=Gn.RUNTIME.WORKSPACE;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.workspace");if(!n.runtime?.workspace)throw new Error("Workspace facade not available")}async start(e){}}class bv{name=Gn.RUNTIME.LLM;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.llm");if(!n.runtime?.llm)throw new Error("LLM facade not available")}async start(e){}}class Iv{name=Gn.RUNTIME.TASKS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.tasks");if(!n.runtime?.tasks)throw new Error("Tasks facade not available")}async start(e){}}class kv{name=Gn.RUNTIME.SECRETS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.secrets");if(!n.runtime?.secrets)throw new Error("Secrets API not available")}async start(e){}}class Ev{name=Gn.RUNTIME.TERMINALS;version="1.0.0";dependencies=[Gn.KERNEL.EVENTS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(Gn.KERNEL.EVENTS)!==e.BOOTSTRAPPED)throw new Error("kernel.events must be bootstrapped before runtime.terminals");if(!n.runtime?.terminals)throw new Error("Terminals facade not available")}async start(e){}}const Sv=".punica/policy.yaml",Av=void 0;async function xv(){const e=function(){const e=globalThis;return e.punica?.runtime?.fs}(),t=e?.readFile;if("function"!=typeof t)return;if("function"==typeof e?.exists)try{if(!await e.exists(Sv))return}catch{}let n;try{n=await t(Sv,{encoding:"utf8"})}catch{return}if("string"!=typeof n||""===n.trim())return;const{parse:r}=await Promise.resolve().then(function(){return am});return r(n)}function Cv(e){for(const t of e.problems){const e=t.path?` at ${t.path}`:"";console.warn(`[Punica] ${Sv}${e}: ${t.message}`)}try{se.publishEvent({name:e.problems.length>0?"policy.rulesRejected":"policy.rulesLoaded",envelope:{id:se.createCorrelationId(),timestampMs:Date.now(),source:"runtime:policy:rules",kind:e.problems.length>0?"warn":"info"},payload:{file:Sv,present:e.present,installed:e.installed.map(e=>({name:e.name,rules:e.rules.length,digest:e.digest})),retired:e.retired,problems:e.problems}})}catch{}}async function Tv(){const e={installed:[],retired:[],problems:[],present:!1};let t;try{t=await xv()}catch(t){return e.problems.push({path:"",message:`could not be parsed: ${t?.message??String(t)}`}),e.present=!0,e.retired=_v(new Set),Cv(e),e}e.present=void 0!==t;const{templates:n,problems:r}=tt(t??{});e.problems=r;const i=new Set;for(const t of n){const n=await Oe(t.rules);vt.saveTemplate(t.name,{...t,source:"file",digest:n},Av),i.add(t.name),e.installed.push({...t,source:"file",digest:n})}return e.retired=_v(i),Cv(e),e}function _v(e){const t=[];for(const n of vt.listTemplates(Av))"file"===n.source&&(e.has(n.name)||vt.deleteTemplate(n.name,Av)&&t.push(n.name));return t}class Pv{name=Gn.RUNTIME.POLICY_RULES;version="1.0.0";dependencies=[Gn.KERNEL.POLICY,Gn.RUNTIME.FS];#je=e.CREATED;get state(){return this.#je}async bootstrap(t){this.#je=e.BOOTSTRAPPING;try{await Tv()}catch(e){console.warn("[Punica] Policy rules could not be loaded:",e?.message??e)}this.#je=e.BOOTSTRAPPED}async start(t){this.#je=e.STARTING;try{punica.kernel.Commands.manager.registerCommand("policy.rules.reload",{title:"Policy: reload workspace rules",execute:async()=>await Tv()})}catch(e){console.warn("[Punica] policy.rules.reload could not be registered:",e?.message??e)}this.#je=e.STARTED}}function Nv(){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 $v(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 Mv(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 Rv(e,n,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await t(),actor:{type:"user",id:ye()},origin:{kind:n,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function Ov(){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=Nv();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");$v("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await Rv("workspace.readFile","command",t))})}catch(e){Mv("capability.workspace.readFile.error",t,{error:String(e?.message??e)})}}}),e("workspace.writeFile",{title:"Core: workspace.writeFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=String(e?.content??""),i=Nv();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await Rv("workspace.writeFile","command",t)),$v("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Mv("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();$v("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){Mv("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{$v("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await Rv("vcs.status","command",t))})}catch(e){Mv("capability.vcs.status.error",t,{error:String(e?.message??e)})}}}),e("tasks.runCommand",{title:"Core: tasks.runCommand",execute:async(e,t)=>{try{const n=String(e?.command??""),r=Array.isArray(e?.args)?e.args.map(String):[],i=null!=e?.cwd?String(e.cwd):void 0,s=e?.env&&"object"==typeof e.env?e.env:void 0;$v("capability.tasks.runCommand.result",t,{command:n,args:r,cwd:i,...await punica.runtime.capabilities.gateway.call("tasks.runCommand",{command:n,args:r,cwd:i,env:s},await Rv("tasks.runCommand","command",t))})}catch(e){Mv("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?$v("capability.llm.invoke.result",t,r):Mv(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Mv(n,t,i),i}}}),e("llm.plan",{title:"Core: llm.plan",execute:async(e,t)=>{const n="capability.llm.plan.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const r=await punica.kernel.llm.manager.api.plan(e);r.ok?$v("capability.llm.plan.result",t,r):Mv(n,t,r)}catch(e){Mv(n,t,{ok:!1,error:String(e?.message??e),metadata:{instructionClass:"planner",role:"planner"}})}}}),e("llm.generate-code",{title:"Core: llm.generate-code",execute:async(e,t)=>{const n="capability.llm.generate-code.result",r="capability.llm.generate-code.error";try{if(!punica.kernel?.llm?.manager?.api)throw new Error("kernel.llm not available");const i=await punica.kernel.llm.manager.api.generateCode(e);if(i.ok)if(i.structured&&"object"==typeof i.structured){const e=i.structured;if("0.1"===e.specVersion&&Array.isArray(e.files)){const r=await(punica.runtime.workspace?.getCurrent?.());if(!r?.rootUri)throw new Error("No active workspace");const s=r.rootUri.replace(/^file:\/\//,""),o=punica.shell?.View?.showChangesPreview;if("function"!=typeof o)throw new Error("UnsupportedError: shell.View.showChangesPreview is not available (headless substrate — no shell contribution)");$v(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 gi(e,s);if(t.errors.length>0)throw new Error(`Failed to apply some files:\n${t.errors.map(e=>`${e.path}: ${e.error}`).join("\n")}`)}})?{...i,metadata:{...i.metadata,applied:!0}}:{...i,metadata:{...i.metadata,applied:!1,cancelled:!0}})}else $v(n,t,i)}else $v(n,t,i);else Mv(r,t,i)}catch(e){Mv(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?$v("capability.llm.edit-workflow.result",t,r):Mv(n,t,r)}catch(e){Mv(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 Rv("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(Yn.SHELL.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(Yn.SHELL.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(Yn.SHELL.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const Lv="1.0.0",jv=bi,Dv={},Fv=Ad,Bv=Gm,qv=Gw,Uv=new class{#rn=new Map;#in=new Map;#sn=new Map;register(t){if(this.#rn.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#rn.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#rn.set(t.name,t),this.#in.set(t.name,e.CREATED)}get(e){return this.#rn.get(e)}getAll(){return Array.from(this.#rn.values())}resolveBootstrapOrder(){return this.#on()}resolveStartOrder(){return this.#on()}#on(){const e=new Set,t=new Set,n=[],r=i=>{if(t.has(i)){const e=Array.from(t).concat(i);throw new Error(`Circular dependency detected: ${e.join(" → ")}`)}if(e.has(i))return;t.add(i);const s=this.#rn.get(i);if(!s)throw new Error(`Module ${i} not found`);for(const e of s.dependencies)r(e);t.delete(i),e.add(i),n.push(i)};for(const t of this.#rn.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.#rn.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#in.set(n,e.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#in.set(n,e.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#in.set(n,e.BOOTSTRAP_FAILED),this.#sn.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.#rn.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#in.get(n);if(r!==e.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#in.set(n,e.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#in.set(n,e.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#in.set(n,e.START_FAILED),this.#sn.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.#in.get(n)===e.STARTED&&this.#in.set(n,e.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#in.get(e)}areAllModulesReady(){for(const[t,n]of this.#rn){if(this.#in.get(t)!==e.READY)return!1}return!0}getError(e){return this.#sn.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#rn.keys())t.includes(n)&&e.push(n);return e}};function Vv(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:Lv,kernel:jv,shell:Dv,runtime:Fv,extensions:Bv,flow:qv};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=Pt;const t=e.debug??{};t.logTrinityCatalog=Du,t.logTrinityCatalogVerbose=Fu,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=Du,n.logTrinityCatalogVerbose=Fu);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{Ov(),console.log("[Punica] Core commands registered")}catch(e){console.error("[Punica] Failed to register core commands:",e?.message??e,e?.stack)}console.log("[Punica] Initialization completed successfully")}catch(e){throw console.error("[Punica] CRITICAL: Initialization failed:",e?.message??e,e?.stack),e}}async function Wv(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 _t)t.facade&&Object.assign(e,t.facade);return e}()));const n=Gt.manager;for(const e of function(){const e=[];for(const t of _t)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 _t)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(Uv.register(new av),Uv.register(new cv),Uv.register(new uv),Uv.register(new dv),Uv.register(new fv),Uv.register(new zw),Uv.register(new lv),Uv.register(new mv),Uv.register(new hv),Uv.register(new sv),Uv.register(new gv),Uv.register(new yv),Uv.register(new wv),Uv.register(new vv),Uv.register(new bv),Uv.register(new kv),Uv.register(new Ev),Uv.register(new Iv),Uv.register(new od),Uv.register(new Pv),Uv.register(new pv),r){const e=Nt(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(Uv.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}Uv.register(new Yw),console.log(`[Punica] Module registry initialized with ${Uv.getAll().length} modules`),await Uv.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}}async function Kv(){try{console.log("[Punica] Starting system..."),await Uv.startAll(),Uv.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:Lv}}),console.log("[Punica] System started successfully"),Du()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}}Pt({moduleFactories:{"flow.shell":()=>new ov}});var Gv=Object.freeze({__proto__:null,StdioTransport:class{#an;#cn;#ln;#un=null;#dn=null;#pn=null;#fn=null;#hn=null;#mn=new Map;#gn=1;#yn="";constructor(e,t=[],n={}){this.#an=e,this.#cn=t,this.#ln=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#wn(e):await this.#vn()}async#wn(e){this.#pn=e;const{sessionId:t}=await e.spawn({command:this.#an,args:this.#cn,env:this.#ln});this.#dn=t,this.#fn=e.onData(e=>{e.sessionId===t&&this.#bn(e.chunk)}),this.#hn=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.#mn.values())e(n);this.#mn.clear()})}async#vn(){const e=await import(
2
+ /* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#un=e.spawn(this.#an,this.#cn,{env:{...n,...this.#ln},stdio:["pipe","pipe","inherit"]}),this.#un.stdout.setEncoding("utf8"),this.#un.stdout.on("data",e=>{this.#bn(e)}),this.#un.on("error",e=>{for(const{reject:t}of this.#mn.values())t(e);this.#mn.clear()})}#bn(e){let t;for(this.#yn+=e;-1!==(t=this.#yn.indexOf("\n"));){const e=this.#yn.slice(0,t).trim();this.#yn=this.#yn.slice(t+1),e&&this.#In(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#kn(n)}async request(e,t={}){const n=this.#gn++;return new Promise((r,i)=>{this.#mn.set(n,{resolve:r,reject:i});const s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#kn(s)}catch(e){this.#mn.delete(n),i(e instanceof Error?e:new Error(String(e)))}})}#kn(e){if(this.#pn&&this.#dn)this.#pn.write(this.#dn,e);else{if(!this.#un?.stdin)throw new Error("MCP stdio transport is not connected");this.#un.stdin.write(e)}}close(){this.#fn?.(),this.#hn?.(),this.#fn=null,this.#hn=null,this.#pn&&this.#dn&&this.#pn.close(this.#dn),this.#un?.kill(),this.#un=null,this.#dn=null,this.#pn=null;for(const{reject:e}of this.#mn.values())e(new Error("MCP stdio transport closed"));this.#mn.clear()}#In(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#mn.get(t.id);n&&(this.#mn.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var Yv=Object.freeze({__proto__:null,StreamableHttpTransport:class{#En;#Sn;#gn=1;#dn;constructor(e,t={}){this.#En=e.replace(/\/$/,""),this.#Sn=t}async connect(){const e=await fetch(`${this.#En}/sse`,{headers:{...this.#Sn,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#dn=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#An({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#gn++,r=await this.#An({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#An(e){const t={...this.#Sn,"Content-Type":"application/json",Accept:"application/json"};this.#dn&&(t["mcp-session-id"]=this.#dn);const n=await fetch(`${this.#En}/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.#dn=void 0}}});var zv=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return id(im(e))}});export{Yn as COMMAND_IDS,Gn as MODULE_NAMES,e as ModuleLifecycleState,Gt as Profile,bm as STRUCTURAL_SLOTS_BY_MODULE,$ as WORKSPACE_STATE_GITIGNORE,Wv as bootstrap,oa as defaultAgentPolicyProfile,Wt as emitShellEvent,Pm as enterHeadlessScope,Nm as exitHeadlessScope,Bv as extensions,qv as flow,ca as getAgentPolicyProfile,Vt as getProfileValidator,Vv as initialize,re as isEventPersistenceEnabled,$m as isHeadlessScope,mm as isMacPlatform,jv as kernel,gm as parseKeyChord,Em as presentedSlots,Sm as profilePresentsSlot,Pt as registerShell,Mm as runInHeadlessScope,Fv as runtime,la as setAgentPolicyProfile,ne as setEventPersistence,Ut as setProfileValidator,Dv as shell,Hs as sideEffectArrayToEnum,Kv as start,Lv as version};
3
3
  //# sourceMappingURL=index.bundle.esm.js.map