@punica/editor 1.11.0 → 1.11.1

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>=4&&(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){const t=[];return function e(n,r){if(!n||"object"!=typeof n)return;const i=n,s=i.properties;if(s&&"object"==typeof s)for(const[n,i]of Object.entries(s)){if(!i||"object"!=typeof i)continue;const s=i,o=[...r,n];!0===s.sensitive&&t.push(o),e(s,o)}const o=i.items;if(o&&"object"==typeof o)if(Array.isArray(o))for(const t of o)e(t,[...r,"*"]);else e(o,[...r,"*"]);for(const t of["anyOf","oneOf","allOf"]){const n=i[t];if(Array.isArray(n))for(const t of n)e(t,r)}}(e,[]),t}function d(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 p=/^(?:secrets|secret-manager)\./,f=new Set(["value"]);const h={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=p.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]=f.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 m=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 g={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:m};const y={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 w(){return(new Date).toISOString()}function v(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=w(),{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:w(),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:w()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const b=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=v(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 I={manager:b},k=Object.freeze({__proto__:null,createTasksApi:v,default:I,manager:b});const E=6048e5,S={rules:[],defaultTtlMs:E};function A(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 x(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(A(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??E)}const C=".punica/.gitignore",T="# Punica editor — workspace internal state.\n# Auto-generated. Everything under .punica/ is ignored by default;\n# only the authored artifacts and user config below are tracked.\n/*\n\n!.gitignore\n\n# Authored artifacts (user's project content)\n!/ivy-nodes/\n!/ivy-agents/\n!/ivy-mcps/\n!/ivy-inputs/\n\n# Generated, and required by something outside this machine. The CI generator\n# writes the gate drivers here and the workflow it produces calls them by path,\n# so a runner that checks out the repository must find them.\n!/ci/\n\n# User configuration\n!/settings.json\n!/tasks.json\n!/launch.json\n!/database.yaml\n!/experiments.yaml\n!/mlops.yaml\n!/python.yaml\n!/vectors.yaml\n!/mcp.yaml\n!/mcp/\n";function N(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.startsWith("!"))}async function M(){const e=r();if(e&&(!n()||await t()))try{if(!!e.exists&&await e.exists(C)){const t=function(e){if(!e.includes("# Punica editor — workspace internal state."))return null;const t=new Set(N(e)),n=N(T).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(C)??"");return void(t&&e.updateFileContent&&await e.updateFileContent(C,t))}try{await e.createFolder(".punica")}catch{}await e.createFileWithContent(C,T)}catch{}}const P=".punica/events";let _={};function R(e){const t=[],n=[...e];for(;n.length>0;){const e=n.pop();if(e){if(Array.isArray(e.children))for(const t of e.children)n.push(t);!0!==e.isDirectory&&"string"==typeof e.path&&e.path.startsWith(P)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function $(e,t){if(!t)return!0;const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId&&n?.id!==t.correlationId)return!1;if(void 0!==t.name){if(!(Array.isArray(t.name)?t.name:[t.name]).includes(e.name))return!1}return!(void 0!==t.since&&(n?.timestampMs??0)<t.since)&&!(void 0!==t.until&&(n?.timestampMs??0)>t.until)}const L=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(P)}catch{}if(!this.#p){this.#p=!0;try{await i.createFileWithContent(`${P}/.gitignore`,"*\n!.gitignore\n")}catch{}}this.#f||(this.#f=!0,await M());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=`${P}/${n}_${r}.json`,o=l(t);await i.createFileWithContent(s,o)}catch{}try{_.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=R(n),s=[];for(const n of i)try{const r=await t.readFile(n),i=JSON.parse(r);$(i,e)&&s.push(i)}catch{}return s.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),e?.limit&&e.limit>0?s.slice(-e.limit):s}async delete(e){const t=r();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const i=R(n);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if($(JSON.parse(r),e))await t.deleteFile(n),s++;else{const e=n.split("/").pop()??"",t=e.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]??"";o.push({path:n,dateKey:t})}}catch{}if(o.length>this.#d){o.sort((e,t)=>e.dateKey.localeCompare(t.dateKey));const e=o.length-this.#d;for(const n of o.slice(0,e))try{await t.deleteFile(n.path),s++}catch{}}return s}async applyRetention(e,t=Date.now()){const n=r();if(!n)return 0;let i;try{i=await n.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=R(i);let o=0;for(const r of s)try{const i=await n.readFile(r),s=JSON.parse(i),a=s.envelope?.timestampMs??0;a<x(s.name,e,t)&&(await n.deleteFile(r),o++)}catch{}return o}};let O=L;function D(){return O}const j=new class{#h=void 0;get(){return this.#h}runWith(e,t){const n=this.#h;let r;this.#h=e;try{r=t()}catch(e){throw this.#h=n,e}return r&&"function"==typeof r.then?r.then(e=>(this.#h=n,e),e=>{throw this.#h=n,e}):(this.#h=n,r)}};let F=j;function q(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=F.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function B(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(A(e.name,t)){r=!0;break}if(!r)return!1}return!0}class U extends Error{constructor(e){super(e),this.name="EventReplayError"}}let V={exportSpan:()=>{}};function W(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function K(){return Date.now()}function G(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;function o(){try{_.onQueueDepthChange?.(i.length)}catch{}}async function a(){if(0===i.length)return;const e=[...i];i=[],o(),s&&(clearTimeout(s),s=null);try{await D().write(e),Q()}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function c(e){(function(e){if("audit"===e.envelope?.kind)return!0;const t=e.name;return r.some(e=>e.test(t))})(e)&&(i.push(e),o(),i.length>=10?a():s||(s=setTimeout(()=>{a()},5e3)))}function u(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 d(r,i){const s=i,o=s&&"object"==typeof s&&s.name===r?s:{name:r,envelope:{id:W(),timestampMs:K()},payload:i};try{n.push(o),n.length>200&&n.splice(0,n.length-200),c(o)}catch{}const a=e.get(r);if(a&&a.size>0)for(const e of a)try{e(i)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(B(o,t.filter))try{t.listener(o)}catch{}}}async function p(e){try{return await D().query(e)}catch{return[]}}function f(e){let t=[...n];if(e?.correlationId){const n=e.correlationId;t=t.filter(e=>e.envelope?.correlationId===n||e.envelope?.id===n)}if(e?.name){const n=Array.isArray(e.name)?e.name:[e.name];t=t.filter(e=>n.includes(e.name))}if(e?.kind){const n=Array.isArray(e.kind)?e.kind:[e.kind];t=t.filter(e=>n.includes(e.envelope?.kind))}if(e?.source){const n=Array.isArray(e.source)?e.source:[e.source];t=t.filter(e=>e.envelope?.source&&n.includes(e.envelope.source))}return"number"==typeof e?.since&&(t=t.filter(t=>(t.envelope?.timestampMs??0)>=e.since)),"number"==typeof e?.until&&(t=t.filter(t=>(t.envelope?.timestampMs??0)<=e.until)),t.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),"number"==typeof e?.limit&&e.limit>0&&(t=t.slice(-e.limit)),t}return{publish:d,subscribe:u,subscribeMany(e,t){const n=e.map(e=>u(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:W,publishEvent:function(e){const t=q({id:e.envelope?.id??W(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??K(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{V.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 d(n.name,n),t},getRecent(e){const t="number"==typeof e&&e>0?e:n.length;return n.slice(Math.max(0,n.length-t))},filterEvents:f,getTrace:function(e){return f({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?f(e.filter):[...n].sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0));if("csv"===t){const e=["timestamp","name","kind","source","correlationId","id","payload"],t=r.map(e=>[e.envelope?.timestampMs?new Date(e.envelope.timestampMs).toISOString():"",e.name,e.envelope?.kind??"",e.envelope?.source??"",e.envelope?.correlationId??"",e.envelope?.id??"",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:K(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:p,replay:async function(e){"dispatch"===e.mode&&function(){throw new U('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 p({name:e.name,since:e.since,until:e.until})}catch{i=[]}const s=function(e,t,n){const r=new Set,i=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}i.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}i.push(e)}const s={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=i.filter(e=>{if(!B(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)d(e.name,e);return{count:s.length,events:s}}}}const Y=G();var z={manager:Y};let J=S;function H(){return J}async function Q(){try{const e=D(),t=H();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??E;return await e.delete({until:K()-n})??0}catch{return 0}}var Z=Object.freeze({__proto__:null,createCorrelationId:W,createEventsApi:G,default:z,getRetentionConfig:H,manager:Y,runEventRetentionCleanup:Q,setRetentionConfig:function(e){J=e??S}});function X(){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 ee=X();var te={manager:ee},ne=Object.freeze({__proto__:null,createNotificationsApi:X,default:te,manager:ee});const re="punica.kernel.policy.v2";function ie(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function se(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class oe{#m=new Map;constructor(){this.#g()}set(e,t,n){let r=this.#m.get(e);r||(r=new Map,this.#m.set(e,r)),r.set(t,n),this.#y()}get(e,t){return this.#m.get(e)?.get(t)}has(e,t){return this.#m.get(e)?.has(t)??!1}delete(e,t){const n=this.#m.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#m.delete(e),r&&this.#y(),r}list(){const e=[];for(const t of this.#m.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#m.size&&(this.#m.clear(),this.#y())}restoreAll(e){this.#m.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=se(n);if(!e)continue;let r=this.#m.get(n.key);r||(r=new Map,this.#m.set(n.key,r)),r.set(e,n),t++}return this.#y(),t}#g(){const e=ie();if(e)try{const t=e.getItem(re);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=se(e);if(!t)continue;let n=this.#m.get(e.key);n||(n=new Map,this.#m.set(e.key,n)),n.set(t,e)}}catch{}}#y(){const e=ie();if(e)try{let t={};try{const n=e.getItem(re);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(re,JSON.stringify(n))}catch{}}}let ae=new oe;function ce(){return Date.now()}function le(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function ue(e){return`${e.kind}:${e.id}`}function de(e,t){return"workspace"===e?`workspace:${t??""}`:e}function pe(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const fe="punica.kernel.policy.v1",he="punica.kernel.policy.v2";class me{#w="execute";#v;#b=new Set;#I=new Map;#k=[];#E=1e3;constructor(e){this.#v=e??new oe,this.#S()}#S(){const e=pe();if(e)try{const t=e.getItem(he);if(t){const e=JSON.parse(t);if(e&&2===e.v)return void("suggest"!==e.mode&&"execute"!==e.mode||(this.#w=e.mode))}const n=e.getItem(fe);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#w=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#v.restoreAll(n),this.#y();try{e.removeItem(fe)}catch{}return}}}catch{}}#y(){const e=pe();if(e)try{let t={};try{const n=e.getItem(he);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#w,exportedAt:ce()};e.setItem(he,JSON.stringify(n))}catch{}}setMode(e){this.#w=e,this.#y()}getMode(){return this.#w}clearApprovals(){this.#v.clear(),this.#b.clear()}#A(e,t,n="info"){try{Y.publishEvent({name:e,envelope:{id:Y.createCorrelationId(),timestampMs:ce(),source:"kernel:policy",kind:n},payload:t})}catch{}}#x(e,t){return`${e}|${t}`}revokeApproval(e){const t=ue({kind:e.kind,id:e.id}),n="workspace"===e.scope?de("workspace",e.workspaceId):de(e.scope),r=this.#v.delete(t,n);return r&&(this.#C("revocation",{kind:e.kind,id:e.id,risk:"low",approval:"none"},void 0,e.scope,e.workspaceId),this.#A("approval.revoked",{kind:e.kind,id:e.id,scope:e.scope,workspaceId:e.workspaceId}),this.#b.delete(this.#x(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#v.list();if(t)return n;const r=ce();return n.filter(e=>!le(e,r))}hasApproval(e,t,n){const r=ue(e),i="workspace"===t?n?.workspaceId?de("workspace",n.workspaceId):null:de(t);if(null===i)return!1;const s=this.#v.get(r,i);if(!s)return!1;if(le(s,ce())){const e=this.#x(r,i);return this.#b.has(e)||(this.#b.add(e),this.#A("approval.expired",{kind:s.kind,id:s.id,scope:s.scope,workspaceId:s.workspaceId,expiresAt:s.expiresAt,decidedBy:s.decidedBy},"warn")),!1}return!0}recordApproval(e,t,n){if("workspace"===t&&!n?.workspaceId)throw new Error("[Policy] Workspace scope requires workspaceId in context");const r=ue(e),i="workspace"===t?de("workspace",n?.workspaceId):de(t),s={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:ce(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,chainRef:n?.chainRef};return this.#v.set(r,i,s),this.#C("approval",e,void 0,t,n?.workspaceId),this.#b.delete(this.#x(r,i)),this.#A("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:n?.decidedBy,expiresAt:n?.expiresAt}),s}#C(e,t,n,r,i){this.#k.push({timestampMs:ce(),type:e,request:t,decision:n,scope:r,workspaceId:i}),this.#k.length>this.#E&&this.#k.splice(0,this.#k.length-this.#E)}evaluate(e,t){const n=n=>{const r=t,i=r?.correlationId,s=r?.traceId??i;Y.publishEvent({name:"policy.evaluated",envelope:{id:Y.createCorrelationId(),correlationId:i,traceId:s,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})};if("suggest"===this.#w){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===e.approval){const r={allowed:!0,mode:"execute",requiresApproval:!1};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}if("plan"===e.approval){const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (plan)."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (step)."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}requestApproval(e,t){Y.publishEvent({name:"policy.approvalRequested",envelope:{id:Y.createCorrelationId(),correlationId:t?.correlationId,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,context:{workspaceId:t?.workspaceId,traceId:t?.traceId}}})}exportState(){return{version:2,exportedAt:ce(),mode:this.#w,approvals:this.listApprovals({includeExpired:!0})}}importState(e,t){if(!e||"object"!=typeof e)throw new Error("[Policy] Invalid export data");if(2!==e.version)throw new Error(`[Policy] Unsupported export version: ${e.version}. Expected 2.`);const n=t?.merge??!1,r=Array.isArray(e.approvals)?e.approvals:[];"suggest"!==e.mode&&"execute"!==e.mode||(this.#w=e.mode);let i=0;if(n)for(const e of r){if(!e||"string"!=typeof e.key)continue;const t=e.key,n=e.scope,r=e.workspaceId;if("workspace"===n&&!r)continue;const s="workspace"===n?de("workspace",r):de(n);"string"==typeof s&&s&&(this.#v.has(t,s)||(this.#v.set(t,s,e),i++))}else i=this.#v.restoreAll(r),this.#b.clear();return this.#y(),Y.publishEvent({name:"policy.stateImported",envelope:{id:Y.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:i,merged:n}}),i}saveTemplate(e,t,n){const r=n??"global";let i=this.#I.get(r);i||(i=new Map,this.#I.set(r,i));const s={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??ce(),updatedAtMs:ce()};i.set(e,s),this.#y()}getTemplate(e,t){const n=t??"global",r=this.#I.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#I.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#I.get(n);if(!r)return!1;const i=r.delete(e);return i&&this.#y(),i}exportAuditLog(e){const t=e?.format??"json";let n=[...this.#k];if(e?.since&&(n=n.filter(t=>t.timestampMs>=e.since)),e?.until&&(n=n.filter(t=>t.timestampMs<=e.until)),e?.workspaceId&&(n=n.filter(t=>t.workspaceId===e.workspaceId)),"csv"===t){const e=["timestamp","type","kind","id","risk","approval","allowed","requiresApproval","scope","workspaceId","reason"],t=n.map(e=>[new Date(e.timestampMs).toISOString(),e.type,e.request.kind,e.request.id,e.request.risk,e.request.approval,e.decision?.allowed?"true":"false",e.decision?.requiresApproval?"true":"false",e.scope??"",e.workspaceId??"",e.decision?.reason??e.request.reason??""]);return[e.join(","),...t.map(e=>e.map(e=>{const t=String(e);return t.includes(",")||t.includes('"')||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}).join(","))].join("\n")}return JSON.stringify({exportedAt:ce(),version:1,count:n.length,entries:n},null,2)}}const ge=new me(ae);var ye={manager:ge},we=Object.freeze({__proto__:null,PolicyManager:me,default:ye,manager:ge});async function ve(e,n,r){if(r())e.status="cancelled";else if("success"!==e.status&&"cancelled"!==e.status){e.status="running",e.startedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runStepStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=n,s=await t(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:n,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:n},trace:{traceId:i,parentSpanId:void 0},policy:{mode:"execute"}});e.status="success",e.finishedAtMs=Date.now(),e.correlationId=r,e.resultPayload=o,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:n,step:e}})}catch(t){const r=String(t?.message??t);if(r.includes("Approval required")||r.includes("CAPABILITY_APPROVAL_REQUIRED"))throw e.status="blocked",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}}),new Error("blocked");throw e.status="failed",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:n,step:e}}),t}}}async function be(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 ve(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 Ie={estimate:e=>Math.ceil(e.length/4)};function ke(){return Ie}function Ee(e){const t=ke();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 Se={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 Ae="[elided tool result:";function xe(e){const t=(e.content??"").length;return`${Ae} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function Ce(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 Te(e,t,n,r){const i=Ee(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=Ce(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(Ae)?{...e,content:xe(e)}:e);let c=Ee(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=Ee(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 Ne=Object.freeze({narrowThreshold:24,catalogTopN:100,topCategories:64,hotSetSize:40});function Me(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.agent?.toolSelection}catch{return}}function Pe(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function _e(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 Re(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=_e(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 $e(e,t,n){return!!e&&(!n.includes(e)&&("success"===t||"failed"===t))}const Le="punica.kernel.ai.toolUsage.v1";function Oe(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 De(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const je=new class{async read(){const e=De();if(!e)return{};try{const t=e.getItem(Le);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=Oe(t);n&&e&&(r[e]=n)}return r}(JSON.parse(t)):{}}catch{return{}}}async record(e,t,n){const r=De();var i;if(r)try{r.setItem(Le,(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=De();if(e)try{e.removeItem(Le)}catch{}}};let Fe=je;function qe(){return Fe}async function Be(e,t,n){try{await qe().record(e,t,n)}catch{}}function Ue(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}async function Ve(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=Ue(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 We(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=Re(i,e.usage??(a>0?await async function(){try{return await qe().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=Ue(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(Ue(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 Ve(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 Ke=["capability.search","capability.describe"];function Ge(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Ye(e,t,n,r){const i=punica.kernel?.Events?.manager;i&&i.publishEvent({name:e,envelope:{id:i.createCorrelationId(),correlationId:t,timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}function ze(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function Je(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function He(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 Qe(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=Ue(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(ze).sort(Je),deferredIndex:[]};const s=i.filter(e=>Ke.includes(String(e.id)));i=i.filter(e=>!Ke.includes(String(e.id))&&(!function(e){const t=String(e?.id??"");return!("core"!==String(e?.origin??"core")||!t.startsWith("ai.")&&(t.startsWith("capability.")?Ke.includes(t):!t.startsWith("llm.")))}(e)&&(!(!t.includeIvyNodes&&"ivy-node"===String(e.origin))&&!("mcp"===String(e.origin)&&!function(e,t){if(t.includeMcp)return!0;const n=function(e){const t=e.split(".");return"mcp"===t[0]&&t.length>=3?t[1]:void 0}(e);return!!n&&(t.allowedMcpServers??[]).includes(n)}(String(e.id),t)))));const o=function(e){const t={...Ne};for(const n of[Me(),e]){if(!n)continue;for(const e of Object.keys(t))Pe(n[e])&&(t[e]=Math.floor(n[e]));for(const e of["perCategoryCap","rankLimit"])Pe(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(ze).sort(Je),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 Ve(i,t.query,o,a)).map(ze).sort(Je),deferredIndex:[]}}const{hot:c,deferred:l}=await(u={entries:i,intent:t.query,budget:o,pinnedIds:t.pinnedTools,rank:a},We(u));var u;const d=new Set(c.map(e=>String(e.id))),p=s.length===Ke.length?s.map(ze):[{name:"capability.search",description:"Search the deferred tool index by natural-language need; returns candidate tool ids with one-line descriptions.",parameters:{type:"object",required:["query"],properties:{query:{type:"string"},limit:{type:"number"}}}},{name:"capability.describe",description:"Load full definitions (input schema) for up to 16 tool ids from the deferred index; described tools become directly callable.",parameters:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},maxItems:16}}}}],f=l.map(e=>({id:String(e.id),line:He(e),category:Ue(String(e.id))})).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0);return console.log("[AgentLoop] tiered catalog",{hot:c.length,deferred:f.length,hotSetSize:o.hotSetSize,pinned:t.pinnedTools??[],hotIds:[...d]}),{hot:[...p,...c.map(ze)].sort(Je),deferredIndex:f}}async function Ze(e,t,n,r){const i={id:t.id,name:t.name,arguments:t.arguments,status:"success"};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){if(!function(e){const t=String(e?.message??e);return t.includes("Approval required")||t.includes("CAPABILITY_APPROVAL_REQUIRED")}(e))return{...i,status:"failed",error:String(e?.message??e)}}const s=String(n.trace?.traceId??n.sessionId??""),o=await function(e,t,n){return new Promise(r=>{const i=punica.kernel.Events.manager;let s=!1;const o=e=>{if(!s){s=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=i.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed"],n=>{const r=n?.payload?.payload??n?.payload,i=r?.pending;i?.id===e&&(i?.traceId&&i.traceId!==t||o("ai.approvalRecorded"===n?.name?"approved":"dismissed"))})??void 0,c=setInterval(()=>{n()&&o("cancelled")},250),l=setTimeout(()=>o("timeout"),18e4)})}(t.name,s,r);if("approved"!==o)return{...i,status:"blocked",error:`tool "${t.name}" not approved (${o})`};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){return{...i,status:"failed",error:String(e?.message??e)}}}async function Xe(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${nt(n)}\nRejected arguments:\n${nt(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 et(e,t,n,r,i){let s=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Ze(e,{...t,arguments:s},r,i);if("failed"!==l.status||!Ge(l.error))return o?{...l,arguments:s,repaired:!0}:l;if(a=l.error??"",2===c||i())break;const u=await Xe(e,t.name,n,s,a,r);if(!u)break;s=u,o=!0}const c={id:t.id,name:t.name,arguments:s,status:"failed",error:a||"input validation failed"};return o&&(c.repaired=!0),c}function tt(e){return ke().estimate(e)}function nt(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function rt(e,n,r,i){const s=punica.kernel.Events.manager,o=i??s.createCorrelationId(),a="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,c=(l=e.profile,Se[l??"balanced"]);var l;const u=[],d=e.sessionId?punica.kernel?.AI?.sessions:void 0,p=[];let f=0;const h=[],m=Date.now();let g=0,y=0,w=0,v=0,b=!1,I=0,k=!1,E=0;const S=(t,n)=>{const r={inputTokens:g,outputTokens:y,totalTokens:w,latencyMs:Date.now()-m,steps:u.length,toolCalls:E};k&&(r.totalCost=I),b&&(r.cacheReadTokens=v);const i={runId:o,finishReason:t,steps:u,usage:r};if(void 0!==n&&(i.finalText=n),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:u.length}),(t=>{if(d&&e.sessionId&&0!==f)try{const n=[{role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}},...h];t&&n.push({role:"assistant",content:t});const r=n.map(e=>({id:"",createdAtMs:0,role:e.role,content:e.content??"",...e.images&&e.images.length>0?{images:e.images}:{},...e.name?{name:e.name}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolCalls&&e.toolCalls.length>0?{toolCalls:e.toolCalls}:{}}));d.appendMessages(e.sessionId,r,{runId:o})}catch(e){console.warn("[AgentLoop] session persist failed:",e)}})(n),d&&e.sessionId&&f>0)try{d.recordUsage?.(e.sessionId,r)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Ye("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),i};Ye("ai.agentStarted",o,"info",{runId:o,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{}});const A=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!A)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),S("error");const x=await t(),C=function(e,t,n){return{sessionId:e,workspaceId:t,actor:{type:"ai",id:"ai:agent"},origin:{kind:"ai",id:e},trace:{traceId:e,parentSpanId:void 0},policy:{mode:"execute"},...n?{signal:n}:{}}}(o,x,r);let T;e.sessionId&&(C.conversationId=e.sessionId);try{T=await Qe(A,e,C)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),S("error")}const N=[...T.hot];console.log("[AgentLoop] tool catalog built",{hot:N.length,deferred:T.deferredIndex.length,toolFilter:e.toolFilter??null,names:N.map(e=>e.name)});const M=new Map(N.map(e=>[e.name,e.parameters])),P=new Map(T.deferredIndex.map(e=>[e.id,e])),_=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!M.has(String(e.id))).map(ze).sort(Je);for(const e of n)N.push(e),M.set(e.name,e.parameters),P.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:N.length}),n.length};if(p.push({role:"system",content:"You are an autonomous agent operating inside an IDE. You are given a set of tools (capabilities). To accomplish the user request, call the tools you need one or more times; after each tool result, decide whether to call another tool or to answer. When you have enough information, reply with a concise final answer and no further tool calls."}),e.includeProjectContext)try{const e=function(e){const t=e;if(!t||"object"!=typeof t)return null;const n=[],r=t.workspace;r?.name&&n.push(`Project: ${r.name} (${r.kind}) at ${r.rootUri}`+(r.environment?` [env: ${r.environment}]`:"")),Array.isArray(t.stack)&&t.stack.length&&n.push(`Stack: ${t.stack.join(", ")}`);const 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 A("workspace.projectContext",{},C));e&&p.push({role:"system",content:e})}catch(e){console.warn("[AgentLoop] projectContext orientation unavailable:",e)}if(T.deferredIndex.length>0&&p.push(function(e){const t=new Map;for(const n of e){const e=t.get(n.category);e?e.push(n):t.set(n.category,[n])}const n=[];for(const e of[...t.keys()].sort())for(const r of t.get(e))n.push(`[${e}] ${r.id} — ${r.line}`);return{role:"system",content:"Additional tools exist but are not loaded yet. Index (id — purpose):\n"+n.join("\n")+"\nTo use one: call capability.search to find candidates, then capability.describe to load full schemas. You may also call an indexed tool directly by its id if its arguments are obvious."}}(T.deferredIndex)),d&&e.sessionId)try{p.push(...d.getContextMessages(e.sessionId))}catch(e){console.warn("[AgentLoop] session seed failed; running cold:",e)}p.push({role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}}),f=p.length;let R=0;for(let t=0;t<a;t++){if(n())return S("cancelled");let r,i=!1;if(Ee(p)>c.maxContextTokens){const e=await Te(p,c,A,C);e.compacted&&(p.splice(0,p.length,...e.messages),R=0,i=!0,Ye("ai.agentContextCompacted",o,"info",{runId:o,step:t,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const s=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:t,messageCount:p.length,toolsSent:N.length,toolChoice:"auto",toolNames:N.map(e=>e.name)});const n={stableToolsAndSystem:!0,stableMessagePrefix:R,cacheKey:o};r=await A("llm.chatStream",{messages:p,tools:N,toolChoice:"auto",correlationId:o,cacheHints:n,...e.profile?{profile:e.profile}:{}},C),R=p.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:t,textLen:(r?.text??"").length,toolCalls:r?.toolCalls?.length??0})}catch(e){return console.error("[AgentLoop] llm.chatStream call failed; aborting run:",e),S("error")}if(n())return S("cancelled");const a=Date.now()-s,l=(r.text??"").trim(),d="string"==typeof r.thinking?r.thinking:void 0,f=r.toolCalls??[],m={index:t,assistantText:l||void 0,thinking:d,toolCalls:[],latencyMs:a},x=r.usage,T=r.meta;x?(m.usage=x,g+=x.inputTokens??0,y+=x.outputTokens??0,w+=x.totalTokens??(x.inputTokens??0)+(x.outputTokens??0),"number"==typeof x.cacheReadInputTokens&&(v+=x.cacheReadInputTokens,b=!0)):T&&(m.usage={inputTokens:T.promptTokens,outputTokens:T.completionTokens,totalTokens:T.promptTokens+T.completionTokens},g+=T.promptTokens,y+=T.completionTokens,w+=T.promptTokens+T.completionTokens),T&&"number"==typeof T.totalCost&&(I+=T.totalCost,k=!0);const $={runId:o,step:t,estToolDefTokens:tt(JSON.stringify(N)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+tt(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+tt(t.content??""),0),toolCount:N.length,deferredToolCount:P.size,compactionApplied:i};if(m.usage&&($.reportedInputTokens=m.usage.inputTokens,$.reportedOutputTokens=m.usage.outputTokens,"number"==typeof m.usage.cacheReadInputTokens&&($.cacheReadTokens=m.usage.cacheReadInputTokens)),Ye("ai.agentTurnUsage",o,"info",{...$}),0===f.length)return u.push(m),Ye("ai.agentStep",o,"info",{runId:o,turn:m}),S("final",l);u.push(m),Ye("ai.agentStep",o,"info",{runId:o,turn:m});const L=f.map(e=>`${e.name}(${nt(e.arguments)})`).join(", "),O={role:"assistant",content:l?`${l}\n[calling tools: ${L}]`:`[calling tools: ${L}]`,toolCalls:f.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};p.push(O),h.push(O);let D=!1;for(const e of f){if(n())return S("cancelled");if(Ye("ai.agentToolCall",o,"info",{runId:o,toolCall:{id:e.id,name:e.name,arguments:e.arguments},status:"running"}),!M.has(e.name)&&P.has(e.name))try{_(await A("capability.describe",{ids:[e.name]},C))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const r=await et(A,e,M.get(e.name),C,n);m.toolCalls.push(r),E++,$e(r.name,r.status,Ke)&&await Be(r.name,"success"===r.status,Date.now()),"success"===r.status&&"capability.describe"===r.name&&_(r.resultPayload),console.log("[AgentLoop] tool dispatched",{step:t,name:r.name,arguments:r.arguments,status:r.status,repaired:r.repaired??!1,error:r.error,resultPreview:"success"===r.status?nt(r.resultPayload).slice(0,300):void 0}),Ye("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const i={role:"tool",content:"success"===r.status?nt(r.resultPayload,c.toolResultMaxChars):`ERROR: ${r.error??"tool failed"}`,name:r.name,toolCallId:r.id};p.push(i),h.push(i),"blocked"===r.status&&(D=!0)}if(D)return S("blocked")}return S("maxSteps")}function it(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 st={KERNEL:{EVENTS:"kernel.events",COMMANDS:"kernel.commands",HISTORY:"kernel.history",TIME_SERVER:"kernel.timeServer",NOTIFICATIONS:"kernel.notifications",AI:"kernel.ai",LLM:"kernel.llm",POLICY:"kernel.policy",TASKS:"kernel.tasks"},RUNTIME:{FS:"runtime.fs",SEARCH:"runtime.search",VCS:"runtime.vcs",WORKSPACE:"runtime.workspace",LLM:"runtime.llm",SECRETS:"runtime.secrets",TASKS:"runtime.tasks",TERMINALS:"runtime.terminals",MCP:"runtime.mcp"},SHELL:{ACTIVITY_BAR:"shell.activityBar",STATUSBAR:"shell.statusbar",VIEW:"shell.view",VIEWS:"shell.views",KEYBOARD_SHORTCUTS:"shell.keyboardShortcuts",LAYOUT:"shell.layout",CONTENT_TABS:"shell.contentTabs",PANEL_TABS:"shell.panelTabs",PANEL_LAYOUT:"shell.panelLayout"},FLOW:{SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},EXTENSIONS:{MANAGER:"extensions.manager"}},ot={SHELL:{TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},AI:{AGENT_RUN:"ai.agent.run",APPROVE_PENDING:"ai.approvePending",ASK:"ai.ask",CANCEL_RUN:"ai.cancelRun",DISMISS_PENDING:"ai.dismissPending",DO:"ai.do",RUN_PLAN:"ai.runPlan",SESSION_ARCHIVE:"ai.session.archive",SESSION_CREATE:"ai.session.create",SESSION_DELETE:"ai.session.delete",SESSION_LIST:"ai.session.list",SESSION_RENAME:"ai.session.rename",SHOW_LAST_TRACE:"ai.showLastTrace",SUMMARIZE:"ai.summarize",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 at(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 ct(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 lt(e,t,n){try{punica.kernel?.Notifications?.manager?.push({id:"",timestamp:"",level:e,title:t,message:n,source:"ai"})}catch{}}function ut(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 dt(e){return`${e} ${1===e?"capability":"capabilities"}`}const pt="punica.kernel.ai.sessions.index.v1";function ft(e){return`punica.kernel.ai.session.${e}.v1`}function ht(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const mt=new class{readIndex(){const e=ht();if(!e)return[];try{const t=e.getItem(pt);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=ht();if(t)try{t.setItem(pt,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=ht();if(t)try{const n=t.getItem(ft(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=ht();if(t)try{t.setItem(ft(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=ht();if(t)try{t.removeItem(ft(e))}catch{}}};let gt=mt;function yt(){return gt}const wt="New chat";function vt(){return Date.now()}function bt(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${vt().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function It(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:vt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function kt(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function Et(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 St=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:_e(n,t)})).sort((e,t)=>t.prior-e.prior||(e.capabilityId<t.capabilityId?-1:1))}(await qe().read()??{},Date.now())}catch{return[]}}async forget(){await qe().forget()}setStore(e){!function(e){Fe=e??je}(e)}},At=new class{#T=null;#N=null;#M=new Map;#P=!1;#_=new Map;initialize(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{!function(e,t){const n=e?.payload??e,r=n?.request;if(!r?.id)return;const i=e?.envelope?.correlationId,s=n?.context?.workspaceId,o=n?.context?.traceId,a=punica.kernel.Events.manager.createCorrelationId(),c={pendingId:a,kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason,correlationId:i,...o?{traceId:o}:{},workspaceId:s,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#M)}),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#T=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(ot.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(ot.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(ot.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=it(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(ot.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(ot.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`+it(e,2))}}),t.registerCommand(ot.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(ot.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(ot.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(ot.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(ot.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(ot.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(ot.AI.CANCEL_RUN,{title:"AI: Cancel Run",description:"Cancel AI runs. Bare: everything (legacy Stop). Pass { runId } or { sessionId } to cancel one run / one conversation only.",execute:t=>{const n=t&&"object"==typeof t&&(t.runId||t.sessionId)?{runId:t.runId,sessionId:t.sessionId}:void 0;e.setCancelRequested(!0,n)}}),t.registerCommand(ot.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(ot.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(ot.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(ot.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(ot.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(ot.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"+it(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+it(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(ot.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"+it(e)),0===e.length?(lt("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):(lt("info",`Tool selection has learned from ${dt(e.length)}`,`Carrying the most weight right now: ${e.slice(0,3).map(ut).join(", ")}. The full list is in the developer console.`),e)}}),t.registerCommand(ot.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 lt("error","Could not erase what tool selection learned",`The record is still on disk. ${e instanceof Error?e.message:String(e)}`),e}lt("info",0===e.length?"There was nothing to forget":`Forgot ${dt(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(ot.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;ct("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:at(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();ct("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:at(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),ct("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){ct("ai.response","error",r,i,punica.kernel.Events.manager.createCorrelationId(),s,o,{kind:"summarize",error:String(e?.message??e)})}}})}({runLastPlan:e=>this.runLastPlan(e),runAgent:e=>this.runAgent(e),getLastPlan:()=>this.getLastPlan(),approvePending:(e,t)=>this.approvePending(e,t),dismissPending:e=>this.dismissPending(e),getPendingApprovals:()=>this.getPendingApprovals(),getLastRun:()=>this.#N,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#_){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#P=e;for(const t of this.#_.values())t.cancelRequested=e,e&&t.controller.abort()}}})}getLastPlan(){return this.#T}getPendingApprovals(){return e=this.#M,Array.from(e.values()).sort((e,t)=>e.timestampMs-t.timestampMs);var e}approvePending(e,t){return function(e,t,n){const r=n.get(e);return!!r&&(punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason},t,{decidedBy:"user",workspaceId:r.workspaceId}),n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.approvalRecorded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r,scope:t}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"approved"}}),!0)}(e,t,this.#M)}dismissPending(e){return function(e,t){const n=t.get(e);return!!n&&(t.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalDismissed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:n}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"dismissed"}}),!0)}(e,this.#M)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#T=e);const t=await be(this.#T,this.#N,()=>this.#P,e=>{this.#T=e});return this.#N=t,this.#P=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#_.set(t,n);try{return await rt(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#_.delete(t)}}},xt=new class{#R;create(e){const t=yt(),n={sessionId:bt("sess"),title:e?.title?.trim()||wt,createdAtMs:vt(),updatedAtMs:vt(),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.#$(i,n),t.writeIndex(i),It("ai.sessionCreated",n),{...n}}list(e){const t=yt().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return yt().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#L(e,e=>{e.title=n});return!!r&&(It("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#L(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(It("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=yt(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[i]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),It("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=yt(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||bt("msg"),createdAtMs:e.createdAtMs||vt(),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=vt(),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===wt){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:wt}(e.content))}r.writeSession(i),this.#O(o),It("ai.sessionUpdated",o,{appendedCount:s.length,runId:n?.runId});const a=this.#R;a?.shouldCompact(i)&&Promise.resolve().then(()=>a.compact(i)).then(t=>{const n=yt().readSession(e);n&&(n.contextView=t,yt().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=yt().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(...kt(n.messages).map(Et)),e}return kt(t.transcript.slice(-40)).map(Et)}setCompactor(e){this.#R=e}recordUsage(e,t){const n=this.#L(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=vt(),e.usage=n});return!!n&&(It("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#L(e,t){const n=yt(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=vt(),n.writeSession(r),this.#O(r.meta),{...r.meta}}#O(e){const t=yt(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#$(e,t){const n=yt(),r=e=>e.workspaceId===t.workspaceId;let i=e.filter(r);for(;i.length>50;){const s=i.filter(e=>e.sessionId!==t.sessionId).sort((e,t)=>{const n=e.archived?0:1,r=t.archived?0:1;return n!==r?n-r:e.updatedAtMs-t.updatedAtMs})[0];if(!s)break;const o=e.findIndex(e=>e.sessionId===s.sessionId);o>=0&&e.splice(o,1),n.deleteSession(s.sessionId),It("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};xt.setCompactor(function(){const e=Se.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=Ce([{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(Ae)?{...e,content:xe(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());const Ct=St;var Tt={manager:At,sessions:xt,toolUsage:Ct},Nt=Object.freeze({__proto__:null,default:Tt,manager:At,sessions:xt,toolUsage:Ct});const Mt=new class{#D=new Map;#j=new Map;#F=new Map;#q;registerProductOriginResolver(e){this.#q=e}#B(e){try{const t=punica.extensions?.manager;if(t){if(t.getExtension(e))return!0;const n=t.getAllExtensions();if(Array.isArray(n))return n.some(t=>t.name===e||t.id===e)}return!0}catch{return!0}}register(e,t){if(!e.id)throw new Error("Instruction class must have an id");if(!e.role)throw new Error("Instruction class must have a role");if(!e.systemPrompt)throw new Error("Instruction class must have a systemPrompt");if(this.#D.has(e.id)){const n=this.#D.get(e.id),r=n?.originExtension||this.#F.get(e.id),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.#q&&(t=this.#q(e.productId)),t&&(e.originExtension=t,this.#F.set(e.id,t)),e.capability||(e.capability=function(e){if(e.capability)return e.capability;const t={id:e.id,title:e.role.charAt(0).toUpperCase()+e.role.slice(1),description:`LLM instruction class: ${e.role}`,version:"1.0.0",tags:["llm","instruction-class",e.role]};return t.inputs={schema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",enum:[e.id],description:"Instruction class identifier"},userPrompt:{type:"string",description:"User prompt/query"},context:{type:"object",properties:{workspaceId:{type:"string"},filePath:{type:"string"},previousOutputs:{type:"object"},capabilities:{type:"array"}}},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"}}}}}},e.outputSchema?t.outputs={schema:e.outputSchema,kind:"direct"}:t.outputs={schema:{type:"object",properties:{text:{type:"string"},structured:{type:"object"}}},kind:"direct"},e.riskLevel?t.policy={risk:e.riskLevel,approval:"high"===e.riskLevel?"step":"plan"}:t.policy={risk:"medium",approval:"step"},t.sideEffects=["llm-invocation"],"json_object"===e.responseFormat&&t.sideEffects.push("structured-output"),t}(e)),this.#D.set(e.id,e),this.#j.set(e.id,e.capability)}unregister(e){this.#D.delete(e),this.#j.delete(e),this.#F.delete(e)}unregisterByOrigin(e){const t=[];this.#F.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>this.unregister(e))}get(e){return this.#D.get(e)}list(e=!1){const t=Array.from(this.#D.values());return e?t.filter(e=>{const t=e.originExtension||this.#F.get(e.id);return!t||this.#B(t)}):t}listSummaries(e=!1){return this.list(e).map(e=>({id:e.id,role:e.role,originExtension:e.originExtension||this.#F.get(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0}))}has(e){return this.#D.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#F.get(e);return!n||this.#B(n)}getCapability(e){return this.#j.get(e)}listCapabilities(){return Array.from(this.#j.values())}};async function Pt(e){const{primaryModelId:t,count:n,exclude:r}=e,i=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{return await e.listInstalled()}catch{return null}}();if(!i||!Array.isArray(i.installed)||0===i.installed.length)return t?[t]:[];const s=new Set(i.installed.map(e=>e.id)),o=[],a=e=>{e&&s.has(e)&&(function(e,t){return!(!t||0===t.length)&&t.includes(e)}(e,r)||o.includes(e)||o.push(e))};if(a(t),o.length<n)for(const e of i.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function _t(e,t){let n=e.riskLevel;if(!n){const r=await async function(e,t){if("risk-assessor"===e.id)return{riskLevel:"medium"};const n=Mt.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,i=[];i.push("Assess the risk level for this task:"),i.push(""),i.push(`Instruction Class: ${e.id}`),i.push(`Role: ${e.role}`),i.push(""),i.push("User Prompt:"),i.push(t.userPrompt),i.push(""),i.push("Context:"),i.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),i.push(`- File Path: ${r?.filePath??"N/A"}`),i.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),i.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),i.push(""),i.push("Consider:"),i.push("- Is this production code?"),i.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),i.push("- Is it a critical business function?"),i.push("- Does it handle sensitive data?"),i.push("- Is it a simple utility or a complex system?"),i.push(""),i.push('Respond with ONLY one word: "low", "medium", or "high".');const s=i.join("\n");try{const e=punica.runtime.capabilities?.gateway,t=e?await e.call("llm.chat",{messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20},{sessionId:"internal",workspaceId:void 0,actor:{type:"extension",extensionName:"kernel:policy"},origin:{kind:"command",id:"risk-assessment"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat({messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20}),r=String(t.text??"").toLowerCase();return/\bhigh\b/.test(r)?{riskLevel:"high"}:/\bmedium\b/.test(r)?{riskLevel:"medium"}:/\blow\b/.test(r)?{riskLevel:"low"}:{riskLevel:"medium"}}catch{return{riskLevel:"medium"}}}(e,t);n=r.riskLevel}if(n||(n="medium"),"high"===n){const t=e.expertModelId,r=e.expertModelIds;let i=[];return i=r&&r.length>0?r.slice():await Pt({primaryModelId:t,count:3}),{strategy:i.length>1?"multi":"single",modelIds:i.length?i:[t].filter(Boolean),riskLevel:n,reason:"High risk detected via LLM-based assessment"}}let r=e.expertModelId??null;return r||(r=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{const t=await e.listInstalled();if(t.activeModelId)return t.activeModelId;const n=t.installed[0];return n?n.id:null}catch{return null}}()),{strategy:"single",modelIds:r?[r]:[],riskLevel:n,reason:"Low/medium risk, single expert sufficient"}}function Rt(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 $t(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function Lt(){const e=globalThis;return e.punica?.runtime?.fs}function Ot(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Dt={type:"ai",id:"llm:context"},jt={kind:"ai",id:"context-builder"};async function Ft(e){if(e.filePath)try{const t=$t(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:Dt,origin:jt,trace:{traceId:Ot()},policy:{mode:"execute"}}):await(Lt()?.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 qt(e){try{const t=$t(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Dt,origin:jt,trace:{traceId:Ot()},policy:{mode:"execute"}}):await(Lt()?.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 Bt(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Ut(){return"undefined"==typeof document?void 0:document}function Vt(){const e=Ut();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 Wt(e){try{const t=Bt();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Vt();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 Kt(){try{const e=Bt();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=Vt();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=Ut();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 Gt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Yt={type:"ai",id:"llm:context"},zt={kind:"ai",id:"context-builder"};async function Jt(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:Yt,origin:zt,trace:{traceId:Gt()},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 Ht(){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 Qt(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 Zt="problems.getDiagnostics";function Xt(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===Zt))return;let r;try{r=t.executeCommand?.(Zt)}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 en(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 tn=new class{#U;#V=[];constructor(e){this.#U=Math.max(1,e?.maxRecords??1e4)}record(e){this.#V.push(e),this.#V.length>this.#U&&this.#V.splice(0,this.#V.length-this.#U)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,i=new Map;let s=0,o=0,a=0,c=0,l=0;for(const e of this.#V){if(e.timestamp<n||e.timestamp>r)continue;const u=en(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.#V.length=0}};function nn(e){return e.remaining[0]}function rn(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 sn(e){return{...e,terminal:!0,pendingQueue:!1}}let on;function an(e){on=e}function cn(e){return!!e&&"string"==typeof e.providerId&&""!==e.providerId.trim()}const ln={onError:"next",onTimeout:"next",onRateLimit:"next"};function un(e){const t=e?.status??e?.statusCode;return"number"==typeof t&&(408!==t&&429!==t&&(401!==t&&403!==t&&(t>=400&&t<500)))}function dn(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 pn(e){const t=e.providerId.trim(),n=t.toLowerCase(),r=n.startsWith("local:")?"local":n.startsWith("remote:")?"remote":void 0;return{providerId:t,...r?{route:r}:{},...e.modelId?{modelId:e.modelId}:{}}}async function fn(e,n){const r=Mt;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(Rt(e)),Ft(e),Promise.resolve(Wt(e)),qt(e),Jt(e),Ht(),Promise.resolve(Kt()),Qt(e),Promise.resolve(Xt(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 _t(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,correlationId: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,n)=>{const r=punica.kernel.Events.manager;return await punica.runtime.capabilities.gateway.call(t,{...a,...n},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}})},h=(e,t,n)=>{try{const r=punica.kernel.Events.manager;r.publishEvent({name:"llm.fallback",envelope:{id:r.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId: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(cn);if(!on)return[];try{const e=on();return Array.isArray(e)?e.filter(cn):[]}catch{return[]}}(i);let g,y;if(m.length>0){let e,t=function(e){return{position:0,attempted:[],remaining:e.slice(),terminal:0===e.length,pendingQueue:!1}}(m);const n=Date.now();for(;!t.terminal;){const n=nn(t);if(!n)break;const r=Date.now();try{l=await f(c,pn(n)),d=Date.now()-r,g=t.position,t=sn(t);break}catch(r){if(e=r,un(r))break;const s=rn(t,dn(r),i.fallbackPolicy??ln,r);if(s.pendingQueue){t={...s,terminal:!0};break}const o=nn(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],n=Date.now();try{const r=punica.kernel.Events.manager;l=await punica.runtime.capabilities.gateway.call(c,{...a,modelId:t},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-n}catch(t){if(!(o.modelIds.length>1)||e.options?.skipFallback)throw t;{let n=t;for(const t of o.modelIds.slice(1))try{const r=Date.now(),s=punica.kernel.Events.manager;try{s.publishEvent({name:"llm.fallback",envelope:{id:s.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,fromModelId:o.modelIds[0],toModelId:t,reason:n?.message??"unknown"}})}catch{}l=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??s.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??s.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-r;break}catch(e){n=e;continue}if(!l)throw n}}}else{const t=Date.now(),n=punica.kernel.Events.manager,r=o.modelIds.map(async t=>{const r=Date.now(),s=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??n.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??n.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),o=Date.now()-r;let c;if(i.outputSchema&&"json_object"===i.responseFormat)try{c=JSON.parse(s.text)}catch{}return{res:s,expert:{modelId:s.modelId??t,text:s.text,structured:c,usage:s.usage,latencyMs:o}}}),s=await Promise.all(r);u=s.map(e=>e.expert);const c=function(e,t){if(!e.length)throw new Error("aggregateBestOfN called with no results");if("json_object"===t.responseFormat){const t=e.filter(e=>void 0!==e.structured);if(t.length>0)return t.reduce((e,t)=>t.latencyMs<e.latencyMs?t:e)}return e.reduce((e,t)=>{const n=e.text.length-e.latencyMs/1e3+.1*(e.usage?.outputTokens??0);return t.text.length-t.latencyMs/1e3+.1*(t.usage?.outputTokens??0)>n?t:e})}(u,i);l={text:c.text,modelId:c.modelId,provider:s.find(e=>e.expert.modelId===c.modelId)?.res.provider,usage:c.usage},d=Date.now()-t}if(i.outputSchema&&"json_object"===i.responseFormat)try{y=JSON.parse(l.text)}catch(e){return{ok:!1,error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}const w={ok:!0,text:l.text,structured:y,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId,tokensUsed:l.usage?.totalTokens,inputTokens:l.usage?.inputTokens,outputTokens:l.usage?.outputTokens,latencyMs:d,modelId:l.modelId,provider:l.provider}};try{const e=l.usage?.inputTokens??0,t=l.usage?.outputTokens??0,n=l.usage?.cacheReadInputTokens??0,r=String(l.provider??"unknown"),s=String(l.modelId??"unknown"),o=0,c={provider:r,model:s,promptTokens:e,completionTokens:t,totalCost:o,latencyMs:d,...void 0!==g?{fallbackChainPosition:g}:{}};tn.record({capabilityId:i.id,provider:r,model:s,promptTokens:e,completionTokens:t,...n>0?{cachedPromptTokens:n}:{},totalCost:o,latencyMs:d,timestamp:Date.now(),workspaceId:p}),punica.kernel.Events.manager.publishEvent({name:"llm.call",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,workspaceId:p,meta:c}})}catch{}return w}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 hn(e){return fn({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 mn(e){return fn({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function gn(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 fn({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function yn(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function wn(e,t){const n=yn(e).split("/").filter(Boolean),r=yn(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function vn(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function bn(e,t){const n=yn(e).split("/").filter(Boolean),r=yn(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 In(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=bn(t,wn(t,yn(r.path)));(e.startsWith("..")||vn(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=yn(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 kn={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 En=new class{api;constructor(){this.api={instructionClassRegistry:Mt,invoke:fn,plan:hn,generateCode:mn,editWorkflow:gn,listInstructionClasses:e=>Mt.listSummaries(e),setDefaultProviderChainResolver:an}}};var Sn={manager:En};const An={Commands:h,History:g,TimeServer:y,Tasks:k,Events:Z,Notifications:ne,Policy:we,AI:Nt,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:kn,applyCodegenBundle:In,default:Sn,manager:En})};function xn(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 Cn=new class{#W=[];register(e){this.#W=this.#W.filter(t=>t.id!==e.id),this.#W.push({priority:0,...e}),this.#W.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#W=this.#W.filter(t=>t.id!==e)}clear(){this.#W=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#W){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>xn(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.#W.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>xn(t,e))}).map(e=>({opener:e,command:e.command}))}};let Tn,Nn,Mn,Pn,_n,Rn;function $n(){if(Tn)return Tn;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return Tn=punica.runtime.resources,Tn}function Ln(){if(Nn)return Nn;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return Nn=e,Nn}function On(){if(Pn)return Pn;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return Pn=e,Pn}function Dn(){if(_n)return _n;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function jn(){if(Rn)return Rn;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return Rn=e,Rn}function Fn(e){let t,n;return{get(){if(void 0!==t)return t;const n=e.resolveHostFallback?.();if(void 0!==n)return t=n,t;throw new Error(e.noProviderMessage)},set(e){t=e,n=void 0},hasProvider:()=>void 0!==t,lastProviderId:()=>n,trackProviderId(e){const t=n;return n=e,{previous:t,changed:void 0!==t&&void 0!==e&&t!==e}}}}function qn(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 Bn=Fn({label:"Runtime.workspace",noProviderMessage:"[Runtime.workspace] No Workspace provider registered. Host must attach punica.runtime.workspace",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.workspace}});function Un(){return Bn.get()}function Vn(e){Bn.set(e),e&&qn({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Wn(e,t,n){try{const r=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!r?.publishEvent||!r?.createCorrelationId)&&(r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:t}),!0)}catch{return!1}}const Kn=Symbol("punica.llm.gatewayGovernedAi");let Gn,Yn,zn;function Jn(){if(Gn)return Gn;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return Gn=punica.runtime.llm,Gn}function Hn(e){if(Gn=e,Yn=void 0,zn=void 0,!e)return;const t=e;Wn("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class Qn{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 Zn=null;function Xn(){return Zn||(Zn=new Qn),Zn}class er{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 tr{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 nr={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}}},rr={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}}},ir={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},sr={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},or={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 ar(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 cr{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=ar("session");return new tr(i,s,t.id,e.language,r,n)}}class lr{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 ur=null;function dr(){return ur||(ur=new lr),ur}class pr{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 fr{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 hr=null;function mr(){return hr||(hr=new fr),hr}class gr{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 yr{#K=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#K.set(e.id,e)}get(e){return this.#K.get(e)}list(){return Array.from(this.#K.values())}select(e){return this.list().find(t=>t.canRun(e))}}let wr=null;function vr(){return wr||(wr=new yr),wr}function br(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 Ir="default";class kr{#G=new Map;#Y(e){const t=e||Ir;let n=this.#G.get(t);return n||(n=new Map,this.#G.set(t,n)),n}upsert(e,t=Ir){const n=this.#Y(t);for(const t of e){if(!t||"string"!=typeof t.id)throw new Error("VectorRecord requires a string id.");n.set(t.id,t)}}query(e,t=10,n=Ir){const r=this.#Y(n),i=[];for(const t of r.values())i.push({id:t.id,score:br(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=Ir){const n=this.#Y(t);for(const t of e)n.delete(t)}clear(e=Ir){this.#G.delete(e||Ir)}count(e=Ir){return this.#Y(e).size}export(e=Ir){return Array.from(this.#Y(e).values())}import(e,t=Ir){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#G.set(t||Ir,n)}}const Er=".punica/vectors";class Sr{#v=new kr;#z=new Set;#J(){try{return punica.runtime?.fs}catch{return}}#H(e){return`${Er}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#Q(e){const t=e||"default";if(this.#z.has(t))return;this.#z.add(t);const n=this.#J();if(n?.readFile)try{const e=await n.readFile(this.#H(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#v.import(r.records,t)}catch{}}async#Z(e){const t=this.#J();if(t)try{if(t.mkdir)try{await t.mkdir(Er)}catch{}const n={version:1,records:this.#v.export(e)},r=this.#H(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.#Q(n),this.#v.upsert(e,n),await this.#Z(n)}async query(e){const t=e.collection??"default";return await this.#Q(t),this.#v.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#Q(n),this.#v.delete(e,n),await this.#Z(n)}async clear(e){const t=e?.collection??"default";await this.#Q(t),this.#v.clear(t),await this.#Z(t)}async count(e){const t=e?.collection??"default";return await this.#Q(t),this.#v.count(t)}}let Ar,xr,Cr;function Tr(){return Ar||(xr||(xr=new Sr),xr)}function Nr(){if(!Cr)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 Cr}var Mr;!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"}(Mr||(Mr={}));class Pr extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const _r=new class{#X=new Map;#ee=new Map;registerCapability(e){if(!e.name)throw new Pr(Mr.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new Pr(Mr.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 Pr(Mr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" version "${e.version}" is not valid semver (expected MAJOR.MINOR.PATCH, e.g. "1.0.0")`,{capability:e.name,version:e.version});if(this.#X.has(e.name))throw new Pr(Mr.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 Pr(Mr.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 Pr(Mr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot require itself`,{capability:e.name,cycle:[e.name,e.name]});for(const t of e.requires){const n=this.#te(t,e.name);if(n)throw new Pr(Mr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#X.set(e.name,e);try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.({name:"capability.registered",envelope:{id:`cap-reg-${e.name}-${Date.now()}`,correlationId:`cap-reg-${e.name}`,timestampMs:Date.now(),source:"runtime:capabilities:registry",kind:"info"},payload:{capability:e.name,version:e.version,origin:"core",risk:e.risk,sideEffect:e.sideEffect,deprecated:e.deprecated??null}})}catch{}}#te(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#X.get(e);if(!r?.requires)return null;for(const i of r.requires){const r=this.#te(i,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#X.has(e.name))throw new Pr(Mr.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ee.set(e.name,e)}getSpec(e){return this.#X.get(e)}getProvider(e){return this.#ee.get(e)}hasCapability(e){return this.#X.has(e)}hasProvider(e){return this.#ee.has(e)}listCapabilities(){return Array.from(this.#X.keys())}getAllSpecs(){return Array.from(this.#X.values())}clear(){this.#X.clear(),this.#ee.clear()}};function Rr(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.requires&&e.requires.length>0&&(t.requires=[...e.requires]),e.permissions&&e.permissions.length>0&&(t["x-permissions"]=[...e.permissions]),e.secretBearing&&(t["x-secretBearing"]=!0),t}function $r(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:jr(e.sideEffects),risk:e.policy?.risk??"low",permissions:n,inputSchema:e.inputs?.schema,outputSchema:e.outputs?.schema};return 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),e.deprecated&&(r.deprecated={...e.deprecated}),Array.isArray(e.requires)&&e.requires.length>0&&(r.requires=[...e.requires]),e.policy&&(r.policy={...e.policy}),r}const Lr=["write","delete","remove","modify","destroy","create","update","install","publish","process","spawn","exec","run"],Or=["network","http","fetch","request","upload","download"],Dr=["read","list","get","query","inspect","search"];function jr(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":Lr.some(t=>e.includes(t))?"write":Or.some(t=>e.includes(t))?"network":Dr.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 Fr=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function qr(){const e=globalThis;return e.punica?.extensions?.manager}function Br(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function Ur(){const e=globalThis;return e.punica?.flow?.registry}function Vr(){const e=globalThis;return e.punica?.flow?.agents}function Wr(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const Kr={core:function(e){const t=_r.getSpec(e);if(t)return{origin:"core",definition:Rr(t)}},extension:function(e){const t=qr();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=Br();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=Ur();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-node",definition:r,metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},"ivy-agent":function(e){const t=Vr();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=Wr();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},Gr={core:function(){return _r.getAllSpecs().map(e=>({origin:"core",definition:Rr(e)}))},extension:function(){const e=qr();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=Br();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=Ur();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-node",definition:e,metadata:{packageRoot:n.manifestPath}})}return t},"ivy-agent":function(){const e=Vr();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=Wr();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Yr={getCapability(e){for(const t of Fr){const n=Kr[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 Fr)if(!t||t.has(e))for(const t of Gr[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 zr(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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Jr={recordSpan:()=>{}};function Hr(e){try{Jr.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function Qr(){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,Hr({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 Hr({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 Pr?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function Zr(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Zr);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Zr(r);return t}return e}const Xr=new WeakMap;function ei(){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=Zr(s);else{const e=function(e){const t=Xr.get(e);if(t)return t;const n=u(e.inputSchema);return Xr.set(e,n),n}(r.spec);r.redactedInput=e.length>0?d(s,e):s}return await t()}}function ti(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function ni(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===ti(t))}const ri=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&&(ni(i,t)||n.push(`Expected type "${i}", got "${ti(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&&(ni(i,r)||n.push(`Field "${t}": expected type "${i}", got "${ti(r)}"`))}}return{ok:0===n.length,errors:n}}};let ii=ri;function si(){return ii}function oi(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=si().validate(s,i);if(!o.ok)throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const ai=Fn({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function ci(){return ai.get()}const li=["path","oldPath","newPath","src","dst","target","linkPath"];function ui(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 di(){try{return ci().cwd}catch{return}}function pi(){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 li){const t=r[e];if("string"!=typeof t)continue;s||(i=di(),s=!0);const n=ui(t,i);if(!n.ok)throw new Pr(Mr.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 fi="encrypted-at-rest";function hi(){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 ci()}catch{return}}();if(!i)throw new Pr(Mr.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:fi,reason:"provider not registered"});if(!i.capabilities?.has(fi))throw new Pr(Mr.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${fi}" capability flag`,{capability:n.name,required:fi,reason:"capability not advertised"});return qn({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:fi}}),t()}}function mi(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 gi(){return async(e,t)=>{const n=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()}catch{return}}();if(!n)return t();const{allowedIds:r,deniedIds:i,allowedOrigins:s}=n.capabilities;if("*"===r&&!i?.length&&!s?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(s&&s.length>0){const e=Yr.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw mi(o,c,"origin-not-allowed",t,a),new Pr(Mr.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 mi(o,c,"in-denylist",void 0,a),new Pr(Mr.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 mi(o,c,"not-in-allowlist",void 0,a),new Pr(Mr.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const yi={alg:"HS256",typ:"PUNICA-APPROVAL"};class wi extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function vi(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 bi(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 Ii(e){return(new TextEncoder).encode(e)}function ki(e){return vi(Ii(JSON.stringify(e)))}function Ei(e){return JSON.parse((t=bi(e),(new TextDecoder).decode(t)));var t}function Si(){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 Ai(){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 xi{#ne;#re;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?Ii(e.secret):Ai()}async sign(e){const t=await this.#ie(),n=ki(yi),r=ki(e),i=Ii(`${n}.${r}`),s=await Si().sign("HMAC",t,i);return`${n}.${r}.${vi(new Uint8Array(s))}`}getSecret(){return this.#ne}async#ie(){return this.#re||(this.#re=await Si().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#re}}class Ci{#ne;#re;#se=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?Ii(e.secret):Ai()}async verify(e){const t=e.split(".");if(3!==t.length)throw new wi("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=Ei(n)}catch{throw new wi("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new wi("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=Ei(r)}catch{throw new wi("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#ie(),c=Ii(`${n}.${r}`);let l;try{l=bi(i)}catch{throw new wi("MALFORMED","Token signature is not valid base64url")}const u=Si();if(!await u.verify("HMAC",a,l,c))throw new wi("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new wi("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new wi("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#se.add(e)}isRevoked(e){return this.#se.has(e)}async#ie(){return this.#re||(this.#re=await Si().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#re}}let Ti;function Ni(){return Ti||(Ti=function(){const e=new xi,t=new Ci({secret:e.getSecret()});return{signer:e,verifier:t}}()),Ti}const Mi=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function Pi(){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 Pr(Mr.CAPABILITY_DENIED,`Policy manager unavailable and capability "${i}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:i,reason:"policy-manager-missing",risk:a,approval:c});return r.policyDecision={allowed:!0,requiresApproval:!1,reason:"policy-manager-missing (fail-open)"},await t()}const c=o.policy??{},l=c.risk??o.risk??"low",u=c.approval??"none";let d=!1,p="";if("ai"===s.actor.type){"approval"===Mi({capabilityId:i,risk:o.risk,sideEffect:o.sideEffect})&&(d=!0,p=`agent-mode policy: ${o.sideEffect}/${o.risk}`)}"high"===o.risk&&(d=!0,p="High risk capability"),"step"!==u&&"plan"!==u||(d=!0,p=`Capability requires ${u} approval`);const f={kind:"capability",id:i,risk:l,approval:u,reason:o.description??o.title??`Capability: ${i}`},h=a.evaluate(f,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});if(r.policyDecision={allowed:h.allowed,requiresApproval:h.requiresApproval||d,approvalToken:s.policy.approvalToken,reason:h.reason||p},d||h.requiresApproval)if(s.policy.approvalToken)try{await Ni().verifier.verify(s.policy.approvalToken)}catch(e){if(e instanceof wi){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 Pr(Mr.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:i,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!(a.hasApproval(f,"always",{workspaceId:s.workspaceId})||a.hasApproval(f,"workspace",{workspaceId:s.workspaceId})||a.hasApproval(f,"once",{workspaceId:s.workspaceId}))){a.requestApproval(f,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:i,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}throw new Pr(Mr.CAPABILITY_APPROVAL_REQUIRED,`Approval required: ${p}`,{capability:i,reason:p})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:s.workspaceId};if(!(a.hasApproval(f,"always",e)||a.hasApproval(f,"workspace",e))&&"function"==typeof a.revokeApproval)try{a.revokeApproval({kind:f.kind,id:f.id,scope:"once"})}catch{}}}if(!h.allowed&&!d&&"suggest"!==h.mode)throw new Pr(Mr.CAPABILITY_DENIED,h.reason??"Policy denied execution",{capability:i,decision:h});return await t()}}const _i=new class{#m=new Map;#oe;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#oe=t<=0?1:t}get(e,t){const n=this.#ae(e,t),r=this.#m.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#m.delete(n),this.#m.set(n,r),r;this.#m.delete(n)}}set(e){const t=this.#ae(e.capabilityId,e.key);for(this.#m.delete(t),this.#m.set(t,e);this.#m.size>this.#oe;){const e=this.#m.keys().next().value;if(void 0===e)break;this.#m.delete(e)}}delete(e,t){return this.#m.delete(this.#ae(e,t))}clear(){this.#m.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#m)r.expiresAtMs<=e&&(this.#m.delete(n),t++);return t}size(){return this.#m.size}#ae(e,t){return`${e}|${t}`}};let Ri=_i;function $i(){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 Pr(Mr.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=Ri,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 Pr(Mr.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 Li=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 Oi(){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(!Li.consumeToken(c,a.perSecond))throw new Pr(Mr.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const Di=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e){const t=this.#le.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function ji(){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 Di.acquire(a,o.max)}catch(e){throw new Pr(Mr.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{Di.release(a)}}}const Fi=new class{#ue=new Map;getBreaker(e){let t=this.#ue.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#ue.set(e,t)),t}};function qi(){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=Fi.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new Pr(Mr.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 Bi(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 Ui(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new Pr(Mr.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),s])}finally{void 0!==i&&clearTimeout(i)}}function Vi(e){return{invocationId:e.invocationId,capability:e.capability,actor:e.actor,origin:e.origin,capabilityOrigin:e.capabilityOrigin,workspace:e.workspaceId,policyDecision:e.policyDecision?{allowed:e.policyDecision.allowed,requiresApproval:e.policyDecision.requiresApproval,reason:e.policyDecision.reason}:void 0,input:e.redactedInput,output:e.redactedOutput,duration:e.durationMs,error:e.error?{message:e.error.message,name:e.error.name}:void 0,timestamp:e.timestamp}}async function Wi(e){try{if(function(e){const t=globalThis.punica?.kernel?.Events?.manager;if(!t||"function"!=typeof t.publishEvent||"function"!=typeof t.createCorrelationId)return!1;try{return t.publishEvent({name:"capability.audited",envelope:{id:t.createCorrelationId(),correlationId:e.invocationId,timestampMs:e.timestamp,source:"runtime:capabilities:gateway",kind:e.error?"error":"info"},payload:Vi(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(Vi(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=ci()}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(Vi(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 Ki=new WeakMap;function Gi(e,t){if(!0===t.secretBearing)return Yi(e);const n=function(e){const t=Ki.get(e);if(t)return t;const n=u(e.outputSchema);return Ki.set(e,n),n}(t);return n.length>0?d(e,n):e}function Yi(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Yi);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Yi(r);return t}return e}function zi(){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=Gi(r.output,o);await Wi({invocationId:n.invocationId,capability:i,actor:s.actor,origin:s.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:s.workspaceId,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Ji=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Hi(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const Qi=new class{async call(e,t,n,r){const i=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let s=_r.getSpec(e),o=s?_r.getProvider(e):void 0,a="core";if(!s){const t=Yr.getCapability(e);if(!t)throw Hi({name:"capability.unknown_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:n.actor}}),new Pr(Mr.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,s=$r(t.definition),o=zr(t.origin,t.definition,t.metadata)}if(!o)throw new Pr(Mr.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(s.requires)for(const t of s.requires)if(!_r.hasCapability(t))throw new Pr(Mr.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});s.deprecated&&Hi({name:"capability.deprecated_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:a,since:s.deprecated.since,reason:s.deprecated.reason,replacement:s.deprecated.replacement,actor:n.actor}});const c={req:{invocationId:i,name:e,input:t,ctx:n,idempotencyKey:r},state:{spec:s,capabilityOrigin:a,startTimeMs:Date.now(),tags:{}}},l=this.#de(o);try{return await this.#pe(l,c)}catch(e){if(e instanceof Pr)throw e;throw new Pr(Mr.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#de(e){const t={auditTrail:zi,traceMetrics:Qr,redaction:ei,validateInput:oi,pathTraversalGuard:pi,encryptionRouting:hi,profileBudget:gi,policyGate:Pi,idempotency:$i,rateLimit:Oi,concurrency:ji,circuitBreaker:qi,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 Ui(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),f<=l&&d&&Bi(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 Ji.map(e=>t[e]())}#pe(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const i=e[n];return n++,await i(t,r)};return r()}};function Zi(e,t){const n=ci(),r=n[t];if("function"!=typeof r)throw new Pr(Mr.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 Xi(e,t,n){const r=ci();if(!r.capabilities?.has(n))throw new Pr(Mr.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 Pr(Mr.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 es{name="fs.readFile";async execute(e,t){const n=ci();return await n.readFile(e.path)}}class ts{name="fs.writeFile";async execute(e,t){const n=ci();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}class ns{name="fs.listFiles";async execute(e,t){const n=ci();return await n.getFileTree()}}class rs{name="fs.stat";async execute(e,t){return await Zi("fs.stat","stat")(e.path)}}class is{name="fs.exists";async execute(e,t){return await Zi("fs.exists","exists")(e.path)}}class ss{name="fs.copy";async execute(e,t){await Zi("fs.copy","copy")(e.src,e.dst)}}class os{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Zi("fs.mkdir","mkdir")(e.path,n)}}class as{name="fs.history";async execute(e,t){return await Xi("fs.history","history","versioning")(e.path)}}class cs{name="fs.readAtVersion";async execute(e,t){return await Xi("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class ls{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Zi("fs.list","list")(e.path,n)}}const us=Fn({label:"Runtime.secrets",noProviderMessage:"[Runtime.secrets] No Secrets provider registered. Host must call punica.runtime.setSecretsProvider() before using Secrets API",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.secrets??function(){const e=new Map,t=new Map;return{set(n,r){const i=String(n??"").trim();if(!i)throw new Error("[Runtime.secrets] Secret name is required");const s=Date.now();if(t.has(i)){const e=t.get(i);t.set(i,{...e,updatedAtMs:s})}else t.set(i,{createdAtMs:s,updatedAtMs:s});e.set(i,String(r??""))},get(t){const n=String(t??"").trim();return n&&e.has(n)?e.get(n):null},delete(n){const r=String(n??"").trim();return!!r&&(t.delete(r),e.delete(r))},list(){const e=[];for(const[n,r]of t.entries())e.push({name:n,createdAtMs:r.createdAtMs,updatedAtMs:r.updatedAtMs});return e.sort((e,t)=>e.name.localeCompare(t.name)),e}}}()}});function ds(){return us.get()}function ps(e){us.set(e),e&&qn({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class fs{name="secrets.get";async execute(e,t){return ds().get(e.name)}}class hs{name="secrets.set";async execute(e,t){ds().set(e.name,e.value)}}function ms(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Kn]=!0,n}class gs{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=ms(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class ys{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=ms(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 ws{name="llm.invoke";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.invoke(e,{correlationId:t.sessionId??t.trace?.traceId})}}class vs{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 bs{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 Is{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 ks{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 Es{name="workspace.readFile";async execute(e,t){const n=ci();return await n.readFile(e.path)}}class Ss{name="workspace.writeFile";async execute(e,t){const n=ci();await n.createFileWithContent(e.path,e.content)}}class As{name="workspace.listFiles";async execute(e,t){const n=ci(),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 xs=[".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"],Cs=["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 Ts(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 Ns={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"},Ms=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 Ps(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 _s(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function Rs(e,t,n){const r=new Map;for(const t of e){if(t.endsWith("/"))continue;const e=Ns[_s(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 $s(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(Ms.has(e)&&n.add(t),n.size>=8)break}return[...n].slice(0,8)}function Ls(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=Ps(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=Ps(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:Rs(e.layout,!!t.node,!!t.python),dependencies:t,entrypoints:$s(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 Os=["readme.md","readme.rst","readme.txt","readme"];async function Ds(e,t){try{return await e.readFile(t)}catch{return}}async function js(){const e=ci(),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(xs),n=new Set(Cs),r=(e.gitignore??"").split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")&&!e.startsWith("!")),i=r.map(Ts).filter(e=>null!=e),s=[],o=new Set,a=e=>{o.has(e)||(o.add(e),s.push(e))};for(const e of xs)a(`${e}/`);for(const e of Cs)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 Ds(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)?Ds(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 Os)if(n.has(t)&&(u=await Ds(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:Ls({workspace:d,layout:i,layoutTruncated:s,packageJson:a,requirementsTxt:c,pyproject:l,readme:u,vcs:p}),noisePatterns:r.patterns}}class Fs{name="workspace.projectContext";async execute(e,t){const{context:n}=await js();return n}}async function qs(e,t,n){try{await e.updateFileContent(t,n)}catch{await e.createFileWithContent(t,n)}}class Bs{name="workspace.writeOrientation";async execute(e,t){const n=!1!==e?.claudeMd,r=!1!==e?.claudeignore,i=ci(),{context:s,noisePatterns:o}=await js(),a=[];if(n&&(await qs(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 qs(i,".claudeignore",e),a.push(".claudeignore")}return{written:a}}}const Us=".punica/facts",Vs=`${Us}/facts.json`;async function Ws(e){let t;try{t=await e.readFile(Vs)}catch{return{}}try{const e=JSON.parse(t);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}class Ks{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=ci(),i=await Ws(r);return i[n]=e.value??null,await async function(e,t){const n=`${JSON.stringify(t,null,2)}\n`;try{await e.updateFileContent(Vs,n)}catch{try{await e.createFolder(".punica")}catch{}try{await e.createFolder(Us)}catch{}await e.createFileWithContent(Vs,n)}}(r,i),{key:n,count:Object.keys(i).length}}}class Gs{name="context.recall";async execute(e,t){const n=ci(),r=await Ws(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 Ys{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 zs{name="terminals.send";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");n.write(e.id,e.text)}}class Js{name="tasks.runCommand";async execute(e,t){const n=globalThis.punica?.runtime?.tasks;if(!n)throw new Error("Tasks provider not available");return await n.run(e)}}class Hs{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 Qs{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 Zs="capability.catalog";class Xs{name=Zs;async execute(e,t){const n=e??{},r=Yr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>eo(e,n));return{capabilities:r,count:r.length}}}function eo(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=to(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=to(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=to(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 to(e){return Array.isArray(e)?e:[e]}const no=["examples","$comment","default","title"];function ro(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 io=["properties","patternProperties","definitions","$defs"];function so(e){if(Array.isArray(e))return e.map(e=>so(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!no.includes(n))if("description"!==n||"string"!=typeof r){if(io.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=so(n);t[n]=e;continue}t[n]=so(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const oo="capability.schemaExport";class ao{name=oo;async execute(e,t){const n=e??{},r=n.filter??{},i=Yr.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>eo(e,r)),s=n.mode??"full",o=i.map(e=>{const t=function(e){const t=e.definition,n={id:t.id,origin:e.origin,version:t.version,title:t.title};void 0!==t.description&&(n.description=t.description);void 0!==t.inputs?.schema&&(n.inputSchema=t.inputs.schema);void 0!==t.outputs?.schema&&(n.outputSchema=t.outputs.schema);t.policy&&(n.policy={risk:t.policy.risk,approval:t.policy.approval});t.tags&&t.tags.length>0&&(n.tags=[...t.tags]);t.sideEffects&&t.sideEffects.length>0&&(n.sideEffects=[...t.sideEffects]);const r=t.requires;r&&r.length>0&&(n.requires=[...r]);t.deprecated&&(n.deprecated={...t.deprecated});if(e.metadata){const t={};for(const[n,r]of Object.entries(e.metadata))void 0!==r&&(t[n]=r);Object.keys(t).length>0&&(n.metadata=t)}return n}(e);return"ai-tools"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=ro(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=so(e.inputSchema));e.policy&&(t.policy={...e.policy});return t}(t):"summary"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=ro(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 co={"ı":"i","ø":"o","đ":"d","ł":"l","ß":"ss","æ":"ae","œ":"oe"};function lo(e){return e.length<4||!e.endsWith("s")||/(?:ss|us|is)$/.test(e)?e:e.slice(0,-1)}function uo(e){return function(e){let t="";for(const n of e)t+=co[n]??n;return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}(e.toLowerCase()).split(/[^a-z0-9]+/).filter(e=>e.length>=2).map(lo)}function po(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function fo(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 ho(e,t){const n=po(uo(e));return t.map(e=>({...e,score:fo(n,po(uo(e.text)))}))}const mo={tr:{roots:{ac:"open",kapat:"close",kaydet:"save",kayit:"record log",sil:"delete remove",olustur:"create new",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",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",metin:"text",yol:"path",uzanti:"extension",surum:"version",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"},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"]}},go=new Map,yo=new Set;for(const e of Object.values(mo)){for(const[t,n]of Object.entries(e.roots)){const e=uo(t).join("");e.length>0&&go.set(e,uo(n))}for(const t of e.stopWords){const e=uo(t).join("");e.length>0&&yo.add(e)}}const wo=[...go.keys()].sort((e,t)=>t.length-e.length);new Map;function vo(e){let t=0;for(const n of e)n.score>t&&(t=n.score);return t}async function bo(e,t,n){const r=t=>("text-similarity"!==t.path&&Wn("llm.normalizeIntent",{intent:e,path:t.path,normalizedAs:t.text,topScore:t.score}),{scores:t.scores,path:t.path,...void 0===t.text?{}:{normalizedAs:t.text}}),i=ho(e,t);let s={scores:i,score:vo(i),path:"text-similarity"};if(s.score>=.25)return r(s);const o=(e,n)=>{const r=ho(e,t),i=vo(r);i>s.score&&(s={scores:r,score:i,path:n,text:e})},a=function(e){const t=[];for(const n of e){if(yo.has(n))continue;const e=wo.find(e=>n.startsWith(e));e?t.push(n,...go.get(e)):t.push(n)}return t}(uo(e)).join(" ");return a.length>0&&o(a,"lexicon"),s.score,r(s)}async function Io(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return{recommendations:[],path:"text-similarity"};const i=Yr.listCapabilities();if(0===i.length)return{recommendations:[],path:"text-similarity"};const s=i.map(e=>({id:e.definition.id,description:e.definition.description,text:ko(e.definition)}));let o,a,c;{const e=await bo(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 Wn("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 ko(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 Eo="capability.recommend";class So{name=Eo;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await Io(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 Ao="capability.describe",xo="capability.search";function Co(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class To{name=Ao;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new ao).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 No{name=xo;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=Yr.listCapabilities(),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await async function(e,t){return(await Io(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:ro(t?.description??t?.title??e,100),category:Co(e)}});return{results:c,count:c.length}}}function Mo(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Po(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 _o{name="ai.session.create";async execute(e,t){const n=e??{};return{session:Mo().create(n)}}}class Ro{name="ai.session.list";async execute(e,t){const n=Mo().list(e?.workspaceId);return{sessions:n,count:n.length}}}class $o{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:Mo().get(n)}}}class Lo{name="ai.session.rename";async execute(e,t){const n=e;return{ok:Mo().rename(String(n?.sessionId??""),String(n?.title??""))}}}class Oo{name="ai.session.archive";async execute(e,t){const n=e;return{ok:Mo().archive(String(n?.sessionId??""),n?.archived)}}}class Do{name="ai.session.delete";async execute(e,t){return{ok:Mo().delete(String(e?.sessionId??""))}}}const jo={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"}]}},Fo={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"}]}},qo=new Set(["low","medium","high"]),Bo={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&qo.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"}]:[]}},Uo=new Set(["none","plan","step"]),Vo={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Uo.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 Wo={id:"untyped-inputs",severity:"warning",check(e){const t=e.inputs;return t&&"object"==typeof t?function(e){const t=e.schema;if(t&&"object"==typeof t){const e=t;if(void 0!==e.type||void 0!==e.properties)return!0}for(const[t,n]of Object.entries(e))if("schema"!==t&&n&&"object"==typeof n&&void 0!==n.type)return!0;return!1}(t)?[]:[{ruleId:"untyped-inputs",severity:"warning",message:`Capability "${e.id}" declares inputs without type information — the agent generates arguments from this; add a JSON Schema (inputs.schema) or per-field types`,capabilityId:String(e.id),path:"inputs",code:"CAP_UNTYPED_INPUTS"}]:[]}},Ko=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,Go={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Ko.test(t)?[]:[{ruleId:"id-naming",severity:"warning",message:`Capability id "${String(t)}" is not a dotted <namespace>.<action> name (e.g. "editor.openFile") — consistent ids project cleanly to MCP and group related tools`,capabilityId:String(t),path:"id",code:"CAP_ID_NAMING"}]}},Yo=new Set(["low","medium","high"]),zo=["write","delete","remove","modify","destroy"],Jo=[jo,Fo,Bo,Vo,Wo,Go,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Yo.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&&zo.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 Ho=new class{#fe=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#fe.values())try{const r=n.check(e);r&&r.length>0&&t.push(...r)}catch(r){t.push({ruleId:n.id,severity:"info",message:`Lint rule "${n.id}" threw during analysis: ${String(r?.message??r)}`,capabilityId:String(e.id),code:"CAP_LINT_RULE_ERROR"})}return{ok:!t.some(e=>"error"===e.severity),issues:t}}lintAll(e){return e.map(e=>({id:String(e.id),...this.lint(e)}))}register(e){if(!e||"function"!=typeof e.check)throw new Error("CapabilityLinter.register: rule must have a check(def) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("CapabilityLinter.register: rule.id must be a non-empty string");this.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of Jo)this.#fe.set(e.id,e)}},Qo="capability.lint";class Zo{name=Qo;async execute(e,t){const n=e??{},r=Yr.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=Ho.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 Xo={type:"object"};function ea(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ta(e){let t;return t=function(e){if(e instanceof Pr)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:ea(e),{content:[{type:"text",text:t}],isError:!0}}const na="capability.serveList",ra="capability.serveCall",ia=new Set([na,ra]);class sa{name=na;async execute(e,t){const n=(e??{}).filter??{},r=Yr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!ia.has(e.definition.id)).filter(e=>eo(e,n)).map(e=>function(e,t){const n=t??e.id,r=e.sideEffects??[];return{name:n,description:e.description??e.title??n,inputSchema:e.inputs?.schema??Xo,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class oa{name=ra;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||ia.has(r)||!Yr.getCapability(r))return ta(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:ea(e)}],isError:!1}}(await Qi.call(r,n.arguments??{},t))}catch(e){return ta(e)}}}const aa="shell.revealView",ca="shell.hideView",la="shell.listViews",ua="shell.toggleView",da="shell.toggleSlot",pa="shell.moveView";function fa(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new Pr(Mr.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:aa});return e}function ha(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 ma{name=aa;async execute(e,t){const{viewId:n,focus:r}=e??{},i=fa();if(!i.getPlacement(n))throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:aa,viewId:n});return await i.reveal(n,ha(t),{focus:r}),{viewId:n,revealed:!0}}}class ga{name=ca;async execute(e,t){const{viewId:n}=e??{};return fa().hide(n,ha(t)),{viewId:n,hidden:!0}}}class ya{name=la;async execute(e,t){return{views:fa().listViews()}}}class wa{name=ua;async execute(e,t){const{viewId:n,focus:r}=e??{},i=fa();if(!i.getPlacement(n))throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:ua,viewId:n});return"visible"===i.getState(n)?(i.hide(n,ha(t)),{viewId:n,visible:!1}):(await i.reveal(n,ha(t),{focus:r}),{viewId:n,visible:!0})}}const va=new Map;class ba{name=da;async execute(e,t){const{slot:n,focus:r}=e??{},i=fa(),s=i.getVisibleView(n);if(s)return va.set(n,s),i.hide(s,ha(t)),{slot:n,visible:!1,viewId:s};const o=va.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,ha(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}class Ia{name=pa;async execute(e,t){const{viewId:n,slot:r}=e??{},i=fa(),s=i.getPlacement(n);if(!s)throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover movable views.`,{capability:pa,viewId:n});const o=s.allowedSlots??[];if(!o.includes(r))throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`View "${n}" cannot be moved to slot "${r}". Allowed slots: ${o.length?o.join(", "):"(none)"}.`,{capability:pa,viewId:n,slot:r});return await i.moveView(n,r,ha(t)),{viewId:n,slot:r,moved:!0}}}function ka(e){try{_r.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function Ea(e){const{definition:t,origin:n,metadata:r}=e;return{id:t.id,origin:n,title:t.title,risk:t.policy?.risk,approval:t.policy?.approval,outputKind:t.outputs?.kind,resultEvent:t.outputs?.resultEvent,extensionName:r?.extensionName,productId:r?.productId,packageRoot:r?.packageRoot}}function Sa(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 Aa(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=Yr.getCapability(e.id);return t?void Sa(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Yr.listCapabilities(n),i=r.map(Ea);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)Sa(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function xa(e){return Aa({...e,verbose:!0})}function Ca(e){switch(e){case"core":return"Core";case"extension":return"Extension";case"instruction-class":return"Instruction class";case"ivy-node":return"Ivy node";case"ivy-agent":return"Ivy agent";case"mcp":return"MCP";default:return String(e)}}function Ta(e){const t=e.definition,n=`[\`${t.id}\`](./${t.id}.md)`,r=t.version,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 Na(e){return JSON.stringify(e,null,2)}const Ma=new class{#he=new Map;get(e){return this.#he.get(e)}list(){return[...this.#he.values()]}register(e,t){for(const e of t)this.#he.set(e.definition.id,e),this.#me(e.definition.id)}unregister(e){for(const[t,n]of this.#he)n.serverId===e&&(this.#he.delete(t),this.#ge(t))}hasServer(e){for(const t of this.#he.values())if(t.serverId===e)return!0;return!1}#me(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.registered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}#ge(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.unregistered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}},Pa=16384,_a="runtime:mcp:client";function Ra(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function $a(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 $a(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=>$a(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]=$a(i,t+1);return n}return e}function La(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=Pa)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify($a(e,0),null,2)??"null";if(r.length<=Pa)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,Pa)+"\n… [truncated]",bytes:n,truncated:!0}}function Oa(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const Da=new class{#ye=new Map;async connect(e){if(this.#ye.has(e.id))return this.#ye.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return Ka}),r=e.toolOverrides??await t(e.id),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:Oa(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=Ra(),s=La(r??{});qn({name:"mcp.request",source:_a,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:ke().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=Ra(),s=Date.now(),o=La(r??{});qn({name:"mcp.request",source:_a,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:ke().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=La(o??null);return qn({name:"mcp.response",source:_a,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:ke().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw qn({name:"mcp.response",source:_a,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 pg});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 fg});return new t(e.url,e.headers??{})}throw new Error(`MCP server "${e.id}": unknown transport kind "${e.kind}"`)}(o));await a.connect(),await a.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"punica-editor",version:"1.0.0"}}),a.notify("notifications/initialized",{});const c=await a.request("tools/list",{}),l=c?.tools??[],u=l.map(e=>{const t=o.toolOverrides?.[e.name]??{},n=function(e,t,n={}){const r=t._meta?.punica??{},i={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},s={timeoutMs:n.executionDefaults?.timeoutMs??r.executionDefaults?.timeoutMs??3e4,idempotency:n.executionDefaults?.idempotency??r.executionDefaults?.idempotency??"none"},o=["mcp",e],a=r.tags??[],c=n.tags??[],l=[...new Set([...o,...a,...c])],u=n.sideEffects??r.sideEffects??["mcp-invocation","network"];return{id:`mcp.${e}.${t.name}`,title:t.name,description:t.description??`MCP tool ${t.name} from server ${e}`,version:"1.0.0",inputs:{schema:t.inputSchema??{type:"object"}},outputs:{schema:{type:"object",properties:{content:{type:"array",items:{type:"object",properties:{type:{type:"string"},text:{type:"string"}}}},isError:{type:"boolean"}}},kind:"direct"},policy:i,sideEffects:u,executionDefaults:s,tags:l}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});Ma.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(),Ma.unregister(e.id),this.#ye.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#ye.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#ye.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#ye.values()].map(e=>e.handle)}listTools(e){return e?this.#ye.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#ye.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},ja=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/,Fa=/^\$\{secret\.([A-Za-z0-9_.-]+)\}$/;async function qa(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 Ba(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(Fa);if(e){const n=e[1],r=await qa(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(ja);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 Ua(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 Gd}),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 Va(){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 hg}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await Ua(e.id),n="stdio"===e.kind?await Ba(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?await Ba(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 Wa(e){if(!e||"object"!=typeof e)return[];const t=e;if(!Array.isArray(t.servers))return[];const n=[];for(const e of t.servers){if(!e||"object"!=typeof e)continue;const t=e;if("string"!=typeof t.id)continue;const r=t.transport??t.kind??"stdio";if("stdio"===r){const e="object"==typeof t.env&&null!==t.env?t.env:{};n.push({id:t.id,name:"string"==typeof t.name?t.name:void 0,kind:"stdio",command:"string"==typeof t.command?t.command:void 0,args:Array.isArray(t.args)?t.args:[],env:e})}else if("streamable-http"===r||"sse"===r){const e="object"==typeof t.headers&&null!==t.headers?t.headers:{};n.push({id:t.id,name:"string"==typeof t.name?t.name:void 0,kind:r,url:"string"==typeof t.url?t.url:void 0,headers:e})}}return n}var Ka=Object.freeze({__proto__:null,loadMcpConfig:Va,loadServerOverrides:Ua,parseStaticConfig:Wa,resolveEnvPlaceholders:Ba});class Ga{name=st.RUNTIME.MCP;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.RUNTIME.FS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){this.#we=e.BOOTSTRAPPING;const n=await Va();this.#ve(n),this.#we=e.BOOTSTRAPPED}async#ve(e){for(const t of e)try{await Da.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#we=e.STARTING,this.#we=e.STARTED,console.log(`[Punica] MCP module started — ${Ma.list().length} capability(ies) active`)}}const Ya=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const za={get capabilities(){return ai.hasProvider()?ai.get().capabilities:void 0},get cwd(){return ai.hasProvider()?ai.get().cwd:void 0},hasProvider:()=>ai.hasProvider(),getFileTree:()=>ai.get().getFileTree(),readFile:e=>ai.get().readFile(e),readBytes:(e,t,n)=>{const r=ai.get();if("function"!=typeof r.readBytes)throw new Error("[Runtime.fs] Provider does not implement readBytes()");return r.readBytes(e,t,n)},updateFileContent:(e,t)=>ai.get().updateFileContent(e,t),createFolder:e=>ai.get().createFolder(e),deleteFolder:e=>ai.get().deleteFolder(e),deleteFile:(e,t)=>ai.get().deleteFile(e,t),renameFile:(e,t)=>ai.get().renameFile(e,t),renameFolder:(e,t)=>ai.get().renameFolder(e,t),revealInOS:e=>{const t=ai.get();if("function"!=typeof t.revealInOS)throw new Error("[Runtime.fs] Provider does not implement revealInOS()");return t.revealInOS(e)},createFileWithContent:(e,t)=>ai.get().createFileWithContent(e,t),list:(e,t)=>{const n=ai.get();if("function"!=typeof n.list)throw new Error("[Runtime.fs] Provider does not implement list()");return n.list(e,t)},stat:e=>{const t=ai.get();if("function"!=typeof t.stat)throw new Error("[Runtime.fs] Provider does not implement stat()");return t.stat(e)},mkdir:(e,t)=>{const n=ai.get();if("function"!=typeof n.mkdir)throw new Error("[Runtime.fs] Provider does not implement mkdir()");return n.mkdir(e,t)},__punicaWrappedFsFacade:!0},Ja=function(e){return e||{query:e=>Ln().query(e),startIndex:e=>{const t=Ln();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(Ya?.search),Ha=function(e){return e||{status:()=>jn().status(),branches:()=>jn().branches(),logs:e=>jn().logs(e),init:e=>jn().init(e),clone:e=>jn().clone(e),commit:e=>jn().commit(e),stage:e=>jn().stage(e),unstage:e=>jn().unstage(e),discard:e=>jn().discard(e),reset:e=>jn().reset(e),switchBranch:e=>jn().switchBranch(e),createBranch:(e,t)=>jn().createBranch(e,t),fetch:e=>jn().fetch(e),pull:e=>jn().pull(e),push:e=>jn().push(e)}}(Ya?.vcs),Qa=function(e){return e||{create:e=>On().create(e),write:(e,t)=>On().write(e,t),resize:(e,t,n)=>On().resize(e,t,n),close:e=>On().close(e),onData:(e,t)=>On().onData(e,t),onExit:(e,t)=>On().onExit(e,t),list:()=>On().list()}}(Ya?.terminals),Za=function(e){return e||{start:e=>Dn().start(e),send:(e,t)=>Dn().send(e,t),onMessage:(e,t)=>Dn().onMessage(e,t),onStderr:(e,t)=>Dn().onStderr(e,t),onExit:(e,t)=>Dn().onExit(e,t),stop:e=>Dn().stop(e),list:()=>Dn().list()}}(Ya?.debug),Xa=function(e){return e||{run:e=>function(){if(Mn)return Mn;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return Mn=e,Mn}().run(e)}}(Ya?.tasks),ec=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&Vn(e),{getCurrent:()=>Bn.get().getCurrent(),list:()=>Bn.get().list(),open:e=>Bn.get().open(e),setEnvironment:(e,t)=>Bn.get().setEnvironment(e,t),onDidChange:e=>Bn.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(Ya?.workspace),tc=function(e){return e||{list:async e=>$n().list(e),get:e=>$n().get(e),register:e=>$n().register(e),unregister:e=>$n().unregister(e),onDidChange:e=>$n().onDidChange(e)}}(Ya?.resources),nc=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&Hn(e),t)return e;function n(e){if("remote"===e?.route)return!0;if("local"===e?.route)return!1;if(e?.providerId){const t=String(e.providerId).toLowerCase();if(t.startsWith("remote:"))return!0;if(t.startsWith("local:"))return!1}return!0}async function r(e,t,n){!function(e,t){(Yn&&Yn!==e||zn&&t&&zn!==t)&&Y.publishEvent({name:"llm.providerChanged",envelope:{id:Y.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:Yn,newProviderId:e,previousEndpoint:zn,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),Yn=e,t&&(zn=t)}(t,n);const r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch(e){return void console.error("[LLM Facade] Error accessing punica.runtime.workspace (gateRemoteRequest):",e?.message??e)}})(),i=e?.correlationId??Y.createCorrelationId(),s=ge.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!s.allowed)throw s.requiresApproval&&ge.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:i}),Y.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:Y.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(s.reason??"[Policy] Remote LLM request denied");return Y.publishEvent({name:"llm.remoteRequestSent",envelope:{id:Y.createCorrelationId(),correlationId:i,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:i,route:"remote",providerId:t}:{...e,correlationId:i}}const i={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",i=e?.providerId??"remote",s=Jn(),o=!0===e?.[Kn];if(!o&&("remote"===t||n(e))){const t=e?.endpoint,n=await r(e,i,t);return await s.chat(n)}const a=await s.chat(e);if(!a)throw new Error("[LLM Facade] No response returned from LLM provider");const c=a?.provider;if(!o&&function(e){if(!e)return!1;const t=String(e).toLowerCase();return!t.startsWith("local:")&&"local"!==t&&"mock"!==t&&"ollama"!==t&&!t.startsWith("ollama-")&&"llama.cpp"!==t&&"llamacpp"!==t}(c)){const n=c&&"remote"!==c?c:i,r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch{return}})(),s=e?.correlationId??Y.createCorrelationId(),o=ge.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw Y.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:Y.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"error"},payload:{providerId:n,route:t,workspaceId:r,messageCount:e.messages?.length??0,reason:"Policy gate bypassed via auto route"}}),o.requiresApproval&&ge.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)");Y.publishEvent({name:"llm.remoteRequestSent",envelope:{id:Y.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:n,workspaceId:r,messageCount:e.messages?.length??0,retroactive:!0,route:t}})}return a},chatStream:async function*(e){if(e?.signal?.aborted)return;const t=e?.route??"auto",i=e?.providerId??"remote",s=Jn();let o=e;if(!(!0===e?.[Kn])&&("remote"===t||n(e))){const t=e?.endpoint;o=await r(e,i,t)}if("function"!=typeof s.chatStream){const e=await s.chat(o);if(!e)throw new Error("[LLM Facade] No response returned from LLM provider");if(o?.signal?.aborted)return;"string"==typeof e.text&&e.text.length>0&&(yield{type:"content",text:e.text});for(const t of e.toolCalls??[])yield{type:"tool_call",toolCall:t};return void(yield{type:"done",response:e})}for await(const e of s.chatStream(o)){if(o?.signal?.aborted)return;yield e}},__punicaWrappedLlmFacade:!0};return i.manager=function(){const e=("undefined"!=typeof window?window.api:void 0)?.llm;if(!e)return;return{listModels:async t=>await(e.listModels?.(t)),listInstalled:async()=>await(e.listInstalled?.()),setActiveModel:async t=>{await(e.setActive?.({modelId:t??null}))},removeModel:async t=>{await(e.remove?.({modelId:t}))},downloadModel:async t=>{await(e.download?.({modelId:t}))},pickModelFile:async()=>await(e.pickModelFile?.()),importModelFile:async t=>{await(e.importModelFile?.(t))},..."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?.())}}}(),i}(Ya?.llm),rc=function(e){if(e)return e;const t=Xn(),n=new er(t),r=new cr(t,n);t.registerLanguageRuntime(nr),t.registerLanguageRuntime(rr),t.registerLanguageRuntime(ir),t.registerLanguageRuntime(sr),t.registerLanguageRuntime(or);const i=new Map;return{async*run(e,t){const n=t?.runId??ar("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}}(Ya?.compute),ic=function(e){if(e)return e;const t=dr(),n=new pr(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}}(Ya?.datasets),sc=function(e){if(e)return e;const t=mr(),n=new gr(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}}(Ya?.models),oc=function(e){if(e)return e;const t=vr();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)}}}(Ya?.modelRuntimes),ac=function(e){if(e)return e;const t=vr();return{async infer(e){const n=e.handle?.runtimeId;if(!n)throw new Error("inference.infer requires a started runtime handle (req.handle from runtime.modelRuntimes.start).");const r=t.get(n);if(!r)throw new Error(`No model runtime registered for handle runtimeId="${n}".`);if("function"!=typeof r.infer)throw new Error(`Model runtime "${n}" does not support inference (no infer()). Task: ${e.task}.`);return r.infer(e)}}}(Ya?.inference),cc=function(e){return e||{upsert:(e,t)=>Tr().upsert(e,t),query:e=>Tr().query(e),delete:(e,t)=>Tr().delete(e,t),clear:e=>Tr().clear(e),count:e=>Tr().count(e)}}(Ya?.vectors),lc=function(e){if(e)return e;function t(){const e=Nr().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=Nr().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=Nr().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=Nr().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:()=>Nr().dataDir(),dataFs:{list:(e,t)=>Nr().dataFs.list(e,t),readFile:e=>Nr().dataFs.readFile(e),stat:e=>Nr().dataFs.stat(e),mkdir:(e,t)=>Nr().dataFs.mkdir(e,t),deleteFile:e=>Nr().dataFs.deleteFile(e),deleteFolder:e=>Nr().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=Nr().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=Nr().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=Cr?.http?.download;if(e)return e=>n().download(e)},get onDownloadProgress(){const e=Cr?.http?.onDownloadProgress;if(e)return e=>n().onDownloadProgress(e)}},get mcpServer(){return Cr?.mcpServer?i:void 0},get system(){return Cr?.system?s:void 0}}}(Ya?.host),uc=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&ps(e);return{set:(e,t)=>us.get().set(e,t),get:e=>us.get().get(e),delete:e=>us.get().delete(e),list:()=>us.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:us.get().get(`secret-manager.${e}`)},__punicaWrappedSecretsFacade:!0}}(Ya?.secrets);console.log("[Runtime] Facades created"),function(){ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new es),ka({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",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),_r.registerProvider(new ts),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),_r.registerProvider(new ns),ka({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",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}}),_r.registerProvider(new rs),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"boolean"},defaults:{timeoutMs:1e4}}),_r.registerProvider(new is),ka({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",risk:"medium",permissions:[],inputSchema:{type:"object",required:["src","dst"],properties:{src:{type:"string"},dst:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),_r.registerProvider(new ss),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),_r.registerProvider(new os),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),_r.registerProvider(new ls),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:1e4}}),_r.registerProvider(new as),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path","versionId"],properties:{path:{type:"string"},versionId:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new cs),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"}}},outputSchema:{type:["string","null"]},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3}}),_r.registerProvider(new fs),ka({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",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"}}),_r.registerProvider(new hs),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),_r.registerProvider(new gs),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),_r.registerProvider(new ys),ka({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",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}}}),_r.registerProvider(new vs),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string"},userPrompt:{type:"string"},context:{type:"object"},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"},stream:{type:"boolean"},skipCache:{type:"boolean"},skipFallback:{type:"boolean"}}}}},outputSchema:{type:"object",properties:{ok:{type:"boolean"},result:{type:"string"},parsed:{}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),_r.registerProvider(new ws),ka({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",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}}),_r.registerProvider(new bs),ka({name:"vcs.status",title:"Uncommitted changes",description:"Show which files have uncommitted changes in version control: modified, added, deleted, and untracked.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),_r.registerProvider(new Is),ka({name:"vcs.commit",title:"Commit changes",description:"Commit the current changes to version control with a message.",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["message"],properties:{message:{type:"string"},all:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),_r.registerProvider(new ks),ka({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.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new Es),ka({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.",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),_r.registerProvider(new Ss),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object"}}}},defaults:{timeoutMs:3e4}}),_r.registerProvider(new As),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new Fs),ka({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",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"}}),_r.registerProvider(new Bs),ka({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",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"}}),_r.registerProvider(new Ks),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{key:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),_r.registerProvider(new Gs),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{title:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),_r.registerProvider(new Ys),ka({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["id","text"],properties:{id:{type:"string"},text:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:5e3,idempotency:"optional"}}),_r.registerProvider(new zs),ka({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",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"}}),_r.registerProvider(new Js),ka({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",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}}),_r.registerProvider(new Hs),ka({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",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"}}),_r.registerProvider(new Qs),ka({name:Zs,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}}),_r.registerProvider(new Xs),ka({name:oo,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}}),_r.registerProvider(new ao),ka({name:Eo,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}}),_r.registerProvider(new So),ka({name:xo,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}}),_r.registerProvider(new No),ka({name:Ao,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}}),_r.registerProvider(new To);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Po("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"}}}),Po("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"}}}),Po("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"}}}),Po("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"}}}),Po("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"}}}),Po("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"}}})]}())ka(e);for(const e of[new _o,new Ro,new $o,new Lo,new Oo,new Do])_r.registerProvider(e);ka({name:Qo,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}}),_r.registerProvider(new Zo),ka({name:na,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}}),_r.registerProvider(new sa),ka({name:ra,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}}),_r.registerProvider(new oa),ka({name:aa,title:"Show a panel",description:"Bring a panel, sidebar, or editor view into view and focus it.",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["viewId","revealed"],properties:{viewId:{type:"string"},revealed:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),_r.registerProvider(new ma),ka({name:ca,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}}),_r.registerProvider(new ga),ka({name:la,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}}),_r.registerProvider(new ya),ka({name:ua,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}}),_r.registerProvider(new wa),ka({name:da,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}}),_r.registerProvider(new ba),ka({name:pa,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}}),_r.registerProvider(new Ia)}(),console.log("[Runtime] Capabilities registered");const dc={lifecyclePhase:Ya?.lifecyclePhase??"bootstrapping",fs:za,fileOpeners:Ya?.fileOpeners??Cn,search:Ja,vcs:Ha,terminals:Qa,debug:Za,tasks:Xa,workspace:ec,resources:tc,secrets:uc,llm:nc,compute:rc,datasets:ic,models:sc,modelRuntimes:oc,inference:ac,vectors:cc,host:lc,capabilities:{gateway:Qi,unifiedRegistry:Yr,logTrinityCatalog:Aa,docs:{formatCapabilityMarkdown:function(e){const t=e.definition,n=[];n.push(`# \`${t.id}\``),n.push(""),n.push(function(e){const t=e.definition,n=[];n.push(`**Origin:** ${e.origin}`),n.push(`**Version:** ${t.version}`);const r=t.policy?.risk??"—",i=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${i}`);const s=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";return n.push(`**Side effects:** ${s}`),n.join(" · ")}(e)),n.push("");const r=t.description??t.title;r&&r.length>0&&(n.push(r),n.push("")),void 0!==t.inputs?.schema&&(n.push("## Input schema"),n.push(""),n.push("```json"),n.push(Na(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Na(t.outputs.schema)),n.push("```"),n.push("")),t.tags&&t.tags.length>0&&(n.push("## Tags"),n.push(""),n.push(t.tags.join(", ")),n.push(""));const 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(`## ${Ca(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(Ta(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:Ma,connect:e=>Da.connect(e),disconnect:e=>Da.disconnect(e),listServers:()=>Da.listServers(),listTools:e=>Da.listTools(e),callTool:(e,t,n)=>Da.callTool(e,t,n)},setFsProvider:function(e){ai.set(e),e&&qn({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:Hn,setComputeProvider:function(e){Xn().registerProvider(e)},setComputeRuntime:function(e){Xn().registerLanguageRuntime(e)},setDatasetProvider:function(e){dr().registerProvider(e)},setModelProvider:function(e){mr().registerProvider(e)},setModelRuntime:function(e){vr().register(e)},setHostProvider:function(e){Cr=e},setVectorsProvider:function(e){Ar=e},setSearchProvider:function(e){Nn=e},setWorkspaceProvider:Vn,setTerminalProvider:function(e){Pn=e},setDebugProvider:function(e){_n=e},setVcsProvider:function(e){Rn=e},setResourcesProvider:function(e){Tn=e},setTasksProvider:function(e){Mn=e},setSecretsProvider:ps};class pc{#be;constructor(e){this.#be=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#be);n?e(n):t(new Error("Extension not found"))})}}let fc=class{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}},hc=class extends fc{constructor(e){super(e)}async execute(){return await super.execute()}},mc=class extends fc{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))}}},gc=class extends fc{constructor(e){super(e)}async execute(){return await super.execute()}};const yc=Symbol.for("yaml.alias"),wc=Symbol.for("yaml.document"),vc=Symbol.for("yaml.map"),bc=Symbol.for("yaml.pair"),Ic=Symbol.for("yaml.scalar"),kc=Symbol.for("yaml.seq"),Ec=Symbol.for("yaml.node.type"),Sc=e=>!!e&&"object"==typeof e&&e[Ec]===yc,Ac=e=>!!e&&"object"==typeof e&&e[Ec]===wc,xc=e=>!!e&&"object"==typeof e&&e[Ec]===vc,Cc=e=>!!e&&"object"==typeof e&&e[Ec]===bc,Tc=e=>!!e&&"object"==typeof e&&e[Ec]===Ic,Nc=e=>!!e&&"object"==typeof e&&e[Ec]===kc;function Mc(e){if(e&&"object"==typeof e)switch(e[Ec]){case vc:case kc:return!0}return!1}function Pc(e){if(e&&"object"==typeof e)switch(e[Ec]){case yc:case vc:case Ic:case kc:return!0}return!1}const _c=Symbol("break visit"),Rc=Symbol("skip children"),$c=Symbol("remove node");function Lc(e,t){const n=Fc(t);if(Ac(e)){Oc(null,e.contents,n,Object.freeze([e]))===$c&&(e.contents=null)}else Oc(null,e,n,Object.freeze([]))}function Oc(e,t,n,r){const i=qc(e,t,n,r);if(Pc(i)||Cc(i))return Bc(e,r,i),Oc(e,i,n,r);if("symbol"!=typeof i)if(Mc(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=Oc(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===_c)return _c;i===$c&&(t.items.splice(e,1),e-=1)}}}else if(Cc(t)){r=Object.freeze(r.concat(t));const e=Oc("key",t.key,n,r);if(e===_c)return _c;e===$c&&(t.key=null);const i=Oc("value",t.value,n,r);if(i===_c)return _c;i===$c&&(t.value=null)}return i}async function Dc(e,t){const n=Fc(t);if(Ac(e)){await jc(null,e.contents,n,Object.freeze([e]))===$c&&(e.contents=null)}else await jc(null,e,n,Object.freeze([]))}async function jc(e,t,n,r){const i=await qc(e,t,n,r);if(Pc(i)||Cc(i))return Bc(e,r,i),jc(e,i,n,r);if("symbol"!=typeof i)if(Mc(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await jc(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===_c)return _c;i===$c&&(t.items.splice(e,1),e-=1)}}}else if(Cc(t)){r=Object.freeze(r.concat(t));const e=await jc("key",t.key,n,r);if(e===_c)return _c;e===$c&&(t.key=null);const i=await jc("value",t.value,n,r);if(i===_c)return _c;i===$c&&(t.value=null)}return i}function Fc(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 qc(e,t,n,r){return"function"==typeof n?n(e,t,r):xc(t)?n.Map?.(e,t,r):Nc(t)?n.Seq?.(e,t,r):Cc(t)?n.Pair?.(e,t,r):Tc(t)?n.Scalar?.(e,t,r):Sc(t)?n.Alias?.(e,t,r):void 0}function Bc(e,t,n){const r=t[t.length-1];if(Mc(r))r.items[e]=n;else if(Cc(r))"key"===e?r.key=n:r.value=n;else{if(!Ac(r)){const e=Sc(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Lc.BREAK=_c,Lc.SKIP=Rc,Lc.REMOVE=$c,Dc.BREAK=_c,Dc.SKIP=Rc,Dc.REMOVE=$c;const Uc={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Vc=e=>e.replace(/[!,[\]{}]/g,e=>Uc[e]);class Wc{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Wc.defaultYaml,e),this.tags=Object.assign({},Wc.defaultTags,t)}clone(){const e=new Wc(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Wc(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Wc.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Wc.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Wc.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Wc.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+Vc(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&&Pc(e.contents)){const t={};Lc(e.contents,(e,n)=>{Pc(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 Kc(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);throw new Error(`Anchor must not contain whitespace or control characters: ${t}`)}return!0}function Gc(e){const t=new Set;return Lc(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Yc(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function zc(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=zc(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=zc(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=zc(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=zc(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function Jc(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Jc(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Tc(r=e)&&!Mc(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)}Wc.defaultYaml={explicit:!1,version:"1.2"},Wc.defaultTags={"!!":"tag:yaml.org,2002:"};class Hc{constructor(e){Object.defineProperty(this,Ec,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Ac(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=Jc(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?zc(i,{"":o},"",o):o}}class Qc extends Hc{constructor(e){super(yc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Lc(e,{Node:(e,n)=>{if(n===this)return Lc.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||(Jc(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=Zc(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(Kc(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${r} `}return r}}function Zc(e,t,n){if(Sc(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Mc(t)){let r=0;for(const i of t.items){const t=Zc(e,i,n);t>r&&(r=t)}return r}if(Cc(t)){const r=Zc(e,t.key,n),i=Zc(e,t.value,n);return Math.max(r,i)}return 1}const Xc=e=>!e||"function"!=typeof e&&"object"!=typeof e;class el extends Hc{constructor(e){super(Ic),this.value=e}toJSON(e,t){return t?.keep?this.value:Jc(this.value,e,t)}toString(){return String(this.value)}}el.BLOCK_FOLDED="BLOCK_FOLDED",el.BLOCK_LITERAL="BLOCK_LITERAL",el.PLAIN="PLAIN",el.QUOTE_DOUBLE="QUOTE_DOUBLE",el.QUOTE_SINGLE="QUOTE_SINGLE";function tl(e,t,n){if(Ac(e)&&(e=e.contents),Pc(e))return e;if(Cc(e)){const t=n.schema[vc].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 Qc(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 el(e);return c&&(c.node=t),t}l=e instanceof Map?o[vc]:Symbol.iterator in Object(e)?o[kc]:o[vc]}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 el(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function nl(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 tl(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 rl=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class il extends Hc{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=>Pc(t)||Cc(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(rl(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Mc(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,nl(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(Mc(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&&Tc(i)?i.value:i:Mc(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Cc(t))return!1;const n=t.value;return null==n||e&&Tc(n)&&null==n.value&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(0===n.length)return this.has(t);const r=this.get(t,!0);return!!Mc(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(Mc(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,nl(this.schema,r,t))}}}}il.maxFlowStringSingleLineLength=60;const sl=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ol(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const al=(e,t,n)=>e.endsWith("\n")?ol(n,t):n.includes("\n")?"\n"+ol(n,t):(e.endsWith(" ")?"":" ")+n,cl="flow",ll="block",ul="quoted";function dl(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===ll&&(m=pl(e,m,t.length),-1!==m&&(f=m+c));for(let r;r=e[m+=1];){if(n===ul&&"\\"===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===ll&&(m=pl(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===ul){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===ul&&u[i]&&(w+=`${e[i]}\\`),w+=`\n${t}${e.slice(i+1,s)}`)}return w}function pl(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 fl=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),hl=e=>/^(%|---|\.\.\.)/m.test(e);function ml(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(hl(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:dl(o,s,ul,fl(t,!1))}function gl(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return ml(e,t);const n=t.indent||(hl(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:dl(r,n,cl,fl(t,!1))}function yl(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=ml;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?gl:i&&!t?ml:n?gl:ml}return r(e,t)}let wl;try{wl=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{wl=/\n+(?!\n|$)/g}function vl({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 yl(n,r);const l=r.indent||(r.forceBlockIndent||hl(n)?" ":""),u="literal"===o||"folded"!==o&&t!==el.BLOCK_FOLDED&&(t===el.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(wl,`$&${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}${dl(`${w}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${f}`,l,ll,fl(r,!0))}`}function bl(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!==el.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=el.QUOTE_DOUBLE);const c=e=>{switch(e){case el.BLOCK_FOLDED:case el.BLOCK_LITERAL:return i||s?yl(o.value,t):vl(o,t,n,r);case el.QUOTE_DOUBLE:return ml(o.value,t);case el.QUOTE_SINGLE:return gl(o.value,t);case el.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 yl(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?yl(s,t):vl(e,t,n,r);if(!a&&!u&&i!==el.PLAIN&&s.includes("\n"))return vl(e,t,n,r);if(hl(s)){if(""===c)return t.forceBlockIndent=!0,vl(e,t,n,r);if(a&&c===l)return yl(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 yl(s,t)}return a?d:dl(d,c,cl,fl(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 Il(e,t){const n=Object.assign({blockQuote:!0,commentString:sl,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 kl(e,t,n,r){if(Cc(e))return e.toString(t,n,r);if(Sc(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=Pc(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(Tc(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=(Tc(e)||Mc(e))&&e.anchor;s&&Kc(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):Tc(s)?bl(s,t,n,r):s.toString(t,n,r);return o?Tc(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function El(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function Sl(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&Al(n))if(r=Sc(r)?r.resolve(e.doc):r,Nc(r))for(const n of r.items)xl(e,t,n);else if(Array.isArray(r))for(const n of r)xl(e,t,n);else xl(e,t,r);else{const i=Jc(n,"",e);if(t instanceof Map)t.set(i,Jc(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(Pc(e)&&n?.doc){const t=Il(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;const r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+'..."'),El(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}(n,i,e),o=Jc(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const Al=e=>"<<"===e||Tc(e)&&"<<"===e.value&&(!e.type||e.type===el.PLAIN);function xl(e,t,n){const r=e&&Sc(n)?n.resolve(e.doc):n;if(!xc(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 Cl(e,t,n){const r=tl(e,void 0,n),i=tl(t,void 0,n);return new Tl(r,i)}class Tl{constructor(e,t=null){Object.defineProperty(this,Ec,{value:bc}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Pc(t)&&(t=t.clone(e)),Pc(n)&&(n=n.clone(e)),new Tl(t,n)}toJSON(e,t){return Sl(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=Pc(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Mc(e)||!Pc(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||Mc(e)||(Tc(e)?e.type===el.BLOCK_FOLDED||e.type===el.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=kl(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+=al(v,n.indent,l(p)):w&&i&&i(),v;y&&(p=null),f?(p&&(v+=al(v,n.indent,l(p))),v=`? ${v}\n${a}:`):(v=`${v}:`,p&&(v+=al(v,n.indent,l(p)))),Pc(t)?(h=!!t.spaceBefore,m=t.commentBefore,g=t.comment):(h=!1,m=null,g=null,t&&"object"==typeof t&&(t=o.createNode(t))),n.implicitKey=!1,f||p||!Tc(t)||(n.indentAtStart=v.length+1),w=!1,u||!(c.length>=2)||n.inFlow||f||!Nc(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let b=!1;const I=kl(t,n,()=>b=!0,()=>w=!0);let k=" ";if(p||h||m)k=h?"\n":"",m&&(k+=`\n${ol(l(m),n.indent)}`),""!==I||n.inFlow?k+=`\n${n.indent}`:"\n"===k&&(k="\n\n");else if(!f&&Mc(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+=al(v,n.indent,l(g)):w&&i&&i(),v}(this,e,t,n):JSON.stringify(this)}}function Nl(e,t,n){return(t.inFlow??e.flow?Pl:Ml)(e,t,n)}function Ml({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(Pc(i))!d&&i.spaceBefore&&p.push(""),_l(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(Cc(i)){const e=Pc(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),_l(n,p,e.commentBefore,d))}d=!1;let a=kl(i,u,()=>o=null,()=>d=!0);o&&(a+=al(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"+ol(l(e),c),a&&a()):d&&o&&o(),f}function Pl({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(Pc(i))i.spaceBefore&&d.push(""),_l(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(Cc(i)){const e=Pc(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),_l(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Pc(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=kl(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=al(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 _l({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=ol(t(r),e);n.push(i.trimStart())}}function Rl(e,t){const n=Tc(t)?t.value:t;for(const r of e)if(Cc(r)){if(r.key===t||r.key===n)return r;if(Tc(r.key)&&r.key.value===n)return r}}class $l extends il{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(vc,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(Cl(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=Cc(e)?e:e&&"object"==typeof e&&"key"in e?new Tl(e.key,e.value):new Tl(e,e?.value);const r=Rl(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Tc(r.value)&&Xc(n.value)?r.value.value=n.value:r.value=n.value}else if(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=Rl(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=Rl(this.items,e),r=n?.value;return(!t&&Tc(r)?r.value:r)??void 0}has(e){return!!Rl(this.items,e)}set(e,t){this.add(new Tl(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const e of this.items)Sl(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!Cc(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Nl(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ll={collection:"map",default:!0,nodeClass:$l,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(xc(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>$l.from(e,t,n)};class Ol extends il{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(kc,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Dl(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Dl(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Tc(r)?r.value:r}has(e){const t=Dl(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Dl(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Tc(r)&&Xc(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const e of this.items)n.push(Jc(e,String(r++),t));return n}toString(e,t,n){return e?Nl(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,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(tl(s,void 0,n))}}return i}}function Dl(e){let t=Tc(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const jl={collection:"seq",default:!0,nodeClass:Ol,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Nc(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Ol.from(e,t,n)},Fl={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>bl(e,t=Object.assign({actualString:!0},t),n,r)},ql={identify:e=>null==e,createNode:()=>new el(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new el(null),stringify:({source:e},t)=>"string"==typeof e&&ql.test.test(e)?e:t.options.nullStr},Bl={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new el("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Bl.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Ul({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 Vl={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:Ul},Wl={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():Ul(e)}},Kl={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const t=new el(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Ul},Gl=e=>"bigint"==typeof e||Number.isInteger(e),Yl=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function zl(e,t,n){const{value:r}=e;return Gl(r)&&r>=0?n+r.toString(t):Ul(e)}const Jl={identify:e=>Gl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Yl(e,2,8,n),stringify:e=>zl(e,8,"0o")},Hl={identify:Gl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Yl(e,0,10,n),stringify:Ul},Ql={identify:e=>Gl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Yl(e,2,16,n),stringify:e=>zl(e,16,"0x")},Zl=[Ll,jl,Fl,ql,Bl,Jl,Hl,Ql,Vl,Wl,Kl];function Xl(e){return"bigint"==typeof e||Number.isInteger(e)}const eu=({value:e})=>JSON.stringify(e),tu=[Ll,jl].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:eu},{identify:e=>null==e,createNode:()=>new el(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:eu},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:eu},{identify:Xl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Xl(e)?e.toString():JSON.stringify(e)},{identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:eu}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),nu={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=el.BLOCK_LITERAL),t!==el.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===el.BLOCK_LITERAL?"\n":" ")}return bl({comment:e,type:t,value:a},r,i,s)}};function ru(e,t){if(Nc(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Cc(r)){if(xc(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Tl(new el(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]=Cc(r)?r:new Tl(r)}}else t("Expected a sequence for this tag");return e}function iu(e,t,n){const{replacer:r}=n,i=new Ol(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(Cl(o,a,n))}return i}const su={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ru,createNode:iu};class ou extends Ol{constructor(){super(),this.add=$l.prototype.add.bind(this),this.delete=$l.prototype.delete.bind(this),this.get=$l.prototype.get.bind(this),this.has=$l.prototype.has.bind(this),this.set=$l.prototype.set.bind(this),this.tag=ou.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(Cc(e)?(r=Jc(e.key,"",t),i=Jc(e.value,r,t)):r=Jc(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=iu(e,t,n),i=new this;return i.items=r.items,i}}ou.tag="tag:yaml.org,2002:omap";const au={collection:"seq",identify:e=>e instanceof Map,nodeClass:ou,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=ru(e,t),r=[];for(const{key:e}of n.items)Tc(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new ou,n)},createNode:(e,t,n)=>ou.from(e,t,n)};function cu({value:e,source:t},n){return t&&(e?lu:uu).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const lu={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 el(!0),stringify:cu},uu={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 el(!1),stringify:cu},du={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:Ul},pu={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():Ul(e)}},fu={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 el(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:Ul},hu=e=>"bigint"==typeof e||Number.isInteger(e);function mu(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 gu(e,t,n){const{value:r}=e;if(hu(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return Ul(e)}const yu={identify:hu,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>mu(e,2,2,n),stringify:e=>gu(e,2,"0b")},wu={identify:hu,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>mu(e,1,8,n),stringify:e=>gu(e,8,"0")},vu={identify:hu,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>mu(e,0,10,n),stringify:Ul},bu={identify:hu,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>mu(e,2,16,n),stringify:e=>gu(e,16,"0x")};class Iu extends $l{constructor(e){super(e),this.tag=Iu.tag}add(e){let t;t=Cc(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Tl(e.key,null):new Tl(e,null);Rl(this.items,t.key)||this.items.push(t)}get(e,t){const n=Rl(this.items,e);return!t&&Cc(n)?Tc(n.key)?n.key.value:n.key:n}set(e,t){if("boolean"!=typeof t)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof t);const n=Rl(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Tl(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:r}=n,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(Cl(e,null,n));return i}}Iu.tag="tag:yaml.org,2002:set";const ku={collection:"map",identify:e=>e instanceof Set,nodeClass:Iu,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Iu.from(e,t,n),resolve(e,t){if(xc(e)){if(e.hasAllNullValues(!0))return Object.assign(new Iu,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function Eu(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,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 Su(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Ul(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 Au={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>Eu(e,n),stringify:Su},xu={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Eu(e,!1),stringify:Su},Cu={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(Cu.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=Eu(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")},Tu=[Ll,jl,Fl,ql,lu,uu,yu,wu,vu,bu,du,pu,fu,nu,au,su,ku,Au,xu,Cu],Nu=new Map([["core",Zl],["failsafe",[Ll,jl,Fl]],["json",tu],["yaml11",Tu],["yaml-1.1",Tu]]),Mu={binary:nu,bool:Bl,float:Kl,floatExp:Wl,floatNaN:Vl,floatTime:xu,int:Hl,intHex:Ql,intOct:Jl,intTime:Au,map:Ll,null:ql,omap:au,pairs:su,seq:jl,set:ku,timestamp:Cu},Pu={"tag:yaml.org,2002:binary":nu,"tag:yaml.org,2002:omap":au,"tag:yaml.org,2002:pairs":su,"tag:yaml.org,2002:set":ku,"tag:yaml.org,2002:timestamp":Cu};function _u(e,t){let n=Nu.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(Nu.keys()).filter(e=>"yaml11"!==e).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}n=[]}if(Array.isArray(e))for(const t of e)n=n.concat(t);else"function"==typeof e&&(n=e(n.slice()));return n.map(e=>{if("string"!=typeof e)return e;const t=Mu[e];if(t)return t;const n=Object.keys(Mu).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const Ru=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class $u{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?_u(e,"compat"):e?_u(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Pu:{},this.tags=_u(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,vc,{value:Ll}),Object.defineProperty(this,Ic,{value:Fl}),Object.defineProperty(this,kc,{value:jl}),this.sortMapEntries="function"==typeof s?s:!0===s?Ru:null}clone(){const e=Object.create($u.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Lu{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ec,{value:wc});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 Wc({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Lu.prototype,{[Ec]:{value:wc}});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=Pc(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ou(this.contents)&&this.contents.add(e)}addIn(e,t){Ou(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Gc(this);e.anchor=!t||n.has(t)?Yc(t||"a",n):t}return new Qc(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=Gc(e));const s=Yc(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Tc(t.node)&&!Mc(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=tl(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&Mc(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 Tl(r,i)}delete(e){return!!Ou(this.contents)&&this.contents.delete(e)}deleteIn(e){return rl(e)?null!=this.contents&&(this.contents=null,!0):!!Ou(this.contents)&&this.contents.deleteIn(e)}get(e,t){return Mc(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return rl(e)?!t&&Tc(this.contents)?this.contents.value:this.contents:Mc(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!Mc(this.contents)&&this.contents.has(e)}hasIn(e){return rl(e)?void 0!==this.contents:!!Mc(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=nl(this.schema,[e],t):Ou(this.contents)&&this.contents.set(e,t)}setIn(e,t){rl(e)?this.contents=t:null==this.contents?this.contents=nl(this.schema,Array.from(e),t):Ou(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 Wc({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 Wc({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 $u(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=Jc(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?zc(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=Il(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(ol(t,""))}let o=!1,a=null;if(e.contents){if(Pc(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(ol(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=kl(e.contents,i,()=>a=null,t);a&&(c+=al(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(kl(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(ol(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(ol(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Ou(e){if(Mc(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Du extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class ju extends Du{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Fu extends Du{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const qu=(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 Bu(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 Uu(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(Uu(t.key)||Uu(t.value))return!0}return!1;default:return!0}}function Vu(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&Uu(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function Wu(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Tc(t)&&Tc(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const Ku="All mapping items must start at the same column";function Gu(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 Yu="Block collections are not allowed within flow collections",zu=e=>e&&("block-map"===e.type||"block-seq"===e.type);function Ju(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??$l)(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=Bu(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",Ku)),!f.anchor&&!f.tag&&!d){c=f.end,f.comment&&(o.comment?o.comment+="\n"+f.comment:o.comment=f.comment);continue}(f.hasNewlineAfterProp||Uu(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",Ku);const m=f.end,g=u?e(n,u,f,i):t(n,m,l,null,f,i);n.schema.compat&&Vu(r.indent,u,i),Wu(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Bu(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&&Vu(r.indent,p,i),a=c.range[2];const l=new Tl(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 Tl(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??Ol)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Bu(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&&Vu(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?$l:Ol))(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=Bu(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&&Uu(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];Cc(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);zu(p)&&i(g.range,"BLOCK_IN_FLOW",Yu);const y=Bu(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?zu(h)&&i(w.range,"BLOCK_IN_FLOW",Yu):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const v=new Tl(g,w);if(n.options.keepSourceTokens&&(v.srcToken=l),o){const e=c;Wu(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(v)}else{const e=new $l(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],zu(h)&&i(r.range,"BLOCK_IN_FLOW",Yu)}}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=Gu(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 Hu(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?el.BLOCK_FOLDED:el.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===el.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 Qu(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=el.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 Zu(e)}(s,l);break;case"single-quoted-scalar":a=el.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return Zu(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=el.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}=Xu(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=ed[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+=td(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=Gu(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Zu(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 Xu(e,t){let n="",r=e[t+1];for(;!(" "!==r&&"\t"!==r&&"\n"!==r&&"\r"!==r||"\r"===r&&"\n"!==e[t+2]);)"\n"===r&&(n+="\n"),r=e[(t+=1)+1];return n||(n=" "),{fold:n,offset:t}}const ed={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function td(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 nd(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?Hu(e,t,r):Qu(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[Ic];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[Ic]}(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[Ic];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[Ic];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[Ic];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Tc(s)?s:new el(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new el(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 rd(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 id={composeNode:sd,composeEmptyNode:od};function sd(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 Qc(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=Gu(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=nd(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===$l.tagName&&"map"===o||s===Ol.tagName&&"seq"===o||!o)return Ju(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),Ju(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=Ju(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Pc(l)?l:new el(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(id,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=od(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 od(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=nd(e,{type:"scalar",offset:rd(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 ad(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 cd(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 ld{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=ad(e);r?this.warnings.push(new Fu(i,t,n)):this.errors.push(new ju(i,t,n))},this.directives=new Wc({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=cd(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(Mc(i)&&!i.flow&&i.items.length>0){let e=i.items[0];Cc(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:cd(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=ad(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 Lu(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Bu(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?sd(l,i,u,o):od(l,u.end,r,null,u,o);const d=c.contents.range[2],p=Gu(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 ju(ad(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 ju(ad(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=Gu(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 ju(ad(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 Lu(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 ud(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 dd(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 pd(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=pd(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=fd(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=fd(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=fd(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 fd({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=pd(t)),n)for(const e of n)i+=e.source;return r&&(i+=pd(r)),i}const hd=Symbol("break visit"),md=Symbol("skip children"),gd=Symbol("remove item");function yd(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),wd(Object.freeze([]),e,t)}function wd(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=wd(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===hd)return hd;r===gd&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}yd.BREAK=hd,yd.SKIP=md,yd.REMOVE=gd,yd.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},yd.parentCollection=(e,t)=>{const n=yd.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 vd="\ufeff",bd="",Id="",kd="";function Ed(e){switch(e){case vd:return"byte-order-mark";case bd:return"doc-mode";case Id:return"flow-error-end";case kd: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 Sd=Object.freeze({__proto__:null,BOM:vd,DOCUMENT:bd,FLOW_END:Id,SCALAR:kd,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=bl({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 ud(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 vd:return"<BOM>";case bd:return"<DOC>";case Id:return"<FLOW_END>";case kd: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 ju([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Qu(e,t,r);case"block-scalar":return Hu({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=bl({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}];ud(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'"':dd(e,c,"double-quoted-scalar");break;case"'":dd(e,c,"single-quoted-scalar");break;default:dd(e,c,"scalar")}},stringify:e=>"type"in e?pd(e):fd(e),tokenType:Ed,visit:yd});function Ad(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const xd=new Set("0123456789ABCDEFabcdef"),Cd=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Td=new Set(",[]{}"),Nd=new Set(" ,[]{}\n\r\t"),Md=e=>!e||Nd.has(e);class Pd{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)&&Ad(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]===vd&&(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 bd,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&&Ad(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&Ad(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ad(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)&&Ad(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(Md),"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("..."))&&Ad(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield Id,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(Md),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Ad(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=>Ad(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 kd,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(Ad(t)||e&&Td.has(t))break;n=r}else if(Ad(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&&Td.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&&Td.has(t))break;n=r}return t||this.atEnd?(yield kd,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(Md))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Ad(t)||e&&Td.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,t=this.buffer[e];for(;!Ad(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(Cd.has(t))t=this.buffer[++e];else{if("%"!==t||!xd.has(this.buffer[e+1])||!xd.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 _d{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 Rd(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function $d(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 Ld(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 Od(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 Dd(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 jd(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Rd(t.start,"explicit-key-ind")||Rd(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Ld(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 Fd{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 Pd,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=e.length);const t=Ed(e);if(t)if("scalar"===t)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&" "===e[0]&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if("doc-end"!==this.type||e&&"doc-end"===e.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&jd(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===$d(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!==$d(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=Dd(Od(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(Rd(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(Ld(t.key)&&!Rd(t.sep,"newline")){const e=Dd(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(Rd(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Dd(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]}):Rd(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||Rd(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=Dd(Od(t));jd(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=Dd(Od(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=Dd(Od(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 qd(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new _d||null,prettyErrors:t}}function Bd(e,t={}){const{lineCounter:n,prettyErrors:r}=qd(t),i=new Fd(n?.addNewLine),s=new ld(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(qu(e,n)),t.warnings.forEach(qu(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Ud(e,t={}){const{lineCounter:n,prettyErrors:r}=qd(t),i=new Fd(n?.addNewLine),s=new ld(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 ju(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(qu(e,n)),o.warnings.forEach(qu(e,n))),o}function Vd(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=Ud(e,n);if(!i)return null;if(i.warnings.forEach(e=>El(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 Wd(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 Lu(e,r,n).toString(n)}var Kd=Object.freeze({__proto__:null,Alias:Qc,CST:Sd,Composer:ld,Document:Lu,Lexer:Pd,LineCounter:_d,Pair:Tl,Parser:Fd,Scalar:el,Schema:$u,YAMLError:Du,YAMLMap:$l,YAMLParseError:ju,YAMLSeq:Ol,YAMLWarning:Fu,isAlias:Sc,isCollection:Mc,isDocument:Ac,isMap:xc,isNode:Pc,isPair:Cc,isScalar:Tc,isSeq:Nc,parse:Vd,parseAllDocuments:Bd,parseDocument:Ud,stringify:Wd,visit:Lc,visitAsync:Dc}),Gd=Object.freeze({__proto__:null,Alias:Qc,CST:Sd,Composer:ld,Document:Lu,Lexer:Pd,LineCounter:_d,Pair:Tl,Parser:Fd,Scalar:el,Schema:$u,YAMLError:Du,YAMLMap:$l,YAMLParseError:ju,YAMLSeq:Ol,YAMLWarning:Fu,default:Kd,isAlias:Sc,isCollection:Mc,isDocument:Ac,isMap:xc,isNode:Pc,isPair:Cc,isScalar:Tc,isSeq:Nc,parse:Vd,parseAllDocuments:Bd,parseDocument:Ud,stringify:Wd,visit:Lc,visitAsync:Dc});class Yd{#ke;constructor(e){this.#ke=e}execute(){return new Promise((e,t)=>{const n=`${this.#ke}.punica/config.yaml`;fetch(n,{method:"GET"}).then(e=>{if(!e.ok)throw new Error(`Failed to load extension config: ${n} (${e.status})`);return e.text()}).then(async t=>{const n=Kd.parse(t);if(n.moduleURL=this.#ke,n.hasCapabilities){const e=`${this.#ke}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=Kd.parse(await t.text());n.capabilities=e??{}}else console.warn(`[Extensions] ${n.name}: hasCapabilities is set but ${e} could not be loaded (${t.status}).`)}catch{n.capabilities={}}}const r=n.instructionClasses;if(Array.isArray(r)&&r.length>0){const e=await Promise.all(r.map(async e=>{const t=`${this.#ke}.punica/instruction-classes/${e}`,n=await fetch(t,{method:"GET"});if(!n.ok)throw new Error(`Failed to load instruction class: ${t} (${n.status})`);return Kd.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class zd{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}}class Jd{#n;#Ee;constructor(){this.#n=new Map,this.#Ee=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#Ee.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#Ee.has(t)||console.warn(`Unknown event type: ${t}`)}}class Hd{}class Qd extends Hd{#Se;constructor(e){super(),this.#Se=e}execute(){}}let Zd=class extends zd{#Ae;constructor(e){super(e),this.#Ae=new Jd,this.#Ae.register("onExtension",Qd),this.#Ae.markKnown("onCommand"),this.#Ae.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Ae.handleEvent(e)),e}},Xd=class extends zd{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 ep(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}function tp(e,t=ep()){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 np=class extends zd{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(t){const{keybindings:e}=t;e&&e.forEach(e=>{if(!e.capability)return void console.warn(`[Keybindings] Missing capability for keybinding: ${e.key}`);const t=e.capability,n=e.key,r=e.when;punica.shell.KeyboardShortcuts.manager.registerShortcut({command:t,keys:[tp(n)],when:r})})}return e}},rp=class extends zd{constructor(e){super(e)}async execute(){return await super.execute()}};class ip extends zd{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=dc.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}}function sp(e){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){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;r?.id&&n.registerPlacement({viewId:r.id,slot:"primarySidebar",extensionName:e.name,title:r.title??r.name,icon:r.icon,fallbackCommand:r.capability??a?.capability??a?.command});s?.id&&n.registerPlacement({viewId:s.id,slot:"contentSidebar",extensionName:e.name,title:s.title??s.name,icon:s.icon,fallbackCommand:s.capability});if(o?.id){const t=Array.isArray(o.toolbar)?o.toolbar:void 0;op(e,o,"panel",{order:o.order,panelToolbar:t})}i?.id&&op(e,i,"secondarySidebar",{})}(e,{primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r})}function op(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=s?.getSlotOverride?.(t.id),u=l&&c.includes(l)?l:n,d=!1===t.showOnStartup;if(i.registerPlacement({viewId:t.id,slot:u,homeSlot:n,allowedSlots:c,extensionName:e.name,title:t.title??t.name,icon:t.icon,order:r.order,fallbackCommand:t.capability,onDemand:d,panelToolbar:r.panelToolbar}),!d){const e=o?.forSlot?.(u)??("panel"===u?punica.shell?.PanelTabs:null);e?.open?.({id:t.id,title:t.title??t.name??t.id,commandId:t.capability??"",iconClass:t.icon,order:r.order,autoActivate:!1,toolbar:r.panelToolbar})}}let ap=0;function cp(){ap++}function lp(){ap>0&&ap--}function up(){return ap>0}async function dp(e){cp();try{return await e()}finally{lp()}}const pp=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#xe(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#xe(e))}getExtensionCapabilities(e){const t=punica.extensions.manager.getExtension(e);if(!t)return;const n=t.capabilities;return n?Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>{const n=t;return[e,Object.freeze({id:n.id??e,title:n.title,description:n.description,inputs:n.inputs?Object.freeze({schema:n.inputs.schema?Object.freeze(n.inputs.schema):void 0}):void 0,outputs:n.outputs?Object.freeze({schema:n.outputs.schema?Object.freeze(n.outputs.schema):void 0,kind:n.outputs.kind,resultEvent:n.outputs.resultEvent,errorEvent:n.outputs.errorEvent}):void 0,policy:n.policy?Object.freeze({risk:n.policy.risk,approval:n.policy.approval}):void 0,sideEffects:n.sideEffects?Object.freeze([...n.sideEffects]):void 0,requiredContext:n.requiredContext?Object.freeze([...n.requiredContext]):void 0,examples:n.examples?Object.freeze(n.examples.map(e=>Object.freeze({input:e.input,output:e.output,description:e.description}))):void 0,version:n.version,tags:n.tags?Object.freeze([...n.tags]):void 0})]}))):void 0}#xe(e){const t=e.integrations?.configuration?{title:e.integrations.configuration.title,properties:Object.freeze(Object.fromEntries(Object.entries(e.integrations.configuration.properties??{}).map(([e,t])=>{const n=t,r={type:n.type,default:n.default,description:n.description};let 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 fp=new class{#Ce=".punica/settings.json";#Te;#Ne=null;#Me=null;#Pe=new Map;#_e=null;#z=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Te=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Te="localStorage:punica.settings":this.#Te="settings.json"}async load(){this.#z||(await this.#Re(),await this.#$e(),this.#z=!0)}async#Re(){try{if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#Me=await this.#Le(e)}else this.#Me={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Te),t=JSON.parse(e);this.#Me=await this.#Le(t)}catch{this.#Me={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Me={version:"1.0",extensions:{},system:{}}}}async#$e(){try{const e=await punica.runtime.fs.readFile(this.#Ce),t=JSON.parse(e);this.#Ne=await this.#Le(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Ne=null}}async save(e="project"){this.#_e&&clearTimeout(this.#_e),this.#_e=window.setTimeout(async()=>{"global"===e?await this.#Oe():await this.#De(),this.#_e=null},500)}async#Oe(){if(this.#Me)if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#Me,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Te,JSON.stringify(this.#Me,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#De(){this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Ce,JSON.stringify(this.#Ne,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#z)return void this.load();if("system"===e){const e=this.#Ne?.system?.[t];if(void 0!==e)return e;const n=this.#Me?.system?.[t];return void 0!==n?n:void 0}const n=this.#Ne?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#Me?.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.#z||await this.load(),"system"===e){const i=this.get(e,t);return"global"===r?(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system||(this.#Me.system={}),this.#Me.system[t]=n,await this.save("global")):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system||(this.#Ne.system={}),this.#Ne.system[t]=n,await this.save("project")),void this.#je(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.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]||(this.#Me.extensions[e]={}),this.#Me.extensions[e][t]=n,await this.save("global")):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]||(this.#Ne.extensions[e]={}),this.#Ne.extensions[e][t]=n,await this.save("project")),this.#je(e,t,n,s)}getAll(e){if(!this.#z)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#Me?.extensions?.[e]??{},i=this.#Ne?.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.#Ne?.system?.[t],i=void 0!==this.#Me?.system?.[t];if(!r&&!i)return;return r&&delete this.#Ne.system[t],i&&delete this.#Me.system[t],r&&await this.#De(),i&&await this.#Oe(),void this.#je(e,t,void 0,n)}const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Ne?.extensions?.[e]&&(delete this.#Ne.extensions[e][t],await this.save("project")),this.#Me?.extensions?.[e]&&(delete this.#Me.extensions[e][t],await this.save("global"))):await this.set(e,t,r,"project")}async resetExtension(e){const t=punica.extensions.metadata.manager.getExtension(e);if(t?.configuration?.properties)for(const n of Object.keys(t.configuration.properties))await this.reset(e,n)}getScope(e,t){return this.#z?"system"===e?void 0!==this.#Ne?.system?.[t]?"project":void 0!==this.#Me?.system?.[t]?"global":"default":void 0!==this.#Ne?.extensions?.[e]?.[t]?"project":void 0!==this.#Me?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#Pe.has(e)||this.#Pe.set(e,new Set),this.#Pe.get(e).add(t),()=>{this.#Pe.get(e)?.delete(t)}}async export(e){this.#z||await this.load();const t=e?.scope??"merged",n={version:this.#Me?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Ne?.system:"global"===t?this.#Me?.system:{...this.#Me?.system,...this.#Ne?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#Me?.extensions??{}),...Object.keys(this.#Ne?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Ne?.extensions?.[e]??{}:"global"===t?this.#Me?.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.#Ne:this.#Me)||("project"===r?this.#Ne={version:"1.0",extensions:{},system:{}}:this.#Me={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Ne:this.#Me;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.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]=n.extensions[e]):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]=n.extensions[e]));else"project"===r?this.#Ne={...this.#Ne,...n,version:this.#Ne?.version??"1.0"}:this.#Me={...this.#Me,...n,version:this.#Me?.version??"1.0"};n.system&&("project"===r?(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system=n.system):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system=n.system))}await this.save(r)}async#Le(e){return e.version,e}#je(e,t,n,r){const i=this.#Pe.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}})}},hp="system",mp="ui.language",gp="en";const yp=new class{#Fe=new Map;#Pe=new Set;#qe=null;#Be=new Set;#Ue=new Map;getLocale(){return this.#qe??=this.#Ve(),this.#qe}supportedLocales(){const e=this.#We()?.supported;return Array.isArray(e)&&e.length?e:[gp]}async setLocale(e){const t=String(e||"").trim();if(t&&t!==this.getLocale()){try{await punica.extensions.settings.manager.set(hp,mp,t,"global")}catch(e){throw e instanceof Error?e:new Error(String(e))}this.#qe=t,this.#Ke(t)}}onDidChange(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}#Ke(e){for(const t of[...this.#Pe])try{t(e)}catch{}}#We(){try{return punica.shell?.Profile?.manager?.registry?.getActive?.()?.localization}catch{return}}#Ve(){const e=this.supportedLocales();try{const t=punica.extensions?.settings?.manager?.get?.(hp,mp);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.#We()?.default;return t&&e.includes(t)?t:e.includes(gp)?gp:e[0]}refresh(){const e=this.#Ve();e!==this.#qe&&(this.#qe=e,this.#Ke(e))}register(e,t){e&&t&&this.#Fe.set(e,t)}t(e,t,n){const r=this.#Ge(e,t,n?.count);return void 0===r?(this.#Ye(`${e}:${t}`,e,t),t):n?r.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):r}#Ge(e,t,n){const r=this.#Fe.get(e);if(!r)return;const i=[],s=e=>{e&&!i.includes(e)&&i.push(e)};s(this.getLocale()),s(this.#We()?.default),s(gp);const o=[];"number"==typeof n&&Number.isFinite(n)&&o.push(`${t}.${this.#ze(this.getLocale(),n)}`,`${t}.other`),o.push(t);for(const e of i){const t=r[e];if(t)for(const e of o){const n=t[e];if("string"==typeof n)return n}}}#ze(e,t){let n=this.#Ue.get(e);if(!n){try{n=new Intl.PluralRules(e)}catch{n=new Intl.PluralRules(gp)}this.#Ue.set(e,n)}return n.select(t)}#Ye(e,t,n){this.#Be.has(e)||(this.#Be.add(e),console.warn(`[i18n] missing message "${n}" for ${t} (${this.getLocale()})`))}resetForTesting(){this.#Fe.clear(),this.#Pe.clear(),this.#qe=null,this.#Be.clear(),this.#Ue.clear()}};function wp(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 vp=new Map;function bp(e){const t=vp.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),vp.delete(e)}const Ip={register(e,t,n){const r=n?.target??document.head,i=vp.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),vp.set(e,i),{id:e,dispose(){bp(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),vp.set(e,s),{id:e,dispose(){bp(e)}}},unregister(e){bp(e)},has:e=>!!vp.has(e)||!!document.getElementById(e)};const kp={manager:new class{#Je;#He;#Qe;#Ze;#Xe;#et;#tt;#nt;#rt;constructor(){this.#Je=new Map,this.#He=new Map,this.#Qe=new Map,this.#Ze=new Map,this.#Xe=new Set,this.#et=new Set,this.#tt=new Map,this.#nt=new Map,this.#rt=new Map}getRuntimeState(e){return this.#He.get(e)}registerBuiltinCapabilities(e){const t=Array.isArray(e)?e:[];for(const e of t){const t=String(e?.id??""),n=String(e?.extensionName??""),r=e?.definition??{};if(!t)throw new Error("[Extensions] registerBuiltinCapabilities: Missing id");if(!n)throw new Error(`[Extensions] registerBuiltinCapabilities: Missing extensionName (id="${t}")`);const i=this.#nt.get(t);if(i&&i.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${i.extensionName}" and "${n}".`);this.#nt.set(t,{id:t,extensionName:n,definition:r})}}#it(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.#nt.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.#nt.set(t,i)}this.#st(e,n)}}#st(e,t){const n=Ho.lintAll(Object.values(t));let r=0;for(const t of n)for(const n of t.issues)"error"===n.severity?console.warn(`[Extensions] capability lint [${e.name}] ${n.message}`):"warning"===n.severity&&r++;r>0&&console.warn(`[Extensions] capability lint [${e.name}]: ${r} authoring warning(s) — run capability.lint for detail`)}#ot(e){const t=e.instructionClasses;if(!Array.isArray(t)||0===t.length)return;const n=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;if(n){for(const r of t)try{n.register(r,e.name)}catch(e){console.error(`[Extensions] IC register failed ${r?.id}:`,e)}console.log(`[Extensions] Registered ${t.length} instruction class(es) from "${e.name}"`)}}async load(e,...t){try{const n=[e,...t],r=await Promise.allSettled(n.map(e=>(e=>{const t=new Yd(e),n=new Xd(t),r=new np(n),i=new rp(r),s=new ip(i);return new Zd(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.#Je.set(r.name,r),this.#He.set(r.name,"loaded"),this.#it(r),this.#ot(r);try{sp(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.#Xe.add(r.name),i.includes("onStartup:finish")&&this.#et.add(r.name),i.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#tt.get(t);n||(n=new Set,this.#tt.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#He.get(e))return;const n=this.#Qe.get(e);if(n)return n;if(!this.#Je.get(e))return void console.error(`Extension "${e}" not found.`);const r=function(e){const t=e?.reason??"host",n=e?.presentation??("capability"===t||"extension"===t?"headless":"interactive");return{reason:t,trigger:e?.trigger,presentation:n}}(t),i=this.#at(e,r);this.#Qe.set(e,i);try{await i}finally{this.#Qe.delete(e)}}async#at(e,t){this.#He.set(e,"activating"),wp("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new pc(e),n=new mc(t),r=new gc(n);return new hc(r)})(e),r=await n.execute();if(!r||!r.module||"function"!=typeof r.module.activate)throw new Error(`Failed to activate extension "${e}". The "activate" method is missing or invalid.`);{const n=this.#ct(e,t);"headless"===t.presentation?await dp(()=>r.module.activate(n)):await r.module.activate(n);const i=this.#Ze.get(e);i&&(i.module=r.module),this.#He.set(e,"active"),wp("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#He.set(e,"failed"),wp("extension.lifecycle.activationFailed",{extensionName:e,reason:t.reason,trigger:t.trigger,error:n instanceof Error?n.message:String(n)}),console.error(`Error activating extension "${e}":`,n),n}}#ct(e,t){const n=[];this.#Ze.set(e,{subscriptions:n});return{activation:Object.freeze({reason:t.reason,trigger:t.trigger,presentation:t.presentation}),subscriptions:n,capabilities:{registerHandler:(t,n)=>{this.#rt.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const i=globalThis.punica?.shell?.Views?.manager;if(!i?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const s=i.registerProvider(t,r,e);return n.push(s),s},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway;if(i?.call){const s=r.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await i.call("shell.revealView",{viewId:e,focus:n?.focus??!1},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:o},policy:{mode:"execute"}})}const s=r.punica?.shell?.Views?.manager;if(!s?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await s.reveal(e,{kind:"extension",id:t})}(t,e,n)},hide:async t=>{await async function(e,t){const n=globalThis,r=n.punica?.runtime?.capabilities?.gateway;if(r?.call){const i=n.punica?.kernel?.Events?.manager,s=i?.createCorrelationId?.()??`ext-hide-${Date.now()}`;return void await r.call("shell.hideView",{viewId:e},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:s},policy:{mode:"execute"}})}const i=n.punica?.shell?.Views?.manager;if(!i?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);i.hide(e,{kind:"extension",id:t})}(t,e)},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.#lt(this.#Xe,"startup:begin")}async startupFinish(){await this.#lt(this.#et,"startup:finish")}async#lt(e,t){for(const n of e)try{await this.activate(n,{reason:t})}catch(e){console.error(`Error activating extension "${n}" on${t}:`,e)}}getExtension(e){return this.#Je.get(e)}getAllExtensions(){return Array.from(this.#Je.values())}getCapability(e){return this.#nt.get(e)?.definition}listCapabilities(){return Array.from(this.#nt.values())}validateCapabilityInput(e,t){const n=this.getCapability(e);if(!n)return{ok:!0};const r=n.inputs?.schema;if(!r)return{ok:!0};const i=si().validate(r,t);return i.ok?{ok:!0}:{ok:!1,errors:i.errors}}registerCapabilityHandler(e,t){this.#rt.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#nt.get(e);if(!r)throw new Pr(Mr.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#He.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new Pr(Mr.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.#rt.get(e);if(!i)throw new Pr(Mr.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.#He.get(e))return;const t=this.#Je.get(e);this.#He.set(e,"deactivating");try{const n=globalThis.punica?.shell?.Views?.manager;try{n?.unmountByExtension?.(e)}catch(t){console.warn(`[Extensions] view unmount failed for "${e}":`,t)}try{const n=this.#Ze.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#Ze.get(e);if(r){for(const t of r.subscriptions)try{t.dispose()}catch(t){console.warn(`[Extensions] subscription dispose failed for "${e}":`,t)}this.#Ze.delete(e)}for(const[t,n]of this.#rt)n.extensionName===e&&this.#rt.delete(t)}finally{this.#He.set(e,"loaded"),wp("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#He.get(e);if(void 0===t)return;if("loaded"!==t&&"failed"!==t)throw new Error(`[Extensions] cannot unload "${e}" while ${t} — deactivate() it first.`);try{const t=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;t?.unregisterByOrigin?.(e)}catch(t){console.warn(`[Extensions] instruction-class unregister failed for "${e}":`,t)}for(const[t,n]of this.#nt)n.extensionName===e&&this.#nt.delete(t);for(const[t,n]of this.#tt)n.delete(e)&&0===n.size&&this.#tt.delete(t);const n=this.#Je.get(e)?.integrations?.views;if(n){const t=globalThis.punica?.shell;try{n.activityBar?.id&&t?.ActivityBar?.manager?.removeItem?.(n.activityBar.id),n.statusBar?.id&&t?.Statusbar?.manager?.removeItem?.(n.statusBar.id),n.panel?.id&&t?.PanelTabs?.close?.(n.panel.id)}catch(t){console.warn(`[Extensions] UI contribution retract failed for "${e}":`,t)}}this.#Xe.delete(e),this.#et.delete(e),this.#Qe.delete(e),this.#Ze.delete(e),this.#Je.delete(e),this.#He.delete(e),wp("extension.lifecycle.unloaded",{extensionName:e})}async reload(e,t,n){if(await this.deactivate(e),await this.unload(e),await this.load(t),"loaded"!==this.#He.get(e))throw new Error(`[Extensions] reload failed: "${e}" did not load from ${t}`);await this.activate(e,n??{reason:"host",trigger:e})}getExtensionsForCommand(e){const t=this.#tt.get(e);return t?Array.from(t):[]}},Styles:Ip,metadata:{manager:pp},settings:{manager:fp},i18n:{manager:yp}};function Ep(e){if(null==e)return!1;if(Array.isArray(e))return e.some(Ep);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(Ep)}return!1}function Sp(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=Ap(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=Ap(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?Ep(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 Ap(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 xp{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await Un().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=ci();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[NodeRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return Cp(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[NodeRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n),i=Sp(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 Cp(e,t){for(const n of e)n.isDirectory?n.children&&Cp(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let Tp;function Np(){return Tp||(Tp=new xp),Tp}function Mp(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 Pp(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 _p(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 Rp=/token|secret|key|password|passwd|api[_-]?key/i;function $p(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=Rp.test(i)?"[REDACTED]":e[i],o=i.length+JSON.stringify(s??null).length;n+o>16e3?r=!0:(n+=o,t[i]=s)}return r&&(t.__truncated__=!0),t}async function Lp(e,t){const n=Date.now(),r=Np().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=Sp(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(Ep(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=Mp(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 Pp(k,E,s,t.timeoutMs),n=$p(_p(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()}}function Op(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Dp(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function jp(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Fp(e,t){const n=e.value;switch(e.type){case"isType":return{passed:Dp(t)===String(n??""),expected:String(n??""),actual:Dp(t)};case"equals":return{passed:jp(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=>jp(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:Dp(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:Dp(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):Dp(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:Dp(t)}}}function qp(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=Op(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=Fp(a,r);else if("string"==typeof a)o=Fp({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=Fp({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 Bp(e,t,n){const r=!0===e.assertions?.expectsError,i=e.assertions?.errorPattern;let s;return s=r?i?new RegExp(i).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:s,error:t,assertions:{error:{passed:r,expected:i,actual:t}}}}function Up(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 Vp(){return Date.now()}function Wp(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Kp(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function Gp(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Yp(){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 zp(){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 Jp(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 Hp(e){try{const n=Yp();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 Qp(e,n){const r=Yp();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 Zp(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:Vp(),source:i?.source??"flow:engine",kind:n},payload:r})}const Xp=new Set(["sensitive","secret"]);function ef(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function tf(e,t,n,r){if(!function(e,t,n){return!(!n||!Xp.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:ef(e)}}const nf=new class{#ut=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#ut.set(e,(this.#ut.get(e)??0)+r),!0;const i=this.#ut.get(e)??0;return!(i+r>n)&&(this.#ut.set(e,i+r),!0)}used(e){return this.#ut.get(e)??0}release(e){this.#ut.delete(e)}reset(){this.#ut.clear()}};class rf{async ensureBase(){await Hp(".punica"),await Hp(Gp(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await Hp(Gp(".punica","workflow-runs",e)),await Hp(Gp(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=Vp();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=tf(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=Gp(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let f;f=d?String(u??""):Wp(l??{},2);const h=n.sizeBudget?.maxBytes;if(c||"number"!=typeof h)"number"==typeof h&&nf.acquire(e,f.length,h);else{nf.acquire(e,f.length,h)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,f.length),f=Wp(c,2),nf.acquire(e,f.length,h))}await Qp(p,f);const m=f.length,g=Kp(d?String(u??""):Wp(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 Zp("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function sf(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 of(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function af(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 cf(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 lf(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 uf(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function df(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 pf(e,t,n){const r=df(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 ff(e,t){const n=df(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 hf(e,t){const n=df(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 mf(e,t=".punica"){const n=uf(t,"workflow-runs",e.runId),r=uf(n,"checkpoint.json"),i=uf(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await ff("writeCheckpoint",n),await pf("writeCheckpoint",i,s);try{await async function(e,t,n){const r=df(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 hf("writeCheckpoint",r)}catch{}await pf("writeCheckpoint",r,s);try{await hf("writeCheckpoint",i)}catch{}}}async function gf(e,t=".punica"){const n=uf(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=df(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 yf(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 wf{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:Vp(),startedAtMs:Vp(),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=af(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}),Zp("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),yf({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",Zp("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 gf(e);if(!n)return!1;{const r=n.dependencyGraphState?af(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"),Zp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"RUNNING"}},{traceId:t.run.traceId,spanId:t.rootSpanId}),await this.persistRun(e),await this.persistCheckpoint(e),!0}async cancelRun(e,t){const n=this.runs.get(e);if(!n)return!1;n.cancelled=!0,n.run.status="CANCELLED",n.run.endedAtMs=Vp();const r=this.runIdToSession.get(e);if(r){try{"hard"===(t??"best-effort")?await r.restart():await r.interrupt()}catch(t){console.warn(`[FlowEngine] Error cancelling session for run ${e}:`,t)}this.runIdToSession.delete(e)}return Zp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),Zp("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=Gp(".punica","workflow-runs",e,"run.json");await Qp(n,Wp({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=Gp(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Qp(e,Wp({version:1,updatedAtMs:Vp(),runs:t},2))}async persistCheckpoint(e){const t=this.runs.get(e);if(!t)return;const n={runId:e,timestampMs:Date.now(),run:t.run,spec:t.spec,cursor:t.cursor,inFlightNodes:Array.from(t.inFlightNodes??[])};await mf(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=Gp(".punica","workflow-runs","index.json"),n=await async function(e){const n=Yp();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);Zp("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class vf{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,i,s){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=i,this.resumeRunLoop=s}setupApprovalSubscription(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{const t=e?.event?.payload?e.event:e,n=t?.envelope?.correlationId;if(!n)return;const r=this.pendingToRunStep.get(n);if(!r)return;const i=t?.payload??{},s=i?.request??{},o=i?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(s?.kind??"capability"),id:String(s?.id??""),risk:String(s?.risk??"low"),approval:String(s?.approval??"once"),reason:"string"==typeof s?.reason?s.reason:void 0,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:Vp()};this.pendingByCorrelation.set(n,c);const l=this.runs.get(r.runId);if(l){const e=l.run.steps.find(e=>e.stepId===r.stepId);e&&(e.status="WAITING_APPROVAL",e.approval={pendingId:a,required:!0,requestedAtMs:Vp(),resolved:!1},Zp("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",Zp("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}),Zp("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),yf({name:"flow.approval.requested",correlationId:l.run.runId,traceId:l.run.traceId,payload:{runId:l.run.runId,stepId:r.stepId,pendingId:c.pendingId,attemptCorrelationId:n,capability:{kind:c.kind,id:c.id},risk:c.risk,approval:c.approval,workspaceId:c.workspaceId}}),this.persistRun(l.run.runId)}})}approvePending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=e?.scope??"once",r=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!r)return!1;const i=this.pendingToRunStep.get(r.attemptCorrelationId);if(!i)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id},n,{workspaceId:r.workspaceId})}catch{}Zp("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:Vp()},{traceId:i.runId}),yf({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",Zp("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;Zp("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:Vp()},{traceId:r.runId}),yf({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=Vp(),Zp("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}),Zp("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 bf=3e4,If={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const kf=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e,t){const n=this.#le.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function Ef(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function Sf(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 Af=new class{#dt=new Map;register(e,t){this.#dt.set(e,t)}get(e){return this.#dt.get(e)}resolveOrThrow(e){const t=this.#dt.get(e.ref.kind);if(!t)throw new Error(`No executor registered for node ref.kind: "${e.ref.kind}" (node id: ${e.id})`);return t}clear(){this.#dt.clear()}};function xf(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 Cf(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=xf(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function Tf(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 Nf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Mf(e){return String(e??"").split(".").filter(e=>e.length>0)}function Pf(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];Nf(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function _f(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={...Nf(e.defaults)?e.defaults:{},...Nf(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?Mf(e.fromPath):[],i=r.length?xf(t,r):t;if(void 0===i)continue;const o=e.toPath?Mf(e.toPath):[];o.length?Pf(s,o,i):Nf(i)?Object.assign(s,i):s[e.fromId]=i}return s}class Rf 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 $f(e,t){if(function(e){return!0===e.cancelled}(e))throw new Rf(e.run?.runId,t)}class Lf{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=Yp();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",Zp("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=Vp(),a.endedAtMs=void 0,a.error=void 0;const c=punica.kernel.Events.manager.createCorrelationId(),u=punica.kernel.Events.manager.createCorrelationId();a.attemptCorrelationId=c,a.spanId=u,this.pendingToRunStep.set(c,{runId:e,stepId:a.stepId}),Zp("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}),yf({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:_f(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),Zp("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}),yf({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",Zp("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",Zp("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=Vp(),a.error={message:o},Zp("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}),yf({name:"flow.node.failed",kind:"error",correlationId:e,traceId:r,payload:{runId:e,nodeId:a.nodeId,attempt:a.attempt,endedAtMs:a.endedAtMs,attemptCorrelationId:c,spanId:u,error:{message:o}}}),n.run.status="FAILED",n.run.endedAtMs=Vp(),n.run.error={message:o,nodeId:s,correlationId:c},Zp("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),Zp("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),yf({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=Sf(h,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",Zp("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=Vp(),Zp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),Zp("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),yf({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=uf(n,"workflow-runs",e.runId),i=uf(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await ff("writeRunHistory",r),await pf("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=uf(t,"workflow-runs",e,"checkpoint.json");try{await hf("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;!of(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=sf(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=>{lf(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 cf(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void cf(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;){$f(r),f++,l.attempt=f,l.status="RUNNING",l.startedAtMs=Vp();const e=punica.kernel.Events.manager.createCorrelationId(),n=punica.kernel.Events.manager.createCorrelationId();l.attemptCorrelationId=e,l.spanId=n;try{const o=await this.executeNodeAttempt(c,l,a,{attemptCorrelationId:e,spanId:n,rootSpanId: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:_f(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 Rf)throw l.status="CANCELLED",l.endedAtMs=Vp(),e;const t=String(e?.message??e);if(f<=d){const e=Sf(f,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=Vp(),l.error={message:t},e}}h&&(cf(o,!0,n),await this.persistRun(e))}catch(t){cf(o,!1,n),t instanceof Rf||(r.run.status="FAILED",r.run.endedAtMs=Vp(),r.run.error={message:String(t?.message??t),nodeId:o},a&&(r.cancelled=!0),await this.persistRun(e))}finally{r.inFlightNodes?.delete(o)}});await Promise.allSettled(u)}"RUNNING"===r.run.status?(r.run.status="COMPLETED",r.run.endedAtMs=Vp(),Zp("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),Zp("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),yf({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&&(yf({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=Af.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:bf,retry:{...If},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=Af.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,Ef(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=Vp(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return Af.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class Of 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 Df(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new Of(e??0,t);return n}const jf="__default__";class Ff{workspaceId;#pt=new Map;#ft=new Map;#ht=new Map;#mt=new rf;#gt=!1;#yt=new Map;#wt;#vt;#bt;constructor(e=jf){this.workspaceId=e,this.#wt=new wf(this.#pt,this.#yt,this.#mt),this.#vt=new vf(this.#pt,this.#ft,this.#ht,e=>this.#wt.persistRun(e),()=>this.#wt.persistIndex(),e=>this.#It(e)),this.#bt=new Lf(this.#pt,this.#ht,this.#yt,this.#mt,e=>this.#wt.persistRun(e),e=>this.#wt.persistCheckpoint(e),()=>this.#wt.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#gt||(this.#gt=!0,this.#vt.setupApprovalSubscription(),this.#wt.loadIndex())}async startRun(e){const t=await this.#wt.startRun(e);return this.#It(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#wt.pauseRun(e)}async resumeRun(e){const t=await this.#wt.resumeRun(e);return t&&this.#It(e,{}),t}async cancelRun(e,t){return this.#wt.cancelRun(e,t)}getRun(e){return this.#wt.getRun(e)}listRuns(e){return this.#wt.listRuns(e)}approvePending(e){return this.#vt.approvePending(e)}rejectPending(e){return this.#vt.rejectPending(e)}hasRun(e){return this.#pt.has(e)}getNodeOutput(e,t){const n=this.#pt.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=Df(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#wt.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;yf({name:"flow.subflow.spawned",correlationId:n,traceId:e.parentTraceId,payload:{runId:n,depth:t,parentRunId:e.parentRunId,parentTraceId:e.parentTraceId,workspaceId:this.workspaceId,flowId:e.spec.id}});const r=new Promise(e=>{const t=this.#kt.get(n);if(t)return this.#kt.delete(n),void e(t);this.#Et.set(n,e)});this.#It(n,{workspaceId:this.workspaceId});const 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.#Et.get(e);if(n)return this.#Et.delete(e),void n(t);this.#kt.set(e,t)}#Et=new Map;#kt=new Map;hasPending(e){return this.#ht.has(e)}async#It(e,t){const n=this.#pt.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;const r=void 0!==n.dependencyGraph,i=n.dependencyGraph;r&&i?await this.#bt.executeParallel(e,t,i,n):await this.#bt.executeSequential(e,t)}}const qf=new Map,Bf=new Map,Uf=new Map;function Vf(e){const t=e??jf;let n=qf.get(t);return n||(n=new Ff(t),qf.set(t,n)),n}let Wf=!1;const Kf=new class{initialize(){if(Wf)return;Wf=!0;const e=punica.kernel.Commands.manager;e.registerCommand(ot.WORKFLOW.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(ot.WORKFLOW.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(ot.WORKFLOW.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(ot.WORKFLOW.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(ot.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:jf}(e),n=Vf(t);n.initialize();const r=await n.startRun(e);return Bf.set(r.runId,t),r}async pauseRun(e){const t=this.#St(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#St(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#St(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#St(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#St(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of qf.values())t.push(...n.listRuns({status:e?.status}));return"number"==typeof e?.limit&&e.limit>0?t.slice(0,e.limit):t}approvePending(e){const t=this.#At(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#At(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(Df(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=Vf(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Bf.set(n.runId,t.workspaceId),n}#St(e){const t=Bf.get(e);if(t)return qf.get(t);for(const[t,n]of qf.entries())if(n.hasRun(e))return Bf.set(e,t),n}#At(e){const t=Uf.get(e);if(t)return qf.get(t);for(const[t,n]of qf.entries())if(n.hasPending(e))return Uf.set(e,t),n}};function Gf(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 Yf(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class zf{packages=new Map;async discover(){this.packages.clear();try{if(!await Un().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=ci();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[AgentRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return Jf(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[AgentRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n);if(!Yf(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 Jf(e,t){for(const n of e)n.isDirectory?n.children&&Jf(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let Hf;function Qf(){return Hf||(Hf=new zf),Hf}const Zf=new Set(["COMPLETED","FAILED","CANCELLED"]);function Xf(e){return new Promise(t=>setTimeout(t,e))}async function eh(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&&(Zf.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await Xf(250)}return{record:i,timedOut:!0}}async function th(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(Bp(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await eh(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(Bp(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(Bp(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(qp(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(Bp(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const nh={validator:{validate:Sp},registry:{discover:()=>Np().discover(),get:e=>Np().get(e),list:()=>Np().list(),search:e=>Np().search(e),setTestReport:(e,t)=>Np().setTestReport(e,t),getLatestTestReport:e=>Np().getLatestTestReport(e)},runner:{run:Lp},test:{run:async function(e,t){const n=Np(),r=n.get(e);if(!r){if(t?.manifest){if(Yf(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=Kf,o=Gf(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 th(s,o,e,n,t?.workspaceId))}const l=Up({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{Np().setTestReport(r,l)}catch{}return l}(t.manifest);throw new Error(`Manifest for ${e} is not a testable IvyAgent (expected kind 'IvyAgent' with a graph).`)}throw new Error(`IvyNode not found: ${e}`)}const i=r.manifest,s=i.tests;if(!s)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of s.cases||[]){if(t.skip){a.push({caseId:t.id,status:"skip",durationMs:0,error:"string"==typeof t.skip?t.skip:void 0});continue}const n=Date.now();let r;try{const i=await Lp(e,{input:t.input,runId:`test-${e}-${t.id}-${Date.now()}`,timeoutMs:s.timeoutMs||3e4}),o=i.events.filter(e=>"error"===e.type).map(e=>{const t=e.data;return t?.message||""}).join(" "),a=qp(t,i.output,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:i.output,assertions:a.assertions}}catch(e){const i=Bp(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=Up({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}}},rh={discover:()=>Qf().discover(),get:e=>Qf().get(e),list:()=>Qf().list(),search:e=>Qf().search(e),unregister:e=>Qf().unregister(e),run:(e,t)=>async function(e,t){const n=Qf().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??Kf,i=t?.timeoutMs??3e4,s=Gf(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 eh(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:Gf,isAgentManifest:Yf},ih=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",[]]]),sh=new Set(["COMPLETED","FAILED","CANCELLED"]);const oh=new class{canTransitionTo(e,t){if(e===t)return!1;const n=ih.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 ih.get(e)??[]}isTerminal(e){return sh.has(e)}},ah=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],ch={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const lh={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function uh(e){return{x:lh.marginX+e%6*240,y:lh.marginY+120*Math.floor(e/6)}}function dh(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 ph(e,t){const n={...lh,...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]=uh(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]=uh(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,dh(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 fh;function hh(e){if(!fh)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 fh}function mh(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");fh=e}function gh(){fh=void 0}function yh(){return fh}function wh(e){return hh("createFlowRenderer").createRenderer(e)}function vh(e){return hh("createViewportController").createViewportController(e)}function bh(e,t){return hh("attachZoomControl").attachZoomControl(e,t)}function Ih(e,t){return hh("attachMinimap").attachMinimap(e,t)}function kh(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 Eh={setRendererProvider:mh,resetRendererProvider:gh,getRendererProvider:yh,createFlowRenderer:wh,createViewportController:vh,attachZoomControl:bh,attachMinimap:Ih,mergeViewSnapshotIntoNotebook:kh,computeFlowLayout:ph,gridFallbackPosition:uh,get rendererProvider(){return fh}},Sh=Object.freeze({__proto__:null,attachMinimap:Ih,attachZoomControl:bh,computeFlowLayout:ph,createFlowRenderer:wh,createViewportController:vh,default:Eh,getRendererProvider:yh,gridFallbackPosition:uh,mergeViewSnapshotIntoNotebook:kh,resetRendererProvider:gh,setRendererProvider:mh});function Ah(e,t,n){return{path:e,message:t,severity:"error",code:n}}function xh(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const Ch="WF_INVALID_VERSION",Th="WF_INVALID_EDGE_REF",Nh=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Mh(e){return"string"==typeof e&&Nh.test(e)}const Ph=new class{#xt=new Map;register(e,t){if("string"!=typeof e||0===e.length)throw new Error("LambdaRegistry.register: id must be a non-empty string");if("function"!=typeof t)throw new Error("LambdaRegistry.register: fn must be a function");this.#xt.set(e,t)}unregister(e){return this.#xt.delete(e)}get(e){return this.#xt.get(e)}list(){return Array.from(this.#xt.keys())}clear(){this.#xt.clear()}},_h={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}},Rh={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}},$h={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}},Lh={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 Oh(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function Dh(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 jh={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=Oh(o.ref),l=Oh(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=Dh(p,s.fromPath),m=Dh(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}},Fh=["while","forEach"],qh={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(!Fh.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 Bh(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+Bh(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const Uh={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Bh(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}},Vh=[_h,Rh,$h,Lh,jh,qh,Uh];const Wh=new class{#fe=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#fe.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.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of Vh)this.#fe.set(e.id,e)}};function Kh(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 Gh(e){return e.map(e=>`${e.from}=>${e.to}`)}function Yh(e,t){return`${e}=>${t}`}const zh=new class{#Ct=new Map;register(e){if(!e||"function"!=typeof e.transform)throw new Error("MigrationRegistry.register: transformer must have a transform(doc) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("MigrationRegistry.register: transformer.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("MigrationRegistry.register: transformer.to must be a non-empty string");if(e.from===e.to)throw new Error("MigrationRegistry.register: transformer.from must differ from transformer.to (no self-edges)");this.#Ct.set(Yh(e.from,e.to),e)}unregister(e,t){return this.#Ct.delete(Yh(e,t))}find(e,t){return this.#Ct.get(Yh(e,t))}list(){return Array.from(this.#Ct.values())}clear(){this.#Ct.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,i=e.targetVersion;if(!Mh(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(!Mh(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)=>Kh(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:Gh(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:Gh(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:Gh(a)}}return{ok:!0,document:o,appliedTransformers:Gh(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Kh(this.#Ct,e,t)}};function Jh(){return Date.now()}class Hh{#he=new Map;#Pe=new Set;register(e,t){if(!e||"string"!=typeof e.id||0===e.id.length)throw new Error("ManualTriggerProvider.register: trigger.id must be a non-empty string");if("string"!=typeof e.kind||0===e.kind.length)throw new Error("ManualTriggerProvider.register: trigger.kind must be a non-empty string");if("string"!=typeof e.flowId||0===e.flowId.length)throw new Error("ManualTriggerProvider.register: trigger.flowId must be a non-empty string");if("function"!=typeof t)throw new Error("ManualTriggerProvider.register: callback must be a function");const n={trigger:e,callback:t,unsubscribed:!1};return this.#he.set(e.id,n),this.#Ke({type:"registered",triggerId:e.id,kind:e.kind,ts:Jh()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#he.get(e.id)===n&&(this.#he.delete(e.id),this.#Ke({type:"unregistered",triggerId:e.id,ts:Jh()}))}}}unregister(e){const t=this.#he.get(e);return!!t&&(t.unsubscribed=!0,this.#he.delete(e),this.#Ke({type:"unregistered",triggerId:e,ts:Jh()}),!0)}list(){return Array.from(this.#he.values()).map(e=>e.trigger)}subscribe(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}async fire(e,t){const n=this.#he.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Jh()}-${Math.floor(1e6*Math.random())}`,i=Jh();this.#Ke({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),yf({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.#Ke({type:"error",triggerId:e,ts:Jh(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#he.values())e.unsubscribed=!0;this.#he.clear(),this.#Pe.clear()}#Ke(e){for(const t of this.#Pe)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const Qh=new Hh;let Zh=Qh;const Xh={get manager(){return Zh},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()");Zh!==e&&Zh instanceof Hh&&Zh.clear(),Zh=e},resetProvider(){Zh instanceof Hh&&Zh.clear(),Zh=Qh}};function em(e,t){return`${e}=>${t}`}const tm={migrators:new class{#Tt=new Map;register(e){if(!e||"function"!=typeof e.migrate)throw new Error("CheckpointMigratorRegistry.register: migrator must have a migrate(checkpoint) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("CheckpointMigratorRegistry.register: migrator.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("CheckpointMigratorRegistry.register: migrator.to must be a non-empty string");if(e.from===e.to)throw new Error("CheckpointMigratorRegistry.register: migrator.from must differ from migrator.to");this.#Tt.set(em(e.from,e.to),e)}unregister(e,t){return this.#Tt.delete(em(e,t))}find(e,t){return this.#Tt.get(em(e,t))}list(){return Array.from(this.#Tt.values())}clear(){this.#Tt.clear()}},isFresh:function(e,t,n=Date.now()){if("number"!=typeof e||Number.isNaN(e))return!1;if(!t||"number"!=typeof t.maxAgeMs)return!0;if(t.maxAgeMs<0)return!0;const r=n-e;return r>=0&&r<=t.maxAgeMs}},nm={...nh,agents:rh,engine:{manager:Kf,statusStateMachine:oh,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=ch[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(ah,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:Sh,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(Ah("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',Ch)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(Ah("kind",'kind must equal "Workflow"',Ch)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!Mh(o)){const e=Ah("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(Ah("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(Ah("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(Ah("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(Ah(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(Ah(`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(Ah(`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(Ah(`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(Ah(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(Ah(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(Ah(`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(Ah("graph.nodes","flow-input node is required when edges reference it")),f&&!d&&n.push(Ah("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(Ah("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(Ah(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(Ah(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(Ah(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,Th)),i&&!l.has(i)&&n.push(Ah(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,Th))}),"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(Ah("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(xh(`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?Ah:xh)(`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:Ph,linter:Wh,migrations:zh,checkpoints:tm},triggers:Xh},rm=[];function im(e){rm.push(e)}function sm(){const e={};for(const t of rm)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function om(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function am(e){return"string"==typeof e}function cm(e){return"string"==typeof e&&e.trim().length>0}function lm(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const um=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"]),dm=new Set(["light","dark","auto"]),pm=new Set(["compact","comfortable"]),fm=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const hm=new class{validate(e){const t=[];if(!om(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)}`),om(e.identity)?(cm(e.identity.id)||t.push("identity.id must be a non-empty string"),cm(e.identity.name)||t.push("identity.name must be a non-empty string"),cm(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),om(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys(sm()),r=new Set([...um,...n]);e.shell.activeModules.forEach((e,n)=>{am(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&&(om(e.shell.layout)?(cm(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),om(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(om(e.theme)?(dm.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||pm.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"),om(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||lm(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||lm(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)=>{am(e)&&fm.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 mm;function gm(e){mm=e}function ym(){return mm??hm}function wm(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 vm{#Nt=new Map;#Mt;register(e){if(this.#Nt.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#Nt.set(e.identity.id,e),void 0===this.#Mt&&(this.#Mt=e.identity.id)}get(e){return this.#Nt.get(e)}getActive(){if(void 0===this.#Mt||!this.#Nt.has(this.#Mt))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#Nt.get(this.#Mt)}setActive(e){if(!this.#Nt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#Mt=e}switchProfile(e){if(!this.#Nt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#Mt=e,wm({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Nt.has(e)}list(){return Array.from(this.#Nt.values())}}const bm={manager:new class{registry=new vm;get validator(){return ym()}loadProfile(e){if("string"==typeof e){if(this.registry.has(e))return void this.registry.setActive(e);let t;try{t=JSON.parse(e)}catch{throw new Error(`loadProfile: '${e}' is not a registered profile id and could not be parsed as JSON`)}return void this.#Pt(t)}this.#Pt(e)}#Pt(e){const t=this.validator.validate(e);if(!t.valid)throw wm({name:"shell.profile.load_failed",payload:{errors:t.errors}}),new Error(`ApplicationProfile validation failed:\n ${t.errors.join("\n ")}`);this.registry.has(t.profile.identity.id)||this.registry.register(t.profile),this.registry.setActive(t.profile.identity.id),wm({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}};class Im{name=st.EXTENSIONS.MANAGER;version="1.0.0";dependencies=[st.KERNEL.COMMANDS,st.KERNEL.EVENTS,st.RUNTIME.WORKSPACE];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.COMMANDS),s=r.getState(st.KERNEL.EVENTS),o=r.getState(st.RUNTIME.WORKSPACE),a=r.getState(st.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 km{name=st.FLOW.VALIDATOR;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel)throw new Error("Kernel not available");if(!t.flow?.validateWorkflowDocument)throw new Error("Flow validator not available")}async start(e){}}function Em(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 Sm{prepareExecutionConfig(e){const t=Em(e);if(!t)return{};const n=zp(),r=n?.getSpec?.(t);return{capabilityDefaults:Jp(r)}}async acquireResources(e,t,n){const r=Em(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 kf.acquire(n,e.concurrency.max),()=>{kf.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=Em(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Yp();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=zp(),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:Kp(Wp(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Am(e){return e.data??{}}function xm(e){return e.nodeOutputs??new Map}async function Cm(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:Kp(Wp(i,0),320),artifactIds:[s.id]}}class Tm{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=Am(e),i=Cf(r.predicate,xm(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:Tf(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Cm(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Cm(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Am(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=Cf(r.collection,xm(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 Cm(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Am(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=Cf(r.predicate,xm(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=Tf(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Cm(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Am(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 Cm(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Cm(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Cm(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Am(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=Ph.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=Cf(r.input,xm(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:Kp(Wp(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 Nm{async execute(e,t){return{output:t.runInput??null}}}class Mm{async execute(e,t){return{output:t.resolvedInput??null}}}let Pm=!1;class _m{name=st.FLOW.ENGINE;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.KERNEL.POLICY,st.KERNEL.COMMANDS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.EVENTS),s=r.getState(st.KERNEL.POLICY),o=r.getState(st.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(Pm||(Af.register("ivyNode",new Sm),Af.register("primitive",new Tm),Af.register("flowInput",new Nm),Af.register("flowOutput",new Mm),Pm=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class Rm{name=st.FLOW.SHELL;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 $m{name=st.KERNEL.EVENTS;version="1.0.0";dependencies=[];#we=e.CREATED;#l=null;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Events?.manager)throw new Error("Events manager not available");this.#l=t.kernel.Events.manager}async start(e){}get api(){return this.#l}}class Lm{name=st.KERNEL.COMMANDS;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class Om{name=st.KERNEL.POLICY;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Dm{name=st.KERNEL.HISTORY;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class jm{name=st.KERNEL.TIME_SERVER;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class Fm{name=st.KERNEL.TASKS;version="1.0.0";dependencies=[st.RUNTIME.TERMINALS,st.RUNTIME.WORKSPACE];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.RUNTIME.TERMINALS),s=r.getState(st.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 qm{name=st.KERNEL.NOTIFICATIONS;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class Bm{name=st.KERNEL.AI;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.KERNEL.POLICY,st.KERNEL.LLM];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.EVENTS),s=r.getState(st.KERNEL.POLICY),o=r.getState(st.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 Um=class{name=st.KERNEL.LLM;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.KERNEL.POLICY];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.EVENTS),s=r.getState(st.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:kn,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class Vm{name=st.RUNTIME.FS;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class Wm{name=st.RUNTIME.SEARCH;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Km{name=st.RUNTIME.VCS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Gm{name=st.RUNTIME.WORKSPACE;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Ym{name=st.RUNTIME.LLM;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 zm{name=st.RUNTIME.TASKS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Jm{name=st.RUNTIME.SECRETS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Hm{name=st.RUNTIME.TERMINALS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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){}}function Qm(){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 Zm(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 Xm(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 eg(e,n,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await t(),actor:{type:"user",id:void 0},origin:{kind:n,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function tg(){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=Qm();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");Zm("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await eg("workspace.readFile","command",t))})}catch(e){Xm("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=Qm();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await eg("workspace.writeFile","command",t)),Zm("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){Xm("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();Zm("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){Xm("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{Zm("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await eg("vcs.status","command",t))})}catch(e){Xm("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;Zm("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 eg("tasks.runCommand","command",t))})}catch(e){Xm("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?Zm("capability.llm.invoke.result",t,r):Xm(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return Xm(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?Zm("capability.llm.plan.result",t,r):Xm(n,t,r)}catch(e){Xm(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)");Zm(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 In(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 Zm(n,t,i)}else Zm(n,t,i);else Xm(r,t,i)}catch(e){Xm(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?Zm("capability.llm.edit-workflow.result",t,r):Xm(n,t,r)}catch(e){Xm(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 eg("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(ot.SHELL.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(ot.SHELL.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(ot.SHELL.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const ng="1.0.0",rg=An,ig={},sg=dc,og=kp,ag=nm,cg=new class{#_t=new Map;#Rt=new Map;#$t=new Map;register(t){if(this.#_t.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#_t.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#_t.set(t.name,t),this.#Rt.set(t.name,e.CREATED)}get(e){return this.#_t.get(e)}getAll(){return Array.from(this.#_t.values())}resolveBootstrapOrder(){return this.#Lt()}resolveStartOrder(){return this.#Lt()}#Lt(){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.#_t.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.#_t.keys())e.has(t)||r(t);return n}async bootstrapAll(){const t=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#Rt.set(n,e.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#Rt.set(n,e.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Rt.set(n,e.BOOTSTRAP_FAILED),this.#$t.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} bootstrap failed:`,r),new Error(`Critical module ${n} failed to bootstrap: ${r.message}`)}}console.log("[ModuleRegistry] All modules bootstrapped successfully")}async startAll(){const t=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#Rt.get(n);if(r!==e.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#Rt.set(n,e.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#Rt.set(n,e.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Rt.set(n,e.START_FAILED),this.#$t.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.#Rt.get(n)===e.STARTED&&this.#Rt.set(n,e.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#Rt.get(e)}areAllModulesReady(){for(const[t,n]of this.#_t){if(this.#Rt.get(t)!==e.READY)return!1}return!0}getError(e){return this.#$t.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#_t.keys())t.includes(n)&&e.push(n);return e}};function lg(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:ng,kernel:rg,shell:ig,runtime:sg,extensions:og,flow:ag};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=im;const t=e.debug??{};t.logTrinityCatalog=Aa,t.logTrinityCatalogVerbose=xa,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=Aa,n.logTrinityCatalogVerbose=xa);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{tg(),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 ug(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 rm)t.facade&&Object.assign(e,t.facade);return e}()));const n=bm.manager;for(const e of function(){const e=[];for(const t of rm)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 rm)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(cg.register(new $m),cg.register(new Lm),cg.register(new Dm),cg.register(new jm),cg.register(new qm),cg.register(new km),cg.register(new Om),cg.register(new Um),cg.register(new Bm),cg.register(new _m),cg.register(new Vm),cg.register(new Wm),cg.register(new Km),cg.register(new Gm),cg.register(new Ym),cg.register(new Jm),cg.register(new Hm),cg.register(new zm),cg.register(new Ga),cg.register(new Fm),r){const e=sm(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(cg.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}cg.register(new Im),console.log(`[Punica] Module registry initialized with ${cg.getAll().length} modules`),await cg.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}}async function dg(){try{console.log("[Punica] Starting system..."),await cg.startAll(),cg.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:ng}}),console.log("[Punica] System started successfully"),Aa()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}}im({moduleFactories:{"flow.shell":()=>new Rm}});var pg=Object.freeze({__proto__:null,StdioTransport:class{#Ot;#Dt;#jt;#Ft=null;#qt=null;#Bt=null;#Ut=null;#Vt=null;#Wt=new Map;#Kt=1;#Gt="";constructor(e,t=[],n={}){this.#Ot=e,this.#Dt=t,this.#jt=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#Yt(e):await this.#zt()}async#Yt(e){this.#Bt=e;const{sessionId:t}=await e.spawn({command:this.#Ot,args:this.#Dt,env:this.#jt});this.#qt=t,this.#Ut=e.onData(e=>{e.sessionId===t&&this.#Jt(e.chunk)}),this.#Vt=e.onExit(e=>{if(e.sessionId!==t)return;const n=new Error(e.error??`MCP stdio process exited (${e.code})`);for(const{reject:e}of this.#Wt.values())e(n);this.#Wt.clear()})}async#zt(){const e=await import(
2
- /* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#Ft=e.spawn(this.#Ot,this.#Dt,{env:{...n,...this.#jt},stdio:["pipe","pipe","inherit"]}),this.#Ft.stdout.setEncoding("utf8"),this.#Ft.stdout.on("data",e=>{this.#Jt(e)}),this.#Ft.on("error",e=>{for(const{reject:t}of this.#Wt.values())t(e);this.#Wt.clear()})}#Jt(e){let t;for(this.#Gt+=e;-1!==(t=this.#Gt.indexOf("\n"));){const e=this.#Gt.slice(0,t).trim();this.#Gt=this.#Gt.slice(t+1),e&&this.#Ht(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#Qt(n)}async request(e,t={}){const n=this.#Kt++;return new Promise((r,i)=>{this.#Wt.set(n,{resolve:r,reject:i});const s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#Qt(s)}catch(e){this.#Wt.delete(n),i(e instanceof Error?e:new Error(String(e)))}})}#Qt(e){if(this.#Bt&&this.#qt)this.#Bt.write(this.#qt,e);else{if(!this.#Ft?.stdin)throw new Error("MCP stdio transport is not connected");this.#Ft.stdin.write(e)}}close(){this.#Ut?.(),this.#Vt?.(),this.#Ut=null,this.#Vt=null,this.#Bt&&this.#qt&&this.#Bt.close(this.#qt),this.#Ft?.kill(),this.#Ft=null,this.#qt=null,this.#Bt=null;for(const{reject:e}of this.#Wt.values())e(new Error("MCP stdio transport closed"));this.#Wt.clear()}#Ht(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#Wt.get(t.id);n&&(this.#Wt.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var fg=Object.freeze({__proto__:null,StreamableHttpTransport:class{#Zt;#Xt;#Kt=1;#qt;constructor(e,t={}){this.#Zt=e.replace(/\/$/,""),this.#Xt=t}async connect(){const e=await fetch(`${this.#Zt}/sse`,{headers:{...this.#Xt,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#qt=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#en({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#Kt++,r=await this.#en({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#en(e){const t={...this.#Xt,"Content-Type":"application/json",Accept:"application/json"};this.#qt&&(t["mcp-session-id"]=this.#qt);const n=await fetch(`${this.#Zt}/messages`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw new Error(`MCP request failed: ${n.status} ${n.statusText}`);return await n.json()}close(){this.#qt=void 0}}});var hg=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return Wa(Vd(e))}});export{ot as COMMAND_IDS,st as MODULE_NAMES,e as ModuleLifecycleState,bm as Profile,ug as bootstrap,wm as emitShellEvent,cp as enterHeadlessScope,lp as exitHeadlessScope,og as extensions,ag as flow,ym as getProfileValidator,lg as initialize,up as isHeadlessScope,ep as isMacPlatform,rg as kernel,tp as parseKeyChord,im as registerShell,dp as runInHeadlessScope,sg as runtime,gm as setProfileValidator,ig as shell,dg as start,ng 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>=4&&(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){const t=[];return function e(n,r){if(!n||"object"!=typeof n)return;const i=n,s=i.properties;if(s&&"object"==typeof s)for(const[n,i]of Object.entries(s)){if(!i||"object"!=typeof i)continue;const s=i,o=[...r,n];!0===s.sensitive&&t.push(o),e(s,o)}const o=i.items;if(o&&"object"==typeof o)if(Array.isArray(o))for(const t of o)e(t,[...r,"*"]);else e(o,[...r,"*"]);for(const t of["anyOf","oneOf","allOf"]){const n=i[t];if(Array.isArray(n))for(const t of n)e(t,r)}}(e,[]),t}function d(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 p=/^(?:secrets|secret-manager)\./,f=new Set(["value"]);const h={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=p.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]=f.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 m=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 g={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:m};const y={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 w(){return(new Date).toISOString()}function v(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=w(),{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:w(),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:w()};r.set(t,i),s(i)},onDidChangeRun:e=>(i.add(e),()=>{i.delete(e)})};return o}const b=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=v(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 I={manager:b},k=Object.freeze({__proto__:null,createTasksApi:v,default:I,manager:b});const E=6048e5,S={rules:[],defaultTtlMs:E};function A(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 x(e,t,n){const r=function(e,t){let n=null,r=-1;for(const i of t)if(A(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??E)}const C=".punica/.gitignore",T="# Punica editor — workspace internal state.\n# Auto-generated. Everything under .punica/ is ignored by default;\n# only the authored artifacts and user config below are tracked.\n/*\n\n!.gitignore\n\n# Authored artifacts (user's project content)\n!/ivy-nodes/\n!/ivy-agents/\n!/ivy-mcps/\n!/ivy-inputs/\n\n# Generated, and required by something outside this machine. The CI generator\n# writes the gate drivers here and the workflow it produces calls them by path,\n# so a runner that checks out the repository must find them.\n!/ci/\n\n# User configuration\n!/settings.json\n!/tasks.json\n!/launch.json\n!/database.yaml\n!/experiments.yaml\n!/mlops.yaml\n!/python.yaml\n!/vectors.yaml\n!/mcp.yaml\n!/mcp/\n";function N(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.startsWith("!"))}async function M(){const e=r();if(e&&(!n()||await t()))try{if(!!e.exists&&await e.exists(C)){const t=function(e){if(!e.includes("# Punica editor — workspace internal state."))return null;const t=new Set(N(e)),n=N(T).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(C)??"");return void(t&&e.updateFileContent&&await e.updateFileContent(C,t))}try{await e.createFolder(".punica")}catch{}await e.createFileWithContent(C,T)}catch{}}const P=".punica/events";let _={};function R(e){const t=[],n=[...e];for(;n.length>0;){const e=n.pop();if(e){if(Array.isArray(e.children))for(const t of e.children)n.push(t);!0!==e.isDirectory&&"string"==typeof e.path&&e.path.startsWith(P)&&e.path.endsWith(".json")&&t.push(e.path)}}return t}function L(e,t){if(!t)return!0;const n=e.envelope;if(void 0!==t.correlationId&&n?.correlationId!==t.correlationId&&n?.id!==t.correlationId)return!1;if(void 0!==t.name){if(!(Array.isArray(t.name)?t.name:[t.name]).includes(e.name))return!1}return!(void 0!==t.since&&(n?.timestampMs??0)<t.since)&&!(void 0!==t.until&&(n?.timestampMs??0)>t.until)}const $=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(P)}catch{}if(!this.#p){this.#p=!0;try{await i.createFileWithContent(`${P}/.gitignore`,"*\n!.gitignore\n")}catch{}}this.#f||(this.#f=!0,await M());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=`${P}/${n}_${r}.json`,o=l(t);await i.createFileWithContent(s,o)}catch{}try{_.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=R(n),s=[];for(const n of i)try{const r=await t.readFile(n),i=JSON.parse(r);L(i,e)&&s.push(i)}catch{}return s.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),e?.limit&&e.limit>0?s.slice(-e.limit):s}async delete(e){const t=r();if(!t)return 0;let n;try{n=await t.getFileTree()}catch{return 0}if(!Array.isArray(n))return 0;const i=R(n);let s=0;const o=[];for(const n of i)try{const r=await t.readFile(n);if(L(JSON.parse(r),e))await t.deleteFile(n),s++;else{const e=n.split("/").pop()??"",t=e.match(/^(\d{4}-\d{2}-\d{2})_/)?.[1]??"";o.push({path:n,dateKey:t})}}catch{}if(o.length>this.#d){o.sort((e,t)=>e.dateKey.localeCompare(t.dateKey));const e=o.length-this.#d;for(const n of o.slice(0,e))try{await t.deleteFile(n.path),s++}catch{}}return s}async applyRetention(e,t=Date.now()){const n=r();if(!n)return 0;let i;try{i=await n.getFileTree()}catch{return 0}if(!Array.isArray(i))return 0;const s=R(i);let o=0;for(const r of s)try{const i=await n.readFile(r),s=JSON.parse(i),a=s.envelope?.timestampMs??0;a<x(s.name,e,t)&&(await n.deleteFile(r),o++)}catch{}return o}};let O=$;function D(){return O}const j=new class{#h=void 0;get(){return this.#h}runWith(e,t){const n=this.#h;let r;this.#h=e;try{r=t()}catch(e){throw this.#h=n,e}return r&&"function"==typeof r.then?r.then(e=>(this.#h=n,e),e=>{throw this.#h=n,e}):(this.#h=n,r)}};let F=j;function q(e){if(void 0!==e.traceId&&void 0!==e.spanId&&void 0!==e.parentSpanId)return e;const t=F.get();return t?{...e,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}:e}function B(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(A(e.name,t)){r=!0;break}if(!r)return!1}return!0}class U extends Error{constructor(e){super(e),this.name="EventReplayError"}}let V={exportSpan:()=>{}};function W(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`evt_${Date.now()}_${Math.floor(1e6*Math.random())}`}function K(){return Date.now()}function G(){const e=new Map,t=[],n=[],r=[/^policy\./,/^capability\.approval/,/^capability\.failed/,/^punica\./,/\.error$/,/\.failed$/];let i=[],s=null;function o(){try{_.onQueueDepthChange?.(i.length)}catch{}}async function a(){if(0===i.length)return;const e=[...i];i=[],o(),s&&(clearTimeout(s),s=null);try{await D().write(e),Q()}catch(e){console.warn("[Events] Failed to flush persistence queue:",e)}}function c(e){(function(e){if("audit"===e.envelope?.kind)return!0;const t=e.name;return r.some(e=>e.test(t))})(e)&&(i.push(e),o(),i.length>=10?a():s||(s=setTimeout(()=>{a()},5e3)))}function u(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 d(r,i){const s=i,o=s&&"object"==typeof s&&s.name===r?s:{name:r,envelope:{id:W(),timestampMs:K()},payload:i};try{n.push(o),n.length>200&&n.splice(0,n.length-200),c(o)}catch{}const a=e.get(r);if(a&&a.size>0)for(const e of a)try{e(i)}catch{}if(t.length>0){const e=t.slice();for(const t of e)if(B(o,t.filter))try{t.listener(o)}catch{}}}async function p(e){try{return await D().query(e)}catch{return[]}}function f(e){let t=[...n];if(e?.correlationId){const n=e.correlationId;t=t.filter(e=>e.envelope?.correlationId===n||e.envelope?.id===n)}if(e?.name){const n=Array.isArray(e.name)?e.name:[e.name];t=t.filter(e=>n.includes(e.name))}if(e?.kind){const n=Array.isArray(e.kind)?e.kind:[e.kind];t=t.filter(e=>n.includes(e.envelope?.kind))}if(e?.source){const n=Array.isArray(e.source)?e.source:[e.source];t=t.filter(e=>e.envelope?.source&&n.includes(e.envelope.source))}return"number"==typeof e?.since&&(t=t.filter(t=>(t.envelope?.timestampMs??0)>=e.since)),"number"==typeof e?.until&&(t=t.filter(t=>(t.envelope?.timestampMs??0)<=e.until)),t.sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0)),"number"==typeof e?.limit&&e.limit>0&&(t=t.slice(-e.limit)),t}return{publish:d,subscribe:u,subscribeMany(e,t){const n=e.map(e=>u(e,n=>t({name:e,payload:n})));return()=>{n.forEach(e=>e())}},createCorrelationId:W,publishEvent:function(e){const t=q({id:e.envelope?.id??W(),correlationId:e.envelope?.correlationId,traceId:e.envelope?.traceId,spanId:e.envelope?.spanId,parentSpanId:e.envelope?.parentSpanId,timestampMs:e.envelope?.timestampMs??K(),source:e.envelope?.source,kind:e.envelope?.kind}),n={name:e.name,envelope:t,payload:e.payload};try{V.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 d(n.name,n),t},getRecent(e){const t="number"==typeof e&&e>0?e:n.length;return n.slice(Math.max(0,n.length-t))},filterEvents:f,getTrace:function(e){return f({correlationId:e})},exportEvents:function(e){const t=e?.format??"json",r=e?.filter?f(e.filter):[...n].sort((e,t)=>(e.envelope?.timestampMs??0)-(t.envelope?.timestampMs??0));if("csv"===t){const e=["timestamp","name","kind","source","correlationId","id","payload"],t=r.map(e=>[e.envelope?.timestampMs?new Date(e.envelope.timestampMs).toISOString():"",e.name,e.envelope?.kind??"",e.envelope?.source??"",e.envelope?.correlationId??"",e.envelope?.id??"",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:K(),version:1,count:r.length,events:r})},clearAudit(){n.splice(0,n.length)},loadPersistedEvents:p,replay:async function(e){"dispatch"===e.mode&&function(){throw new U('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 p({name:e.name,since:e.since,until:e.until})}catch{i=[]}const s=function(e,t,n){const r=new Set,i=[];for(const t of e){const e=t.envelope?.id;if(e){if(r.has(e))continue;r.add(e)}i.push(t)}for(const e of t){const t=e.envelope?.id;if(t){if(r.has(t))continue;r.add(t)}i.push(e)}const s={name:n.name,correlationId:n.correlationId,traceId:n.traceId,kind:n.kind,source:n.source};let o=i.filter(e=>{if(!B(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)d(e.name,e);return{count:s.length,events:s}}}}const Y=G();var z={manager:Y};let J=S;function H(){return J}async function Q(){try{const e=D(),t=H();if("function"==typeof e.applyRetention)return await e.applyRetention(t)??0;const n=t.defaultTtlMs??E;return await e.delete({until:K()-n})??0}catch{return 0}}var Z=Object.freeze({__proto__:null,createCorrelationId:W,createEventsApi:G,default:z,getRetentionConfig:H,manager:Y,runEventRetentionCleanup:Q,setRetentionConfig:function(e){J=e??S}});function X(){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 ee=X();var te={manager:ee},ne=Object.freeze({__proto__:null,createNotificationsApi:X,default:te,manager:ee});const re="punica.kernel.policy.v2";function ie(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}function se(e){return"workspace"===e.scope?e.workspaceId?`workspace:${e.workspaceId}`:null:e.scope}class oe{#m=new Map;constructor(){this.#g()}set(e,t,n){let r=this.#m.get(e);r||(r=new Map,this.#m.set(e,r)),r.set(t,n),this.#y()}get(e,t){return this.#m.get(e)?.get(t)}has(e,t){return this.#m.get(e)?.has(t)??!1}delete(e,t){const n=this.#m.get(e);if(!n)return!1;const r=n.delete(t);return 0===n.size&&this.#m.delete(e),r&&this.#y(),r}list(){const e=[];for(const t of this.#m.values())for(const n of t.values())e.push(n);return e}clear(){0!==this.#m.size&&(this.#m.clear(),this.#y())}restoreAll(e){this.#m.clear();let t=0;for(const n of e){if(!n||"string"!=typeof n.key)continue;const e=se(n);if(!e)continue;let r=this.#m.get(n.key);r||(r=new Map,this.#m.set(n.key,r)),r.set(e,n),t++}return this.#y(),t}#g(){const e=ie();if(e)try{const t=e.getItem(re);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=se(e);if(!t)continue;let n=this.#m.get(e.key);n||(n=new Map,this.#m.set(e.key,n)),n.set(t,e)}}catch{}}#y(){const e=ie();if(e)try{let t={};try{const n=e.getItem(re);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(re,JSON.stringify(n))}catch{}}}let ae=new oe;function ce(){return Date.now()}function le(e,t){return void 0!==e.expiresAt&&e.expiresAt<=t}function ue(e){return`${e.kind}:${e.id}`}function de(e,t){return"workspace"===e?`workspace:${t??""}`:e}function pe(){try{const e=globalThis,t=e?.localStorage;return t&&"function"==typeof t.getItem?t:null}catch{return null}}const fe="punica.kernel.policy.v1",he="punica.kernel.policy.v2";class me{#w="execute";#v;#b=new Set;#I=new Map;#k=[];#E=1e3;constructor(e){this.#v=e??new oe,this.#S()}#S(){const e=pe();if(e)try{const t=e.getItem(he);if(t){const e=JSON.parse(t);if(e&&2===e.v)return void("suggest"!==e.mode&&"execute"!==e.mode||(this.#w=e.mode))}const n=e.getItem(fe);if(n){const t=JSON.parse(n);if(t&&1===t.v){"suggest"!==t.mode&&"execute"!==t.mode||(this.#w=t.mode);const n=Array.isArray(t.approvals)?t.approvals:[];this.#v.restoreAll(n),this.#y();try{e.removeItem(fe)}catch{}return}}}catch{}}#y(){const e=pe();if(e)try{let t={};try{const n=e.getItem(he);if(n){const e=JSON.parse(n);e&&"object"==typeof e&&(t=e)}}catch{}const n={...t,v:2,mode:this.#w,exportedAt:ce()};e.setItem(he,JSON.stringify(n))}catch{}}setMode(e){this.#w=e,this.#y()}getMode(){return this.#w}clearApprovals(){this.#v.clear(),this.#b.clear()}#A(e,t,n="info"){try{Y.publishEvent({name:e,envelope:{id:Y.createCorrelationId(),timestampMs:ce(),source:"kernel:policy",kind:n},payload:t})}catch{}}#x(e,t){return`${e}|${t}`}revokeApproval(e){const t=ue({kind:e.kind,id:e.id}),n="workspace"===e.scope?de("workspace",e.workspaceId):de(e.scope),r=this.#v.delete(t,n);return r&&(this.#C("revocation",{kind:e.kind,id:e.id,risk:"low",approval:"none"},void 0,e.scope,e.workspaceId),this.#A("approval.revoked",{kind:e.kind,id:e.id,scope:e.scope,workspaceId:e.workspaceId}),this.#b.delete(this.#x(t,n))),r}listApprovals(e){const t=e?.includeExpired??!1,n=this.#v.list();if(t)return n;const r=ce();return n.filter(e=>!le(e,r))}hasApproval(e,t,n){const r=ue(e),i="workspace"===t?n?.workspaceId?de("workspace",n.workspaceId):null:de(t);if(null===i)return!1;const s=this.#v.get(r,i);if(!s)return!1;if(le(s,ce())){const e=this.#x(r,i);return this.#b.has(e)||(this.#b.add(e),this.#A("approval.expired",{kind:s.kind,id:s.id,scope:s.scope,workspaceId:s.workspaceId,expiresAt:s.expiresAt,decidedBy:s.decidedBy},"warn")),!1}return!0}recordApproval(e,t,n){if("workspace"===t&&!n?.workspaceId)throw new Error("[Policy] Workspace scope requires workspaceId in context");const r=ue(e),i="workspace"===t?de("workspace",n?.workspaceId):de(t),s={key:r,kind:e.kind,id:e.id,scope:t,workspaceId:"workspace"===t?n?.workspaceId:void 0,decidedBy:n?.decidedBy,timestampMs:ce(),risk:e.risk,approval:e.approval,reason:e.reason,expiresAt:n?.expiresAt,chainRef:n?.chainRef};return this.#v.set(r,i,s),this.#C("approval",e,void 0,t,n?.workspaceId),this.#b.delete(this.#x(r,i)),this.#A("approval.granted",{request:e,scope:t,workspaceId:n?.workspaceId,decidedBy:n?.decidedBy,expiresAt:n?.expiresAt}),s}#C(e,t,n,r,i){this.#k.push({timestampMs:ce(),type:e,request:t,decision:n,scope:r,workspaceId:i}),this.#k.length>this.#E&&this.#k.splice(0,this.#k.length-this.#E)}evaluate(e,t){const n=n=>{const r=t,i=r?.correlationId,s=r?.traceId??i;Y.publishEvent({name:"policy.evaluated",envelope:{id:Y.createCorrelationId(),correlationId:i,traceId:s,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,decision:n,context:{workspaceId:t?.workspaceId}}})};if("suggest"===this.#w){const r={allowed:!1,mode:"suggest",requiresApproval:!1,reason:"Policy mode is suggest; execution is disabled."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}if("none"===e.approval){const r={allowed:!0,mode:"execute",requiresApproval:!1};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}if("plan"===e.approval){const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (plan)."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}const r=this.hasApproval(e,"once",t)||this.hasApproval(e,"workspace",t)||this.hasApproval(e,"always",t)?{allowed:!0,mode:"execute",requiresApproval:!1}:{allowed:!1,mode:"execute",requiresApproval:!0,suggestedScope:"once",reason:"Approval required (step)."};return this.#C("decision",e,r,void 0,t?.workspaceId),n(r),r}requestApproval(e,t){Y.publishEvent({name:"policy.approvalRequested",envelope:{id:Y.createCorrelationId(),correlationId:t?.correlationId,timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{request:e,context:{workspaceId:t?.workspaceId,traceId:t?.traceId}}})}exportState(){return{version:2,exportedAt:ce(),mode:this.#w,approvals:this.listApprovals({includeExpired:!0})}}importState(e,t){if(!e||"object"!=typeof e)throw new Error("[Policy] Invalid export data");if(2!==e.version)throw new Error(`[Policy] Unsupported export version: ${e.version}. Expected 2.`);const n=t?.merge??!1,r=Array.isArray(e.approvals)?e.approvals:[];"suggest"!==e.mode&&"execute"!==e.mode||(this.#w=e.mode);let i=0;if(n)for(const e of r){if(!e||"string"!=typeof e.key)continue;const t=e.key,n=e.scope,r=e.workspaceId;if("workspace"===n&&!r)continue;const s="workspace"===n?de("workspace",r):de(n);"string"==typeof s&&s&&(this.#v.has(t,s)||(this.#v.set(t,s,e),i++))}else i=this.#v.restoreAll(r),this.#b.clear();return this.#y(),Y.publishEvent({name:"policy.stateImported",envelope:{id:Y.createCorrelationId(),timestampMs:Date.now(),source:"kernel:policy",kind:"info"},payload:{imported:i,merged:n}}),i}saveTemplate(e,t,n){const r=n??"global";let i=this.#I.get(r);i||(i=new Map,this.#I.set(r,i));const s={...t,name:e,workspaceId:n,createdAtMs:t.createdAtMs??ce(),updatedAtMs:ce()};i.set(e,s),this.#y()}getTemplate(e,t){const n=t??"global",r=this.#I.get(n);return r?.get(e)??null}listTemplates(e){const t=e??"global",n=this.#I.get(t);return n?Array.from(n.values()):[]}deleteTemplate(e,t){const n=t??"global",r=this.#I.get(n);if(!r)return!1;const i=r.delete(e);return i&&this.#y(),i}exportAuditLog(e){const t=e?.format??"json";let n=[...this.#k];if(e?.since&&(n=n.filter(t=>t.timestampMs>=e.since)),e?.until&&(n=n.filter(t=>t.timestampMs<=e.until)),e?.workspaceId&&(n=n.filter(t=>t.workspaceId===e.workspaceId)),"csv"===t){const e=["timestamp","type","kind","id","risk","approval","allowed","requiresApproval","scope","workspaceId","reason"],t=n.map(e=>[new Date(e.timestampMs).toISOString(),e.type,e.request.kind,e.request.id,e.request.risk,e.request.approval,e.decision?.allowed?"true":"false",e.decision?.requiresApproval?"true":"false",e.scope??"",e.workspaceId??"",e.decision?.reason??e.request.reason??""]);return[e.join(","),...t.map(e=>e.map(e=>{const t=String(e);return t.includes(",")||t.includes('"')||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}).join(","))].join("\n")}return JSON.stringify({exportedAt:ce(),version:1,count:n.length,entries:n},null,2)}}const ge=new me(ae);var ye={manager:ge},we=Object.freeze({__proto__:null,PolicyManager:me,default:ye,manager:ge});async function ve(e,n,r){if(r())e.status="cancelled";else if("success"!==e.status&&"cancelled"!==e.status){e.status="running",e.startedAtMs=Date.now(),punica.kernel.Events.manager.publishEvent({name:"ai.runStepStarted",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}});try{const r=punica.kernel.Events.manager.createCorrelationId(),i=n,s=await t(),o=await punica.runtime.capabilities.gateway.call(e.capabilityId,e.input,{sessionId:n,workspaceId:s,actor:{type:"ai",id:void 0},origin:{kind:"ai",id:n},trace:{traceId:i,parentSpanId:void 0},policy:{mode:"execute"}});e.status="success",e.finishedAtMs=Date.now(),e.correlationId=r,e.resultPayload=o,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"result"},payload:{runId:n,step:e}})}catch(t){const r=String(t?.message??t);if(r.includes("Approval required")||r.includes("CAPABILITY_APPROVAL_REQUIRED"))throw e.status="blocked",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{runId:n,step:e}}),new Error("blocked");throw e.status="failed",e.finishedAtMs=Date.now(),e.error=r,punica.kernel.Events.manager.publishEvent({name:"ai.runStepFinished",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"kernel:ai",kind:"error"},payload:{runId:n,step:e}}),t}}}async function be(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 ve(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 Ie={estimate:e=>Math.ceil(e.length/4)};function ke(){return Ie}function Ee(e){const t=ke();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 Se={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 Ae="[elided tool result:";function xe(e){const t=(e.content??"").length;return`${Ae} ${e.name??"tool"}, ${t} chars — re-run the tool if the data is needed]`}function Ce(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 Te(e,t,n,r){const i=Ee(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=Ce(e,t.keepLastTurnsVerbatim),a=e.map((e,t)=>t>0&&t<o&&"tool"===e.role&&!(e.content??"").startsWith(Ae)?{...e,content:xe(e)}:e);let c=Ee(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=Ee(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 Ne=Object.freeze({narrowThreshold:24,catalogTopN:100,topCategories:64,hotSetSize:40});function Me(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()?.agent?.toolSelection}catch{return}}function Pe(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function _e(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 Re(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=_e(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 Le(e,t,n){return!!e&&(!n.includes(e)&&("success"===t||"failed"===t))}const $e="punica.kernel.ai.toolUsage.v1";function Oe(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 De(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const je=new class{async read(){const e=De();if(!e)return{};try{const t=e.getItem($e);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=Oe(t);n&&e&&(r[e]=n)}return r}(JSON.parse(t)):{}}catch{return{}}}async record(e,t,n){const r=De();var i;if(r)try{r.setItem($e,(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=De();if(e)try{e.removeItem($e)}catch{}}};let Fe=je;function qe(){return Fe}async function Be(e,t,n){try{await qe().record(e,t,n)}catch{}}function Ue(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}async function Ve(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=Ue(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 We(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=Re(i,e.usage??(a>0?await async function(){try{return await qe().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=Ue(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(Ue(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 Ve(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 Ke=["capability.search","capability.describe"];function Ge(e){const t=String(e?.message??e);return t.includes("CAPABILITY_INPUT_INVALID")||t.includes("Input validation failed")}function Ye(e,t,n,r){const i=punica.kernel?.Events?.manager;i&&i.publishEvent({name:e,envelope:{id:i.createCorrelationId(),correlationId:t,timestampMs:Date.now(),source:"kernel:ai",kind:n},payload:r})}function ze(e){return{name:String(e.id),description:String(e.description??e.title??e.id),parameters:e.inputSchema??{type:"object",properties:{}}}}function Je(e,t){return e.name<t.name?-1:e.name>t.name?1:0}function He(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 Qe(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=Ue(String(t.id));return e[n]=(e[n]??0)+1,e},{}),ids:i.map(e=>String(e.id))}),t.toolFilter)return{hot:i.map(ze).sort(Je),deferredIndex:[]};const s=i.filter(e=>Ke.includes(String(e.id)));i=i.filter(e=>!Ke.includes(String(e.id))&&(!function(e){const t=String(e?.id??"");return!("core"!==String(e?.origin??"core")||!t.startsWith("ai.")&&(t.startsWith("capability.")?Ke.includes(t):!t.startsWith("llm.")))}(e)&&(!(!t.includeIvyNodes&&"ivy-node"===String(e.origin))&&!("mcp"===String(e.origin)&&!function(e,t){if(t.includeMcp)return!0;const n=function(e){const t=e.split(".");return"mcp"===t[0]&&t.length>=3?t[1]:void 0}(e);return!!n&&(t.allowedMcpServers??[]).includes(n)}(String(e.id),t)))));const o=function(e){const t={...Ne};for(const n of[Me(),e]){if(!n)continue;for(const e of Object.keys(t))Pe(n[e])&&(t[e]=Math.floor(n[e]));for(const e of["perCategoryCap","rankLimit"])Pe(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(ze).sort(Je),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 Ve(i,t.query,o,a)).map(ze).sort(Je),deferredIndex:[]}}const{hot:c,deferred:l}=await(u={entries:i,intent:t.query,budget:o,pinnedIds:t.pinnedTools,rank:a},We(u));var u;const d=new Set(c.map(e=>String(e.id))),p=s.length===Ke.length?s.map(ze):[{name:"capability.search",description:"Search the deferred tool index by natural-language need; returns candidate tool ids with one-line descriptions.",parameters:{type:"object",required:["query"],properties:{query:{type:"string"},limit:{type:"number"}}}},{name:"capability.describe",description:"Load full definitions (input schema) for up to 16 tool ids from the deferred index; described tools become directly callable.",parameters:{type:"object",required:["ids"],properties:{ids:{type:"array",items:{type:"string"},maxItems:16}}}}],f=l.map(e=>({id:String(e.id),line:He(e),category:Ue(String(e.id))})).sort((e,t)=>e.id<t.id?-1:e.id>t.id?1:0);return console.log("[AgentLoop] tiered catalog",{hot:c.length,deferred:f.length,hotSetSize:o.hotSetSize,pinned:t.pinnedTools??[],hotIds:[...d]}),{hot:[...p,...c.map(ze)].sort(Je),deferredIndex:f}}async function Ze(e,t,n,r){const i={id:t.id,name:t.name,arguments:t.arguments,status:"success"};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){if(!function(e){const t=String(e?.message??e);return t.includes("Approval required")||t.includes("CAPABILITY_APPROVAL_REQUIRED")}(e))return{...i,status:"failed",error:String(e?.message??e)}}const s=String(n.trace?.traceId??n.sessionId??""),o=await function(e,t,n){return new Promise(r=>{const i=punica.kernel.Events.manager;let s=!1;const o=e=>{if(!s){s=!0;try{a?.()}catch{}clearTimeout(l),clearInterval(c),r(e)}},a=i.subscribeMany?.(["ai.approvalRecorded","ai.pendingApprovalDismissed"],n=>{const r=n?.payload?.payload??n?.payload,i=r?.pending;i?.id===e&&(i?.traceId&&i.traceId!==t||o("ai.approvalRecorded"===n?.name?"approved":"dismissed"))})??void 0,c=setInterval(()=>{n()&&o("cancelled")},250),l=setTimeout(()=>o("timeout"),18e4)})}(t.name,s,r);if("approved"!==o)return{...i,status:"blocked",error:`tool "${t.name}" not approved (${o})`};try{const r=await e(t.name,t.arguments,n);return{...i,status:"success",resultPayload:r}}catch(e){return{...i,status:"failed",error:String(e?.message??e)}}}async function Xe(e,t,n,r,i,s){const o=`The arguments for tool "${t}" failed schema validation.\nJSON Schema:\n${nt(n)}\nRejected arguments:\n${nt(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 et(e,t,n,r,i){let s=t.arguments,o=!1,a="";for(let c=0;c<=2;c++){const l=await Ze(e,{...t,arguments:s},r,i);if("failed"!==l.status||!Ge(l.error))return o?{...l,arguments:s,repaired:!0}:l;if(a=l.error??"",2===c||i())break;const u=await Xe(e,t.name,n,s,a,r);if(!u)break;s=u,o=!0}const c={id:t.id,name:t.name,arguments:s,status:"failed",error:a||"input validation failed"};return o&&(c.repaired=!0),c}function tt(e){return ke().estimate(e)}function nt(e,t=4e3){try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"…":n}catch{return String(e)}}async function rt(e,n,r,i){const s=punica.kernel.Events.manager,o=i??s.createCorrelationId(),a="number"==typeof e.maxSteps&&e.maxSteps>0?e.maxSteps:8,c=(l=e.profile,Se[l??"balanced"]);var l;const u=[],d=e.sessionId?punica.kernel?.AI?.sessions:void 0,p=[];let f=0;const h=[],m=Date.now();let g=0,y=0,w=0,v=0,b=!1,I=0,k=!1,E=0;const S=(t,n)=>{const r={inputTokens:g,outputTokens:y,totalTokens:w,latencyMs:Date.now()-m,steps:u.length,toolCalls:E};k&&(r.totalCost=I),b&&(r.cacheReadTokens=v);const i={runId:o,finishReason:t,steps:u,usage:r};if(void 0!==n&&(i.finalText=n),console.log("[AgentLoop] finish",{finishReason:t,finalTextLen:(n??"").length,steps:u.length}),(t=>{if(d&&e.sessionId&&0!==f)try{const n=[{role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}},...h];t&&n.push({role:"assistant",content:t});const r=n.map(e=>({id:"",createdAtMs:0,role:e.role,content:e.content??"",...e.images&&e.images.length>0?{images:e.images}:{},...e.name?{name:e.name}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolCalls&&e.toolCalls.length>0?{toolCalls:e.toolCalls}:{}}));d.appendMessages(e.sessionId,r,{runId:o})}catch(e){console.warn("[AgentLoop] session persist failed:",e)}})(n),d&&e.sessionId&&f>0)try{d.recordUsage?.(e.sessionId,r)}catch(e){console.warn("[AgentLoop] session usage record failed:",e)}return Ye("ai.agentFinished",o,"info",{runId:o,finishReason:t,finalText:n,steps:u,usage:r,...e.sessionId?{sessionId:e.sessionId}:{}}),i};Ye("ai.agentStarted",o,"info",{runId:o,query:e.query,...e.sessionId?{sessionId:e.sessionId}:{}});const A=punica.runtime?.capabilities?.gateway?.call?.bind(punica.runtime.capabilities.gateway);if(!A)return console.error("[AgentLoop] capability gateway unavailable; aborting run"),S("error");const x=await t(),C=function(e,t,n){return{sessionId:e,workspaceId:t,actor:{type:"ai",id:"ai:agent"},origin:{kind:"ai",id:e},trace:{traceId:e,parentSpanId:void 0},policy:{mode:"execute"},...n?{signal:n}:{}}}(o,x,r);let T;e.sessionId&&(C.conversationId=e.sessionId);try{T=await Qe(A,e,C)}catch(e){return console.error("[AgentLoop] buildToolCatalog failed; aborting run:",e),S("error")}const N=[...T.hot];console.log("[AgentLoop] tool catalog built",{hot:N.length,deferred:T.deferredIndex.length,toolFilter:e.toolFilter??null,names:N.map(e=>e.name)});const M=new Map(N.map(e=>[e.name,e.parameters])),P=new Map(T.deferredIndex.map(e=>[e.id,e])),_=e=>{const t=e?.tools;if(!Array.isArray(t))return 0;const n=t.filter(e=>e?.id&&!M.has(String(e.id))).map(ze).sort(Je);for(const e of n)N.push(e),M.set(e.name,e.parameters),P.delete(e.name);return n.length>0&&console.log("[AgentLoop] promoted deferred tools",{names:n.map(e=>e.name),totalLoaded:N.length}),n.length};if(p.push({role:"system",content:"You are an autonomous agent operating inside an IDE. You are given a set of tools (capabilities). To accomplish the user request, call the tools you need one or more times; after each tool result, decide whether to call another tool or to answer. When you have enough information, reply with a concise final answer and no further tool calls."}),e.includeProjectContext)try{const e=function(e){const t=e;if(!t||"object"!=typeof t)return null;const n=[],r=t.workspace;r?.name&&n.push(`Project: ${r.name} (${r.kind}) at ${r.rootUri}`+(r.environment?` [env: ${r.environment}]`:"")),Array.isArray(t.stack)&&t.stack.length&&n.push(`Stack: ${t.stack.join(", ")}`);const 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 A("workspace.projectContext",{},C));e&&p.push({role:"system",content:e})}catch(e){console.warn("[AgentLoop] projectContext orientation unavailable:",e)}if(T.deferredIndex.length>0&&p.push(function(e){const t=new Map;for(const n of e){const e=t.get(n.category);e?e.push(n):t.set(n.category,[n])}const n=[];for(const e of[...t.keys()].sort())for(const r of t.get(e))n.push(`[${e}] ${r.id} — ${r.line}`);return{role:"system",content:"Additional tools exist but are not loaded yet. Index (id — purpose):\n"+n.join("\n")+"\nTo use one: call capability.search to find candidates, then capability.describe to load full schemas. You may also call an indexed tool directly by its id if its arguments are obvious."}}(T.deferredIndex)),d&&e.sessionId)try{p.push(...d.getContextMessages(e.sessionId))}catch(e){console.warn("[AgentLoop] session seed failed; running cold:",e)}p.push({role:"user",content:e.query,...e.images&&e.images.length>0?{images:e.images}:{}}),f=p.length;let R=0;for(let t=0;t<a;t++){if(n())return S("cancelled");let r,i=!1;if(Ee(p)>c.maxContextTokens){const e=await Te(p,c,A,C);e.compacted&&(p.splice(0,p.length,...e.messages),R=0,i=!0,Ye("ai.agentContextCompacted",o,"info",{runId:o,step:t,strategy:e.strategy,preTokens:e.preTokens,postTokens:e.postTokens,estSavedTokens:e.estSavedTokens}))}const s=Date.now();try{console.log("[AgentLoop] -> llm.chatStream request",{step:t,messageCount:p.length,toolsSent:N.length,toolChoice:"auto",toolNames:N.map(e=>e.name)});const n={stableToolsAndSystem:!0,stableMessagePrefix:R,cacheKey:o};r=await A("llm.chatStream",{messages:p,tools:N,toolChoice:"auto",correlationId:o,cacheHints:n,...e.profile?{profile:e.profile}:{}},C),R=p.length,console.log("[AgentLoop] gateway llm.chatStream returned",{step:t,textLen:(r?.text??"").length,toolCalls:r?.toolCalls?.length??0})}catch(e){return console.error("[AgentLoop] llm.chatStream call failed; aborting run:",e),S("error")}if(n())return S("cancelled");const a=Date.now()-s,l=(r.text??"").trim(),d="string"==typeof r.thinking?r.thinking:void 0,f=r.toolCalls??[],m={index:t,assistantText:l||void 0,thinking:d,toolCalls:[],latencyMs:a},x=r.usage,T=r.meta;x?(m.usage=x,g+=x.inputTokens??0,y+=x.outputTokens??0,w+=x.totalTokens??(x.inputTokens??0)+(x.outputTokens??0),"number"==typeof x.cacheReadInputTokens&&(v+=x.cacheReadInputTokens,b=!0)):T&&(m.usage={inputTokens:T.promptTokens,outputTokens:T.completionTokens,totalTokens:T.promptTokens+T.completionTokens},g+=T.promptTokens,y+=T.completionTokens,w+=T.promptTokens+T.completionTokens),T&&"number"==typeof T.totalCost&&(I+=T.totalCost,k=!0);const L={runId:o,step:t,estToolDefTokens:tt(JSON.stringify(N)),estHistoryTokens:p.filter(e=>"system"!==e.role).reduce((e,t)=>e+tt(t.content??""),0),estSystemTokens:p.filter(e=>"system"===e.role).reduce((e,t)=>e+tt(t.content??""),0),toolCount:N.length,deferredToolCount:P.size,compactionApplied:i};if(m.usage&&(L.reportedInputTokens=m.usage.inputTokens,L.reportedOutputTokens=m.usage.outputTokens,"number"==typeof m.usage.cacheReadInputTokens&&(L.cacheReadTokens=m.usage.cacheReadInputTokens)),Ye("ai.agentTurnUsage",o,"info",{...L}),0===f.length)return u.push(m),Ye("ai.agentStep",o,"info",{runId:o,turn:m}),S("final",l);u.push(m),Ye("ai.agentStep",o,"info",{runId:o,turn:m});const $=f.map(e=>`${e.name}(${nt(e.arguments)})`).join(", "),O={role:"assistant",content:l?`${l}\n[calling tools: ${$}]`:`[calling tools: ${$}]`,toolCalls:f.map(e=>({id:e.id,name:e.name,arguments:e.arguments}))};p.push(O),h.push(O);let D=!1;for(const e of f){if(n())return S("cancelled");if(Ye("ai.agentToolCall",o,"info",{runId:o,toolCall:{id:e.id,name:e.name,arguments:e.arguments},status:"running"}),!M.has(e.name)&&P.has(e.name))try{_(await A("capability.describe",{ids:[e.name]},C))}catch(e){console.warn("[AgentLoop] auto-describe failed:",e)}const r=await et(A,e,M.get(e.name),C,n);m.toolCalls.push(r),E++,Le(r.name,r.status,Ke)&&await Be(r.name,"success"===r.status,Date.now()),"success"===r.status&&"capability.describe"===r.name&&_(r.resultPayload),console.log("[AgentLoop] tool dispatched",{step:t,name:r.name,arguments:r.arguments,status:r.status,repaired:r.repaired??!1,error:r.error,resultPreview:"success"===r.status?nt(r.resultPayload).slice(0,300):void 0}),Ye("ai.agentToolResult",o,"result",{runId:o,toolCall:r,status:r.status});const i={role:"tool",content:"success"===r.status?nt(r.resultPayload,c.toolResultMaxChars):`ERROR: ${r.error??"tool failed"}`,name:r.name,toolCallId:r.id};p.push(i),h.push(i),"blocked"===r.status&&(D=!0)}if(D)return S("blocked")}return S("maxSteps")}function it(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 st={KERNEL:{EVENTS:"kernel.events",COMMANDS:"kernel.commands",HISTORY:"kernel.history",TIME_SERVER:"kernel.timeServer",NOTIFICATIONS:"kernel.notifications",AI:"kernel.ai",LLM:"kernel.llm",POLICY:"kernel.policy",TASKS:"kernel.tasks"},RUNTIME:{FS:"runtime.fs",SEARCH:"runtime.search",VCS:"runtime.vcs",WORKSPACE:"runtime.workspace",LLM:"runtime.llm",SECRETS:"runtime.secrets",TASKS:"runtime.tasks",TERMINALS:"runtime.terminals",MCP:"runtime.mcp"},SHELL:{ACTIVITY_BAR:"shell.activityBar",STATUSBAR:"shell.statusbar",VIEW:"shell.view",VIEWS:"shell.views",KEYBOARD_SHORTCUTS:"shell.keyboardShortcuts",LAYOUT:"shell.layout",CONTENT_TABS:"shell.contentTabs",PANEL_TABS:"shell.panelTabs",PANEL_LAYOUT:"shell.panelLayout"},FLOW:{SHELL:"flow.shell",ENGINE:"flow.engine",VALIDATOR:"flow.validator"},EXTENSIONS:{MANAGER:"extensions.manager"}},ot={SHELL:{TOGGLE_PANEL:"shell.togglePanel",TOGGLE_PRIMARY_SIDEBAR:"shell.togglePrimarySidebar",TOGGLE_SECONDARY_SIDEBAR:"shell.toggleSecondarySidebar"},AI:{AGENT_RUN:"ai.agent.run",APPROVE_PENDING:"ai.approvePending",ASK:"ai.ask",CANCEL_RUN:"ai.cancelRun",DISMISS_PENDING:"ai.dismissPending",DO:"ai.do",RUN_PLAN:"ai.runPlan",SESSION_ARCHIVE:"ai.session.archive",SESSION_CREATE:"ai.session.create",SESSION_DELETE:"ai.session.delete",SESSION_LIST:"ai.session.list",SESSION_RENAME:"ai.session.rename",SHOW_LAST_TRACE:"ai.showLastTrace",SUMMARIZE:"ai.summarize",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 at(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 ct(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 lt(e,t,n){try{punica.kernel?.Notifications?.manager?.push({id:"",timestamp:"",level:e,title:t,message:n,source:"ai"})}catch{}}function ut(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 dt(e){return`${e} ${1===e?"capability":"capabilities"}`}const pt="punica.kernel.ai.sessions.index.v1";function ft(e){return`punica.kernel.ai.session.${e}.v1`}function ht(){try{const e=globalThis.localStorage;return e&&"function"==typeof e.getItem?e:null}catch{return null}}const mt=new class{readIndex(){const e=ht();if(!e)return[];try{const t=e.getItem(pt);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n?.sessions)?n.sessions:[]}catch{return[]}}writeIndex(e){const t=ht();if(t)try{t.setItem(pt,JSON.stringify({v:1,sessions:e}))}catch{}}readSession(e){const t=ht();if(t)try{const n=t.getItem(ft(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=ht();if(t)try{t.setItem(ft(e.meta.sessionId),JSON.stringify(e))}catch{}}deleteSession(e){const t=ht();if(t)try{t.removeItem(ft(e))}catch{}}};let gt=mt;function yt(){return gt}const wt="New chat";function vt(){return Date.now()}function bt(e){const t=globalThis.punica?.kernel?.Events?.manager;return t?.createCorrelationId?String(t.createCorrelationId()):`${e}-${vt().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function It(e,t,n){const r=globalThis.punica?.kernel?.Events?.manager;r&&r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:t.sessionId,timestampMs:vt(),source:"kernel:ai",kind:"info"},payload:{session:{...t},...n??{}}})}function kt(e){let t=0;for(;t<e.length&&"tool"===e[t].role;)t++;return 0===t?e:e.slice(t)}function Et(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 St=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:_e(n,t)})).sort((e,t)=>t.prior-e.prior||(e.capabilityId<t.capabilityId?-1:1))}(await qe().read()??{},Date.now())}catch{return[]}}async forget(){await qe().forget()}setStore(e){!function(e){Fe=e??je}(e)}},At=new class{#T=null;#N=null;#M=new Map;#P=!1;#_=new Map;initialize(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{!function(e,t){const n=e?.payload??e,r=n?.request;if(!r?.id)return;const i=e?.envelope?.correlationId,s=n?.context?.workspaceId,o=n?.context?.traceId,a=punica.kernel.Events.manager.createCorrelationId(),c={pendingId:a,kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason,correlationId:i,...o?{traceId:o}:{},workspaceId:s,timestampMs:Date.now()};t.set(a,c),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalAdded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:c}})}(e,this.#M)}),punica.kernel.Events.manager.subscribe("ai.planGenerated",e=>{try{const t=e?.payload??e?.event?.payload,n=t?.plan;n?.planId&&(this.#T=n)}catch{}}),function(e){if(!punica.kernel?.Commands?.manager)return;const t=punica.kernel.Commands.manager;t.registerCommand(ot.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(ot.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(ot.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=it(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(ot.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(ot.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`+it(e,2))}}),t.registerCommand(ot.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(ot.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(ot.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(ot.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(ot.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(ot.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(ot.AI.CANCEL_RUN,{title:"AI: Cancel Run",description:"Cancel AI runs. Bare: everything (legacy Stop). Pass { runId } or { sessionId } to cancel one run / one conversation only.",execute:t=>{const n=t&&"object"==typeof t&&(t.runId||t.sessionId)?{runId:t.runId,sessionId:t.sessionId}:void 0;e.setCancelRequested(!0,n)}}),t.registerCommand(ot.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(ot.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(ot.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(ot.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(ot.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(ot.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"+it(t)),punica.kernel?.Events?.manager&&console.log("[AI] recentEvents\n"+it(punica.kernel.Events.manager.getRecent(50)))}}),t.registerCommand(ot.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"+it(e)),0===e.length?(lt("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):(lt("info",`Tool selection has learned from ${dt(e.length)}`,`Carrying the most weight right now: ${e.slice(0,3).map(ut).join(", ")}. The full list is in the developer console.`),e)}}),t.registerCommand(ot.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 lt("error","Could not erase what tool selection learned",`The record is still on disk. ${e instanceof Error?e.message:String(e)}`),e}lt("info",0===e.length?"There was nothing to forget":`Forgot ${dt(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(ot.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;ct("ai.request","info",r,i,s,t?.__punica?.parentSpanId,o,{kind:"summarize",input:{chars:n.length,preview:at(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();ct("ai.response","result",r,i,u,s,o,{kind:"summarize",output:{summaryPreview:at(l,260),modelId:c?.modelId,provider:c?.provider,usage:c?.usage}}),ct("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){ct("ai.response","error",r,i,punica.kernel.Events.manager.createCorrelationId(),s,o,{kind:"summarize",error:String(e?.message??e)})}}})}({runLastPlan:e=>this.runLastPlan(e),runAgent:e=>this.runAgent(e),getLastPlan:()=>this.getLastPlan(),approvePending:(e,t)=>this.approvePending(e,t),dismissPending:e=>this.dismissPending(e),getPendingApprovals:()=>this.getPendingApprovals(),getLastRun:()=>this.#N,setCancelRequested:(e,t)=>{if(t?.runId||t?.sessionId)for(const[n,r]of this.#_){(t.runId&&n===t.runId||t.sessionId&&r.sessionId===t.sessionId)&&(r.cancelRequested=e,e&&r.controller.abort())}else{this.#P=e;for(const t of this.#_.values())t.cancelRequested=e,e&&t.controller.abort()}}})}getLastPlan(){return this.#T}getPendingApprovals(){return e=this.#M,Array.from(e.values()).sort((e,t)=>e.timestampMs-t.timestampMs);var e}approvePending(e,t){return function(e,t,n){const r=n.get(e);return!!r&&(punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id,risk:r.risk,approval:r.approval,reason:r.reason},t,{decidedBy:"user",workspaceId:r.workspaceId}),n.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.approvalRecorded",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:r,scope:t}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:r.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"approved"}}),!0)}(e,t,this.#M)}dismissPending(e){return function(e,t){const n=t.get(e);return!!n&&(t.delete(e),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalDismissed",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pending:n}}),punica.kernel.Events.manager.publishEvent({name:"ai.pendingApprovalRemoved",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:n.correlationId,timestampMs:Date.now(),source:"kernel:ai",kind:"info"},payload:{pendingId:e,reason:"dismissed"}}),!0)}(e,this.#M)}async runLastPlan(e){e?.planId&&Array.isArray(e.steps)&&(this.#T=e);const t=await be(this.#T,this.#N,()=>this.#P,e=>{this.#T=e});return this.#N=t,this.#P=!1,t}async runAgent(e){const t=punica.kernel.Events.manager.createCorrelationId(),n={cancelRequested:!1,controller:new AbortController,...e.sessionId?{sessionId:e.sessionId}:{}};this.#_.set(t,n);try{return await rt(e,()=>n.cancelRequested,n.controller.signal,t)}finally{this.#_.delete(t)}}},xt=new class{#R;create(e){const t=yt(),n={sessionId:bt("sess"),title:e?.title?.trim()||wt,createdAtMs:vt(),updatedAtMs:vt(),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.#L(i,n),t.writeIndex(i),It("ai.sessionCreated",n),{...n}}list(e){const t=yt().readIndex();return(e?t.filter(t=>t.workspaceId===e):t).map(e=>({...e})).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}get(e){return yt().readSession(e)??null}rename(e,t){const n=t.trim();if(!n)return!1;const r=this.#$(e,e=>{e.title=n});return!!r&&(It("ai.sessionRenamed",r),!0)}archive(e,t=!0){const n=this.#$(e,e=>{t?e.archived=!0:delete e.archived});return!!n&&(It("ai.sessionArchived",n,{archived:t}),!0)}delete(e){const t=yt(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e);if(r<0)return!1;const[i]=n.splice(r,1);return t.writeIndex(n),t.deleteSession(e),It("ai.sessionDeleted",i),!0}appendMessages(e,t,n){if(0===t.length)return;const r=yt(),i=r.readSession(e);if(!i)return;const s=t.map(e=>{const t={...e,id:e.id||bt("msg"),createdAtMs:e.createdAtMs||vt(),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=vt(),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===wt){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:wt}(e.content))}r.writeSession(i),this.#O(o),It("ai.sessionUpdated",o,{appendedCount:s.length,runId:n?.runId});const a=this.#R;a?.shouldCompact(i)&&Promise.resolve().then(()=>a.compact(i)).then(t=>{const n=yt().readSession(e);n&&(n.contextView=t,yt().writeSession(n))}).catch(e=>{console.warn("[AiSessions] compaction failed:",e)})}getContextMessages(e){const t=yt().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(...kt(n.messages).map(Et)),e}return kt(t.transcript.slice(-40)).map(Et)}setCompactor(e){this.#R=e}recordUsage(e,t){const n=this.#$(e,e=>{const n=e.usage??{inputTokens:0,outputTokens:0,totalTokens:0,cacheReadTokens:0,runCount:0};n.inputTokens+=t.inputTokens,n.outputTokens+=t.outputTokens,n.totalTokens+=t.totalTokens,n.cacheReadTokens+=t.cacheReadTokens??0,"number"==typeof t.totalCost&&(n.totalCostUsd=(n.totalCostUsd??0)+t.totalCost),n.runCount+=1,n.lastRunAtMs=vt(),e.usage=n});return!!n&&(It("ai.sessionUpdated",n,{usageRecorded:!0}),!0)}#$(e,t){const n=yt(),r=n.readSession(e);if(r)return t(r.meta),r.meta.updatedAtMs=vt(),n.writeSession(r),this.#O(r.meta),{...r.meta}}#O(e){const t=yt(),n=t.readIndex(),r=n.findIndex(t=>t.sessionId===e.sessionId);r>=0?n[r]={...e}:n.push({...e}),t.writeIndex(n)}#L(e,t){const n=yt(),r=e=>e.workspaceId===t.workspaceId;let i=e.filter(r);for(;i.length>50;){const s=i.filter(e=>e.sessionId!==t.sessionId).sort((e,t)=>{const n=e.archived?0:1,r=t.archived?0:1;return n!==r?n-r:e.updatedAtMs-t.updatedAtMs})[0];if(!s)break;const o=e.findIndex(e=>e.sessionId===s.sessionId);o>=0&&e.splice(o,1),n.deleteSession(s.sessionId),It("ai.sessionDeleted",s,{evicted:!0}),i=e.filter(r)}}};xt.setCompactor(function(){const e=Se.balanced;return{shouldCompact:t=>(t.meta.tokenEstimate??0)>e.maxContextTokens,async compact(t){const n=t.transcript.slice(-40),r=Ce([{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(Ae)?{...e,content:xe(e)}:e),compactedUpToMessageId:t.transcript[t.transcript.length-n.length-1]?.id,updatedAtMs:Date.now()}}}}());const Ct=St;var Tt={manager:At,sessions:xt,toolUsage:Ct},Nt=Object.freeze({__proto__:null,default:Tt,manager:At,sessions:xt,toolUsage:Ct});const Mt=new class{#D=new Map;#j=new Map;#F=new Map;#q;registerProductOriginResolver(e){this.#q=e}#B(e){try{const t=punica.extensions?.manager;if(t){if(t.getExtension(e))return!0;const n=t.getAllExtensions();if(Array.isArray(n))return n.some(t=>t.name===e||t.id===e)}return!0}catch{return!0}}register(e,t){if(!e.id)throw new Error("Instruction class must have an id");if(!e.role)throw new Error("Instruction class must have a role");if(!e.systemPrompt)throw new Error("Instruction class must have a systemPrompt");if(this.#D.has(e.id)){const n=this.#D.get(e.id),r=n?.originExtension||this.#F.get(e.id),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.#q&&(t=this.#q(e.productId)),t&&(e.originExtension=t,this.#F.set(e.id,t)),e.capability||(e.capability=function(e){if(e.capability)return e.capability;const t={id:e.id,title:e.role.charAt(0).toUpperCase()+e.role.slice(1),description:`LLM instruction class: ${e.role}`,version:"1.0.0",tags:["llm","instruction-class",e.role]};return t.inputs={schema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string",enum:[e.id],description:"Instruction class identifier"},userPrompt:{type:"string",description:"User prompt/query"},context:{type:"object",properties:{workspaceId:{type:"string"},filePath:{type:"string"},previousOutputs:{type:"object"},capabilities:{type:"array"}}},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"}}}}}},e.outputSchema?t.outputs={schema:e.outputSchema,kind:"direct"}:t.outputs={schema:{type:"object",properties:{text:{type:"string"},structured:{type:"object"}}},kind:"direct"},e.riskLevel?t.policy={risk:e.riskLevel,approval:"high"===e.riskLevel?"step":"plan"}:t.policy={risk:"medium",approval:"step"},t.sideEffects=["llm-invocation"],"json_object"===e.responseFormat&&t.sideEffects.push("structured-output"),t}(e)),this.#D.set(e.id,e),this.#j.set(e.id,e.capability)}unregister(e){this.#D.delete(e),this.#j.delete(e),this.#F.delete(e)}unregisterByOrigin(e){const t=[];this.#F.forEach((n,r)=>{n===e&&t.push(r)}),t.forEach(e=>this.unregister(e))}get(e){return this.#D.get(e)}list(e=!1){const t=Array.from(this.#D.values());return e?t.filter(e=>{const t=e.originExtension||this.#F.get(e.id);return!t||this.#B(t)}):t}listSummaries(e=!1){return this.list(e).map(e=>({id:e.id,role:e.role,originExtension:e.originExtension||this.#F.get(e.id),productId:e.productId,outputSchemaSummary:e.outputSchema?JSON.stringify(e.outputSchema).substring(0,200):void 0}))}has(e){return this.#D.has(e)}isAvailable(e){if(!this.has(e))return!1;const t=this.get(e);if(!t)return!1;const n=t.originExtension||this.#F.get(e);return!n||this.#B(n)}getCapability(e){return this.#j.get(e)}listCapabilities(){return Array.from(this.#j.values())}};async function Pt(e){const{primaryModelId:t,count:n,exclude:r}=e,i=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{return await e.listInstalled()}catch{return null}}();if(!i||!Array.isArray(i.installed)||0===i.installed.length)return t?[t]:[];const s=new Set(i.installed.map(e=>e.id)),o=[],a=e=>{e&&s.has(e)&&(function(e,t){return!(!t||0===t.length)&&t.includes(e)}(e,r)||o.includes(e)||o.push(e))};if(a(t),o.length<n)for(const e of i.installed){if(o.length>=n)break;a(e.id)}return o.slice(0,n)}async function _t(e,t){let n=e.riskLevel;if(!n){const r=await async function(e,t){if("risk-assessor"===e.id)return{riskLevel:"medium"};const n=Mt.get("risk-assessor");if(!n)return{riskLevel:"medium"};const r=t.context,i=[];i.push("Assess the risk level for this task:"),i.push(""),i.push(`Instruction Class: ${e.id}`),i.push(`Role: ${e.role}`),i.push(""),i.push("User Prompt:"),i.push(t.userPrompt),i.push(""),i.push("Context:"),i.push(`- Workspace ID: ${r?.workspaceId??"N/A"}`),i.push(`- File Path: ${r?.filePath??"N/A"}`),i.push("- Previous Outputs: "+(r?.previousOutputs?"Yes":"No")),i.push(`- Capabilities Provided: ${r?.capabilities&&r.capabilities.length>0?r.capabilities.map(e=>e.id).filter(Boolean).join(", "):"None"}`),i.push(""),i.push("Consider:"),i.push("- Is this production code?"),i.push("- Does it involve security-sensitive operations (auth, payment, banking)?"),i.push("- Is it a critical business function?"),i.push("- Does it handle sensitive data?"),i.push("- Is it a simple utility or a complex system?"),i.push(""),i.push('Respond with ONLY one word: "low", "medium", or "high".');const s=i.join("\n");try{const e=punica.runtime.capabilities?.gateway,t=e?await e.call("llm.chat",{messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20},{sessionId:"internal",workspaceId:void 0,actor:{type:"extension",extensionName:"kernel:policy"},origin:{kind:"command",id:"risk-assessment"},trace:{traceId:punica.kernel.Events.manager.createCorrelationId()},policy:{mode:"execute"}}):await punica.runtime.llm.chat({messages:[{role:"system",content:n.systemPrompt},{role:"user",content:s}],profile:"fast",temperature:n.temperature??.1,maxTokens:n.maxTokens??20}),r=String(t.text??"").toLowerCase();return/\bhigh\b/.test(r)?{riskLevel:"high"}:/\bmedium\b/.test(r)?{riskLevel:"medium"}:/\blow\b/.test(r)?{riskLevel:"low"}:{riskLevel:"medium"}}catch{return{riskLevel:"medium"}}}(e,t);n=r.riskLevel}if(n||(n="medium"),"high"===n){const t=e.expertModelId,r=e.expertModelIds;let i=[];return i=r&&r.length>0?r.slice():await Pt({primaryModelId:t,count:3}),{strategy:i.length>1?"multi":"single",modelIds:i.length?i:[t].filter(Boolean),riskLevel:n,reason:"High risk detected via LLM-based assessment"}}let r=e.expertModelId??null;return r||(r=await async function(){const e=punica.runtime.llm?.manager;if(!e||"function"!=typeof e.listInstalled)return null;try{const t=await e.listInstalled();if(t.activeModelId)return t.activeModelId;const n=t.installed[0];return n?n.id:null}catch{return null}}()),{strategy:"single",modelIds:r?[r]:[],riskLevel:n,reason:"Low/medium risk, single expert sufficient"}}function Rt(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 Lt(){const e=globalThis;return e.punica?.runtime?.capabilities?.gateway}function $t(){const e=globalThis;return e.punica?.runtime?.fs}function Ot(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Dt={type:"ai",id:"llm:context"},jt={kind:"ai",id:"context-builder"};async function Ft(e){if(e.filePath)try{const t=Lt(),n=t?await t.call("fs.readFile",{path:e.filePath},{sessionId:"internal",workspaceId:e.workspaceId,actor:Dt,origin:jt,trace:{traceId:Ot()},policy:{mode:"execute"}}):await($t()?.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 qt(e){try{const t=Lt(),n=t?await t.call("fs.listFiles",{},{sessionId:"internal",workspaceId:e.workspaceId,actor:Dt,origin:jt,trace:{traceId:Ot()},policy:{mode:"execute"}}):await($t()?.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 Bt(){const e=globalThis;return e.punica?.shell?.ContentTabs}function Ut(){return"undefined"==typeof document?void 0:document}function Vt(){const e=Ut();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 Wt(e){try{const t=Bt();if(!(e.filePath??t?.getActivePath?.()??null))return;const n=Vt();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 Kt(){try{const e=Bt();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=Vt();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=Ut();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 Gt(){const e=globalThis;return e.punica?.kernel?.Events?.manager?.createCorrelationId?.()??""}const Yt={type:"ai",id:"llm:context"},zt={kind:"ai",id:"context-builder"};async function Jt(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:Yt,origin:zt,trace:{traceId:Gt()},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 Ht(){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 Qt(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 Zt="problems.getDiagnostics";function Xt(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===Zt))return;let r;try{r=t.executeCommand?.(Zt)}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 en(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 tn=new class{#U;#V=[];constructor(e){this.#U=Math.max(1,e?.maxRecords??1e4)}record(e){this.#V.push(e),this.#V.length>this.#U&&this.#V.splice(0,this.#V.length-this.#U)}report(e){const t=e?.scope??"capability",n=e?.rangeStart??-1/0,r=e?.rangeEnd??1/0,i=new Map;let s=0,o=0,a=0,c=0,l=0;for(const e of this.#V){if(e.timestamp<n||e.timestamp>r)continue;const u=en(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.#V.length=0}};function nn(e){return e.remaining[0]}function rn(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 sn(e){return{...e,terminal:!0,pendingQueue:!1}}let on;function an(e){on=e}function cn(e){return!!e&&"string"==typeof e.providerId&&""!==e.providerId.trim()}const ln={onError:"next",onTimeout:"next",onRateLimit:"next"};function un(e){const t=e?.status??e?.statusCode;return"number"==typeof t&&(408!==t&&429!==t&&(401!==t&&403!==t&&(t>=400&&t<500)))}function dn(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 pn(e){const t=e.providerId.trim(),n=t.toLowerCase(),r=n.startsWith("local:")?"local":n.startsWith("remote:")?"remote":void 0;return{providerId:t,...r?{route:r}:{},...e.modelId?{modelId:e.modelId}:{}}}async function fn(e,n){const r=Mt;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(Rt(e)),Ft(e),Promise.resolve(Wt(e)),qt(e),Jt(e),Ht(),Promise.resolve(Kt()),Qt(e),Promise.resolve(Xt(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 _t(i,e),a={messages:[{role:"system",content:i.systemPrompt},{role:"user",content:s,...e.images&&e.images.length>0?{images:e.images}:{}}],profile:"balanced",temperature:e.options?.temperature??i.temperature??.2,maxTokens:e.options?.maxTokens??i.maxTokens??2e3,responseFormat:i.responseFormat,correlationId: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,n)=>{const r=punica.kernel.Events.manager;return await punica.runtime.capabilities.gateway.call(t,{...a,...n},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}})},h=(e,t,n)=>{try{const r=punica.kernel.Events.manager;r.publishEvent({name:"llm.fallback",envelope:{id:r.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId: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(cn);if(!on)return[];try{const e=on();return Array.isArray(e)?e.filter(cn):[]}catch{return[]}}(i);let g,y;if(m.length>0){let e,t=function(e){return{position:0,attempted:[],remaining:e.slice(),terminal:0===e.length,pendingQueue:!1}}(m);const n=Date.now();for(;!t.terminal;){const n=nn(t);if(!n)break;const r=Date.now();try{l=await f(c,pn(n)),d=Date.now()-r,g=t.position,t=sn(t);break}catch(r){if(e=r,un(r))break;const s=rn(t,dn(r),i.fallbackPolicy??ln,r);if(s.pendingQueue){t={...s,terminal:!0};break}const o=nn(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],n=Date.now();try{const r=punica.kernel.Events.manager;l=await punica.runtime.capabilities.gateway.call(c,{...a,modelId:t},{sessionId:a.correlationId??r.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??r.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-n}catch(t){if(!(o.modelIds.length>1)||e.options?.skipFallback)throw t;{let n=t;for(const t of o.modelIds.slice(1))try{const r=Date.now(),s=punica.kernel.Events.manager;try{s.publishEvent({name:"llm.fallback",envelope:{id:s.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,fromModelId:o.modelIds[0],toModelId:t,reason:n?.message??"unknown"}})}catch{}l=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??s.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??s.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),d=Date.now()-r;break}catch(e){n=e;continue}if(!l)throw n}}}else{const t=Date.now(),n=punica.kernel.Events.manager,r=o.modelIds.map(async t=>{const r=Date.now(),s=await punica.runtime.capabilities.gateway.call("llm.chat",{...a,modelId:t},{sessionId:a.correlationId??n.createCorrelationId(),workspaceId:p,actor:{type:"user",id:void 0},origin:{kind:"ai",id:e.instructionClass},trace:{traceId:a.correlationId??n.createCorrelationId(),parentSpanId:void 0},policy:{mode:"execute"}}),o=Date.now()-r;let c;if(i.outputSchema&&"json_object"===i.responseFormat)try{c=JSON.parse(s.text)}catch{}return{res:s,expert:{modelId:s.modelId??t,text:s.text,structured:c,usage:s.usage,latencyMs:o}}}),s=await Promise.all(r);u=s.map(e=>e.expert);const c=function(e,t){if(!e.length)throw new Error("aggregateBestOfN called with no results");if("json_object"===t.responseFormat){const t=e.filter(e=>void 0!==e.structured);if(t.length>0)return t.reduce((e,t)=>t.latencyMs<e.latencyMs?t:e)}return e.reduce((e,t)=>{const n=e.text.length-e.latencyMs/1e3+.1*(e.usage?.outputTokens??0);return t.text.length-t.latencyMs/1e3+.1*(t.usage?.outputTokens??0)>n?t:e})}(u,i);l={text:c.text,modelId:c.modelId,provider:s.find(e=>e.expert.modelId===c.modelId)?.res.provider,usage:c.usage},d=Date.now()-t}if(i.outputSchema&&"json_object"===i.responseFormat)try{y=JSON.parse(l.text)}catch(e){return{ok:!1,error:`Failed to parse structured output: ${e instanceof Error?e.message:String(e)}`,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId}}}const w={ok:!0,text:l.text,structured:y,metadata:{instructionClass:i.id,role:i.role,originExtension:i.originExtension,productId:i.productId,tokensUsed:l.usage?.totalTokens,inputTokens:l.usage?.inputTokens,outputTokens:l.usage?.outputTokens,latencyMs:d,modelId:l.modelId,provider:l.provider}};try{const e=l.usage?.inputTokens??0,t=l.usage?.outputTokens??0,n=l.usage?.cacheReadInputTokens??0,r=String(l.provider??"unknown"),s=String(l.modelId??"unknown"),o=0,c={provider:r,model:s,promptTokens:e,completionTokens:t,totalCost:o,latencyMs:d,...void 0!==g?{fallbackChainPosition:g}:{}};tn.record({capabilityId:i.id,provider:r,model:s,promptTokens:e,completionTokens:t,...n>0?{cachedPromptTokens:n}:{},totalCost:o,latencyMs:d,timestamp:Date.now(),workspaceId:p}),punica.kernel.Events.manager.publishEvent({name:"llm.call",envelope:{id:punica.kernel.Events.manager.createCorrelationId(),correlationId:a.correlationId,timestampMs:Date.now(),source:"kernel:llm",kind:"info"},payload:{capabilityId:i.id,workspaceId:p,meta:c}})}catch{}return w}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 hn(e){return fn({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 mn(e){return fn({instructionClass:"code-generator",userPrompt:e.language?`Generate ${e.language} code:\n${e.requirements}`:e.requirements,context:e.context})}async function gn(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 fn({instructionClass:"workflow-editor",userPrompt:t,context:e.context})}function yn(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function wn(e,t){const n=yn(e).split("/").filter(Boolean),r=yn(t).split("/").filter(Boolean);for(const e of r)".."===e?n.length>0&&n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}function vn(e){return e.startsWith("/")||/^[A-Za-z]:/.test(e)}function bn(e,t){const n=yn(e).split("/").filter(Boolean),r=yn(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 In(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=bn(t,wn(t,yn(r.path)));(e.startsWith("..")||vn(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=yn(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 kn={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 En=new class{api;constructor(){this.api={instructionClassRegistry:Mt,invoke:fn,plan:hn,generateCode:mn,editWorkflow:gn,listInstructionClasses:e=>Mt.listSummaries(e),setDefaultProviderChainResolver:an}}};var Sn={manager:En};const An={Commands:h,History:g,TimeServer:y,Tasks:k,Events:Z,Notifications:ne,Policy:we,AI:Nt,llm:Object.freeze({__proto__:null,CodegenBundleV0_1Schema:kn,applyCodegenBundle:In,default:Sn,manager:En})};function xn(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 Cn=new class{#W=[];register(e){this.#W=this.#W.filter(t=>t.id!==e.id),this.#W.push({priority:0,...e}),this.#W.sort((e,t)=>(t.priority??0)-(e.priority??0)),console.log("[Runtime.FileOpeners] register",e.id,"→",e.command,"matches:",e.matches)}unregister(e){this.#W=this.#W.filter(t=>t.id!==e)}clear(){this.#W=[],console.log("[Runtime.FileOpeners] clear")}resolve(e){const t=[];for(const n of this.#W){const r=n.matches;if(r&&0!==r.length){if(r.some(t=>xn(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.#W.filter(t=>{const n=t.matches;return!!n&&n.length>0&&n.some(t=>xn(t,e))}).map(e=>({opener:e,command:e.command}))}};let Tn,Nn,Mn,Pn,_n,Rn;function Ln(){if(Tn)return Tn;if(!punica.runtime.resources)throw new Error("[Runtime.resources] No Resources provider registered. Host must attach punica.runtime.resources");return Tn=punica.runtime.resources,Tn}function $n(){if(Nn)return Nn;const e=punica.runtime?.search;if(!e)throw new Error("[Runtime.search] No Search provider registered. Host must attach punica.runtime.search");return Nn=e,Nn}function On(){if(Pn)return Pn;const e=punica.runtime?.terminals;if(!e)throw new Error("[Runtime.terminals] No Terminal provider registered. Host must attach punica.runtime.terminals");return Pn=e,Pn}function Dn(){if(_n)return _n;throw new Error("[Runtime.debug] No debug-adapter provider registered. Debugging requires a host with local process access (Punica desktop).")}function jn(){if(Rn)return Rn;const e=punica.runtime?.vcs;if(!e)throw new Error("[Runtime.vcs] No Vcs provider registered. Host must attach punica.runtime.vcs");return Rn=e,Rn}function Fn(e){let t,n;return{get(){if(void 0!==t)return t;const n=e.resolveHostFallback?.();if(void 0!==n)return t=n,t;throw new Error(e.noProviderMessage)},set(e){t=e,n=void 0},hasProvider:()=>void 0!==t,lastProviderId:()=>n,trackProviderId(e){const t=n;return n=e,{previous:t,changed:void 0!==t&&void 0!==e&&t!==e}}}}function qn(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 Bn=Fn({label:"Runtime.workspace",noProviderMessage:"[Runtime.workspace] No Workspace provider registered. Host must attach punica.runtime.workspace",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.workspace}});function Un(){return Bn.get()}function Vn(e){Bn.set(e),e&&qn({name:"workspace.providerRegistered",source:"runtime:workspace",payload:{}})}function Wn(e,t,n){try{const r=function(){const e=globalThis;return e.punica?.kernel?.Events?.manager}();return!(!r?.publishEvent||!r?.createCorrelationId)&&(r.publishEvent({name:e,envelope:{id:r.createCorrelationId(),correlationId:n,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:t}),!0)}catch{return!1}}const Kn=Symbol("punica.llm.gatewayGovernedAi");let Gn,Yn,zn;function Jn(){if(Gn)return Gn;if(!punica.runtime.llm)throw new Error("[Runtime.llm] No LLM provider registered. Host must attach punica.runtime.llm");return Gn=punica.runtime.llm,Gn}function Hn(e){if(Gn=e,Yn=void 0,zn=void 0,!e)return;const t=e;Wn("llm.providerRegistered",{providerId:t.id??(t.manager?"electron":"unknown"),capabilities:t.capabilities?Array.from(t.capabilities):void 0})}class Qn{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 Zn=null;function Xn(){return Zn||(Zn=new Qn),Zn}class er{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 tr{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 nr={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}}},rr={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}}},ir={language:"java",prepare(e,t){throw new Error("Java execution is not yet supported. Use Python or Node.js for now.")}},sr={language:"dotnet",prepare(e,t){throw new Error(".NET execution is not yet supported. Use Python or Node.js for now.")}},or={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 ar(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 cr{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=ar("session");return new tr(i,s,t.id,e.language,r,n)}}class lr{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 ur=null;function dr(){return ur||(ur=new lr),ur}class pr{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 fr{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 hr=null;function mr(){return hr||(hr=new fr),hr}class gr{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 yr{#K=new Map;register(e){if(!e.id)throw new Error("Model runtime must have an id");this.#K.set(e.id,e)}get(e){return this.#K.get(e)}list(){return Array.from(this.#K.values())}select(e){return this.list().find(t=>t.canRun(e))}}let wr=null;function vr(){return wr||(wr=new yr),wr}function br(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 Ir="default";class kr{#G=new Map;#Y(e){const t=e||Ir;let n=this.#G.get(t);return n||(n=new Map,this.#G.set(t,n)),n}upsert(e,t=Ir){const n=this.#Y(t);for(const t of e){if(!t||"string"!=typeof t.id)throw new Error("VectorRecord requires a string id.");n.set(t.id,t)}}query(e,t=10,n=Ir){const r=this.#Y(n),i=[];for(const t of r.values())i.push({id:t.id,score:br(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=Ir){const n=this.#Y(t);for(const t of e)n.delete(t)}clear(e=Ir){this.#G.delete(e||Ir)}count(e=Ir){return this.#Y(e).size}export(e=Ir){return Array.from(this.#Y(e).values())}import(e,t=Ir){const n=new Map;for(const t of e)t&&"string"==typeof t.id&&n.set(t.id,t);this.#G.set(t||Ir,n)}}const Er=".punica/vectors";class Sr{#v=new kr;#z=new Set;#J(){try{return punica.runtime?.fs}catch{return}}#H(e){return`${Er}/${t=e,((t||"default").trim()||"default").replace(/[^a-zA-Z0-9_-]/g,"_")}.json`;var t}async#Q(e){const t=e||"default";if(this.#z.has(t))return;this.#z.add(t);const n=this.#J();if(n?.readFile)try{const e=await n.readFile(this.#H(t)),r=JSON.parse(e);Array.isArray(r?.records)&&this.#v.import(r.records,t)}catch{}}async#Z(e){const t=this.#J();if(t)try{if(t.mkdir)try{await t.mkdir(Er)}catch{}const n={version:1,records:this.#v.export(e)},r=this.#H(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.#Q(n),this.#v.upsert(e,n),await this.#Z(n)}async query(e){const t=e.collection??"default";return await this.#Q(t),this.#v.query(e.vector,e.topK??10,t)}async delete(e,t){const n=t?.collection??"default";await this.#Q(n),this.#v.delete(e,n),await this.#Z(n)}async clear(e){const t=e?.collection??"default";await this.#Q(t),this.#v.clear(t),await this.#Z(t)}async count(e){const t=e?.collection??"default";return await this.#Q(t),this.#v.count(t)}}let Ar,xr,Cr;function Tr(){return Ar||(xr||(xr=new Sr),xr)}function Nr(){if(!Cr)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 Cr}var Mr;!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"}(Mr||(Mr={}));class Pr extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="CapabilityError"}}const _r=new class{#X=new Map;#ee=new Map;registerCapability(e){if(!e.name)throw new Pr(Mr.CAPABILITY_SPEC_INVALID,"Capability name is required");if(!e.version)throw new Pr(Mr.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 Pr(Mr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" version "${e.version}" is not valid semver (expected MAJOR.MINOR.PATCH, e.g. "1.0.0")`,{capability:e.name,version:e.version});if(this.#X.has(e.name))throw new Pr(Mr.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 Pr(Mr.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 Pr(Mr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot require itself`,{capability:e.name,cycle:[e.name,e.name]});for(const t of e.requires){const n=this.#te(t,e.name);if(n)throw new Pr(Mr.CAPABILITY_SPEC_INVALID,`Capability "${e.name}" cannot be registered: dependency cycle detected (${[e.name,...n].join(" → ")})`,{capability:e.name,cycle:[e.name,...n]})}}this.#X.set(e.name,e);try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.({name:"capability.registered",envelope:{id:`cap-reg-${e.name}-${Date.now()}`,correlationId:`cap-reg-${e.name}`,timestampMs:Date.now(),source:"runtime:capabilities:registry",kind:"info"},payload:{capability:e.name,version:e.version,origin:"core",risk:e.risk,sideEffect:e.sideEffect,deprecated:e.deprecated??null}})}catch{}}#te(e,t,n=new Set){if(e===t)return[e];if(n.has(e))return null;n.add(e);const r=this.#X.get(e);if(!r?.requires)return null;for(const i of r.requires){const r=this.#te(i,t,n);if(r)return[e,...r]}return null}registerProvider(e){if(!this.#X.has(e.name))throw new Pr(Mr.CAPABILITY_NOT_FOUND,`Cannot register provider for unknown capability "${e.name}"`);this.#ee.set(e.name,e)}getSpec(e){return this.#X.get(e)}getProvider(e){return this.#ee.get(e)}hasCapability(e){return this.#X.has(e)}hasProvider(e){return this.#ee.has(e)}listCapabilities(){return Array.from(this.#X.keys())}getAllSpecs(){return Array.from(this.#X.values())}clear(){this.#X.clear(),this.#ee.clear()}};function Rr(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.requires&&e.requires.length>0&&(t.requires=[...e.requires]),e.permissions&&e.permissions.length>0&&(t["x-permissions"]=[...e.permissions]),e.secretBearing&&(t["x-secretBearing"]=!0),t}function Lr(e){const t=e,n=Array.isArray(t["x-permissions"])?t["x-permissions"].slice():[],r={name:e.id,version:e.version,sideEffect:jr(e.sideEffects),risk:e.policy?.risk??"low",permissions:n,inputSchema:e.inputs?.schema,outputSchema:e.outputs?.schema};return 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),e.deprecated&&(r.deprecated={...e.deprecated}),Array.isArray(e.requires)&&e.requires.length>0&&(r.requires=[...e.requires]),e.policy&&(r.policy={...e.policy}),r}const $r=["write","delete","remove","modify","destroy","create","update","install","publish","process","spawn","exec","run"],Or=["network","http","fetch","request","upload","download"],Dr=["read","list","get","query","inspect","search"];function jr(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":$r.some(t=>e.includes(t))?"write":Or.some(t=>e.includes(t))?"network":Dr.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 Fr=["core","extension","instruction-class","ivy-node","ivy-agent","mcp"];function qr(){const e=globalThis;return e.punica?.extensions?.manager}function Br(){const e=globalThis;return e.punica?.kernel?.llm?.api?.instructionClassRegistry}function Ur(){const e=globalThis;return e.punica?.flow?.registry}function Vr(){const e=globalThis;return e.punica?.flow?.agents}function Wr(){const e=globalThis;return e.punica?.runtime?.mcp?._registry}const Kr={core:function(e){const t=_r.getSpec(e);if(t)return{origin:"core",definition:Rr(t)}},extension:function(e){const t=qr();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=Br();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=Ur();if(!t)return;const n=t.get(e),r=n?.manifest?.capability;return r?{origin:"ivy-node",definition:r,metadata:n?.manifestPath?{packageRoot:n.manifestPath}:void 0}:void 0},"ivy-agent":function(e){const t=Vr();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=Wr();if(!t)return;const n=t.get(e);return n?{origin:"mcp",definition:n.definition,metadata:{mcpServerId:n.serverId,mcpToolName:n.toolName}}:void 0}},Gr={core:function(){return _r.getAllSpecs().map(e=>({origin:"core",definition:Rr(e)}))},extension:function(){const e=qr();return e?e.listCapabilities().map(e=>({origin:"extension",definition:e.definition,metadata:{extensionName:e.extensionName}})):[]},"instruction-class":function(){const e=Br();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=Ur();if(!e)return[];const t=[];for(const n of e.list()){const e=n.manifest?.capability;e&&t.push({origin:"ivy-node",definition:e,metadata:{packageRoot:n.manifestPath}})}return t},"ivy-agent":function(){const e=Vr();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=Wr();return e?e.list().map(e=>({origin:"mcp",definition:e.definition,metadata:{mcpServerId:e.serverId,mcpToolName:e.toolName}})):[]}},Yr={getCapability(e){for(const t of Fr){const n=Kr[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 Fr)if(!t||t.has(e))for(const t of Gr[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 zr(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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.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 Pr(Mr.CAPABILITY_PROVIDER_MISSING,`createProviderForOrigin called with 'core' origin for "${t.id}" — use capabilityRegistry.getProvider() instead`,{capability:t.id,origin:"core"})}}let Jr={recordSpan:()=>{}};function Hr(e){try{Jr.recordSpan(e)}catch(e){console.warn("[CapabilityGateway] Telemetry exporter recordSpan failed:",e)}}function Qr(){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,Hr({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 Hr({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 Pr?e.code:void 0,errorMessage:r.error.message,attributes:{...r.tags}}),e}}}function Zr(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Zr);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Zr(r);return t}return e}const Xr=new WeakMap;function ei(){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=Zr(s);else{const e=function(e){const t=Xr.get(e);if(t)return t;const n=u(e.inputSchema);return Xr.set(e,n),n}(r.spec);r.redactedInput=e.length>0?d(s,e):s}return await t()}}function ti(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function ni(e,t){return"null"===e||("integer"===e?"number"==typeof t&&Number.isInteger(t):"number"===e?"number"==typeof t:e===ti(t))}const ri=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&&(ni(i,t)||n.push(`Expected type "${i}", got "${ti(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&&(ni(i,r)||n.push(`Field "${t}": expected type "${i}", got "${ti(r)}"`))}}return{ok:0===n.length,errors:n}}};let ii=ri;function si(){return ii}function oi(){return async(e,t)=>{const{req:n,state:r}=e,{input:i}=n,{inputSchema:s}=r.spec,o=si().validate(s,i);if(!o.ok)throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Input validation failed: ${o.errors.join(", ")}`,{errors:o.errors,input:r.redactedInput});return await t()}}const ai=Fn({label:"Runtime.fs",noProviderMessage:"[Runtime.fs] No FileSystem provider registered. Host must call punica.runtime.setFsProvider() before using FileSystem API"});function ci(){return ai.get()}const li=["path","oldPath","newPath","src","dst","target","linkPath"];function ui(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 di(){try{return ci().cwd}catch{return}}function pi(){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 li){const t=r[e];if("string"!=typeof t)continue;s||(i=di(),s=!0);const n=ui(t,i);if(!n.ok)throw new Pr(Mr.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 fi="encrypted-at-rest";function hi(){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 ci()}catch{return}}();if(!i)throw new Pr(Mr.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:fi,reason:"provider not registered"});if(!i.capabilities?.has(fi))throw new Pr(Mr.CAPABILITY_ENCRYPTION_REQUIRED,`Capability "${n.name}" carries sensitive data and requires the registered FileSystemProvider to advertise the "${fi}" capability flag`,{capability:n.name,required:fi,reason:"capability not advertised"});return qn({name:"fs.encrypted.routingApplied",source:"runtime:capabilities:gateway",correlationId:e.req.invocationId,payload:{capability:n.name,dataClassification:"sensitive",providerCapabilityMatched:fi}}),t()}}function mi(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 gi(){return async(e,t)=>{const n=function(){try{const e=globalThis;return e.punica?.shell?.Profile?.manager?.registry?.getActive?.()}catch{return}}();if(!n)return t();const{allowedIds:r,deniedIds:i,allowedOrigins:s}=n.capabilities;if("*"===r&&!i?.length&&!s?.length)return t();const o=e.state.spec.name,a=e.req.invocationId,c=n.identity.id;if(s&&s.length>0){const e=Yr.getCapability(o),t=e?.origin;if(!t||!s.includes(t))throw mi(o,c,"origin-not-allowed",t,a),new Pr(Mr.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 mi(o,c,"in-denylist",void 0,a),new Pr(Mr.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 mi(o,c,"not-in-allowlist",void 0,a),new Pr(Mr.CAPABILITY_NOT_IN_PROFILE,`Capability "${o}" is not in profile "${c}" allowedIds`,{capability:o,profile:c,reason:"not-in-allowlist"})}return t()}}const yi={alg:"HS256",typ:"PUNICA-APPROVAL"};class wi extends Error{code;constructor(e,t){super(t),this.code=e,this.name="ApprovalTokenError"}}function vi(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 bi(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 Ii(e){return(new TextEncoder).encode(e)}function ki(e){return vi(Ii(JSON.stringify(e)))}function Ei(e){return JSON.parse((t=bi(e),(new TextDecoder).decode(t)));var t}function Si(){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 Ai(){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 xi{#ne;#re;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?Ii(e.secret):Ai()}async sign(e){const t=await this.#ie(),n=ki(yi),r=ki(e),i=Ii(`${n}.${r}`),s=await Si().sign("HMAC",t,i);return`${n}.${r}.${vi(new Uint8Array(s))}`}getSecret(){return this.#ne}async#ie(){return this.#re||(this.#re=await Si().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"])),this.#re}}class Ci{#ne;#re;#se=new Set;constructor(e){e?.secret instanceof Uint8Array?this.#ne=e.secret:this.#ne="string"==typeof e?.secret?Ii(e.secret):Ai()}async verify(e){const t=e.split(".");if(3!==t.length)throw new wi("MALFORMED","Token must have 3 dot-separated segments");const[n,r,i]=t;let s,o;try{s=Ei(n)}catch{throw new wi("MALFORMED","Token header is not valid base64url JSON")}if("HS256"!==s.alg||"PUNICA-APPROVAL"!==s.typ)throw new wi("BAD_HEADER",`Unexpected token header: alg=${s.alg??"(missing)"} typ=${s.typ??"(missing)"}`);try{o=Ei(r)}catch{throw new wi("MALFORMED","Token payload is not valid base64url JSON")}const a=await this.#ie(),c=Ii(`${n}.${r}`);let l;try{l=bi(i)}catch{throw new wi("MALFORMED","Token signature is not valid base64url")}const u=Si();if(!await u.verify("HMAC",a,l,c))throw new wi("BAD_SIGNATURE","Token signature mismatch");if("number"==typeof o.expiry&&o.expiry<=Date.now())throw new wi("EXPIRED","Token expired");if(this.isRevoked(o.jti))throw new wi("REVOKED",`Token jti "${o.jti}" revoked`);return o}revoke(e){this.#se.add(e)}isRevoked(e){return this.#se.has(e)}async#ie(){return this.#re||(this.#re=await Si().importKey("raw",this.#ne,{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"])),this.#re}}let Ti;function Ni(){return Ti||(Ti=function(){const e=new xi,t=new Ci({secret:e.getSecret()});return{signer:e,verifier:t}}()),Ti}const Mi=({risk:e,sideEffect:t})=>"high"===e||"write"===t?"approval":"auto";function Pi(){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 Pr(Mr.CAPABILITY_DENIED,`Policy manager unavailable and capability "${i}" is ${"high"===a?"high-risk":`${c}-approval`}; denied under fail-closed policy.`,{capability:i,reason:"policy-manager-missing",risk:a,approval:c});return r.policyDecision={allowed:!0,requiresApproval:!1,reason:"policy-manager-missing (fail-open)"},await t()}const c=o.policy??{},l=c.risk??o.risk??"low",u=c.approval??"none";let d=!1,p="";if("ai"===s.actor.type){"approval"===Mi({capabilityId:i,risk:o.risk,sideEffect:o.sideEffect})&&(d=!0,p=`agent-mode policy: ${o.sideEffect}/${o.risk}`)}"high"===o.risk&&(d=!0,p="High risk capability"),"step"!==u&&"plan"!==u||(d=!0,p=`Capability requires ${u} approval`);const f={kind:"capability",id:i,risk:l,approval:u,reason:o.description??o.title??`Capability: ${i}`},h=a.evaluate(f,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});if(r.policyDecision={allowed:h.allowed,requiresApproval:h.requiresApproval||d,approvalToken:s.policy.approvalToken,reason:h.reason||p},d||h.requiresApproval)if(s.policy.approvalToken)try{await Ni().verifier.verify(s.policy.approvalToken)}catch(e){if(e instanceof wi){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 Pr(Mr.CAPABILITY_APPROVAL_REQUIRED,`Approval token rejected: ${e.code}`,{capability:i,reason:p,tokenError:e.code})}throw e}else{if("function"!=typeof a.hasApproval||!(a.hasApproval(f,"always",{workspaceId:s.workspaceId})||a.hasApproval(f,"workspace",{workspaceId:s.workspaceId})||a.hasApproval(f,"once",{workspaceId:s.workspaceId}))){a.requestApproval(f,{workspaceId:s.workspaceId,correlationId:n.invocationId,traceId:s.trace.traceId});try{const e=globalThis.punica?.kernel?.Events?.manager;e&&e.publishEvent({name:"capability.approvalRequired",envelope:{id:e.createCorrelationId(),correlationId:n.invocationId,traceId:s.trace.traceId,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{invocationId:n.invocationId,capability:i,reason:p}})}catch(e){console.warn("[CapabilityGateway] Failed to emit capability.approvalRequired event:",e)}throw new Pr(Mr.CAPABILITY_APPROVAL_REQUIRED,`Approval required: ${p}`,{capability:i,reason:p})}{r.policyDecision.requiresApproval=!1;const e={workspaceId:s.workspaceId};if(!(a.hasApproval(f,"always",e)||a.hasApproval(f,"workspace",e))&&"function"==typeof a.revokeApproval)try{a.revokeApproval({kind:f.kind,id:f.id,scope:"once"})}catch{}}}if(!h.allowed&&!d&&"suggest"!==h.mode)throw new Pr(Mr.CAPABILITY_DENIED,h.reason??"Policy denied execution",{capability:i,decision:h});return await t()}}const _i=new class{#m=new Map;#oe;ttlMs;constructor(e){this.ttlMs=e?.ttlMs??864e5;const t=e?.maxEntries??1e4;this.#oe=t<=0?1:t}get(e,t){const n=this.#ae(e,t),r=this.#m.get(n);if(r){if(!(r.expiresAtMs<=Date.now()))return this.#m.delete(n),this.#m.set(n,r),r;this.#m.delete(n)}}set(e){const t=this.#ae(e.capabilityId,e.key);for(this.#m.delete(t),this.#m.set(t,e);this.#m.size>this.#oe;){const e=this.#m.keys().next().value;if(void 0===e)break;this.#m.delete(e)}}delete(e,t){return this.#m.delete(this.#ae(e,t))}clear(){this.#m.clear()}purgeExpired(){const e=Date.now();let t=0;for(const[n,r]of this.#m)r.expiresAtMs<=e&&(this.#m.delete(n),t++);return t}size(){return this.#m.size}#ae(e,t){return`${e}|${t}`}};let Ri=_i;function Li(){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 Pr(Mr.CAPABILITY_IDEMPOTENCY_KEY_MISSING,`Capability "${i}" declares idempotency: 'required' but the invocation did not supply idempotencyKey`,{capability:i});if(!o)return t();const c=Ri,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 Pr(Mr.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 $i=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 Oi(){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(!$i.consumeToken(c,a.perSecond))throw new Pr(Mr.CAPABILITY_RATE_LIMITED,`Rate limit exceeded for capability "${i}" (${a.perSecond}/s)`,{capability:i,perSecond:a.perSecond,key:c});return await t()}}const Di=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e){const t=this.#le.get(e);if(!t)return;t.count--;const n=t.queue.shift();n&&(t.count++,n.resolve())}};function ji(){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 Di.acquire(a,o.max)}catch(e){throw new Pr(Mr.CAPABILITY_PROVIDER_ERROR,`Failed to acquire concurrency permit: ${String(e)}`,{key:a,max:o.max})}try{return await t()}finally{Di.release(a)}}}const Fi=new class{#ue=new Map;getBreaker(e){let t=this.#ue.get(e);return t||(t={status:"closed",consecutiveFailures:0,openedAtMs:0},this.#ue.set(e,t)),t}};function qi(){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=Fi.getBreaker(i),l=Date.now();if("open"===c.status&&l-c.openedAtMs>=a&&(c.status="half-open"),"open"===c.status)throw new Pr(Mr.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 Bi(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 Ui(e,t,n,r){let i;const s=new Promise((e,t)=>{i=setTimeout(()=>{t(new Pr(Mr.CAPABILITY_TIMEOUT,`Execution timeout after ${r}ms`))},r)});try{return await Promise.race([e.execute(t,n.req.ctx),s])}finally{void 0!==i&&clearTimeout(i)}}function Vi(e){return{invocationId:e.invocationId,capability:e.capability,actor:e.actor,origin:e.origin,capabilityOrigin:e.capabilityOrigin,workspace:e.workspaceId,policyDecision:e.policyDecision?{allowed:e.policyDecision.allowed,requiresApproval:e.policyDecision.requiresApproval,reason:e.policyDecision.reason}:void 0,input:e.redactedInput,output:e.redactedOutput,duration:e.durationMs,error:e.error?{message:e.error.message,name:e.error.name}:void 0,timestamp:e.timestamp}}async function Wi(e){try{if(function(e){const t=globalThis.punica?.kernel?.Events?.manager;if(!t||"function"!=typeof t.publishEvent||"function"!=typeof t.createCorrelationId)return!1;try{return t.publishEvent({name:"capability.audited",envelope:{id:t.createCorrelationId(),correlationId:e.invocationId,timestampMs:e.timestamp,source:"runtime:capabilities:gateway",kind:e.error?"error":"info"},payload:Vi(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(Vi(e)),!0}catch{return!1}}(e))return;if(await async function(e){let t;try{t=ci()}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(Vi(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 Ki=new WeakMap;function Gi(e,t){if(!0===t.secretBearing)return Yi(e);const n=function(e){const t=Ki.get(e);if(t)return t;const n=u(e.outputSchema);return Ki.set(e,n),n}(t);return n.length>0?d(e,n):e}function Yi(e){if("string"==typeof e)return"***";if(Array.isArray(e))return e.map(Yi);if(e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Yi(r);return t}return e}function zi(){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=Gi(r.output,o);await Wi({invocationId:n.invocationId,capability:i,actor:s.actor,origin:s.origin,capabilityOrigin:r.capabilityOrigin,workspaceId:s.workspaceId,policyDecision:r.policyDecision,redactedInput:r.redactedInput,redactedOutput:e,durationMs:r.durationMs,error:r.error,timestamp:Date.now()})}}return c}}const Ji=["auditTrail","traceMetrics","redaction","validateInput","pathTraversalGuard","encryptionRouting","profileBudget","policyGate","idempotency","rateLimit","concurrency","circuitBreaker","timeoutRetry"];function Hi(e){try{const t=globalThis.punica?.kernel?.Events?.manager;t?.publishEvent?.(e)}catch{}}const Qi=new class{async call(e,t,n,r){const i=function(){const e=globalThis;return e.crypto?.randomUUID?e.crypto.randomUUID():`inv_${Date.now()}_${Math.floor(1e6*Math.random())}`}();let s=_r.getSpec(e),o=s?_r.getProvider(e):void 0,a="core";if(!s){const t=Yr.getCapability(e);if(!t)throw Hi({name:"capability.unknown_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"warn"},payload:{capability:e,origin:null,actor:n.actor}}),new Pr(Mr.CAPABILITY_NOT_FOUND,`Capability "${e}" not found in registry`);a=t.origin,s=Lr(t.definition),o=zr(t.origin,t.definition,t.metadata)}if(!o)throw new Pr(Mr.CAPABILITY_PROVIDER_MISSING,`Provider not registered for capability "${e}"`);if(s.requires)for(const t of s.requires)if(!_r.hasCapability(t))throw new Pr(Mr.CAPABILITY_PROVIDER_MISSING,`Capability "${e}" requires "${t}" but that capability is not registered`,{capability:e,missingRequirement:t});s.deprecated&&Hi({name:"capability.deprecated_called",envelope:{id:i,correlationId:i,timestampMs:Date.now(),source:"runtime:capabilities:gateway",kind:"info"},payload:{capability:e,origin:a,since:s.deprecated.since,reason:s.deprecated.reason,replacement:s.deprecated.replacement,actor:n.actor}});const c={req:{invocationId:i,name:e,input:t,ctx:n,idempotencyKey:r},state:{spec:s,capabilityOrigin:a,startTimeMs:Date.now(),tags:{}}},l=this.#de(o);try{return await this.#pe(l,c)}catch(e){if(e instanceof Pr)throw e;throw new Pr(Mr.CAPABILITY_PROVIDER_ERROR,`Provider execution failed: ${String(e)}`,{originalError:String(e)})}}#de(e){const t={auditTrail:zi,traceMetrics:Qr,redaction:ei,validateInput:oi,pathTraversalGuard:pi,encryptionRouting:hi,profileBudget:gi,policyGate:Pi,idempotency:Li,rateLimit:Oi,concurrency:ji,circuitBreaker:qi,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 Ui(e,s,t,c);return i.output=n,n}catch(e){if(p=e instanceof Error?e:new Error(String(e)),f<=l&&d&&Bi(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 Ji.map(e=>t[e]())}#pe(e,t){let n=0;const r=async()=>{if(n>=e.length)throw new Error("Middleware chain ended without provider execution");const i=e[n];return n++,await i(t,r)};return r()}};function Zi(e,t){const n=ci(),r=n[t];if("function"!=typeof r)throw new Pr(Mr.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 Xi(e,t,n){const r=ci();if(!r.capabilities?.has(n))throw new Pr(Mr.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 Pr(Mr.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 es{name="fs.readFile";async execute(e,t){const n=ci();return await n.readFile(e.path)}}class ts{name="fs.writeFile";async execute(e,t){const n=ci();try{await n.updateFileContent(e.path,e.content)}catch{await n.createFileWithContent(e.path,e.content)}}}const ns=89478485;class rs{name="fs.writeBytes";async execute(e,t){if(e.base64.length>ns)throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Capability "fs.writeBytes" received a ${e.base64.length}-character base64 payload, over the 89478485 limit`,{capability:"fs.writeBytes",limit:ns});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 Pr(Mr.CAPABILITY_INPUT_INVALID,'Capability "fs.writeBytes" received a malformed base64 payload',{capability:"fs.writeBytes"})}await Zi("fs.writeBytes","writeBytes")(e.path,n)}}class is{name="fs.listFiles";async execute(e,t){const n=ci();return await n.getFileTree()}}class ss{name="fs.stat";async execute(e,t){return await Zi("fs.stat","stat")(e.path)}}class os{name="fs.exists";async execute(e,t){return await Zi("fs.exists","exists")(e.path)}}class as{name="fs.copy";async execute(e,t){await Zi("fs.copy","copy")(e.src,e.dst)}}class cs{name="fs.mkdir";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;await Zi("fs.mkdir","mkdir")(e.path,n)}}class ls{name="fs.history";async execute(e,t){return await Xi("fs.history","history","versioning")(e.path)}}class us{name="fs.readAtVersion";async execute(e,t){return await Xi("fs.readAtVersion","readAtVersion","versioning")(e.path,e.versionId)}}class ds{name="fs.list";async execute(e,t){const n=void 0!==e.recursive?{recursive:e.recursive}:void 0;return await Zi("fs.list","list")(e.path,n)}}const ps=Fn({label:"Runtime.secrets",noProviderMessage:"[Runtime.secrets] No Secrets provider registered. Host must call punica.runtime.setSecretsProvider() before using Secrets API",resolveHostFallback:()=>{const e=globalThis;return e.punica?.runtime?.secrets??function(){const e=new Map,t=new Map;return{set(n,r){const i=String(n??"").trim();if(!i)throw new Error("[Runtime.secrets] Secret name is required");const s=Date.now();if(t.has(i)){const e=t.get(i);t.set(i,{...e,updatedAtMs:s})}else t.set(i,{createdAtMs:s,updatedAtMs:s});e.set(i,String(r??""))},get(t){const n=String(t??"").trim();return n&&e.has(n)?e.get(n):null},delete(n){const r=String(n??"").trim();return!!r&&(t.delete(r),e.delete(r))},list(){const e=[];for(const[n,r]of t.entries())e.push({name:n,createdAtMs:r.createdAtMs,updatedAtMs:r.updatedAtMs});return e.sort((e,t)=>e.name.localeCompare(t.name)),e}}}()}});function fs(){return ps.get()}function hs(e){ps.set(e),e&&qn({name:"secrets.providerRegistered",source:"runtime:secrets",payload:{}})}class ms{name="secrets.get";async execute(e,t){return fs().get(e.name)}}class gs{name="secrets.set";async execute(e,t){fs().set(e.name,e.value)}}function ys(e,t){if("ai"!==t.actor?.type)return e;const n={...e};return n[Kn]=!0,n}class ws{name="llm.chat";async execute(e,t){const n=globalThis.punica?.runtime?.llm;if(!n)throw new Error("LLM provider not available");const r=ys(t.signal&&!e.signal?{...e,signal:t.signal}:e,t);return await n.chat(r)}}class vs{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=ys(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 bs{name="llm.invoke";async execute(e,t){const n=globalThis.punica?.kernel?.llm?.manager;if(!n)throw new Error("Kernel LLM manager not available");return await n.api.invoke(e,{correlationId:t.sessionId??t.trace?.traceId})}}class Is{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 ks{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 Es{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 Ss{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 As{name="workspace.readFile";async execute(e,t){const n=ci();return await n.readFile(e.path)}}class xs{name="workspace.writeFile";async execute(e,t){const n=ci();await n.createFileWithContent(e.path,e.content)}}class Cs{name="workspace.listFiles";async execute(e,t){const n=ci(),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 Ts=[".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"],Ns=["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 Ms(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 Ps={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"},_s=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 Rs(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 Ls(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function $s(e,t,n){const r=new Map;for(const t of e){if(t.endsWith("/"))continue;const e=Ps[Ls(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 Os(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(_s.has(e)&&n.add(t),n.size>=8)break}return[...n].slice(0,8)}function Ds(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=Rs(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=Rs(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:$s(e.layout,!!t.node,!!t.python),dependencies:t,entrypoints:Os(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 js=["readme.md","readme.rst","readme.txt","readme"];async function Fs(e,t){try{return await e.readFile(t)}catch{return}}async function qs(){const e=ci(),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(Ts),n=new Set(Ns),r=(e.gitignore??"").split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")&&!e.startsWith("!")),i=r.map(Ms).filter(e=>null!=e),s=[],o=new Set,a=e=>{o.has(e)||(o.add(e),s.push(e))};for(const e of Ts)a(`${e}/`);for(const e of Ns)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 Fs(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)?Fs(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 js)if(n.has(t)&&(u=await Fs(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:Ds({workspace:d,layout:i,layoutTruncated:s,packageJson:a,requirementsTxt:c,pyproject:l,readme:u,vcs:p}),noisePatterns:r.patterns}}class Bs{name="workspace.projectContext";async execute(e,t){const{context:n}=await qs();return n}}async function Us(e,t,n){try{await e.updateFileContent(t,n)}catch{await e.createFileWithContent(t,n)}}class Vs{name="workspace.writeOrientation";async execute(e,t){const n=!1!==e?.claudeMd,r=!1!==e?.claudeignore,i=ci(),{context:s,noisePatterns:o}=await qs(),a=[];if(n&&(await Us(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 Us(i,".claudeignore",e),a.push(".claudeignore")}return{written:a}}}const Ws=".punica/facts",Ks=`${Ws}/facts.json`;async function Gs(e){let t;try{t=await e.readFile(Ks)}catch{return{}}try{const e=JSON.parse(t);return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}class Ys{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=ci(),i=await Gs(r);return i[n]=e.value??null,await async function(e,t){const n=`${JSON.stringify(t,null,2)}\n`;try{await e.updateFileContent(Ks,n)}catch{try{await e.createFolder(".punica")}catch{}try{await e.createFolder(Ws)}catch{}await e.createFileWithContent(Ks,n)}}(r,i),{key:n,count:Object.keys(i).length}}}class zs{name="context.recall";async execute(e,t){const n=ci(),r=await Gs(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 Js{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 Hs{name="terminals.send";async execute(e,t){const n=globalThis.punica?.runtime?.terminals;if(!n)throw new Error("Terminals provider not available");n.write(e.id,e.text)}}class Qs{name="tasks.runCommand";async execute(e,t){const n=globalThis.punica?.runtime?.tasks;if(!n)throw new Error("Tasks provider not available");return await n.run(e)}}class Zs{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 Xs{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 eo="capability.catalog";class to{name=eo;async execute(e,t){const n=e??{},r=Yr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>no(e,n));return{capabilities:r,count:r.length}}}function no(e,t){if(void 0!==t.extension&&e.metadata?.extensionName!==t.extension)return!1;if(void 0!==t.risk){const n=ro(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=ro(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=ro(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 ro(e){return Array.isArray(e)?e:[e]}const io=["examples","$comment","default","title"];function so(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 oo=["properties","patternProperties","definitions","$defs"];function ao(e){if(Array.isArray(e))return e.map(e=>ao(e));if(!e||"object"!=typeof e)return e;const t={};for(const[n,r]of Object.entries(e))if(!io.includes(n))if("description"!==n||"string"!=typeof r){if(oo.includes(n)&&r&&"object"==typeof r&&!Array.isArray(r)){const e={};for(const[t,n]of Object.entries(r))e[t]=ao(n);t[n]=e;continue}t[n]=ao(r)}else t[n]=r.length>120?r.slice(0,119).trimEnd()+"…":r;return t}const co="capability.schemaExport";class lo{name=co;async execute(e,t){const n=e??{},r=n.filter??{},i=Yr.listCapabilities(r.origin?{origin:r.origin}:void 0).filter(e=>no(e,r)),s=n.mode??"full",o=i.map(e=>{const t=function(e){const t=e.definition,n={id:t.id,origin:e.origin,version:t.version,title:t.title};void 0!==t.description&&(n.description=t.description);void 0!==t.inputs?.schema&&(n.inputSchema=t.inputs.schema);void 0!==t.outputs?.schema&&(n.outputSchema=t.outputs.schema);t.policy&&(n.policy={risk:t.policy.risk,approval:t.policy.approval});t.tags&&t.tags.length>0&&(n.tags=[...t.tags]);t.sideEffects&&t.sideEffects.length>0&&(n.sideEffects=[...t.sideEffects]);const r=t.requires;r&&r.length>0&&(n.requires=[...r]);t.deprecated&&(n.deprecated={...t.deprecated});if(e.metadata){const t={};for(const[n,r]of Object.entries(e.metadata))void 0!==r&&(t[n]=r);Object.keys(t).length>0&&(n.metadata=t)}return n}(e);return"ai-tools"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=so(e.description??e.title,200);n&&(t.description=n);void 0!==e.inputSchema&&(t.inputSchema=ao(e.inputSchema));e.policy&&(t.policy={...e.policy});return t}(t):"summary"===s?function(e){const t={id:e.id,origin:e.origin,version:e.version,title:e.title},n=so(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 uo={"ı":"i","ø":"o","đ":"d","ł":"l","ß":"ss","æ":"ae","œ":"oe"};function po(e){return e.length<4||!e.endsWith("s")||/(?:ss|us|is)$/.test(e)?e:e.slice(0,-1)}function fo(e){return function(e){let t="";for(const n of e)t+=uo[n]??n;return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}(e.toLowerCase()).split(/[^a-z0-9]+/).filter(e=>e.length>=2).map(po)}function ho(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return t}function mo(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 go(e,t){const n=ho(fo(e));return t.map(e=>({...e,score:mo(n,ho(fo(e.text)))}))}const yo={tr:{roots:{ac:"open",kapat:"close",kaydet:"save",kayit:"record log",sil:"delete remove",olustur:"create new",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",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",metin:"text",yol:"path",uzanti:"extension",surum:"version",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"},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"]}},wo=new Map,vo=new Set;for(const e of Object.values(yo)){for(const[t,n]of Object.entries(e.roots)){const e=fo(t).join("");e.length>0&&wo.set(e,fo(n))}for(const t of e.stopWords){const e=fo(t).join("");e.length>0&&vo.add(e)}}const bo=[...wo.keys()].sort((e,t)=>t.length-e.length);new Map;function Io(e){let t=0;for(const n of e)n.score>t&&(t=n.score);return t}async function ko(e,t,n){const r=t=>("text-similarity"!==t.path&&Wn("llm.normalizeIntent",{intent:e,path:t.path,normalizedAs:t.text,topScore:t.score}),{scores:t.scores,path:t.path,...void 0===t.text?{}:{normalizedAs:t.text}}),i=go(e,t);let s={scores:i,score:Io(i),path:"text-similarity"};if(s.score>=.25)return r(s);const o=(e,n)=>{const r=go(e,t),i=Io(r);i>s.score&&(s={scores:r,score:i,path:n,text:e})},a=function(e){const t=[];for(const n of e){if(vo.has(n))continue;const e=bo.find(e=>n.startsWith(e));e?t.push(n,...wo.get(e)):t.push(n)}return t}(fo(e)).join(" ");return a.length>0&&o(a,"lexicon"),s.score,r(s)}async function Eo(e,t){const n=t?.limit??5,r=String(e??"").trim();if(!r)return{recommendations:[],path:"text-similarity"};const i=Yr.listCapabilities();if(0===i.length)return{recommendations:[],path:"text-similarity"};const s=i.map(e=>({id:e.definition.id,description:e.definition.description,text:So(e.definition)}));let o,a,c;{const e=await ko(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 Wn("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 So(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 Ao="capability.recommend";class xo{name=Ao;async execute(e,t){const n=e??{},r=String(n.intent??""),i=await Eo(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 Co="capability.describe",To="capability.search";function No(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}class Mo{name=Co;async execute(e,t){const n=(e?.ids??[]).map(e=>String(e)).slice(0,16),r=new Set(n),i=(await(new lo).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 Po{name=To;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=Yr.listCapabilities(),o=new Map(s.map(e=>[String(e.definition.id),e.definition]));let a=[];try{const e=await async function(e,t){return(await Eo(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:so(t?.description??t?.title??e,100),category:No(e)}});return{results:c,count:c.length}}}function _o(){const e=globalThis.punica?.kernel?.AI?.sessions;if(!e)throw new Error("AI session service not available");return e}function Ro(e,t){return{name:e,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 Lo{name="ai.session.create";async execute(e,t){const n=e??{};return{session:_o().create(n)}}}class $o{name="ai.session.list";async execute(e,t){const n=_o().list(e?.workspaceId);return{sessions:n,count:n.length}}}class Oo{name="ai.session.get";async execute(e,t){const n=String(e?.sessionId??"");return{session:_o().get(n)}}}class Do{name="ai.session.rename";async execute(e,t){const n=e;return{ok:_o().rename(String(n?.sessionId??""),String(n?.title??""))}}}class jo{name="ai.session.archive";async execute(e,t){const n=e;return{ok:_o().archive(String(n?.sessionId??""),n?.archived)}}}class Fo{name="ai.session.delete";async execute(e,t){return{ok:_o().delete(String(e?.sessionId??""))}}}const qo={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"}]}},Bo={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"}]}},Uo=new Set(["low","medium","high"]),Vo={id:"invalid-risk",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.risk?"string"==typeof t.risk&&Uo.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"}]:[]}},Wo=new Set(["none","plan","step"]),Ko={id:"invalid-approval",severity:"error",check(e){const t=e.policy;return t&&void 0!==t.approval?"string"==typeof t.approval&&Wo.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 Go={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"}]:[]}},Yo=/^[a-z][a-zA-Z0-9-]*(\.[a-z][a-zA-Z0-9-]*)+$/,zo={id:"id-naming",severity:"warning",check(e){const t=e.id;return"string"==typeof t&&Yo.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"}]}},Jo=new Set(["low","medium","high"]),Ho=["write","delete","remove","modify","destroy"],Qo=[qo,Bo,Vo,Ko,Go,zo,{id:"risk-approval-consistency",severity:"warning",check(e){const t=e.policy;if(!t||"string"!=typeof t.risk)return[];if(!Jo.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&&Ho.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 Zo=new class{#fe=new Map;constructor(){this.reset()}lint(e){const t=[];for(const n of this.#fe.values())try{const r=n.check(e);r&&r.length>0&&t.push(...r)}catch(r){t.push({ruleId:n.id,severity:"info",message:`Lint rule "${n.id}" threw during analysis: ${String(r?.message??r)}`,capabilityId:String(e.id),code:"CAP_LINT_RULE_ERROR"})}return{ok:!t.some(e=>"error"===e.severity),issues:t}}lintAll(e){return e.map(e=>({id:String(e.id),...this.lint(e)}))}register(e){if(!e||"function"!=typeof e.check)throw new Error("CapabilityLinter.register: rule must have a check(def) function");if("string"!=typeof e.id||0===e.id.length)throw new Error("CapabilityLinter.register: rule.id must be a non-empty string");this.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of Qo)this.#fe.set(e.id,e)}},Xo="capability.lint";class ea{name=Xo;async execute(e,t){const n=e??{},r=Yr.listCapabilities().map(e=>e.definition).filter(e=>!n.capabilityId||e.id===n.capabilityId),i=Zo.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 ta={type:"object"};function na(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ra(e){let t;return t=function(e){if(e instanceof Pr)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:na(e),{content:[{type:"text",text:t}],isError:!0}}const ia="capability.serveList",sa="capability.serveCall",oa=new Set([ia,sa]);class aa{name=ia;async execute(e,t){const n=(e??{}).filter??{},r=Yr.listCapabilities(n.origin?{origin:n.origin}:void 0).filter(e=>!oa.has(e.definition.id)).filter(e=>no(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??ta,annotations:{destructiveHint:"high"===e.policy?.risk,readOnlyHint:0===r.length}}}(e.definition));return{tools:r,count:r.length}}}class ca{name=sa;async execute(e,t){const n=e??{},r=String(n.name??"");if(!r||oa.has(r)||!Yr.getCapability(r))return ra(new Error(`unknown tool: ${r||"(empty)"}`));try{return function(e){return{content:[{type:"text",text:na(e)}],isError:!1}}(await Qi.call(r,n.arguments??{},t))}catch(e){return ra(e)}}}const la="shell.revealView",ua="shell.hideView",da="shell.listViews",pa="shell.toggleView",fa="shell.toggleSlot",ha="shell.moveView";function ma(){const e=globalThis.punica?.shell?.Views?.manager;if(!e)throw new Pr(Mr.CAPABILITY_PROVIDER_MISSING,"shell.Views manager is not initialized — the shell.views module is not active in this profile.",{capability:la});return e}function ga(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 ya{name=la;async execute(e,t){const{viewId:n,focus:r}=e??{},i=ma();if(!i.getPlacement(n))throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover revealable views.`,{capability:la,viewId:n});return await i.reveal(n,ga(t),{focus:r}),{viewId:n,revealed:!0}}}class wa{name=ua;async execute(e,t){const{viewId:n}=e??{};return ma().hide(n,ga(t)),{viewId:n,hidden:!0}}}class va{name=da;async execute(e,t){return{views:ma().listViews()}}}class ba{name=pa;async execute(e,t){const{viewId:n,focus:r}=e??{},i=ma();if(!i.getPlacement(n))throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover toggleable views.`,{capability:pa,viewId:n});return"visible"===i.getState(n)?(i.hide(n,ga(t)),{viewId:n,visible:!1}):(await i.reveal(n,ga(t),{focus:r}),{viewId:n,visible:!0})}}const Ia=new Map;class ka{name=fa;async execute(e,t){const{slot:n,focus:r}=e??{},i=ma(),s=i.getVisibleView(n);if(s)return Ia.set(n,s),i.hide(s,ga(t)),{slot:n,visible:!1,viewId:s};const o=Ia.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,ga(t),{focus:r}),{slot:n,visible:!0,viewId:a}):{slot:n,visible:!1}}}class Ea{name=ha;async execute(e,t){const{viewId:n,slot:r}=e??{},i=ma(),s=i.getPlacement(n);if(!s)throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`Unknown view "${n}" — no placement is registered. Call shell.listViews to discover movable views.`,{capability:ha,viewId:n});const o=s.allowedSlots??[];if(!o.includes(r))throw new Pr(Mr.CAPABILITY_INPUT_INVALID,`View "${n}" cannot be moved to slot "${r}". Allowed slots: ${o.length?o.join(", "):"(none)"}.`,{capability:ha,viewId:n,slot:r});return await i.moveView(n,r,ga(t)),{viewId:n,slot:r,moved:!0}}}function Sa(e){try{_r.registerCapability(e)}catch(t){console.error(`[CapabilityRegistry] Failed to register capability "${e.name}":`,t)}}function Aa(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 xa(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 Ca(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=Yr.getCapability(e.id);return t?void xa(t):void console.warn(`[Punica] capability not found: "${e.id}"`)}const n=e?.origin?{origin:e.origin}:void 0,r=Yr.listCapabilities(n),i=r.map(Aa);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)xa(e)}}else console.log("[Punica] Trinity catalog is empty (load extensions / activate LLM extensions, then retry).")}async function Ta(e){return Ca({...e,verbose:!0})}function Na(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 Ma(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 Pa(e){return JSON.stringify(e,null,2)}const _a=new class{#he=new Map;get(e){return this.#he.get(e)}list(){return[...this.#he.values()]}register(e,t){for(const e of t)this.#he.set(e.definition.id,e),this.#me(e.definition.id)}unregister(e){for(const[t,n]of this.#he)n.serverId===e&&(this.#he.delete(t),this.#ge(t))}hasServer(e){for(const t of this.#he.values())if(t.serverId===e)return!0;return!1}#me(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.registered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}#ge(e){try{const t=globalThis;t.punica?.kernel?.events?.publish?.({name:"capability.unregistered",envelope:{id:e,correlationId:e,timestampMs:Date.now(),source:"runtime:mcp:registry",kind:"info"},payload:{capability:e,origin:"mcp"}})}catch{}}},Ra=16384,La="runtime:mcp:client";function $a(){const e=globalThis.crypto;return e?.randomUUID?.()??`mcp_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Oa(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 Oa(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=>Oa(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]=Oa(i,t+1);return n}return e}function Da(e){let t;try{t=JSON.stringify(e??null,null,2)??"null"}catch{t=String(e)}const n=t.length;if(n<=Ra)return{json:t,bytes:n,truncated:!1};try{const r=JSON.stringify(Oa(e,0),null,2)??"null";if(r.length<=Ra)return{json:r,bytes:n,truncated:!0};t=r}catch{}return{json:t.slice(0,Ra)+"\n… [truncated]",bytes:n,truncated:!0}}function ja(e,t){if("tools/call"!==e)return;const n=t?.name;return"string"==typeof n&&n?n:void 0}const Fa=new class{#ye=new Map;async connect(e){if(this.#ye.has(e.id))return this.#ye.get(e.id).handle;const{loadServerOverrides:t,resolveEnvPlaceholders:n}=await Promise.resolve().then(function(){return Ya}),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:ja(n,r),callId:t});return{connect:()=>t.connect(),close:()=>t.close(),notify(e,r){const i=$a(),s=Da(r??{});qn({name:"mcp.request",source:La,correlationId:i,payload:{...n(i,e,r),kind:"notification",requestJson:s.json,requestBytes:s.bytes,requestTokens:ke().estimate(s.json),truncated:s.truncated}}),t.notify(e,r)},async request(e,r){const i=$a(),s=Date.now(),o=Da(r??{});qn({name:"mcp.request",source:La,correlationId:i,payload:{...n(i,e,r),kind:"request",requestJson:o.json,requestBytes:o.bytes,requestTokens:ke().estimate(o.json),truncated:o.truncated}});try{const o=await t.request(e,r),a=Da(o??null);return qn({name:"mcp.response",source:La,correlationId:i,payload:{...n(i,e,r),kind:"request",isError:!1,durationMs:Date.now()-s,responseJson:a.json,responseBytes:a.bytes,responseTokens:ke().estimate(a.json),truncated:a.truncated}}),o}catch(t){throw qn({name:"mcp.response",source:La,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 hg});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 mg});return new t(e.url,e.headers??{})}throw new Error(`MCP server "${e.id}": unknown transport kind "${e.kind}"`)}(o));await a.connect(),await a.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"punica-editor",version:"1.0.0"}}),a.notify("notifications/initialized",{});const c=await a.request("tools/list",{}),l=c?.tools??[],u=l.map(e=>{const t=o.toolOverrides?.[e.name]??{},n=function(e,t,n={}){const r=t._meta?.punica??{},i={risk:n.policy?.risk??r.policy?.risk??"medium",approval:n.policy?.approval??r.policy?.approval??"step"},s={timeoutMs:n.executionDefaults?.timeoutMs??r.executionDefaults?.timeoutMs??3e4,idempotency:n.executionDefaults?.idempotency??r.executionDefaults?.idempotency??"none"},o=["mcp",e],a=r.tags??[],c=n.tags??[],l=[...new Set([...o,...a,...c])],u=n.sideEffects??r.sideEffects??["mcp-invocation","network"];return{id:`mcp.${e}.${t.name}`,title:t.name,description:t.description??`MCP tool ${t.name} from server ${e}`,version:"1.0.0",inputs:{schema:t.inputSchema??{type:"object"}},outputs:{schema:{type:"object",properties:{content:{type:"array",items:{type:"object",properties:{type:{type:"string"},text:{type:"string"}}}},isError:{type:"boolean"}}},kind:"direct"},policy:i,sideEffects:u,executionDefaults:s,tags:l}}(o.id,e,t);return{serverId:o.id,toolName:e.name,definition:n}});_a.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(),_a.unregister(e.id),this.#ye.delete(e.id),console.log(`[Punica] MCP server "${o.id}" disconnected`)}};return this.#ye.set(o.id,{handle:d,transport:a}),d}async disconnect(e){const t=this.#ye.get(e);t&&await t.handle.disconnect()}listServers(){return[...this.#ye.values()].map(e=>e.handle)}listTools(e){return e?this.#ye.get(e)?.handle.tools??[]:this.listServers().flatMap(e=>e.tools)}async callTool(e,t,n){const r=this.#ye.get(e);if(!r)throw new Error(`MCP server "${e}" is not connected`);return await r.transport.request("tools/call",{name:t,arguments:n})??{}}},qa=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/,Ba=/^\$\{secret\.([A-Za-z0-9_.-]+)\}$/;async function Ua(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 Va(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(Ba);if(e){const n=e[1],r=await Ua(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(qa);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 Wa(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 zd}),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 Ka(){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 gg}),o=s(i);return Promise.all(o.map(e=>async function(e){const t=await Wa(e.id),n="stdio"===e.kind?await Va(e.env):e.env,r="streamable-http"===e.kind||"sse"===e.kind?await Va(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 Ga(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 Ya=Object.freeze({__proto__:null,loadMcpConfig:Ka,loadServerOverrides:Wa,parseStaticConfig:Ga,resolveEnvPlaceholders:Va});class za{name=st.RUNTIME.MCP;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.RUNTIME.FS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){this.#we=e.BOOTSTRAPPING;const n=await Ka();this.#ve(n),this.#we=e.BOOTSTRAPPED}async#ve(e){for(const t of e)try{await Fa.connect(t)}catch(e){console.error(`[Punica] MCP server "${t.id}" failed to connect:`,e?.message??e)}}async start(t){this.#we=e.STARTING,this.#we=e.STARTED,console.log(`[Punica] MCP module started — ${_a.list().length} capability(ies) active`)}}const Ja=(globalThis.punica??{}).runtime??void 0;console.log("[Runtime] Creating facades...");const Ha={get capabilities(){return ai.hasProvider()?ai.get().capabilities:void 0},get cwd(){return ai.hasProvider()?ai.get().cwd:void 0},hasProvider:()=>ai.hasProvider(),getFileTree:()=>ai.get().getFileTree(),readFile:e=>ai.get().readFile(e),get readBytes(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.readBytes?e.readBytes.bind(e):void 0},get writeBytes(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.writeBytes?e.writeBytes.bind(e):void 0},updateFileContent:(e,t)=>ai.get().updateFileContent(e,t),createFolder:e=>ai.get().createFolder(e),deleteFolder:e=>ai.get().deleteFolder(e),deleteFile:(e,t)=>ai.get().deleteFile(e,t),renameFile:(e,t)=>ai.get().renameFile(e,t),renameFolder:(e,t)=>ai.get().renameFolder(e,t),get revealInOS(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.revealInOS?e.revealInOS.bind(e):void 0},createFileWithContent:(e,t)=>ai.get().createFileWithContent(e,t),get list(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.list?e.list.bind(e):void 0},get stat(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.stat?e.stat.bind(e):void 0},get mkdir(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.mkdir?e.mkdir.bind(e):void 0},get copy(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.copy?e.copy.bind(e):void 0},get exists(){if(!ai.hasProvider())return;const e=ai.get();return"function"==typeof e.exists?e.exists.bind(e):void 0},__punicaWrappedFsFacade:!0},Qa=function(e){return e||{query:e=>$n().query(e),startIndex:e=>{const t=$n();return t.startIndex?t.startIndex(e):Promise.resolve()}}}(Ja?.search),Za=function(e){return e||{status:()=>jn().status(),branches:()=>jn().branches(),logs:e=>jn().logs(e),init:e=>jn().init(e),clone:e=>jn().clone(e),commit:e=>jn().commit(e),stage:e=>jn().stage(e),unstage:e=>jn().unstage(e),discard:e=>jn().discard(e),reset:e=>jn().reset(e),switchBranch:e=>jn().switchBranch(e),createBranch:(e,t)=>jn().createBranch(e,t),fetch:e=>jn().fetch(e),pull:e=>jn().pull(e),push:e=>jn().push(e)}}(Ja?.vcs),Xa=function(e){return e||{create:e=>On().create(e),write:(e,t)=>On().write(e,t),resize:(e,t,n)=>On().resize(e,t,n),close:e=>On().close(e),onData:(e,t)=>On().onData(e,t),onExit:(e,t)=>On().onExit(e,t),list:()=>On().list()}}(Ja?.terminals),ec=function(e){return e||{start:e=>Dn().start(e),send:(e,t)=>Dn().send(e,t),onMessage:(e,t)=>Dn().onMessage(e,t),onStderr:(e,t)=>Dn().onStderr(e,t),onExit:(e,t)=>Dn().onExit(e,t),stop:e=>Dn().stop(e),list:()=>Dn().list()}}(Ja?.debug),tc=function(e){return e||{run:e=>function(){if(Mn)return Mn;const e=punica.runtime?.tasks;if(!e)throw new Error("[Runtime.tasks] No Tasks provider registered. Host must attach punica.runtime.tasks");return Mn=e,Mn}().run(e)}}(Ja?.tasks),nc=function(e){return"object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedWorkspaceFacade?e:(void 0!==e&&Vn(e),{getCurrent:()=>Bn.get().getCurrent(),list:()=>Bn.get().list(),open:e=>Bn.get().open(e),setEnvironment:(e,t)=>Bn.get().setEnvironment(e,t),onDidChange:e=>Bn.get().onDidChange(e),__punicaWrappedWorkspaceFacade:!0});var t}(Ja?.workspace),rc=function(e){return e||{list:async e=>Ln().list(e),get:e=>Ln().get(e),register:e=>Ln().register(e),unregister:e=>Ln().unregister(e),onDidChange:e=>Ln().onDidChange(e)}}(Ja?.resources),ic=function(e){console.log("[LLM Facade] createLlmFacade called",{hasExisting:!!e});const t=Boolean(e?.__punicaWrappedLlmFacade);if(e&&!t&&Hn(e),t)return e;function n(e){if("remote"===e?.route)return!0;if("local"===e?.route)return!1;if(e?.providerId){const t=String(e.providerId).toLowerCase();if(t.startsWith("remote:"))return!0;if(t.startsWith("local:"))return!1}return!0}async function r(e,t,n){!function(e,t){(Yn&&Yn!==e||zn&&t&&zn!==t)&&Y.publishEvent({name:"llm.providerChanged",envelope:{id:Y.createCorrelationId(),timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{previousProviderId:Yn,newProviderId:e,previousEndpoint:zn,newEndpoint:t,note:"Provider/endpoint change may affect policy approvals"}}),Yn=e,t&&(zn=t)}(t,n);const r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch(e){return void console.error("[LLM Facade] Error accessing punica.runtime.workspace (gateRemoteRequest):",e?.message??e)}})(),i=e?.correlationId??Y.createCorrelationId(),s=ge.evaluate({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r});if(!s.allowed)throw s.requiresApproval&&ge.requestApproval({kind:"llm.remote",id:t,risk:"high",approval:"step",reason:"Remote LLM request"},{workspaceId:r,correlationId:i}),Y.publishEvent({name:"llm.remoteRequestDenied",envelope:{id:Y.createCorrelationId(),correlationId:i,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:t,workspaceId:r,messageCount:e.messages?.length??0}}),new Error(s.reason??"[Policy] Remote LLM request denied");return Y.publishEvent({name:"llm.remoteRequestSent",envelope:{id:Y.createCorrelationId(),correlationId:i,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:i,route:"remote",providerId:t}:{...e,correlationId:i}}const i={chat:async e=>{if(e?.signal?.aborted)throw new DOMException("Aborted","AbortError");const t=e?.route??"auto",i=e?.providerId??"remote",s=Jn(),o=!0===e?.[Kn];if(!o&&("remote"===t||n(e))){const t=e?.endpoint,n=await r(e,i,t);return await s.chat(n)}const a=await s.chat(e);if(!a)throw new Error("[LLM Facade] No response returned from LLM provider");const c=a?.provider;if(!o&&function(e){if(!e)return!1;const t=String(e).toLowerCase();return!t.startsWith("local:")&&"local"!==t&&"mock"!==t&&"ollama"!==t&&!t.startsWith("ollama-")&&"llama.cpp"!==t&&"llamacpp"!==t}(c)){const n=c&&"remote"!==c?c:i,r=await(async()=>{try{const e=await punica.runtime.workspace.getCurrent();return e?.id}catch{return}})(),s=e?.correlationId??Y.createCorrelationId(),o=ge.evaluate({kind:"llm.remote",id:n,risk:"high",approval:"step",reason:"Remote LLM request (auto route fallback)"},{workspaceId:r});if(!o.allowed)throw Y.publishEvent({name:"llm.remoteRequestBypassed",envelope:{id:Y.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"error"},payload:{providerId:n,route:t,workspaceId:r,messageCount:e.messages?.length??0,reason:"Policy gate bypassed via auto route"}}),o.requiresApproval&&ge.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)");Y.publishEvent({name:"llm.remoteRequestSent",envelope:{id:Y.createCorrelationId(),correlationId:s,timestampMs:Date.now(),source:"runtime:llm",kind:"info"},payload:{providerId:n,workspaceId:r,messageCount:e.messages?.length??0,retroactive:!0,route:t}})}return a},chatStream:async function*(e){if(e?.signal?.aborted)return;const t=e?.route??"auto",i=e?.providerId??"remote",s=Jn();let o=e;if(!(!0===e?.[Kn])&&("remote"===t||n(e))){const t=e?.endpoint;o=await r(e,i,t)}if("function"!=typeof s.chatStream){const e=await s.chat(o);if(!e)throw new Error("[LLM Facade] No response returned from LLM provider");if(o?.signal?.aborted)return;"string"==typeof e.text&&e.text.length>0&&(yield{type:"content",text:e.text});for(const t of e.toolCalls??[])yield{type:"tool_call",toolCall:t};return void(yield{type:"done",response:e})}for await(const e of s.chatStream(o)){if(o?.signal?.aborted)return;yield e}},__punicaWrappedLlmFacade:!0};return i.manager=function(){const e=("undefined"!=typeof window?window.api:void 0)?.llm;if(!e)return;return{listModels:async t=>await(e.listModels?.(t)),listInstalled:async()=>await(e.listInstalled?.()),setActiveModel:async t=>{await(e.setActive?.({modelId:t??null}))},removeModel:async t=>{await(e.remove?.({modelId:t}))},downloadModel:async t=>{await(e.download?.({modelId:t}))},pickModelFile:async()=>await(e.pickModelFile?.()),importModelFile:async t=>{await(e.importModelFile?.(t))},..."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?.())}}}(),i}(Ja?.llm),sc=function(e){if(e)return e;const t=Xn(),n=new er(t),r=new cr(t,n);t.registerLanguageRuntime(nr),t.registerLanguageRuntime(rr),t.registerLanguageRuntime(ir),t.registerLanguageRuntime(sr),t.registerLanguageRuntime(or);const i=new Map;return{async*run(e,t){const n=t?.runId??ar("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}}(Ja?.compute),oc=function(e){if(e)return e;const t=dr(),n=new pr(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}}(Ja?.datasets),ac=function(e){if(e)return e;const t=mr(),n=new gr(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}}(Ja?.models),cc=function(e){if(e)return e;const t=vr();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)}}}(Ja?.modelRuntimes),lc=function(e){if(e)return e;const t=vr();return{async infer(e){const n=e.handle?.runtimeId;if(!n)throw new Error("inference.infer requires a started runtime handle (req.handle from runtime.modelRuntimes.start).");const r=t.get(n);if(!r)throw new Error(`No model runtime registered for handle runtimeId="${n}".`);if("function"!=typeof r.infer)throw new Error(`Model runtime "${n}" does not support inference (no infer()). Task: ${e.task}.`);return r.infer(e)}}}(Ja?.inference),uc=function(e){return e||{upsert:(e,t)=>Tr().upsert(e,t),query:e=>Tr().query(e),delete:(e,t)=>Tr().delete(e,t),clear:e=>Tr().clear(e),count:e=>Tr().count(e)}}(Ja?.vectors),dc=function(e){if(e)return e;function t(){const e=Nr().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=Nr().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=Nr().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=Nr().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:()=>Nr().dataDir(),dataFs:{list:(e,t)=>Nr().dataFs.list(e,t),readFile:e=>Nr().dataFs.readFile(e),stat:e=>Nr().dataFs.stat(e),mkdir:(e,t)=>Nr().dataFs.mkdir(e,t),deleteFile:e=>Nr().dataFs.deleteFile(e),deleteFolder:e=>Nr().dataFs.deleteFolder(e),readBytes:(e,t,n)=>{const r=Nr().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=Nr().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=Cr?.http?.download;if(e)return e=>n().download(e)},get onDownloadProgress(){const e=Cr?.http?.onDownloadProgress;if(e)return e=>n().onDownloadProgress(e)}},get mcpServer(){return Cr?.mcpServer?i:void 0},get system(){return Cr?.system?s:void 0}}}(Ja?.host),pc=function(e){if("object"==typeof(t=e)&&null!==t&&!0===t.__punicaWrappedSecretsFacade)return e;var t;void 0!==e&&hs(e);return{set:(e,t)=>ps.get().set(e,t),get:e=>ps.get().get(e),delete:e=>ps.get().delete(e),list:()=>ps.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:ps.get().get(`secret-manager.${e}`)},__punicaWrappedSecretsFacade:!0}}(Ja?.secrets);console.log("[Runtime] Facades created"),function(){Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new es),Sa({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",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),_r.registerProvider(new ts),Sa({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",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","base64"],properties:{path:{type:"string"},base64:{type:"string",sensitive:!0,maxLength:89478485}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),_r.registerProvider(new rs),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),_r.registerProvider(new is),Sa({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",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}}),_r.registerProvider(new ss),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"boolean"},defaults:{timeoutMs:1e4}}),_r.registerProvider(new os),Sa({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",risk:"medium",permissions:[],inputSchema:{type:"object",required:["src","dst"],properties:{src:{type:"string"},dst:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:6e4,idempotency:"optional"}}),_r.registerProvider(new as),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),_r.registerProvider(new cs),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{path:{type:"string"},recursive:{type:"boolean"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:3e4}}),_r.registerProvider(new ds),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"array",items:{type:"object"}},defaults:{timeoutMs:1e4}}),_r.registerProvider(new ls),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["path","versionId"],properties:{path:{type:"string"},versionId:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new us),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["name"],properties:{name:{type:"string"}}},outputSchema:{type:["string","null"]},secretBearing:!0,dataClassification:"sensitive",defaults:{timeoutMs:5e3}}),_r.registerProvider(new ms),Sa({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",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"}}),_r.registerProvider(new gs),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),_r.registerProvider(new ws),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["messages"],properties:{messages:{type:"array"},profile:{type:"string"},temperature:{type:"number"},maxTokens:{type:"number"},route:{type:"string"}}},outputSchema:{type:"object",properties:{text:{type:"string"},modelId:{type:"string"},provider:{type:"string"}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:10}}}),_r.registerProvider(new vs),Sa({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",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}}}),_r.registerProvider(new Is),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["instructionClass","userPrompt"],properties:{instructionClass:{type:"string"},userPrompt:{type:"string"},context:{type:"object"},options:{type:"object",properties:{temperature:{type:"number"},maxTokens:{type:"number"},timeoutMs:{type:"number"},stream:{type:"boolean"},skipCache:{type:"boolean"},skipFallback:{type:"boolean"}}}}},outputSchema:{type:"object",properties:{ok:{type:"boolean"},result:{type:"string"},parsed:{}}},defaults:{timeoutMs:12e4,rateLimit:{perSecond:5}}}),_r.registerProvider(new bs),Sa({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",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}}),_r.registerProvider(new ks),Sa({name:"vcs.status",title:"Uncommitted changes",description:"Show which files have uncommitted changes in version control: modified, added, deleted, and untracked.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),_r.registerProvider(new Es),Sa({name:"vcs.commit",title:"Commit changes",description:"Commit the current changes to version control with a message.",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["message"],properties:{message:{type:"string"},all:{type:"boolean"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),_r.registerProvider(new Ss),Sa({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.",version:"1.0.0",sideEffect:"read",risk:"low",permissions:[],inputSchema:{type:"object",required:["path"],properties:{path:{type:"string"}}},outputSchema:{type:"string"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new As),Sa({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.",version:"1.0.0",sideEffect:"write",risk:"medium",permissions:[],inputSchema:{type:"object",required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:3e4,idempotency:"optional"}}),_r.registerProvider(new xs),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object"}}}},defaults:{timeoutMs:3e4}}),_r.registerProvider(new Cs),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{}},outputSchema:{type:"object"},defaults:{timeoutMs:3e4}}),_r.registerProvider(new Bs),Sa({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",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"}}),_r.registerProvider(new Vs),Sa({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",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"}}),_r.registerProvider(new Ys),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{key:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4}}),_r.registerProvider(new zs),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",properties:{title:{type:"string"}}},outputSchema:{type:"object"},defaults:{timeoutMs:1e4,idempotency:"optional"}}),_r.registerProvider(new Js),Sa({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",risk:"low",permissions:[],inputSchema:{type:"object",required:["id","text"],properties:{id:{type:"string"},text:{type:"string"}}},outputSchema:{type:"null"},defaults:{timeoutMs:5e3,idempotency:"optional"}}),_r.registerProvider(new Hs),Sa({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",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"}}),_r.registerProvider(new Qs),Sa({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",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}}),_r.registerProvider(new Zs),Sa({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",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"}}),_r.registerProvider(new Xs),Sa({name:eo,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}}),_r.registerProvider(new to),Sa({name:co,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}}),_r.registerProvider(new lo),Sa({name:Ao,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}}),_r.registerProvider(new xo),Sa({name:To,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}}),_r.registerProvider(new Po),Sa({name:Co,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}}),_r.registerProvider(new Mo);for(const e of function(){const e={sessionId:{type:"string",description:"Session id."}};return[Ro("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"}}}),Ro("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"}}}),Ro("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"}}}),Ro("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"}}}),Ro("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"}}}),Ro("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"}}})]}())Sa(e);for(const e of[new Lo,new $o,new Oo,new Do,new jo,new Fo])_r.registerProvider(e);Sa({name:Xo,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}}),_r.registerProvider(new ea),Sa({name:ia,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}}),_r.registerProvider(new aa),Sa({name:sa,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}}),_r.registerProvider(new ca),Sa({name:la,title:"Show a panel",description:"Bring a panel, sidebar, or editor view into view and focus it.",version:"1.0.0",sideEffect:"write",risk:"low",permissions:[],inputSchema:{type:"object",required:["viewId"],properties:{viewId:{type:"string"},focus:{type:"boolean"}}},outputSchema:{type:"object",required:["viewId","revealed"],properties:{viewId:{type:"string"},revealed:{type:"boolean"}}},defaults:{timeoutMs:1e4}}),_r.registerProvider(new ya),Sa({name:ua,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}}),_r.registerProvider(new wa),Sa({name:da,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}}),_r.registerProvider(new va),Sa({name:pa,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}}),_r.registerProvider(new ba),Sa({name:fa,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}}),_r.registerProvider(new ka),Sa({name:ha,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}}),_r.registerProvider(new Ea)}(),console.log("[Runtime] Capabilities registered");const fc={lifecyclePhase:Ja?.lifecyclePhase??"bootstrapping",fs:Ha,fileOpeners:Ja?.fileOpeners??Cn,search:Qa,vcs:Za,terminals:Xa,debug:ec,tasks:tc,workspace:nc,resources:rc,secrets:pc,llm:ic,compute:sc,datasets:oc,models:ac,modelRuntimes:cc,inference:lc,vectors:uc,host:dc,capabilities:{gateway:Qi,unifiedRegistry:Yr,logTrinityCatalog:Ca,docs:{formatCapabilityMarkdown:function(e){const t=e.definition,n=[];n.push(`# \`${t.id}\``),n.push(""),n.push(function(e){const t=e.definition,n=[];n.push(`**Origin:** ${e.origin}`),n.push(`**Version:** ${t.version}`);const r=t.policy?.risk??"—",i=t.policy?.approval??"—";n.push(`**Risk:** ${r}`),n.push(`**Approval:** ${i}`);const s=t.sideEffects&&t.sideEffects.length>0?t.sideEffects.join(", "):"—";return n.push(`**Side effects:** ${s}`),n.join(" · ")}(e)),n.push("");const r=t.description??t.title;r&&r.length>0&&(n.push(r),n.push("")),void 0!==t.inputs?.schema&&(n.push("## Input schema"),n.push(""),n.push("```json"),n.push(Pa(t.inputs.schema)),n.push("```"),n.push("")),void 0!==t.outputs?.schema&&(n.push("## Output schema"),n.push(""),n.push("```json"),n.push(Pa(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(`## ${Na(e)} (${r.length})`),t.push(""),t.push("| ID | Version | Risk | Description |"),t.push("|----|---------|------|-------------|");for(const e of r)t.push(Ma(e));t.push("")}}for(;t.length>1&&""===t[t.length-1];)t.pop();return t.join("\n")+"\n"}}},mcp:{_registry:_a,connect:e=>Fa.connect(e),disconnect:e=>Fa.disconnect(e),listServers:()=>Fa.listServers(),listTools:e=>Fa.listTools(e),callTool:(e,t,n)=>Fa.callTool(e,t,n)},setFsProvider:function(e){ai.set(e),e&&qn({name:"fs.providerRegistered",source:"runtime:fs",payload:{cwd:e.cwd,capabilities:e.capabilities?Array.from(e.capabilities):void 0}})},setLlmProvider:Hn,setComputeProvider:function(e){Xn().registerProvider(e)},setComputeRuntime:function(e){Xn().registerLanguageRuntime(e)},setDatasetProvider:function(e){dr().registerProvider(e)},setModelProvider:function(e){mr().registerProvider(e)},setModelRuntime:function(e){vr().register(e)},setHostProvider:function(e){Cr=e},setVectorsProvider:function(e){Ar=e},setSearchProvider:function(e){Nn=e},setWorkspaceProvider:Vn,setTerminalProvider:function(e){Pn=e},setDebugProvider:function(e){_n=e},setVcsProvider:function(e){Rn=e},setResourcesProvider:function(e){Tn=e},setTasksProvider:function(e){Mn=e},setSecretsProvider:hs};class hc{#be;constructor(e){this.#be=e}execute(){return new Promise((e,t)=>{const n=punica.extensions.manager.getExtension(this.#be);n?e(n):t(new Error("Extension not found"))})}}let mc=class{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}},gc=class extends mc{constructor(e){super(e)}async execute(){return await super.execute()}},yc=class extends mc{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))}}},wc=class extends mc{constructor(e){super(e)}async execute(){return await super.execute()}};const vc=Symbol.for("yaml.alias"),bc=Symbol.for("yaml.document"),Ic=Symbol.for("yaml.map"),kc=Symbol.for("yaml.pair"),Ec=Symbol.for("yaml.scalar"),Sc=Symbol.for("yaml.seq"),Ac=Symbol.for("yaml.node.type"),xc=e=>!!e&&"object"==typeof e&&e[Ac]===vc,Cc=e=>!!e&&"object"==typeof e&&e[Ac]===bc,Tc=e=>!!e&&"object"==typeof e&&e[Ac]===Ic,Nc=e=>!!e&&"object"==typeof e&&e[Ac]===kc,Mc=e=>!!e&&"object"==typeof e&&e[Ac]===Ec,Pc=e=>!!e&&"object"==typeof e&&e[Ac]===Sc;function _c(e){if(e&&"object"==typeof e)switch(e[Ac]){case Ic:case Sc:return!0}return!1}function Rc(e){if(e&&"object"==typeof e)switch(e[Ac]){case vc:case Ic:case Ec:case Sc:return!0}return!1}const Lc=Symbol("break visit"),$c=Symbol("skip children"),Oc=Symbol("remove node");function Dc(e,t){const n=Bc(t);if(Cc(e)){jc(null,e.contents,n,Object.freeze([e]))===Oc&&(e.contents=null)}else jc(null,e,n,Object.freeze([]))}function jc(e,t,n,r){const i=Uc(e,t,n,r);if(Rc(i)||Nc(i))return Vc(e,r,i),jc(e,i,n,r);if("symbol"!=typeof i)if(_c(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=jc(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Lc)return Lc;i===Oc&&(t.items.splice(e,1),e-=1)}}}else if(Nc(t)){r=Object.freeze(r.concat(t));const e=jc("key",t.key,n,r);if(e===Lc)return Lc;e===Oc&&(t.key=null);const i=jc("value",t.value,n,r);if(i===Lc)return Lc;i===Oc&&(t.value=null)}return i}async function Fc(e,t){const n=Bc(t);if(Cc(e)){await qc(null,e.contents,n,Object.freeze([e]))===Oc&&(e.contents=null)}else await qc(null,e,n,Object.freeze([]))}async function qc(e,t,n,r){const i=await Uc(e,t,n,r);if(Rc(i)||Nc(i))return Vc(e,r,i),qc(e,i,n,r);if("symbol"!=typeof i)if(_c(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const i=await qc(e,t.items[e],n,r);if("number"==typeof i)e=i-1;else{if(i===Lc)return Lc;i===Oc&&(t.items.splice(e,1),e-=1)}}}else if(Nc(t)){r=Object.freeze(r.concat(t));const e=await qc("key",t.key,n,r);if(e===Lc)return Lc;e===Oc&&(t.key=null);const i=await qc("value",t.value,n,r);if(i===Lc)return Lc;i===Oc&&(t.value=null)}return i}function Bc(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 Uc(e,t,n,r){return"function"==typeof n?n(e,t,r):Tc(t)?n.Map?.(e,t,r):Pc(t)?n.Seq?.(e,t,r):Nc(t)?n.Pair?.(e,t,r):Mc(t)?n.Scalar?.(e,t,r):xc(t)?n.Alias?.(e,t,r):void 0}function Vc(e,t,n){const r=t[t.length-1];if(_c(r))r.items[e]=n;else if(Nc(r))"key"===e?r.key=n:r.value=n;else{if(!Cc(r)){const e=xc(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}r.contents=n}}Dc.BREAK=Lc,Dc.SKIP=$c,Dc.REMOVE=Oc,Fc.BREAK=Lc,Fc.SKIP=$c,Fc.REMOVE=Oc;const Wc={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Kc=e=>e.replace(/[!,[\]{}]/g,e=>Wc[e]);class Gc{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Gc.defaultYaml,e),this.tags=Object.assign({},Gc.defaultTags,t)}clone(){const e=new Gc(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Gc(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Gc.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Gc.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Gc.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Gc.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+Kc(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&&Rc(e.contents)){const t={};Dc(e.contents,(e,n)=>{Rc(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 Yc(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 zc(e){const t=new Set;return Dc(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Jc(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function Hc(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=Hc(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=Hc(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=Hc(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=Hc(e,r,t,n);void 0===i?delete r[t]:i!==n&&(r[t]=i)}return e.call(t,n,r)}function Qc(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Qc(e,String(t),n));if(e&&"function"==typeof e.toJSON){if(!n||(!Mc(r=e)&&!_c(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)}Gc.defaultYaml={explicit:!1,version:"1.2"},Gc.defaultTags={"!!":"tag:yaml.org,2002:"};class Zc{constructor(e){Object.defineProperty(this,Ac,{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(!Cc(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=Qc(this,"",s);if("function"==typeof r)for(const{count:e,res:t}of s.anchors.values())r(t,e);return"function"==typeof i?Hc(i,{"":o},"",o):o}}class Xc extends Zc{constructor(e){super(vc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return Dc(e,{Node:(e,n)=>{if(n===this)return Dc.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||(Qc(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=el(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(Yc(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 el(e,t,n){if(xc(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(_c(t)){let r=0;for(const i of t.items){const t=el(e,i,n);t>r&&(r=t)}return r}if(Nc(t)){const r=el(e,t.key,n),i=el(e,t.value,n);return Math.max(r,i)}return 1}const tl=e=>!e||"function"!=typeof e&&"object"!=typeof e;class nl extends Zc{constructor(e){super(Ec),this.value=e}toJSON(e,t){return t?.keep?this.value:Qc(this.value,e,t)}toString(){return String(this.value)}}nl.BLOCK_FOLDED="BLOCK_FOLDED",nl.BLOCK_LITERAL="BLOCK_LITERAL",nl.PLAIN="PLAIN",nl.QUOTE_DOUBLE="QUOTE_DOUBLE",nl.QUOTE_SINGLE="QUOTE_SINGLE";function rl(e,t,n){if(Cc(e)&&(e=e.contents),Rc(e))return e;if(Nc(e)){const t=n.schema[Ic].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 Xc(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 nl(e);return c&&(c.node=t),t}l=e instanceof Map?o[Ic]:Symbol.iterator in Object(e)?o[Sc]:o[Ic]}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 nl(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function il(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 rl(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 sl=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class ol extends Zc{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=>Rc(t)||Nc(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(sl(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(_c(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,il(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(_c(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&&Mc(i)?i.value:i:_c(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Nc(t))return!1;const n=t.value;return null==n||e&&Mc(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!!_c(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(_c(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,il(this.schema,r,t))}}}}ol.maxFlowStringSingleLineLength=60;const al=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function cl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const ll=(e,t,n)=>e.endsWith("\n")?cl(n,t):n.includes("\n")?"\n"+cl(n,t):(e.endsWith(" ")?"":" ")+n,ul="flow",dl="block",pl="quoted";function fl(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===dl&&(m=hl(e,m,t.length),-1!==m&&(f=m+c));for(let r;r=e[m+=1];){if(n===pl&&"\\"===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===dl&&(m=hl(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===pl){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===pl&&u[i]&&(w+=`${e[i]}\\`),w+=`\n${t}${e.slice(i+1,s)}`)}return w}function hl(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 ml=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),gl=e=>/^(%|---|\.\.\.)/m.test(e);function yl(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(gl(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:fl(o,s,pl,ml(t,!1))}function wl(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return yl(e,t);const n=t.indent||(gl(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?r:fl(r,n,ul,ml(t,!1))}function vl(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=yl;else{const t=e.includes('"'),i=e.includes("'");r=t&&!i?wl:i&&!t?yl:n?wl:yl}return r(e,t)}let bl;try{bl=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{bl=/\n+(?!\n|$)/g}function Il({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 vl(n,r);const l=r.indent||(r.forceBlockIndent||gl(n)?" ":""),u="literal"===o||"folded"!==o&&t!==nl.BLOCK_FOLDED&&(t===nl.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(bl,`$&${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}${fl(`${w}${n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`)}${f}`,l,dl,ml(r,!0))}`}function kl(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!==nl.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=nl.QUOTE_DOUBLE);const c=e=>{switch(e){case nl.BLOCK_FOLDED:case nl.BLOCK_LITERAL:return i||s?vl(o.value,t):Il(o,t,n,r);case nl.QUOTE_DOUBLE:return yl(o.value,t);case nl.QUOTE_SINGLE:return wl(o.value,t);case nl.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 vl(s,t);if(!s||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes("\n")?vl(s,t):Il(e,t,n,r);if(!a&&!u&&i!==nl.PLAIN&&s.includes("\n"))return Il(e,t,n,r);if(gl(s)){if(""===c)return t.forceBlockIndent=!0,Il(e,t,n,r);if(a&&c===l)return vl(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 vl(s,t)}return a?d:fl(d,c,ul,ml(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 El(e,t){const n=Object.assign({blockQuote:!0,commentString:al,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 Sl(e,t,n,r){if(Nc(e))return e.toString(t,n,r);if(xc(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=Rc(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(Mc(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=(Mc(e)||_c(e))&&e.anchor;s&&Yc(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):Mc(s)?kl(s,t,n,r):s.toString(t,n,r);return o?Mc(s)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function Al(e,t){"debug"!==e&&"warn"!==e||("undefined"!=typeof process&&process.emitWarning?process.emitWarning(t):console.warn(t))}function xl(e,t,{key:n,value:r}){if(e?.doc.schema.merge&&Cl(n))if(r=xc(r)?r.resolve(e.doc):r,Pc(r))for(const n of r.items)Tl(e,t,n);else if(Array.isArray(r))for(const n of r)Tl(e,t,n);else Tl(e,t,r);else{const i=Qc(n,"",e);if(t instanceof Map)t.set(i,Qc(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(Rc(e)&&n?.doc){const t=El(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)+'..."'),Al(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=Qc(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}const Cl=e=>"<<"===e||Mc(e)&&"<<"===e.value&&(!e.type||e.type===nl.PLAIN);function Tl(e,t,n){const r=e&&xc(n)?n.resolve(e.doc):n;if(!Tc(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 Nl(e,t,n){const r=rl(e,void 0,n),i=rl(t,void 0,n);return new Ml(r,i)}class Ml{constructor(e,t=null){Object.defineProperty(this,Ac,{value:kc}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Rc(t)&&(t=t.clone(e)),Rc(n)&&(n=n.clone(e)),new Ml(t,n)}toJSON(e,t){return xl(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=Rc(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(_c(e)||!Rc(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||_c(e)||(Mc(e)?e.type===nl.BLOCK_FOLDED||e.type===nl.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=Sl(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+=ll(v,n.indent,l(p)):w&&i&&i(),v;y&&(p=null),f?(p&&(v+=ll(v,n.indent,l(p))),v=`? ${v}\n${a}:`):(v=`${v}:`,p&&(v+=ll(v,n.indent,l(p)))),Rc(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||!Mc(t)||(n.indentAtStart=v.length+1),w=!1,u||!(c.length>=2)||n.inFlow||f||!Pc(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let b=!1;const I=Sl(t,n,()=>b=!0,()=>w=!0);let k=" ";if(p||h||m)k=h?"\n":"",m&&(k+=`\n${cl(l(m),n.indent)}`),""!==I||n.inFlow?k+=`\n${n.indent}`:"\n"===k&&(k="\n\n");else if(!f&&_c(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+=ll(v,n.indent,l(g)):w&&i&&i(),v}(this,e,t,n):JSON.stringify(this)}}function Pl(e,t,n){return(t.inFlow??e.flow?Rl:_l)(e,t,n)}function _l({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(Rc(i))!d&&i.spaceBefore&&p.push(""),Ll(n,p,i.commentBefore,d),i.comment&&(o=i.comment);else if(Nc(i)){const e=Rc(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&p.push(""),Ll(n,p,e.commentBefore,d))}d=!1;let a=Sl(i,u,()=>o=null,()=>d=!0);o&&(a+=ll(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"+cl(l(e),c),a&&a()):d&&o&&o(),f}function Rl({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(Rc(i))i.spaceBefore&&d.push(""),Ll(t,d,i.commentBefore,!1),i.comment&&(s=i.comment);else if(Nc(i)){const e=Rc(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(""),Ll(t,d,e.commentBefore,!1),e.comment&&(l=!0));const n=Rc(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=Sl(i,c,()=>s=null);n<e.length-1&&(o+=","),s&&(o+=ll(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 Ll({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){const i=cl(t(r),e);n.push(i.trimStart())}}function $l(e,t){const n=Mc(t)?t.value:t;for(const r of e)if(Nc(r)){if(r.key===t||r.key===n)return r;if(Mc(r.key)&&r.key.value===n)return r}}class Ol extends ol{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ic,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(Nl(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=Nc(e)?e:e&&"object"==typeof e&&"key"in e?new Ml(e.key,e.value):new Ml(e,e?.value);const r=$l(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);Mc(r.value)&&tl(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=$l(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=$l(this.items,e),r=n?.value;return(!t&&Mc(r)?r.value:r)??void 0}has(e){return!!$l(this.items,e)}set(e,t){this.add(new Ml(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)xl(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items)if(!Nc(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})),Pl(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Dl={collection:"map",default:!0,nodeClass:Ol,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(Tc(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Ol.from(e,t,n)};class jl extends ol{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Sc,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Fl(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Fl(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&Mc(r)?r.value:r}has(e){const t=Fl(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Fl(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];Mc(r)&&tl(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(Qc(e,String(r++),t));return n}toString(e,t,n){return e?Pl(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(rl(s,void 0,n))}}return i}}function Fl(e){let t=Mc(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const ql={collection:"seq",default:!0,nodeClass:jl,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>(Pc(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>jl.from(e,t,n)},Bl={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,r)=>kl(e,t=Object.assign({actualString:!0},t),n,r)},Ul={identify:e=>null==e,createNode:()=>new nl(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new nl(null),stringify:({source:e},t)=>"string"==typeof e&&Ul.test.test(e)?e:t.options.nullStr},Vl={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new nl("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Vl.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Wl({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 Kl={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:Wl},Gl={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():Wl(e)}},Yl={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 nl(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Wl},zl=e=>"bigint"==typeof e||Number.isInteger(e),Jl=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Hl(e,t,n){const{value:r}=e;return zl(r)&&r>=0?n+r.toString(t):Wl(e)}const Ql={identify:e=>zl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Jl(e,2,8,n),stringify:e=>Hl(e,8,"0o")},Zl={identify:zl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Jl(e,0,10,n),stringify:Wl},Xl={identify:e=>zl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Jl(e,2,16,n),stringify:e=>Hl(e,16,"0x")},eu=[Dl,ql,Bl,Ul,Vl,Ql,Zl,Xl,Kl,Gl,Yl];function tu(e){return"bigint"==typeof e||Number.isInteger(e)}const nu=({value:e})=>JSON.stringify(e),ru=[Dl,ql].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:nu},{identify:e=>null==e,createNode:()=>new nl(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:nu},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>"true"===e,stringify:nu},{identify:tu,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})=>tu(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:nu}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),iu={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=nl.BLOCK_LITERAL),t!==nl.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===nl.BLOCK_LITERAL?"\n":" ")}return kl({comment:e,type:t,value:a},r,i,s)}};function su(e,t){if(Pc(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Nc(r)){if(Tc(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");const e=r.items[0]||new Ml(new nl(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]=Nc(r)?r:new Ml(r)}}else t("Expected a sequence for this tag");return e}function ou(e,t,n){const{replacer:r}=n,i=new jl(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(Nl(o,a,n))}return i}const au={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:su,createNode:ou};class cu extends jl{constructor(){super(),this.add=Ol.prototype.add.bind(this),this.delete=Ol.prototype.delete.bind(this),this.get=Ol.prototype.get.bind(this),this.has=Ol.prototype.has.bind(this),this.set=Ol.prototype.set.bind(this),this.tag=cu.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(Nc(e)?(r=Qc(e.key,"",t),i=Qc(e.value,r,t)):r=Qc(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=ou(e,t,n),i=new this;return i.items=r.items,i}}cu.tag="tag:yaml.org,2002:omap";const lu={collection:"seq",identify:e=>e instanceof Map,nodeClass:cu,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=su(e,t),r=[];for(const{key:e}of n.items)Mc(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new cu,n)},createNode:(e,t,n)=>cu.from(e,t,n)};function uu({value:e,source:t},n){return t&&(e?du:pu).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const du={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 nl(!0),stringify:uu},pu={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 nl(!1),stringify:uu},fu={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:Wl},hu={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():Wl(e)}},mu={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 nl(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:Wl},gu=e=>"bigint"==typeof e||Number.isInteger(e);function yu(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 wu(e,t,n){const{value:r}=e;if(gu(r)){const e=r.toString(t);return r<0?"-"+n+e.substr(1):n+e}return Wl(e)}const vu={identify:gu,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>yu(e,2,2,n),stringify:e=>wu(e,2,"0b")},bu={identify:gu,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>yu(e,1,8,n),stringify:e=>wu(e,8,"0")},Iu={identify:gu,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>yu(e,0,10,n),stringify:Wl},ku={identify:gu,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>yu(e,2,16,n),stringify:e=>wu(e,16,"0x")};class Eu extends Ol{constructor(e){super(e),this.tag=Eu.tag}add(e){let t;t=Nc(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new Ml(e.key,null):new Ml(e,null);$l(this.items,t.key)||this.items.push(t)}get(e,t){const n=$l(this.items,e);return!t&&Nc(n)?Mc(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=$l(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ml(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(Nl(e,null,n));return i}}Eu.tag="tag:yaml.org,2002:set";const Su={collection:"map",identify:e=>e instanceof Set,nodeClass:Eu,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Eu.from(e,t,n),resolve(e,t){if(Tc(e)){if(e.hasAllNullValues(!0))return Object.assign(new Eu,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function Au(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 xu(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Wl(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 Cu={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})=>Au(e,n),stringify:xu},Tu={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=>Au(e,!1),stringify:xu},Nu={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(Nu.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=Au(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$/,"")},Mu=[Dl,ql,Bl,Ul,du,pu,vu,bu,Iu,ku,fu,hu,mu,iu,lu,au,Su,Cu,Tu,Nu],Pu=new Map([["core",eu],["failsafe",[Dl,ql,Bl]],["json",ru],["yaml11",Mu],["yaml-1.1",Mu]]),_u={binary:iu,bool:Vl,float:Yl,floatExp:Gl,floatNaN:Kl,floatTime:Tu,int:Zl,intHex:Xl,intOct:Ql,intTime:Cu,map:Dl,null:Ul,omap:lu,pairs:au,seq:ql,set:Su,timestamp:Nu},Ru={"tag:yaml.org,2002:binary":iu,"tag:yaml.org,2002:omap":lu,"tag:yaml.org,2002:pairs":au,"tag:yaml.org,2002:set":Su,"tag:yaml.org,2002:timestamp":Nu};function Lu(e,t){let n=Pu.get(t);if(!n){if(!Array.isArray(e)){const e=Array.from(Pu.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=_u[e];if(t)return t;const n=Object.keys(_u).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)})}const $u=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Ou{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?Lu(e,"compat"):e?Lu(null,e):null,this.merge=!!n,this.name="string"==typeof i&&i||"core",this.knownTags=r?Ru:{},this.tags=Lu(t,this.name),this.toStringOptions=o??null,Object.defineProperty(this,Ic,{value:Dl}),Object.defineProperty(this,Ec,{value:Bl}),Object.defineProperty(this,Sc,{value:ql}),this.sortMapEntries="function"==typeof s?s:!0===s?$u:null}clone(){const e=Object.create(Ou.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Du{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ac,{value:bc});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 Gc({version:s}),this.setSchema(s,n),this.contents=void 0===e?null:this.createNode(e,r,n)}clone(){const e=Object.create(Du.prototype,{[Ac]:{value:bc}});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=Rc(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ju(this.contents)&&this.contents.add(e)}addIn(e,t){ju(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=zc(this);e.anchor=!t||n.has(t)?Jc(t||"a",n):t}return new Xc(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=zc(e));const s=Jc(t,i);return i.add(s),s},setAnchors:()=>{for(const e of n){const t=r.get(e);if("object"!=typeof t||!t.anchor||!Mc(t.node)&&!_c(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=rl(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p});return o&&_c(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 Ml(r,i)}delete(e){return!!ju(this.contents)&&this.contents.delete(e)}deleteIn(e){return sl(e)?null!=this.contents&&(this.contents=null,!0):!!ju(this.contents)&&this.contents.deleteIn(e)}get(e,t){return _c(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return sl(e)?!t&&Mc(this.contents)?this.contents.value:this.contents:_c(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!_c(this.contents)&&this.contents.has(e)}hasIn(e){return sl(e)?void 0!==this.contents:!!_c(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=il(this.schema,[e],t):ju(this.contents)&&this.contents.set(e,t)}setIn(e,t){sl(e)?this.contents=t:null==this.contents?this.contents=il(this.schema,Array.from(e),t):ju(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 Gc({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 Gc({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 Ou(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=Qc(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?Hc(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=El(e,t),{commentString:s}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=s(e.commentBefore);n.unshift(cl(t,""))}let o=!1,a=null;if(e.contents){if(Rc(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){const t=s(e.contents.commentBefore);n.push(cl(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=Sl(e.contents,i,()=>a=null,t);a&&(c+=ll(c,"",s(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(Sl(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=s(e.comment);t.includes("\n")?(n.push("..."),n.push(cl(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(cl(s(t),"")))}return n.join("\n")+"\n"}(this,e)}}function ju(e){if(_c(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Fu extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class qu extends Fu{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Bu extends Fu{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Uu=(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 Vu(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 Wu(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(Wu(t.key)||Wu(t.value))return!0}return!1;default:return!0}}function Ku(e,t,n){if("flow-collection"===t?.type){const r=t.end[0];if(r.indent===e&&("]"===r.source||"}"===r.source)&&Wu(t)){n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function Gu(e,t,n){const{uniqueKeys:r}=e.options;if(!1===r)return!1;const i="function"==typeof r?r:(t,n)=>t===n||Mc(t)&&Mc(n)&&t.value===n.value&&!("<<"===t.value&&e.schema.merge);return t.some(e=>i(e.key,n))}const Yu="All mapping items must start at the same column";function zu(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 Ju="Block collections are not allowed within flow collections",Hu=e=>e&&("block-map"===e.type||"block-seq"===e.type);function Qu(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??Ol)(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=Vu(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",Yu)),!f.anchor&&!f.tag&&!d){c=f.end,f.comment&&(o.comment?o.comment+="\n"+f.comment:o.comment=f.comment);continue}(f.hasNewlineAfterProp||Wu(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",Yu);const m=f.end,g=u?e(n,u,f,i):t(n,m,l,null,f,i);n.schema.compat&&Ku(r.indent,u,i),Gu(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Vu(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&&Ku(r.indent,p,i),a=c.range[2];const l=new Ml(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 Ml(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??jl)(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,c=null;for(const{start:s,value:l}of r.items){const u=Vu(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&&Ku(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?Ol:jl))(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=Vu(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&&Wu(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];Nc(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);Hu(p)&&i(g.range,"BLOCK_IN_FLOW",Ju);const y=Vu(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?Hu(h)&&i(w.range,"BLOCK_IN_FLOW",Ju):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const v=new Ml(g,w);if(n.options.keepSourceTokens&&(v.srcToken=l),o){const e=c;Gu(n,e.items,g)&&i(s,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(v)}else{const e=new Ol(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],Hu(h)&&i(r.range,"BLOCK_IN_FLOW",Ju)}}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=zu(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 Zu(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?nl.BLOCK_FOLDED:nl.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===nl.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 Xu(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=nl.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 ed(e)}(s,l);break;case"single-quoted-scalar":a=nl.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return ed(e.slice(1,-1)).replace(/''/g,"'")}(s,l);break;case"double-quoted-scalar":a=nl.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}=td(e,r);n+=t,r=i}else if("\\"===i){let i=e[++r];const s=nd[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+=rd(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=zu(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function ed(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 td(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 nd={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function rd(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 id(e,t,n,r){const{value:i,type:s,comment:o,range:a}="block-scalar"===t.type?Zu(e,t,r):Xu(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[Ec];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[Ec]}(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[Ec];if(t.compat){const o=t.compat.find(e=>e.default&&e.test?.test(n))??t[Ec];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[Ec];let u;try{const s=l.resolve(i,e=>r(n??t,"TAG_RESOLVE_FAILED",e),e.options);u=Mc(s)?s:new nl(s)}catch(e){const s=e instanceof Error?e.message:String(e);r(n??t,"TAG_RESOLVE_FAILED",s),u=new nl(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 sd(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 od={composeNode:ad,composeEmptyNode:cd};function ad(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 Xc(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=zu(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=id(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===Ol.tagName&&"map"===o||s===jl.tagName&&"seq"===o||!o)return Qu(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),Qu(e,t,n,i,s);t.schema.tags.push(Object.assign({},c,{default:!1})),a=c}const c=Qu(e,t,n,i,s,a),l=a.resolve?.(c,e=>i(r,"TAG_RESOLVE_FAILED",e),t.options)??c,u=Rc(l)?l:new nl(l);return u.range=c.range,u.tag=s,a?.format&&(u.format=a.format),u}(od,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=cd(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 cd(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){const u=id(e,{type:"scalar",offset:sd(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 ld(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 ud(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 dd{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=ld(e);r?this.warnings.push(new Bu(i,t,n)):this.errors.push(new qu(i,t,n))},this.directives=new Gc({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=ud(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(_c(i)&&!i.flow&&i.items.length>0){let e=i.items[0];Nc(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:ud(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=ld(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 Du(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Vu(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?ad(l,i,u,o):cd(l,u.end,r,null,u,o);const d=c.contents.range[2],p=zu(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 qu(ld(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 qu(ld(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=zu(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 qu(ld(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 Du(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 pd(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 fd(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 hd(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=hd(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=md(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=md(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=md(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 md({start:e,key:t,sep:n,value:r}){let i="";for(const t of e)i+=t.source;if(t&&(i+=hd(t)),n)for(const e of n)i+=e.source;return r&&(i+=hd(r)),i}const gd=Symbol("break visit"),yd=Symbol("skip children"),wd=Symbol("remove item");function vd(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),bd(Object.freeze([]),e,t)}function bd(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=bd(Object.freeze(e.concat([[i,t]])),s.items[t],n);if("number"==typeof r)t=r-1;else{if(r===gd)return gd;r===wd&&(s.items.splice(t,1),t-=1)}}"function"==typeof r&&"key"===i&&(r=r(t,e))}}return"function"==typeof r?r(t,e):r}vd.BREAK=gd,vd.SKIP=yd,vd.REMOVE=wd,vd.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},vd.parentCollection=(e,t)=>{const n=vd.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 Id="\ufeff",kd="",Ed="",Sd="";function Ad(e){switch(e){case Id:return"byte-order-mark";case kd:return"doc-mode";case Ed:return"flow-error-end";case Sd: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 xd=Object.freeze({__proto__:null,BOM:Id,DOCUMENT:kd,FLOW_END:Ed,SCALAR:Sd,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,a=kl({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 pd(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 Id:return"<BOM>";case kd:return"<DOC>";case Ed:return"<FLOW_END>";case Sd: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 qu([i,i+1],t,r);n(i,t,r)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Xu(e,t,r);case"block-scalar":return Zu({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=kl({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}];pd(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'"':fd(e,c,"double-quoted-scalar");break;case"'":fd(e,c,"single-quoted-scalar");break;default:fd(e,c,"scalar")}},stringify:e=>"type"in e?hd(e):md(e),tokenType:Ad,visit:vd});function Cd(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const Td=new Set("0123456789ABCDEFabcdef"),Nd=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Md=new Set(",[]{}"),Pd=new Set(" ,[]{}\n\r\t"),_d=e=>!e||Pd.has(e);class Rd{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)&&Cd(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]===Id&&(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 kd,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&&Cd(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"doc";if("..."===e&&Cd(this.charAt(3)))return yield*this.pushCount(3),"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Cd(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)&&Cd(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(_d),"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("..."))&&Cd(r[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===r[0]||"}"===r[0])))return this.flowLevel=0,yield Ed,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(_d),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Cd(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=>Cd(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 Sd,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(Cd(t)||e&&Md.has(t))break;n=r}else if(Cd(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&&Md.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&&Md.has(t))break;n=r}return t||this.atEnd?(yield Sd,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(_d))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Cd(t)||e&&Md.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(;!Cd(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(Nd.has(t))t=this.buffer[++e];else{if("%"!==t||!Td.has(this.buffer[e+1])||!Td.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,n=this.pos-1;do{t=this.buffer[++n]}while(" "===t||e&&"\t"===t);const r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class Ld{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(0===t)return{line:0,col:e};return{line:t,col:e-this.lineStarts[t-1]+1}}}}function $d(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Od(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 Dd(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 jd(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 Fd(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 qd(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||$d(t.start,"explicit-key-ind")||$d(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Dd(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 Bd{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 Rd,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=Ad(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&&qd(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===Od(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!==Od(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=Fd(jd(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($d(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(Dd(t.key)&&!$d(t.sep,"newline")){const e=Fd(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($d(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=Fd(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]}):$d(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||$d(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=Fd(jd(t));qd(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=Fd(jd(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=Fd(jd(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 Ud(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new Ld||null,prettyErrors:t}}function Vd(e,t={}){const{lineCounter:n,prettyErrors:r}=Ud(t),i=new Bd(n?.addNewLine),s=new dd(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(const t of o)t.errors.forEach(Uu(e,n)),t.warnings.forEach(Uu(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Wd(e,t={}){const{lineCounter:n,prettyErrors:r}=Ud(t),i=new Bd(n?.addNewLine),s=new dd(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 qu(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(Uu(e,n)),o.warnings.forEach(Uu(e,n))),o}function Kd(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=Wd(e,n);if(!i)return null;if(i.warnings.forEach(e=>Al(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 Gd(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 Du(e,r,n).toString(n)}var Yd=Object.freeze({__proto__:null,Alias:Xc,CST:xd,Composer:dd,Document:Du,Lexer:Rd,LineCounter:Ld,Pair:Ml,Parser:Bd,Scalar:nl,Schema:Ou,YAMLError:Fu,YAMLMap:Ol,YAMLParseError:qu,YAMLSeq:jl,YAMLWarning:Bu,isAlias:xc,isCollection:_c,isDocument:Cc,isMap:Tc,isNode:Rc,isPair:Nc,isScalar:Mc,isSeq:Pc,parse:Kd,parseAllDocuments:Vd,parseDocument:Wd,stringify:Gd,visit:Dc,visitAsync:Fc}),zd=Object.freeze({__proto__:null,Alias:Xc,CST:xd,Composer:dd,Document:Du,Lexer:Rd,LineCounter:Ld,Pair:Ml,Parser:Bd,Scalar:nl,Schema:Ou,YAMLError:Fu,YAMLMap:Ol,YAMLParseError:qu,YAMLSeq:jl,YAMLWarning:Bu,default:Yd,isAlias:xc,isCollection:_c,isDocument:Cc,isMap:Tc,isNode:Rc,isPair:Nc,isScalar:Mc,isSeq:Pc,parse:Kd,parseAllDocuments:Vd,parseDocument:Wd,stringify:Gd,visit:Dc,visitAsync:Fc});class Jd{#ke;constructor(e){this.#ke=e}execute(){return new Promise((e,t)=>{const n=`${this.#ke}.punica/config.yaml`;fetch(n,{method:"GET"}).then(e=>{if(!e.ok)throw new Error(`Failed to load extension config: ${n} (${e.status})`);return e.text()}).then(async t=>{const n=Yd.parse(t);if(n.moduleURL=this.#ke,n.hasCapabilities){const e=`${this.#ke}.punica/capabilities.yaml`;try{const t=await fetch(e,{method:"GET"});if(t.ok){const e=Yd.parse(await t.text());n.capabilities=e??{}}else console.warn(`[Extensions] ${n.name}: hasCapabilities is set but ${e} could not be loaded (${t.status}).`)}catch{n.capabilities={}}}const r=n.instructionClasses;if(Array.isArray(r)&&r.length>0){const e=await Promise.all(r.map(async e=>{const t=`${this.#ke}.punica/instruction-classes/${e}`,n=await fetch(t,{method:"GET"});if(!n.ok)throw new Error(`Failed to load instruction class: ${t} (${n.status})`);return Yd.parse(await n.text())}));n.instructionClasses=e}e(n)}).catch(t)})}}class Hd{#Ie;constructor(e){this.#Ie=e}async execute(){return await this.#Ie.execute()}}class Qd{#n;#Ee;constructor(){this.#n=new Map,this.#Ee=new Set}register(e,t){this.#n.set(e,t)}markKnown(e){this.#Ee.add(e)}handleEvent(e){const[t,n]=e.split(":"),r=this.#n.get(t);if(r){return void new r(n).execute()}this.#Ee.has(t)||console.warn(`Unknown event type: ${t}`)}}class Zd{}class Xd extends Zd{#Se;constructor(e){super(),this.#Se=e}execute(){}}let ep=class extends Hd{#Ae;constructor(e){super(e),this.#Ae=new Qd,this.#Ae.register("onExtension",Xd),this.#Ae.markKnown("onCommand"),this.#Ae.markKnown("onView")}async execute(){const e=await super.execute(),{activationEvents:t}=e;return t&&t.filter(e=>!e.startsWith("onStartup")).forEach(e=>this.#Ae.handleEvent(e)),e}},tp=class extends Hd{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 np(){const e="undefined"!=typeof navigator?navigator:void 0;return/mac/i.test(e?.userAgentData?.platform||e?.platform||e?.userAgent||"")}function rp(e,t=np()){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 ip=class extends Hd{constructor(e){super(e)}async execute(){const e=await super.execute(),{integrations:t}=e;if(t){const{keybindings:e}=t;e&&e.forEach(e=>{if(!e.capability)return void console.warn(`[Keybindings] Missing capability for keybinding: ${e.key}`);const t=e.capability,n=e.key,r=e.when;punica.shell.KeyboardShortcuts.manager.registerShortcut({command:t,keys:[rp(n)],when:r})})}return e}},sp=class extends Hd{constructor(e){super(e)}async execute(){return await super.execute()}};class op extends Hd{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=fc.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}}function ap(e){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){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;r?.id&&n.registerPlacement({viewId:r.id,slot:"primarySidebar",extensionName:e.name,title:r.title??r.name,icon:r.icon,fallbackCommand:r.capability??a?.capability??a?.command});s?.id&&n.registerPlacement({viewId:s.id,slot:"contentSidebar",extensionName:e.name,title:s.title??s.name,icon:s.icon,fallbackCommand:s.capability});if(o?.id){const t=Array.isArray(o.toolbar)?o.toolbar:void 0;cp(e,o,"panel",{order:o.order,panelToolbar:t})}i?.id&&cp(e,i,"secondarySidebar",{})}(e,{primarySidebar:s,secondarySidebar:o,contentSidebar:a,panel:c,activityBar:r})}function cp(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=s?.getSlotOverride?.(t.id),u=l&&c.includes(l)?l:n,d=!1===t.showOnStartup;if(i.registerPlacement({viewId:t.id,slot:u,homeSlot:n,allowedSlots:c,extensionName:e.name,title:t.title??t.name,icon:t.icon,order:r.order,fallbackCommand:t.capability,onDemand:d,panelToolbar:r.panelToolbar}),!d){const e=o?.forSlot?.(u)??("panel"===u?punica.shell?.PanelTabs:null);e?.open?.({id:t.id,title:t.title??t.name??t.id,commandId:t.capability??"",iconClass:t.icon,order:r.order,autoActivate:!1,toolbar:r.panelToolbar})}}let lp=0;function up(){lp++}function dp(){lp>0&&lp--}function pp(){return lp>0}async function fp(e){up();try{return await e()}finally{dp()}}const hp=new class{getExtension(e){const t=punica.extensions.manager.getExtension(e);if(t)return this.#xe(t)}getAllExtensions(){return punica.extensions.manager.getAllExtensions().map(e=>this.#xe(e))}getExtensionCapabilities(e){const t=punica.extensions.manager.getExtension(e);if(!t)return;const n=t.capabilities;return n?Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>{const n=t;return[e,Object.freeze({id:n.id??e,title:n.title,description:n.description,inputs:n.inputs?Object.freeze({schema:n.inputs.schema?Object.freeze(n.inputs.schema):void 0}):void 0,outputs:n.outputs?Object.freeze({schema:n.outputs.schema?Object.freeze(n.outputs.schema):void 0,kind:n.outputs.kind,resultEvent:n.outputs.resultEvent,errorEvent:n.outputs.errorEvent}):void 0,policy:n.policy?Object.freeze({risk:n.policy.risk,approval:n.policy.approval}):void 0,sideEffects:n.sideEffects?Object.freeze([...n.sideEffects]):void 0,requiredContext:n.requiredContext?Object.freeze([...n.requiredContext]):void 0,examples:n.examples?Object.freeze(n.examples.map(e=>Object.freeze({input:e.input,output:e.output,description:e.description}))):void 0,version:n.version,tags:n.tags?Object.freeze([...n.tags]):void 0})]}))):void 0}#xe(e){const t=e.integrations?.configuration?{title:e.integrations.configuration.title,properties:Object.freeze(Object.fromEntries(Object.entries(e.integrations.configuration.properties??{}).map(([e,t])=>{const n=t,r={type:n.type,default:n.default,description:n.description};let 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 mp=new class{#Ce=".punica/settings.json";#Te;#Ne=null;#Me=null;#Pe=new Map;#_e=null;#z=!1;constructor(){if("undefined"!=typeof window&&window.api?.getPath){const e=window.api.getPath("userData");this.#Te=`${e}/settings.json`}else"undefined"!=typeof window&&window.localStorage?this.#Te="localStorage:punica.settings":this.#Te="settings.json"}async load(){this.#z||(await this.#Re(),await this.#Le(),this.#z=!0)}async#Re(){try{if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:",""),t=window.localStorage.getItem(e);if(t){const e=JSON.parse(t);this.#Me=await this.#$e(e)}else this.#Me={version:"1.0",extensions:{},system:{}}}else try{const e=await punica.runtime.fs.readFile(this.#Te),t=JSON.parse(e);this.#Me=await this.#$e(t)}catch{this.#Me={version:"1.0",extensions:{},system:{}}}}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Me={version:"1.0",extensions:{},system:{}}}}async#Le(){try{const e=await punica.runtime.fs.readFile(this.#Ce),t=JSON.parse(e);this.#Ne=await this.#$e(t)}catch(e){if(e?.message?.includes("punica.runtime.fs not available"))throw e;this.#Ne=null}}async save(e="project"){this.#_e&&clearTimeout(this.#_e),this.#_e=window.setTimeout(async()=>{"global"===e?await this.#Oe():await this.#De(),this.#_e=null},500)}async#Oe(){if(this.#Me)if(this.#Te.startsWith("localStorage:")){const e=this.#Te.replace("localStorage:","");window.localStorage.setItem(e,JSON.stringify(this.#Me,null,2))}else try{await punica.runtime.fs.updateFileContent(this.#Te,JSON.stringify(this.#Me,null,2))}catch(e){throw console.error("[Settings] Failed to save global settings:",e),e}}async#De(){this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}});try{await punica.runtime.fs.updateFileContent(this.#Ce,JSON.stringify(this.#Ne,null,2))}catch(e){throw console.error("[Settings] Failed to save project settings:",e),e}}get(e,t){if(!this.#z)return void this.load();if("system"===e){const e=this.#Ne?.system?.[t];if(void 0!==e)return e;const n=this.#Me?.system?.[t];return void 0!==n?n:void 0}const n=this.#Ne?.extensions?.[e]?.[t];if(void 0!==n)return n;const r=this.#Me?.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.#z||await this.load(),"system"===e){const i=this.get(e,t);return"global"===r?(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system||(this.#Me.system={}),this.#Me.system[t]=n,await this.save("global")):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system||(this.#Ne.system={}),this.#Ne.system[t]=n,await this.save("project")),void this.#je(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.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]||(this.#Me.extensions[e]={}),this.#Me.extensions[e][t]=n,await this.save("global")):(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]||(this.#Ne.extensions[e]={}),this.#Ne.extensions[e][t]=n,await this.save("project")),this.#je(e,t,n,s)}getAll(e){if(!this.#z)return this.load(),{};const t=punica.extensions.metadata.manager.getExtension(e),n=t?.configuration?.properties??{},r=this.#Me?.extensions?.[e]??{},i=this.#Ne?.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.#Ne?.system?.[t],i=void 0!==this.#Me?.system?.[t];if(!r&&!i)return;return r&&delete this.#Ne.system[t],i&&delete this.#Me.system[t],r&&await this.#De(),i&&await this.#Oe(),void this.#je(e,t,void 0,n)}const n=punica.extensions.metadata.manager.getExtension(e),r=n?.configuration?.properties?.[t]?.default;void 0===r?(this.#Ne?.extensions?.[e]&&(delete this.#Ne.extensions[e][t],await this.save("project")),this.#Me?.extensions?.[e]&&(delete this.#Me.extensions[e][t],await this.save("global"))):await this.set(e,t,r,"project")}async resetExtension(e){const t=punica.extensions.metadata.manager.getExtension(e);if(t?.configuration?.properties)for(const n of Object.keys(t.configuration.properties))await this.reset(e,n)}getScope(e,t){return this.#z?"system"===e?void 0!==this.#Ne?.system?.[t]?"project":void 0!==this.#Me?.system?.[t]?"global":"default":void 0!==this.#Ne?.extensions?.[e]?.[t]?"project":void 0!==this.#Me?.extensions?.[e]?.[t]?"global":"default":(this.load(),"default")}onDidChange(e,t){return this.#Pe.has(e)||this.#Pe.set(e,new Set),this.#Pe.get(e).add(t),()=>{this.#Pe.get(e)?.delete(t)}}async export(e){this.#z||await this.load();const t=e?.scope??"merged",n={version:this.#Me?.version??"1.0",extensions:{},system:e?.includeSystem?"project"===t?this.#Ne?.system:"global"===t?this.#Me?.system:{...this.#Me?.system,...this.#Ne?.system}:void 0,metadata:{exportedAt:(new Date).toISOString(),source:t}},r=e?.extensions??[...new Set([...Object.keys(this.#Me?.extensions??{}),...Object.keys(this.#Ne?.extensions??{})])];for(const e of r)n.extensions[e]="project"===t?this.#Ne?.extensions?.[e]??{}:"global"===t?this.#Me?.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.#Ne:this.#Me)||("project"===r?this.#Ne={version:"1.0",extensions:{},system:{}}:this.#Me={version:"1.0",extensions:{},system:{}});const e="project"===r?this.#Ne:this.#Me;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.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.extensions[e]=n.extensions[e]):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.extensions[e]=n.extensions[e]));else"project"===r?this.#Ne={...this.#Ne,...n,version:this.#Ne?.version??"1.0"}:this.#Me={...this.#Me,...n,version:this.#Me?.version??"1.0"};n.system&&("project"===r?(this.#Ne||(this.#Ne={version:"1.0",extensions:{},system:{}}),this.#Ne.system=n.system):(this.#Me||(this.#Me={version:"1.0",extensions:{},system:{}}),this.#Me.system=n.system))}await this.save(r)}async#$e(e){return e.version,e}#je(e,t,n,r){const i=this.#Pe.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}})}},gp="system",yp="ui.language",wp="en";const vp=new class{#Fe=new Map;#Pe=new Set;#qe=null;#Be=new Set;#Ue=new Map;getLocale(){return this.#qe??=this.#Ve(),this.#qe}supportedLocales(){const e=this.#We()?.supported;return Array.isArray(e)&&e.length?e:[wp]}async setLocale(e){const t=String(e||"").trim();if(t&&t!==this.getLocale()){try{await punica.extensions.settings.manager.set(gp,yp,t,"global")}catch(e){throw e instanceof Error?e:new Error(String(e))}this.#qe=t,this.#Ke(t)}}onDidChange(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}#Ke(e){for(const t of[...this.#Pe])try{t(e)}catch{}}#We(){try{return punica.shell?.Profile?.manager?.registry?.getActive?.()?.localization}catch{return}}#Ve(){const e=this.supportedLocales();try{const t=punica.extensions?.settings?.manager?.get?.(gp,yp);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.#We()?.default;return t&&e.includes(t)?t:e.includes(wp)?wp:e[0]}refresh(){const e=this.#Ve();e!==this.#qe&&(this.#qe=e,this.#Ke(e))}register(e,t){e&&t&&this.#Fe.set(e,t)}t(e,t,n){const r=this.#Ge(e,t,n?.count);return void 0===r?(this.#Ye(`${e}:${t}`,e,t),t):n?r.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):r}#Ge(e,t,n){const r=this.#Fe.get(e);if(!r)return;const i=[],s=e=>{e&&!i.includes(e)&&i.push(e)};s(this.getLocale()),s(this.#We()?.default),s(wp);const o=[];"number"==typeof n&&Number.isFinite(n)&&o.push(`${t}.${this.#ze(this.getLocale(),n)}`,`${t}.other`),o.push(t);for(const e of i){const t=r[e];if(t)for(const e of o){const n=t[e];if("string"==typeof n)return n}}}#ze(e,t){let n=this.#Ue.get(e);if(!n){try{n=new Intl.PluralRules(e)}catch{n=new Intl.PluralRules(wp)}this.#Ue.set(e,n)}return n.select(t)}#Ye(e,t,n){this.#Be.has(e)||(this.#Be.add(e),console.warn(`[i18n] missing message "${n}" for ${t} (${this.getLocale()})`))}resetForTesting(){this.#Fe.clear(),this.#Pe.clear(),this.#qe=null,this.#Be.clear(),this.#Ue.clear()}};function bp(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 Ip=new Map;function kp(e){const t=Ip.get(e)??document.getElementById(e);t&&(t.parentElement?t.parentElement.removeChild(t):t.remove()),Ip.delete(e)}const Ep={register(e,t,n){const r=n?.target??document.head,i=Ip.get(e)??document.getElementById(e);if(i)return n?.overwrite&&(i.textContent=t),Ip.set(e,i),{id:e,dispose(){kp(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),Ip.set(e,s),{id:e,dispose(){kp(e)}}},unregister(e){kp(e)},has:e=>!!Ip.has(e)||!!document.getElementById(e)};const Sp={manager:new class{#Je;#He;#Qe;#Ze;#Xe;#et;#tt;#nt;#rt;constructor(){this.#Je=new Map,this.#He=new Map,this.#Qe=new Map,this.#Ze=new Map,this.#Xe=new Set,this.#et=new Set,this.#tt=new Map,this.#nt=new Map,this.#rt=new Map}getRuntimeState(e){return this.#He.get(e)}registerBuiltinCapabilities(e){const t=Array.isArray(e)?e:[];for(const e of t){const t=String(e?.id??""),n=String(e?.extensionName??""),r=e?.definition??{};if(!t)throw new Error("[Extensions] registerBuiltinCapabilities: Missing id");if(!n)throw new Error(`[Extensions] registerBuiltinCapabilities: Missing extensionName (id="${t}")`);const i=this.#nt.get(t);if(i&&i.extensionName!==n)throw new Error(`[Extensions] Built-in capability id collision "${t}" between "${i.extensionName}" and "${n}".`);this.#nt.set(t,{id:t,extensionName:n,definition:r})}}#it(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.#nt.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.#nt.set(t,i)}this.#st(e,n)}}#st(e,t){const n=Zo.lintAll(Object.values(t));let r=0;for(const t of n)for(const n of t.issues)"error"===n.severity?console.warn(`[Extensions] capability lint [${e.name}] ${n.message}`):"warning"===n.severity&&r++;r>0&&console.warn(`[Extensions] capability lint [${e.name}]: ${r} authoring warning(s) — run capability.lint for detail`)}#ot(e){const t=e.instructionClasses;if(!Array.isArray(t)||0===t.length)return;const n=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;if(n){for(const r of t)try{n.register(r,e.name)}catch(e){console.error(`[Extensions] IC register failed ${r?.id}:`,e)}console.log(`[Extensions] Registered ${t.length} instruction class(es) from "${e.name}"`)}}async load(e,...t){try{const n=[e,...t],r=await Promise.allSettled(n.map(e=>(e=>{const t=new Jd(e),n=new tp(t),r=new ip(n),i=new sp(r),s=new op(i);return new ep(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.#Je.set(r.name,r),this.#He.set(r.name,"loaded"),this.#it(r),this.#ot(r);try{ap(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.#Xe.add(r.name),i.includes("onStartup:finish")&&this.#et.add(r.name),i.filter(e=>e.startsWith("onCommand:")).forEach(e=>{const t=e.slice(10);if(!t)return;let n=this.#tt.get(t);n||(n=new Set,this.#tt.set(t,n)),n.add(r.name)})})}catch(e){console.error(e)}}async activate(e,t){if("active"===this.#He.get(e))return;const n=this.#Qe.get(e);if(n)return n;if(!this.#Je.get(e))return void console.error(`Extension "${e}" not found.`);const r=function(e){const t=e?.reason??"host",n=e?.presentation??("capability"===t||"extension"===t?"headless":"interactive");return{reason:t,trigger:e?.trigger,presentation:n}}(t),i=this.#at(e,r);this.#Qe.set(e,i);try{await i}finally{this.#Qe.delete(e)}}async#at(e,t){this.#He.set(e,"activating"),bp("extension.lifecycle.activating",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation});try{const n=(e=>{const t=new hc(e),n=new yc(t),r=new wc(n);return new gc(r)})(e),r=await n.execute();if(!r||!r.module||"function"!=typeof r.module.activate)throw new Error(`Failed to activate extension "${e}". The "activate" method is missing or invalid.`);{const n=this.#ct(e,t);"headless"===t.presentation?await fp(()=>r.module.activate(n)):await r.module.activate(n);const i=this.#Ze.get(e);i&&(i.module=r.module),this.#He.set(e,"active"),bp("extension.lifecycle.activated",{extensionName:e,reason:t.reason,trigger:t.trigger,presentation:t.presentation})}}catch(n){throw this.#He.set(e,"failed"),bp("extension.lifecycle.activationFailed",{extensionName:e,reason:t.reason,trigger:t.trigger,error:n instanceof Error?n.message:String(n)}),console.error(`Error activating extension "${e}":`,n),n}}#ct(e,t){const n=[];this.#Ze.set(e,{subscriptions:n});return{activation:Object.freeze({reason:t.reason,trigger:t.trigger,presentation:t.presentation}),subscriptions:n,capabilities:{registerHandler:(t,n)=>{this.#rt.set(t,{extensionName:e,fn:n})}},ui:{registerViewProvider:(t,r)=>{const i=globalThis.punica?.shell?.Views?.manager;if(!i?.registerProvider)return console.warn(`[Extensions] shell.Views unavailable — view provider "${t}" not registered (${e}).`),{dispose(){}};const s=i.registerProvider(t,r,e);return n.push(s),s},reveal:async(t,n)=>{await async function(e,t,n){const r=globalThis,i=r.punica?.runtime?.capabilities?.gateway;if(i?.call){const s=r.punica?.kernel?.Events?.manager,o=s?.createCorrelationId?.()??`ext-reveal-${Date.now()}`;return void await i.call("shell.revealView",{viewId:e,focus:n?.focus??!1},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:o},policy:{mode:"execute"}})}const s=r.punica?.shell?.Views?.manager;if(!s?.reveal)throw new Error(`[Extensions] Cannot reveal "${e}": neither the capability gateway nor shell.Views is available.`);await s.reveal(e,{kind:"extension",id:t})}(t,e,n)},hide:async t=>{await async function(e,t){const n=globalThis,r=n.punica?.runtime?.capabilities?.gateway;if(r?.call){const i=n.punica?.kernel?.Events?.manager,s=i?.createCorrelationId?.()??`ext-hide-${Date.now()}`;return void await r.call("shell.hideView",{viewId:e},{sessionId:"default",actor:{type:"extension",extensionName:t},origin:{kind:"command",id:`extension:${t}`},trace:{traceId:s},policy:{mode:"execute"}})}const i=n.punica?.shell?.Views?.manager;if(!i?.hide)throw new Error(`[Extensions] Cannot hide "${e}": neither the capability gateway nor shell.Views is available.`);i.hide(e,{kind:"extension",id:t})}(t,e)},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.#lt(this.#Xe,"startup:begin")}async startupFinish(){await this.#lt(this.#et,"startup:finish")}async#lt(e,t){for(const n of e)try{await this.activate(n,{reason:t})}catch(e){console.error(`Error activating extension "${n}" on${t}:`,e)}}getExtension(e){return this.#Je.get(e)}getAllExtensions(){return Array.from(this.#Je.values())}getCapability(e){return this.#nt.get(e)?.definition}listCapabilities(){return Array.from(this.#nt.values())}validateCapabilityInput(e,t){const n=this.getCapability(e);if(!n)return{ok:!0};const r=n.inputs?.schema;if(!r)return{ok:!0};const i=si().validate(r,t);return i.ok?{ok:!0}:{ok:!1,errors:i.errors}}registerCapabilityHandler(e,t){this.#rt.set(e,{fn:t})}async executeCapability(e,t,n){const r=this.#nt.get(e);if(!r)throw new Pr(Mr.CAPABILITY_NOT_FOUND,`Extension capability "${e}" is not registered in any loaded extension`,{capability:e});if("active"!==this.#He.get(r.extensionName))try{await this.activate(r.extensionName,{reason:"capability",trigger:e,presentation:"headless"})}catch(t){throw new Pr(Mr.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.#rt.get(e);if(!i)throw new Pr(Mr.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.#He.get(e))return;const t=this.#Je.get(e);this.#He.set(e,"deactivating");try{const n=globalThis.punica?.shell?.Views?.manager;try{n?.unmountByExtension?.(e)}catch(t){console.warn(`[Extensions] view unmount failed for "${e}":`,t)}try{const n=this.#Ze.get(e)?.module??t?.module;n?.deactivate?.()}catch(t){console.warn(`[Extensions] module.deactivate() failed for "${e}":`,t)}const r=this.#Ze.get(e);if(r){for(const t of r.subscriptions)try{t.dispose()}catch(t){console.warn(`[Extensions] subscription dispose failed for "${e}":`,t)}this.#Ze.delete(e)}for(const[t,n]of this.#rt)n.extensionName===e&&this.#rt.delete(t)}finally{this.#He.set(e,"loaded"),bp("extension.lifecycle.deactivated",{extensionName:e})}}async unload(e){const t=this.#He.get(e);if(void 0===t)return;if("loaded"!==t&&"failed"!==t)throw new Error(`[Extensions] cannot unload "${e}" while ${t} — deactivate() it first.`);try{const t=globalThis.punica?.kernel?.llm?.manager?.api?.instructionClassRegistry;t?.unregisterByOrigin?.(e)}catch(t){console.warn(`[Extensions] instruction-class unregister failed for "${e}":`,t)}for(const[t,n]of this.#nt)n.extensionName===e&&this.#nt.delete(t);for(const[t,n]of this.#tt)n.delete(e)&&0===n.size&&this.#tt.delete(t);const n=this.#Je.get(e)?.integrations?.views;if(n){const t=globalThis.punica?.shell;try{n.activityBar?.id&&t?.ActivityBar?.manager?.removeItem?.(n.activityBar.id),n.statusBar?.id&&t?.Statusbar?.manager?.removeItem?.(n.statusBar.id),n.panel?.id&&t?.PanelTabs?.close?.(n.panel.id)}catch(t){console.warn(`[Extensions] UI contribution retract failed for "${e}":`,t)}}this.#Xe.delete(e),this.#et.delete(e),this.#Qe.delete(e),this.#Ze.delete(e),this.#Je.delete(e),this.#He.delete(e),bp("extension.lifecycle.unloaded",{extensionName:e})}async reload(e,t,n){if(await this.deactivate(e),await this.unload(e),await this.load(t),"loaded"!==this.#He.get(e))throw new Error(`[Extensions] reload failed: "${e}" did not load from ${t}`);await this.activate(e,n??{reason:"host",trigger:e})}getExtensionsForCommand(e){const t=this.#tt.get(e);return t?Array.from(t):[]}},Styles:Ep,metadata:{manager:hp},settings:{manager:mp},i18n:{manager:vp}};function Ap(e){if(null==e)return!1;if(Array.isArray(e))return e.some(Ap);if("object"==typeof e){const t=e;return!("string"!=typeof t.$ref||!t.$ref.startsWith("node-output:"))||Object.values(t).some(Ap)}return!1}function xp(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=Cp(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=Cp(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?Ap(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 Cp(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 Tp{packages=new Map;testReports=new Map;async discover(){this.packages.clear();try{if(!await Un().getCurrent())return void console.warn("[NodeRegistry] No workspace available");const e=ci();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[NodeRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return Np(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[NodeRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n),i=xp(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 Np(e,t){for(const n of e)n.isDirectory?n.children&&Np(n.children,t):n.path.startsWith(".punica/ivy-nodes/")&&(n.name.endsWith(".ivy.node")||"ivy.node.json"===n.name)&&t.push(n.path)}let Mp;function Pp(){return Mp||(Mp=new Tp),Mp}function _p(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 Rp(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 Lp(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 $p=/token|secret|key|password|passwd|api[_-]?key/i;function Op(e){const t={};let n=0,r=!1;for(const i of Object.keys(e)){const s=$p.test(i)?"[REDACTED]":e[i],o=i.length+JSON.stringify(s??null).length;n+o>16e3?r=!0:(n+=o,t[i]=s)}return r&&(t.__truncated__=!0),t}async function Dp(e,t){const n=Date.now(),r=Pp().get(e);if(!r)throw new Error(`IvyNode not found: ${e}`);const i=xp(r.manifest);if(!i.ok)throw new Error(`Invalid manifest: ${i.issues.map(e=>e.message).join(", ")}`);const s=r.manifest;if(Ap(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=_p(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 Rp(k,E,s,t.timeoutMs),n=Op(Lp(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()}}function jp(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Fp(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"array":typeof e}function qp(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Bp(e,t){const n=e.value;switch(e.type){case"isType":return{passed:Fp(t)===String(n??""),expected:String(n??""),actual:Fp(t)};case"equals":return{passed:qp(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=>qp(e,n)),expected:JSON.stringify(n),actual:JSON.stringify(t)}:{passed:!1,expected:String(n??""),actual:Fp(t)};case"hasProperty":return{passed:null!==t&&"object"==typeof t&&!Array.isArray(t)&&String(n??"")in t,expected:String(n??""),actual:Fp(t)};case"arrayLength":return{passed:Array.isArray(t)&&t.length===Number(n),expected:String(n??""),actual:Array.isArray(t)?String(t.length):Fp(t)};case"greaterThan":return{passed:"number"==typeof t&&t>Number(n),expected:`> ${n}`,actual:String(t)};case"lessThan":return{passed:"number"==typeof t&&t<Number(n),expected:`< ${n}`,actual:String(t)};case"between":{const e=Array.isArray(n)?n:[];return{passed:"number"==typeof t&&2===e.length&&t>=Number(e[0])&&t<=Number(e[1]),expected:JSON.stringify(n),actual:String(t)}}default:return{passed:!0,expected:`unsupported matcher: ${e.type}`,actual:Fp(t)}}}function Up(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=jp(t,n);let o;const a=i.matcher;if(a&&"object"==typeof a)o=Bp(a,r);else if("string"==typeof a)o=Bp({type:a,value:i.expected},r);else{if(void 0===i.expected)continue;o=Bp({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 Vp(e,t,n){const r=!0===e.assertions?.expectsError,i=e.assertions?.errorPattern;let s;return s=r?i?new RegExp(i).test(t)?"pass":"fail":"pass":n?.infrastructure?"error":"fail",{status:s,error:t,assertions:{error:{passed:r,expected:i,actual:t}}}}function Wp(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 Kp(){return Date.now()}function Gp(e,t=2){try{return JSON.stringify(e,null,t)}catch{return JSON.stringify({error:"Failed to stringify"},null,t)}}function Yp(e,t=300){const n=String(e??"").replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t)+"…":n}function zp(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function Jp(){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 Hp(){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 Qp(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 Zp(e){try{const n=Jp();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 Xp(e,n){const r=Jp();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 ef(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:Kp(),source:i?.source??"flow:engine",kind:n},payload:r})}const tf=new Set(["sensitive","secret"]);function nf(e){if(null==e)return 0;if("string"==typeof e)return e.length;try{return JSON.stringify(e).length}catch{return 0}}function rf(e,t,n,r){if(!function(e,t,n){return!(!n||!tf.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:nf(e)}}const sf=new class{#ut=new Map;acquire(e,t,n){const r=Number.isFinite(t)&&t>=0?t:0;if("number"!=typeof n||n<0)return this.#ut.set(e,(this.#ut.get(e)??0)+r),!0;const i=this.#ut.get(e)??0;return!(i+r>n)&&(this.#ut.set(e,i+r),!0)}used(e){return this.#ut.get(e)??0}release(e){this.#ut.delete(e)}reset(){this.#ut.clear()}};class of{async ensureBase(){await Zp(".punica"),await Zp(zp(".punica","workflow-runs"))}async ensureRunDirs(e){await this.ensureBase(),await Zp(zp(".punica","workflow-runs",e)),await Zp(zp(".punica","workflow-runs",e,"artifacts"))}async writeArtifact(e,t,n){const r=punica.kernel.Events.manager.createCorrelationId(),i=Kp();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=rf(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=zp(".punica","workflow-runs",e,"artifacts",`${r}.${d?"txt":"json"}`);let f;f=d?String(u??""):Gp(l??{},2);const h=n.sizeBudget?.maxBytes;if(c||"number"!=typeof h)"number"==typeof h&&sf.acquire(e,f.length,h);else{sf.acquire(e,f.length,h)||(c=function(e,t){return{redacted:!0,reason:"budget",surface:e,originalBytes:t}}(s,f.length),f=Gp(c,2),sf.acquire(e,f.length,h))}await Xp(p,f);const m=f.length,g=Yp(d?String(u??""):Gp(l??{},0),400),y={id:r,runId:e,stepId:t,type:n.type,createdAtMs: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 ef("workflow.artifactCreated",e,"info",{artifact:y},{traceId:e}),y}}function af(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 cf(e){for(const t of e.nodes.values())if("completed"!==t.status&&"failed"!==t.status)return!1;return!0}function lf(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 uf(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 df(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 pf(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/\.\//g,"/").replace(/^\//,"")}function ff(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 hf(e,t,n){const r=ff(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 mf(e,t){const n=ff(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 gf(e,t){const n=ff(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 yf(e,t=".punica"){const n=pf(t,"workflow-runs",e.runId),r=pf(n,"checkpoint.json"),i=pf(n,"checkpoint.json.tmp"),s=JSON.stringify(e,null,2);await mf("writeCheckpoint",n),await hf("writeCheckpoint",i,s);try{await async function(e,t,n){const r=ff(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 gf("writeCheckpoint",r)}catch{}await hf("writeCheckpoint",r,s);try{await gf("writeCheckpoint",i)}catch{}}}async function wf(e,t=".punica"){const n=pf(t,"workflow-runs",e,"checkpoint.json");try{const e=await async function(e,t){const n=ff(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 vf(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 bf{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:Kp(),startedAtMs:Kp(),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=lf(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}),ef("workflow.runStarted",a,"info",{run:{...u,status:"RUNNING"}},{traceId:c,spanId:l}),vf({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",ef("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 wf(e);if(!n)return!1;{const r=n.dependencyGraphState?lf(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"),ef("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=Kp();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 ef("workflow.runUpdated",e,"info",{runId:e,patch:{status:"CANCELLED",endedAtMs:n.run.endedAtMs}},{traceId:n.run.traceId,spanId:n.rootSpanId}),ef("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=zp(".punica","workflow-runs",e,"run.json");await Xp(n,Gp({run:t.run,spec:t.spec},2))}async persistIndex(){await this.artifactStore.ensureBase();const e=zp(".punica","workflow-runs","index.json"),t=this.listRuns({limit:500});await Xp(e,Gp({version:1,updatedAtMs:Kp(),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 yf(n)}async loadIndex(){await this.artifactStore.ensureBase();const e=zp(".punica","workflow-runs","index.json"),n=await async function(e){const n=Jp();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);ef("workflow.runLoaded","workflow","info",{runs:Array.isArray(e?.runs)?e.runs:[]},{traceId:"workflow",source:"flow:engine"})}catch{}}}class If{runs;pendingByCorrelation;pendingToRunStep;persistRun;persistIndex;resumeRunLoop;constructor(e,t,n,r,i,s){this.runs=e,this.pendingByCorrelation=t,this.pendingToRunStep=n,this.persistRun=r,this.persistIndex=i,this.resumeRunLoop=s}setupApprovalSubscription(){punica.kernel.Events.manager.subscribe("policy.approvalRequested",e=>{const t=e?.event?.payload?e.event:e,n=t?.envelope?.correlationId;if(!n)return;const r=this.pendingToRunStep.get(n);if(!r)return;const i=t?.payload??{},s=i?.request??{},o=i?.context??{},a=`wfpa_${n}`,c={pendingId:a,attemptCorrelationId:n,kind:String(s?.kind??"capability"),id:String(s?.id??""),risk:String(s?.risk??"low"),approval:String(s?.approval??"once"),reason:"string"==typeof s?.reason?s.reason:void 0,workspaceId:"string"==typeof o?.workspaceId?o.workspaceId:void 0,timestampMs:Kp()};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:Kp(),resolved:!1},ef("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",ef("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}),ef("workflow.pendingApprovalAdded",l.run.runId,"info",{runId:l.run.runId,stepId:r.stepId,pending:c},{traceId:l.run.traceId,spanId:l.rootSpanId}),vf({name:"flow.approval.requested",correlationId:l.run.runId,traceId:l.run.traceId,payload:{runId:l.run.runId,stepId:r.stepId,pendingId:c.pendingId,attemptCorrelationId:n,capability:{kind:c.kind,id:c.id},risk:c.risk,approval:c.approval,workspaceId:c.workspaceId}}),this.persistRun(l.run.runId)}})}approvePending(e){const t=String(e?.pendingId??"");if(!t)return!1;const n=e?.scope??"once",r=Array.from(this.pendingByCorrelation.values()).find(e=>e.pendingId===t);if(!r)return!1;const i=this.pendingToRunStep.get(r.attemptCorrelationId);if(!i)return!1;try{punica.kernel.Policy.manager.recordApproval({kind:r.kind,id:r.id},n,{workspaceId:r.workspaceId})}catch{}ef("workflow.pendingApprovalResolved",i.runId,"info",{runId:i.runId,stepId:i.stepId,pendingId:t,decision:"approved",scope:n,timestampMs:Kp()},{traceId:i.runId}),vf({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",ef("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;ef("workflow.pendingApprovalResolved",r.runId,"info",{runId:r.runId,stepId:r.stepId,pendingId:t,decision:"rejected",timestampMs:Kp()},{traceId:r.runId}),vf({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=Kp(),ef("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}),ef("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 kf=3e4,Ef={maxAttempts:0,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitter:"none",retryOnTimeout:!1};const Sf=new class{#le=new Map;getSemaphore(e,t){let n=this.#le.get(e);return n||(n={count:0,max:t,queue:[]},this.#le.set(e,n)),n}async acquire(e,t){const n=this.getSemaphore(e,t);if(!(n.count<n.max))return new Promise((e,t)=>{n.queue.push({resolve:e,reject:t})});n.count++}release(e,t){const n=this.#le.get(e);if(!n)return;n.count--;const r=n.queue.shift();r&&(n.count++,r.resolve())}};function Af(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Execution timeout after ${e}ms`))},e)})}function xf(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 Cf=new class{#dt=new Map;register(e,t){this.#dt.set(e,t)}get(e){return this.#dt.get(e)}resolveOrThrow(e){const t=this.#dt.get(e.ref.kind);if(!t)throw new Error(`No executor registered for node ref.kind: "${e.ref.kind}" (node id: ${e.id})`);return t}clear(){this.#dt.clear()}};function Tf(e,t){let n=e;for(const e of t){if(null==n)return;if("object"!=typeof n)return;if(Array.isArray(n)){const t=Number(e);if(!Number.isInteger(t)||t<0||t>=n.length)return;n=n[t];continue}if(!Object.prototype.hasOwnProperty.call(n,e))return;n=n[e]}return n}function Nf(e,t){if(!e||"object"!=typeof e)return{ok:!1,reason:"invalid-ref"};if("literal"===e.kind)return{ok:!0,value:e.value};if("path"===e.kind){const n=String(e.path??"").split(".").filter(e=>e.length>0);if(0===n.length)return{ok:!1,reason:"invalid-ref"};const[r,...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=Tf(s,i);return void 0===o?{ok:!1,reason:"missing-path"}:{ok:!0,value:o}}return{ok:!1,reason:"invalid-ref"}}function Mf(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 Pf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _f(e){return String(e??"").split(".").filter(e=>e.length>0)}function Rf(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){const n=t[e];Pf(r[n])||(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function Lf(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={...Pf(e.defaults)?e.defaults:{},...Pf(i)?i:{}};for(const e of r){const t=n.get(e.fromId),r=e.fromPath?_f(e.fromPath):[],i=r.length?Tf(t,r):t;if(void 0===i)continue;const o=e.toPath?_f(e.toPath):[];o.length?Rf(s,o,i):Pf(i)?Object.assign(s,i):s[e.fromId]=i}return s}class $f extends Error{code="RUN_CANCELLED";runId;mode;constructor(e,t){super(`Run ${e??"<unknown>"} was cancelled (${t??"best-effort"} mode) — substrate refuses to continue in-flight node attempts.`),this.name="RunCancelledError",this.runId=e,this.mode=t}}function Of(e,t){if(function(e){return!0===e.cancelled}(e))throw new $f(e.run?.runId,t)}class Df{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=Jp();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",ef("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=Kp(),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}),ef("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}),vf({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:Lf(o,n.spec.graph.edges,n.nodeOutputs??new Map)});void 0!==s.output&&n.nodeOutputs&&n.nodeOutputs.set(o.id,s.output),ef("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}),vf({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",ef("workflow.stepUpdated",e,"info",{runId:e,stepId:a.stepId,patch:{status:"WAITING_APPROVAL"}},{traceId:r,spanId:u,parentSpanId:i}),n.run.status="WAITING_APPROVAL",ef("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=Kp(),a.error={message:o},ef("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}),vf({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=Kp(),n.run.error={message:o,nodeId:s,correlationId:c},ef("workflow.runUpdated",e,"error",{runId:e,patch:{status:"FAILED",endedAtMs:n.run.endedAtMs,error:n.run.error}},{traceId:r,spanId:i}),ef("workflow.runFinished",e,"error",{runId:e,status:"FAILED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),vf({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=xf(h,l);"RUNNING"!==a.status&&(a.status="RUNNING"),a.status="RETRYING",ef("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=Kp(),ef("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:n.run.endedAtMs}},{traceId:r,spanId:i}),ef("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:n.run.endedAtMs},{traceId:r,spanId:i}),vf({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=pf(n,"workflow-runs",e.runId),i=pf(r,"run.json"),s=JSON.stringify({run:e,spec:t},null,2);await mf("writeRunHistory",r),await hf("writeRunHistory",i,s)}(n.run,n.spec),await async function(e,t=".punica"){const n=pf(t,"workflow-runs",e,"checkpoint.json");try{await gf("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;!cf(n);){if(r.cancelled)return;if(r.paused)return;const c=o-(r.inFlightNodes?.size??0),l=af(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=>{df(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 uf(o,!1,n);if(c.disabled)return l.status="SKIPPED",r.inFlightNodes?.delete(o),void uf(o,!0,n);try{const a=this.prepareNodeExecutionConfig(c,r),u=a.retry,d=u?.maxAttempts??0,p=a.timeoutMs;let f=l.attempt??0,h=!1;for(;f<=d&&!h;){Of(r),f++,l.attempt=f,l.status="RUNNING",l.startedAtMs=Kp();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:Lf(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 $f)throw l.status="CANCELLED",l.endedAtMs=Kp(),e;const t=String(e?.message??e);if(f<=d){const e=xf(f,a);l.status="RETRYING",await new Promise(t=>setTimeout(t,e));continue}throw l.status="FAILED",l.endedAtMs=Kp(),l.error={message:t},e}}h&&(uf(o,!0,n),await this.persistRun(e))}catch(t){uf(o,!1,n),t instanceof $f||(r.run.status="FAILED",r.run.endedAtMs=Kp(),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=Kp(),ef("workflow.runUpdated",e,"info",{runId:e,patch:{status:"COMPLETED",endedAtMs:r.run.endedAtMs}},{traceId:i,spanId:s}),ef("workflow.runFinished",e,"info",{runId:e,status:"COMPLETED",endedAtMs:r.run.endedAtMs},{traceId:i,spanId:s}),vf({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&&(vf({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=Cf.get(e.ref.kind),r=n?.prepareExecutionConfig?.(e)?.capabilityDefaults;return function(e,t){const n={timeoutMs:kf,retry:{...Ef},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=Cf.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,Af(t)])}(n,r.timeoutMs):await n;return t.status="SUCCESS",t.endedAtMs=Kp(),t.outputsPreview=i.outputsPreview,t.artifactIds=i.artifactIds??[],i}finally{s&&s()}}async executeNode(e,t){return Cf.resolveOrThrow(e).execute(e,t,{artifactStore:this.artifactStore})}}class jf extends Error{code="SUBFLOW_DEPTH_EXCEEDED";parentDepth;cap;constructor(e,t=8){super(`Subflow depth ${e+1} exceeds substrate cap (${t}). Substrate refuses to spawn deeper subflows — restructure the flow or reduce nesting before retrying.`),this.name="SubflowDepthExceededError",this.parentDepth=e,this.cap=t}}function Ff(e,t=8){const n=function(e){return("number"==typeof e&&e>=0?e:0)+1}(e);if(n>t)throw new jf(e??0,t);return n}const qf="__default__";class Bf{workspaceId;#pt=new Map;#ft=new Map;#ht=new Map;#mt=new of;#gt=!1;#yt=new Map;#wt;#vt;#bt;constructor(e=qf){this.workspaceId=e,this.#wt=new bf(this.#pt,this.#yt,this.#mt),this.#vt=new If(this.#pt,this.#ft,this.#ht,e=>this.#wt.persistRun(e),()=>this.#wt.persistIndex(),e=>this.#It(e)),this.#bt=new Df(this.#pt,this.#ht,this.#yt,this.#mt,e=>this.#wt.persistRun(e),e=>this.#wt.persistCheckpoint(e),()=>this.#wt.persistIndex(),(e,t)=>this.notifyTerminal(e,t))}initialize(){this.#gt||(this.#gt=!0,this.#vt.setupApprovalSubscription(),this.#wt.loadIndex())}async startRun(e){const t=await this.#wt.startRun(e);return this.#It(t.runId,{workspaceId:t.workspaceId}),{runId:t.runId}}async pauseRun(e){return this.#wt.pauseRun(e)}async resumeRun(e){const t=await this.#wt.resumeRun(e);return t&&this.#It(e,{}),t}async cancelRun(e,t){return this.#wt.cancelRun(e,t)}getRun(e){return this.#wt.getRun(e)}listRuns(e){return this.#wt.listRuns(e)}approvePending(e){return this.#vt.approvePending(e)}rejectPending(e){return this.#vt.rejectPending(e)}hasRun(e){return this.#pt.has(e)}getNodeOutput(e,t){const n=this.#pt.get(e);if(n)return n.nodeOutputs?.get(t)}async runSubflow(e){const t=Ff(e.parentDepth);if(!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const n=(await this.#wt.startRun({spec:e.spec,workspaceId:e.workspaceId,filePathOrUri:e.filePathOrUri,input:e.input})).runId;vf({name:"flow.subflow.spawned",correlationId:n,traceId:e.parentTraceId,payload:{runId:n,depth:t,parentRunId:e.parentRunId,parentTraceId:e.parentTraceId,workspaceId:this.workspaceId,flowId:e.spec.id}});const r=new Promise(e=>{const t=this.#kt.get(n);if(t)return this.#kt.delete(n),void e(t);this.#Et.set(n,e)});this.#It(n,{workspaceId:this.workspaceId});const 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.#Et.get(e);if(n)return this.#Et.delete(e),void n(t);this.#kt.set(e,t)}#Et=new Map;#kt=new Map;hasPending(e){return this.#ht.has(e)}async#It(e,t){const n=this.#pt.get(e);if(!n)return;if("COMPLETED"===n.run.status||"FAILED"===n.run.status||"CANCELLED"===n.run.status)return;if(n.paused)return;if("WAITING_APPROVAL"===n.run.status)return;const r=void 0!==n.dependencyGraph,i=n.dependencyGraph;r&&i?await this.#bt.executeParallel(e,t,i,n):await this.#bt.executeSequential(e,t)}}const Uf=new Map,Vf=new Map,Wf=new Map;function Kf(e){const t=e??qf;let n=Uf.get(t);return n||(n=new Bf(t),Uf.set(t,n)),n}let Gf=!1;const Yf=new class{initialize(){if(Gf)return;Gf=!0;const e=punica.kernel.Commands.manager;e.registerCommand(ot.WORKFLOW.RUN_START,{title:"Workflow: Start Run",execute:e=>{this.startRun(e).catch(e=>{console.error("[FlowEngine] startRun failed",e)})}}),e.registerCommand(ot.WORKFLOW.RUN_PAUSE,{title:"Workflow: Pause Run",execute:e=>this.pauseRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_RESUME,{title:"Workflow: Resume Run",execute:e=>this.resumeRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_CANCEL,{title:"Workflow: Cancel Run",execute:e=>this.cancelRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_GET,{title:"Workflow: Get Run",execute:e=>this.getRun(e)}),e.registerCommand(ot.WORKFLOW.RUN_LIST,{title:"Workflow: List Runs",execute:e=>this.listRuns(e)}),e.registerCommand(ot.WORKFLOW.APPROVAL_APPROVE,{title:"Workflow: Approve Pending",execute:e=>this.approvePending(e)}),e.registerCommand(ot.WORKFLOW.APPROVAL_REJECT,{title:"Workflow: Reject Pending",execute:e=>this.rejectPending(e)}),e.registerCommand(ot.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:qf}(e),n=Kf(t);n.initialize();const r=await n.startRun(e);return Vf.set(r.runId,t),r}async pauseRun(e){const t=this.#St(e);return!!t&&t.pauseRun(e)}async resumeRun(e){const t=this.#St(e);return!!t&&t.resumeRun(e)}async cancelRun(e,t){const n=this.#St(e);return!!n&&n.cancelRun(e,t)}getRun(e){const t=this.#St(e);return t?t.getRun(e):null}getNodeOutput(e,t){const n=this.#St(e);if(n)return n.getNodeOutput(e,t)}listRuns(e){const t=[];for(const n of Uf.values())t.push(...n.listRuns({status:e?.status}));return"number"==typeof e?.limit&&e.limit>0?t.slice(0,e.limit):t}approvePending(e){const t=this.#At(e.pendingId);return!!t&&t.approvePending(e)}rejectPending(e){const t=this.#At(e.pendingId);return!!t&&t.rejectPending(e)}async runSubflow(e){if(Ff(e?.parentDepth),!e||!e.spec)throw new Error("[FlowEngine] runSubflow: input.spec (WorkflowDocument) is required");const t=Kf(e.workspaceId);t.initialize();const n=await t.runSubflow(e);return Vf.set(n.runId,t.workspaceId),n}#St(e){const t=Vf.get(e);if(t)return Uf.get(t);for(const[t,n]of Uf.entries())if(n.hasRun(e))return Vf.set(e,t),n}#At(e){const t=Wf.get(e);if(t)return Uf.get(t);for(const[t,n]of Uf.entries())if(n.hasPending(e))return Wf.set(e,t),n}};function zf(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 Jf(e){const t=e;return!(!t||"object"!=typeof t)&&("IvyAgent"===t.kind||Boolean(t.graph&&t.capability?.id))}class Hf{packages=new Map;async discover(){this.packages.clear();try{if(!await Un().getCurrent())return void console.warn("[AgentRegistry] No workspace available");const e=ci();let t;try{t=await e.getFileTree()}catch(e){return void console.warn("[AgentRegistry] Failed to get file tree:",e)}const n=function(e){const t=[];return Qf(e,t),t}(t);await Promise.all(n.map(t=>this.loadManifest(e,t)))}catch(e){console.error("[AgentRegistry] Discovery failed:",e)}}async loadManifest(e,t){try{const n=await e.readFile(t),r=JSON.parse(n);if(!Jf(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 Qf(e,t){for(const n of e)n.isDirectory?n.children&&Qf(n.children,t):n.path.startsWith(".punica/ivy-agents/")&&("ivy.agent.json"===n.name||n.name.endsWith(".ivy.agent"))&&t.push(n.path)}let Zf;function Xf(){return Zf||(Zf=new Hf),Zf}const eh=new Set(["COMPLETED","FAILED","CANCELLED"]);function th(e){return new Promise(t=>setTimeout(t,e))}async function nh(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&&(eh.has(n)||"WAITING_APPROVAL"===n))return{record:i,timedOut:!1};await th(250)}return{record:i,timedOut:!0}}async function rh(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(Vp(n,`startRun failed: ${t}`))}const{record:c,timedOut:l}=await nh(e,a,r);if(l){try{await e.cancelRun(a)}catch{}return o(Vp(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(Vp(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(Up(n,t),t)}const d=c?.steps?.find(e=>"FAILED"===e.status);return o(Vp(n,c?.error?.message??d?.error?.message??`Run ended with status ${u??"unknown"}`))}const ih={validator:{validate:xp},registry:{discover:()=>Pp().discover(),get:e=>Pp().get(e),list:()=>Pp().list(),search:e=>Pp().search(e),setTestReport:(e,t)=>Pp().setTestReport(e,t),getLatestTestReport:e=>Pp().getLatestTestReport(e)},runner:{run:Dp},test:{run:async function(e,t){const n=Pp(),r=n.get(e);if(!r){if(t?.manifest){if(Jf(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=Yf,o=zf(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 rh(s,o,e,n,t?.workspaceId))}const l=Wp({capabilityId:r,version:String(n?.capability?.version??"0.0.0"),tier:i.tier,results:c,startedAtMs:a});try{Pp().setTestReport(r,l)}catch{}return l}(t.manifest);throw new Error(`Manifest for ${e} is not a testable IvyAgent (expected kind 'IvyAgent' with a graph).`)}throw new Error(`IvyNode not found: ${e}`)}const i=r.manifest,s=i.tests;if(!s)throw new Error(`No test specification found for node: ${e}`);const o=Date.now(),a=[];for(const t of s.cases||[]){if(t.skip){a.push({caseId:t.id,status:"skip",durationMs:0,error:"string"==typeof t.skip?t.skip:void 0});continue}const n=Date.now();let r;try{const i=await Dp(e,{input:t.input,runId:`test-${e}-${t.id}-${Date.now()}`,timeoutMs:s.timeoutMs||3e4}),o=i.events.filter(e=>"error"===e.type).map(e=>{const t=e.data;return t?.message||""}).join(" "),a=Up(t,i.output,o);r={caseId:t.id,status:a.status,durationMs:Date.now()-n,output:i.output,assertions:a.assertions}}catch(e){const i=Vp(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=Wp({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}}},sh={discover:()=>Xf().discover(),get:e=>Xf().get(e),list:()=>Xf().list(),search:e=>Xf().search(e),unregister:e=>Xf().unregister(e),run:(e,t)=>async function(e,t){const n=Xf().get(e);if(!n)throw new Error(`IvyAgent not found: ${e}`);const r=t?.engine??Yf,i=t?.timeoutMs??3e4,s=zf(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 nh(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:zf,isAgentManifest:Jf},oh=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",[]]]),ah=new Set(["COMPLETED","FAILED","CANCELLED"]);const ch=new class{canTransitionTo(e,t){if(e===t)return!1;const n=oh.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 oh.get(e)??[]}isTerminal(e){return ah.has(e)}},lh=["workflow.stepStarted","workflow.stepUpdated","workflow.stepFinished"],uh={PENDING:"waiting",WAITING_APPROVAL:"waiting",PAUSED:"waiting",RUNNING:"running",RETRYING:"running",SUCCESS:"completed",FAILED:"error"};const dh={cardWidth:220,horizontalGap:140,verticalGap:40,marginX:60,marginY:80};function ph(e){return{x:dh.marginX+e%6*240,y:dh.marginY+120*Math.floor(e/6)}}function fh(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 hh(e,t){const n={...dh,...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]=ph(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]=ph(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,fh(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 mh;function gh(e){if(!mh)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 mh}function yh(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");mh=e}function wh(){mh=void 0}function vh(){return mh}function bh(e){return gh("createFlowRenderer").createRenderer(e)}function Ih(e){return gh("createViewportController").createViewportController(e)}function kh(e,t){return gh("attachZoomControl").attachZoomControl(e,t)}function Eh(e,t){return gh("attachMinimap").attachMinimap(e,t)}function Sh(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 Ah={setRendererProvider:yh,resetRendererProvider:wh,getRendererProvider:vh,createFlowRenderer:bh,createViewportController:Ih,attachZoomControl:kh,attachMinimap:Eh,mergeViewSnapshotIntoNotebook:Sh,computeFlowLayout:hh,gridFallbackPosition:ph,get rendererProvider(){return mh}},xh=Object.freeze({__proto__:null,attachMinimap:Eh,attachZoomControl:kh,computeFlowLayout:hh,createFlowRenderer:bh,createViewportController:Ih,default:Ah,getRendererProvider:vh,gridFallbackPosition:ph,mergeViewSnapshotIntoNotebook:Sh,resetRendererProvider:wh,setRendererProvider:yh});function Ch(e,t,n){return{path:e,message:t,severity:"error",code:n}}function Th(e,t,n){return{path:e,message:t,severity:"warning",code:n}}const Nh="WF_INVALID_VERSION",Mh="WF_INVALID_EDGE_REF",Ph=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function _h(e){return"string"==typeof e&&Ph.test(e)}const Rh=new class{#xt=new Map;register(e,t){if("string"!=typeof e||0===e.length)throw new Error("LambdaRegistry.register: id must be a non-empty string");if("function"!=typeof t)throw new Error("LambdaRegistry.register: fn must be a function");this.#xt.set(e,t)}unregister(e){return this.#xt.delete(e)}get(e){return this.#xt.get(e)}list(){return Array.from(this.#xt.keys())}clear(){this.#xt.clear()}},Lh={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}},$h={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}},Oh={id:"dep-cycle",severity:"error",check(e){const t=e.graph.nodes.filter(e=>!e.disabled),n=new Set(t.map(e=>e.id)),r=new Map,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}},Dh={id:"idempotency-required-but-no-key",severity:"error",check(e,t){if(!t.getCapability)return[];const n=[];for(let r=0;r<e.graph.nodes.length;r++){const 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 jh(e){if("ivyNode"!==e.kind&&"workflow"!==e.kind)return;const t=e.id;return"string"==typeof t&&t.length>0?t:void 0}function Fh(e,t){if(!e)return;if(!t)return e;const n=t.split(".").filter(e=>e.length>0);let r=e;for(const e of n){if(!r||"object"!=typeof r)return;r=r.properties?.[e]}return r}const qh={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=jh(o.ref),l=jh(a.ref);if(!c||!l)continue;const u=t.getCapability(c),d=t.getCapability(l);if(!u||!d)continue;const p=u.outputs?.schema,f=d.inputs?.schema;if(!p||!f)continue;const h=Fh(p,s.fromPath),m=Fh(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}},Bh=["while","forEach"],Uh={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(!Bh.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 Vh(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+Vh(e.inline,t,o);if(a>r&&(r=a),r>t)return r}return r}const Wh={id:"subflow-depth-exceeded",severity:"error",check(e,t){const n="number"==typeof t.maxSubflowDepth?t.maxSubflowDepth:8,r=[],i=e.id??"<root>",s=Vh(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}},Kh=[Lh,$h,Oh,Dh,qh,Uh,Wh];const Gh=new class{#fe=new Map;constructor(){this.reset()}lint(e,t){const n=[],r=t??{};for(const t of this.#fe.values())try{const 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.#fe.set(e.id,e)}unregister(e){return this.#fe.delete(e)}list(){return Array.from(this.#fe.keys())}reset(){this.#fe.clear();for(const e of Kh)this.#fe.set(e.id,e)}};function Yh(e,t,n){if(t===n)return[];const r=new Map;for(const t of e.values()){const e=r.get(t.from)??[];e.push(t),r.set(t.from,e)}const 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 zh(e){return e.map(e=>`${e.from}=>${e.to}`)}function Jh(e,t){return`${e}=>${t}`}const Hh=new class{#Ct=new Map;register(e){if(!e||"function"!=typeof e.transform)throw new Error("MigrationRegistry.register: transformer must have a transform(doc) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("MigrationRegistry.register: transformer.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("MigrationRegistry.register: transformer.to must be a non-empty string");if(e.from===e.to)throw new Error("MigrationRegistry.register: transformer.from must differ from transformer.to (no self-edges)");this.#Ct.set(Jh(e.from,e.to),e)}unregister(e,t){return this.#Ct.delete(Jh(e,t))}find(e,t){return this.#Ct.get(Jh(e,t))}list(){return Array.from(this.#Ct.values())}clear(){this.#Ct.clear()}migrate(e){return function(e,t){const n=e.policy??"reject",r=e.document.version,i=e.targetVersion;if(!_h(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(!_h(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)=>Yh(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:zh(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:zh(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:zh(a)}}return{ok:!0,document:o,appliedTransformers:zh(a),fromVersion:r,toVersion:i}}(e,this)}__plan(e,t){return Yh(this.#Ct,e,t)}};function Qh(){return Date.now()}class Zh{#he=new Map;#Pe=new Set;register(e,t){if(!e||"string"!=typeof e.id||0===e.id.length)throw new Error("ManualTriggerProvider.register: trigger.id must be a non-empty string");if("string"!=typeof e.kind||0===e.kind.length)throw new Error("ManualTriggerProvider.register: trigger.kind must be a non-empty string");if("string"!=typeof e.flowId||0===e.flowId.length)throw new Error("ManualTriggerProvider.register: trigger.flowId must be a non-empty string");if("function"!=typeof t)throw new Error("ManualTriggerProvider.register: callback must be a function");const n={trigger:e,callback:t,unsubscribed:!1};return this.#he.set(e.id,n),this.#Ke({type:"registered",triggerId:e.id,kind:e.kind,ts:Qh()}),{triggerId:e.id,unsubscribe:()=>{if(n.unsubscribed)return;n.unsubscribed=!0;this.#he.get(e.id)===n&&(this.#he.delete(e.id),this.#Ke({type:"unregistered",triggerId:e.id,ts:Qh()}))}}}unregister(e){const t=this.#he.get(e);return!!t&&(t.unsubscribed=!0,this.#he.delete(e),this.#Ke({type:"unregistered",triggerId:e,ts:Qh()}),!0)}list(){return Array.from(this.#he.values()).map(e=>e.trigger)}subscribe(e){return this.#Pe.add(e),()=>{this.#Pe.delete(e)}}async fire(e,t){const n=this.#he.get(e);if(!n||n.unsubscribed||n.trigger.disabled)return!1;const r=`manual-${Qh()}-${Math.floor(1e6*Math.random())}`,i=Qh();this.#Ke({type:"fired",triggerId:e,ts:i,payload:t,correlationId:r}),vf({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.#Ke({type:"error",triggerId:e,ts:Qh(),error:{message:String(t?.message??t)}}),!1}}clear(){for(const e of this.#he.values())e.unsubscribed=!0;this.#he.clear(),this.#Pe.clear()}#Ke(e){for(const t of this.#Pe)try{t(e)}catch(e){console.warn("[ManualTriggerProvider] subscriber listener threw:",e)}}}const Xh=new Zh;let em=Xh;const tm={get manager(){return em},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()");em!==e&&em instanceof Zh&&em.clear(),em=e},resetProvider(){em instanceof Zh&&em.clear(),em=Xh}};function nm(e,t){return`${e}=>${t}`}const rm={migrators:new class{#Tt=new Map;register(e){if(!e||"function"!=typeof e.migrate)throw new Error("CheckpointMigratorRegistry.register: migrator must have a migrate(checkpoint) function");if("string"!=typeof e.from||0===e.from.length)throw new Error("CheckpointMigratorRegistry.register: migrator.from must be a non-empty string");if("string"!=typeof e.to||0===e.to.length)throw new Error("CheckpointMigratorRegistry.register: migrator.to must be a non-empty string");if(e.from===e.to)throw new Error("CheckpointMigratorRegistry.register: migrator.from must differ from migrator.to");this.#Tt.set(nm(e.from,e.to),e)}unregister(e,t){return this.#Tt.delete(nm(e,t))}find(e,t){return this.#Tt.get(nm(e,t))}list(){return Array.from(this.#Tt.values())}clear(){this.#Tt.clear()}},isFresh:function(e,t,n=Date.now()){if("number"!=typeof e||Number.isNaN(e))return!1;if(!t||"number"!=typeof t.maxAgeMs)return!0;if(t.maxAgeMs<0)return!0;const r=n-e;return r>=0&&r<=t.maxAgeMs}},im={...ih,agents:sh,engine:{manager:Yf,statusStateMachine:ch,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=uh[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(lh,s)}catch{}return()=>{try{o?.()}catch{}o=null}}},shell:xh,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(Ch("apiVersion",'apiVersion must equal "ivy.workflow/v0.1"',Nh)),{ok:!1,errors:n,warnings:r};if("Workflow"!==e.kind)return n.push(Ch("kind",'kind must equal "Workflow"',Nh)),{ok:!1,errors:n,warnings:r};const o=e.version;if(!_h(o)){const e=Ch("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(Ch("graph","graph is required and must be an object")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.nodes))return n.push(Ch("graph.nodes","graph.nodes must be an array")),{ok:!1,errors:n,warnings:r};if(!Array.isArray(e.graph.edges))return n.push(Ch("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(Ch(`graph.nodes[${t}].id`,"id is required")),r&&(l.has(r)&&n.push(Ch(`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(Ch(`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(Ch(`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(Ch(`graph.nodes[${t}].ref.primitive`,`ref.primitive must be one of: ${e.join(", ")}`))}}else n.push(Ch(`graph.nodes[${t}].ref.kind`,"ref.kind is required"))}else n.push(Ch(`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(Ch("graph.nodes","flow-input node is required when edges reference it")),f&&!d&&n.push(Ch("graph.nodes","flow-output node is required when edges reference it")),e.graph.entryNodeId&&l.has(e.graph.entryNodeId)||n.push(Ch("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(Ch(`graph.edges[${t}].fromId`,"fromId is required")),i||n.push(Ch(`graph.edges[${t}].toId`,"toId is required")),r&&!l.has(r)&&n.push(Ch(`graph.edges[${t}].fromId`,`fromId "${r}" must reference a node.id`,Mh)),i&&!l.has(i)&&n.push(Ch(`graph.edges[${t}].toId`,`toId "${i}" must reference a node.id`,Mh))}),"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(Ch("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(Th(`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?Ch:Th)(`graph.nodes[${t}].ref.id`,`Capability "${a}" not found in the unified registry — flow references must exist in at least one origin (extension / instruction-class / ivy-node)`,"WF_UNKNOWN_CAPABILITY"))}),{ok:0===n.length,errors:n,warnings:r}},primitives:{lambdas:Rh,linter:Gh,migrations:Hh,checkpoints:rm},triggers:tm},sm=[];function om(e){sm.push(e)}function am(){const e={};for(const t of sm)t.moduleFactories&&Object.assign(e,t.moduleFactories);return e}function cm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function lm(e){return"string"==typeof e}function um(e){return"string"==typeof e&&e.trim().length>0}function dm(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}const pm=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"]),fm=new Set(["light","dark","auto"]),hm=new Set(["compact","comfortable"]),mm=new Set(["core","extension","instruction-class","ivy-node","ivy-agent","mcp"]);const gm=new class{validate(e){const t=[];if(!cm(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)}`),cm(e.identity)?(um(e.identity.id)||t.push("identity.id must be a non-empty string"),um(e.identity.name)||t.push("identity.name must be a non-empty string"),um(e.identity.version)||t.push("identity.version must be a non-empty string")):t.push("identity must be an object"),cm(e.shell)){if(Array.isArray(e.shell.activeModules)){const n=Object.keys(am()),r=new Set([...pm,...n]);e.shell.activeModules.forEach((e,n)=>{lm(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&&(cm(e.shell.layout)?(um(e.shell.layout.id)||t.push("shell.layout.id must be a non-empty string"),cm(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(cm(e.theme)?(fm.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||hm.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"),cm(e.capabilities)){const n=e.capabilities.allowedIds;"*"===n||dm(n)||t.push("capabilities.allowedIds must be '*' or string[]"),void 0===e.capabilities.deniedIds||dm(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)=>{lm(e)&&mm.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 ym;function wm(e){ym=e}function vm(){return ym??gm}function bm(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 Im{#Nt=new Map;#Mt;register(e){if(this.#Nt.has(e.identity.id))throw new Error(`ApplicationProfile '${e.identity.id}' is already registered`);this.#Nt.set(e.identity.id,e),void 0===this.#Mt&&(this.#Mt=e.identity.id)}get(e){return this.#Nt.get(e)}getActive(){if(void 0===this.#Mt||!this.#Nt.has(this.#Mt))throw new Error("No ApplicationProfile is currently active. Call loadProfile() before bootstrapping.");return this.#Nt.get(this.#Mt)}setActive(e){if(!this.#Nt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered`);this.#Mt=e}switchProfile(e){if(!this.#Nt.has(e))throw new Error(`ApplicationProfile '${e}' is not registered. Register it first.`);return this.#Mt=e,bm({name:"shell.profile.switched",payload:{profileId:e}}),{reloadRequired:!0}}has(e){return this.#Nt.has(e)}list(){return Array.from(this.#Nt.values())}}const km={manager:new class{registry=new Im;get validator(){return vm()}loadProfile(e){if("string"==typeof e){if(this.registry.has(e))return void this.registry.setActive(e);let t;try{t=JSON.parse(e)}catch{throw new Error(`loadProfile: '${e}' is not a registered profile id and could not be parsed as JSON`)}return void this.#Pt(t)}this.#Pt(e)}#Pt(e){const t=this.validator.validate(e);if(!t.valid)throw bm({name:"shell.profile.load_failed",payload:{errors:t.errors}}),new Error(`ApplicationProfile validation failed:\n ${t.errors.join("\n ")}`);this.registry.has(t.profile.identity.id)||this.registry.register(t.profile),this.registry.setActive(t.profile.identity.id),bm({name:"shell.profile.applied",payload:{profileId:t.profile.identity.id}})}getActiveModules(){return new Set(this.registry.getActive().shell.activeModules)}}};class Em{name=st.EXTENSIONS.MANAGER;version="1.0.0";dependencies=[st.KERNEL.COMMANDS,st.KERNEL.EVENTS,st.RUNTIME.WORKSPACE];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.COMMANDS),s=r.getState(st.KERNEL.EVENTS),o=r.getState(st.RUNTIME.WORKSPACE),a=r.getState(st.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 Sm{name=st.FLOW.VALIDATOR;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel)throw new Error("Kernel not available");if(!t.flow?.validateWorkflowDocument)throw new Error("Flow validator not available")}async start(e){}}function Am(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 xm{prepareExecutionConfig(e){const t=Am(e);if(!t)return{};const n=Hp(),r=n?.getSpec?.(t);return{capabilityDefaults:Qp(r)}}async acquireResources(e,t,n){const r=Am(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 Sf.acquire(n,e.concurrency.max),()=>{Sf.release(n,e.concurrency.max)}}(t,{workspaceId:n.workspaceId,capabilityId:r})}async execute(e,t,n){const r=e.data,i=Am(e),s=void 0!==t.resolvedInput?t.resolvedInput:r?.input;if(!i)throw new Error("capabilityId missing for capability.call node");const o=Jp();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=Hp(),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:Yp(Gp(c??{},0),320),artifactIds:[p.id],output:c??null}}}function Cm(e){return e.data??{}}function Tm(e){return e.nodeOutputs??new Map}async function Nm(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:Yp(Gp(i,0),320),artifactIds:[s.id]}}class Mm{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=Cm(e),i=Nf(r.predicate,Tm(t));if(!i.ok)throw new Error(`[primitive:if] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s={taken:Mf(i.value)?"then":"else",predicate:i.value,thenBodyFlowId:r.thenBodyFlowId??null,elseBodyFlowId:r.elseBodyFlowId??null};return{...await Nm(n,t,e,"if",s),output:s}}(e,t,n);case"else":return async function(e,t,n){const r={marker:"else"};return{...await Nm(n,t,e,"else",r),output:r}}(e,t,n);case"forEach":return async function(e,t,n){const r=Cm(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=Nf(r.collection,Tm(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 Nm(n,t,e,"forEach",l),output:l}}(e,t,n);case"while":return async function(e,t,n){const r=Cm(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=Nf(r.predicate,Tm(t));if(!i.ok)throw new Error(`[primitive:while] predicate did not resolve (${i.reason}) on node "${e.id}"`);const s=Mf(i.value),o={bodyFlowId:r.bodyFlowId,maxIterations:r.maxIterations,initialPredicate:s,initialPredicateValue:i.value};return{...await Nm(n,t,e,"while",o),output:o}}(e,t,n);case"try":return async function(e,t,n){const r=Cm(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 Nm(n,t,e,"try",i),output:i}}(e,t,n);case"catch":return async function(e,t,n){const r={marker:"catch"};return{...await Nm(n,t,e,"catch",r),output:r}}(e,t,n);case"finally":return async function(e,t,n){const r={marker:"finally"};return{...await Nm(n,t,e,"finally",r),output:r}}(e,t,n);case"lambda":return async function(e,t,n){const r=Cm(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=Rh.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=Nf(r.input,Tm(t));if(!n.ok)throw new Error(`[primitive:lambda] input did not resolve (${n.reason}) on node "${e.id}"`);o=n.value}const a=await 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:Yp(Gp(a??{},0),320),artifactIds:[c.id],output:a}}(e,t,n);default:throw new Error(`[PrimitiveExecutor] unknown primitive kind: "${String(r)}" on node "${e.id}"`)}}}class Pm{async execute(e,t){return{output:t.runInput??null}}}class _m{async execute(e,t){return{output:t.resolvedInput??null}}}let Rm=!1;class Lm{name=st.FLOW.ENGINE;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.KERNEL.POLICY,st.KERNEL.COMMANDS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.EVENTS),s=r.getState(st.KERNEL.POLICY),o=r.getState(st.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(Rm||(Cf.register("ivyNode",new xm),Cf.register("primitive",new Mm),Cf.register("flowInput",new Pm),Cf.register("flowOutput",new _m),Rm=!0),!n.flow?.engine?.manager?.initialize)throw new Error("Flow Engine manager not available");n.flow.engine.manager.initialize()}async start(e){}}class $m{name=st.FLOW.SHELL;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Om{name=st.KERNEL.EVENTS;version="1.0.0";dependencies=[];#we=e.CREATED;#l=null;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Events?.manager)throw new Error("Events manager not available");this.#l=t.kernel.Events.manager}async start(e){}get api(){return this.#l}}class Dm{name=st.KERNEL.COMMANDS;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Commands?.manager)throw new Error("Commands manager not available")}async start(e){}}class jm{name=st.KERNEL.POLICY;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Fm{name=st.KERNEL.HISTORY;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.History?.manager)throw new Error("History manager not available")}async start(e){}}class qm{name=st.KERNEL.TIME_SERVER;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.TimeServer?.manager)throw new Error("TimeServer manager not available")}async start(e){}}class Bm{name=st.KERNEL.TASKS;version="1.0.0";dependencies=[st.RUNTIME.TERMINALS,st.RUNTIME.WORKSPACE];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.RUNTIME.TERMINALS),s=r.getState(st.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 Um{name=st.KERNEL.NOTIFICATIONS;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.kernel?.Notifications?.manager)throw new Error("Notifications manager not available")}async start(e){}}class Vm{name=st.KERNEL.AI;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.KERNEL.POLICY,st.KERNEL.LLM];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.EVENTS),s=r.getState(st.KERNEL.POLICY),o=r.getState(st.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 Wm=class{name=st.KERNEL.LLM;version="1.0.0";dependencies=[st.KERNEL.EVENTS,st.KERNEL.POLICY];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t,i=r.getState(st.KERNEL.EVENTS),s=r.getState(st.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:kn,enumerable:!0,configurable:!0,writable:!1})}catch{}}async start(e){}};class Km{name=st.RUNTIME.FS;version="1.0.0";dependencies=[];#we=e.CREATED;get state(){return this.#we}async bootstrap(e){const{punica:t}=e;if(!t.runtime)throw new Error("Runtime not available")}async start(e){}}class Gm{name=st.RUNTIME.SEARCH;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Ym{name=st.RUNTIME.VCS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 zm{name=st.RUNTIME.WORKSPACE;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Jm{name=st.RUNTIME.LLM;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Hm{name=st.RUNTIME.TASKS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Qm{name=st.RUNTIME.SECRETS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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 Zm{name=st.RUNTIME.TERMINALS;version="1.0.0";dependencies=[st.KERNEL.EVENTS];#we=e.CREATED;get state(){return this.#we}async bootstrap(t){const{punica:n,registry:r}=t;if(r.getState(st.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){}}function Xm(){const e=punica.runtime;if(e&&"object"==typeof e){const t="capabilities"in e?e.capabilities:void 0;if(t&&"object"==typeof t&&"gateway"in t)return t.gateway}}function eg(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 tg(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 ng(e,n,r){const i=punica.kernel.Events.manager,s=r?.__punica??{},o=s.correlationId??i.createCorrelationId(),a=s.traceId??o;return{sessionId:"default",workspaceId:await t(),actor:{type:"user",id:void 0},origin:{kind:n,id:e,extension:void 0},trace:{traceId:a,parentSpanId:s.parentSpanId},policy:{mode:"execute"}}}function rg(){const e=(e,t)=>{punica.kernel.Commands.manager.registerCommand(e,t)};e("workspace.readFile",{title:"Core: workspace.readFile",execute:async(e,t)=>{try{const n=String(e?.path??""),r=Xm();if(!r)throw new Error("[CoreCapabilities] Capability gateway not available");eg("capability.workspace.readFile.result",t,{path:n,content:await r.call("workspace.readFile",{path:n},await ng("workspace.readFile","command",t))})}catch(e){tg("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=Xm();if(!i)throw new Error("[CoreCapabilities] Capability gateway not available");await i.call("workspace.writeFile",{path:n,content:r},await ng("workspace.writeFile","command",t)),eg("capability.workspace.writeFile.result",t,{path:n,ok:!0})}catch(e){tg("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();eg("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){tg("capability.workspace.listFiles.error",t,{error:String(e?.message??e)})}}}),e("vcs.status",{title:"Core: vcs.status",execute:async(e,t)=>{try{eg("capability.vcs.status.result",t,{status:await punica.runtime.capabilities.gateway.call("vcs.status",{},await ng("vcs.status","command",t))})}catch(e){tg("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;eg("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 ng("tasks.runCommand","command",t))})}catch(e){tg("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?eg("capability.llm.invoke.result",t,r):tg(n,t,r),r}catch(r){const i={ok:!1,error:String(r?.message??r),metadata:{instructionClass:e?.instructionClass??"unknown",role:"unknown"}};return tg(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?eg("capability.llm.plan.result",t,r):tg(n,t,r)}catch(e){tg(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)");eg(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 In(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 eg(n,t,i)}else eg(n,t,i);else tg(r,t,i)}catch(e){tg(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?eg("capability.llm.edit-workflow.result",t,r):tg(n,t,r)}catch(e){tg(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 ng("shell.toggleSlot","command",n))}catch(t){console.error(`[CoreCapabilities] toggleSlot("${e}") failed:`,String(t?.message??t))}};e(ot.SHELL.TOGGLE_PANEL,{title:"View: Toggle Panel",category:"View",execute:t("panel")}),e(ot.SHELL.TOGGLE_PRIMARY_SIDEBAR,{title:"View: Toggle Primary Side Bar",category:"View",execute:t("primarySidebar")}),e(ot.SHELL.TOGGLE_SECONDARY_SIDEBAR,{title:"View: Toggle Secondary Side Bar",category:"View",execute:t("secondarySidebar")})}console.log("[Punica] Module loading started...");const ig="1.0.0",sg=An,og={},ag=fc,cg=Sp,lg=im,ug=new class{#_t=new Map;#Rt=new Map;#Lt=new Map;register(t){if(this.#_t.has(t.name))throw new Error(`Module ${t.name} already registered`);for(const e of t.dependencies)if(!this.#_t.has(e))throw new Error(`Module ${t.name} depends on ${e}, but ${e} is not registered. Register dependencies before dependent modules.`);this.#_t.set(t.name,t),this.#Rt.set(t.name,e.CREATED)}get(e){return this.#_t.get(e)}getAll(){return Array.from(this.#_t.values())}resolveBootstrapOrder(){return this.#$t()}resolveStartOrder(){return this.#$t()}#$t(){const e=new Set,t=new Set,n=[],r=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.#_t.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.#_t.keys())e.has(t)||r(t);return n}async bootstrapAll(){const t=this.resolveBootstrapOrder();console.log(`[ModuleRegistry] Bootstrap order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);try{this.#Rt.set(n,e.BOOTSTRAPPING),console.log(`[ModuleRegistry] Bootstrapping ${n}...`);const r={phase:"bootstrap",punica:globalThis.punica,registry:this};await t.bootstrap(r),this.#Rt.set(n,e.BOOTSTRAPPED),console.log(`[ModuleRegistry] ✓ ${n} bootstrapped`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Rt.set(n,e.BOOTSTRAP_FAILED),this.#Lt.set(n,r),console.error(`[ModuleRegistry] ✗ ${n} bootstrap failed:`,r),new Error(`Critical module ${n} failed to bootstrap: ${r.message}`)}}console.log("[ModuleRegistry] All modules bootstrapped successfully")}async startAll(){const t=this.resolveStartOrder();console.log(`[ModuleRegistry] Start order: ${t.join(" → ")}`);for(const n of t){const t=this.#_t.get(n);if(!t)throw new Error(`Module ${n} not found in registry`);const r=this.#Rt.get(n);if(r!==e.BOOTSTRAPPED)throw new Error(`Cannot start ${n} - not bootstrapped (state: ${r})`);try{this.#Rt.set(n,e.STARTING),console.log(`[ModuleRegistry] Starting ${n}...`);const r={phase:"start",punica:globalThis.punica,registry:this};await t.start(r),this.#Rt.set(n,e.STARTED),console.log(`[ModuleRegistry] ✓ ${n} started`)}catch(t){const r=t instanceof Error?t:new Error(String(t));throw this.#Rt.set(n,e.START_FAILED),this.#Lt.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.#Rt.get(n)===e.STARTED&&this.#Rt.set(n,e.READY)}console.log("[ModuleRegistry] All modules started successfully")}getState(e){return this.#Rt.get(e)}areAllModulesReady(){for(const[t,n]of this.#_t){if(this.#Rt.get(t)!==e.READY)return!1}return!0}getError(e){return this.#Lt.get(e)}detectPreBootstrapAccess(){const e=[],t=[];for(const n of this.#_t.keys())t.includes(n)&&e.push(n);return e}};function dg(){try{console.log("[Punica] Starting initialization...");const e=globalThis.punica??{version:ig,kernel:sg,shell:og,runtime:ag,extensions:cg,flow:lg};globalThis.punica=e,"undefined"!=typeof window&&(window.punica=e),e.registerShell=om;const t=e.debug??{};t.logTrinityCatalog=Ca,t.logTrinityCatalogVerbose=Ta,e.debug=t;const n=e.runtime?.capabilities;n&&"object"==typeof n&&(n.logTrinityCatalog=Ca,n.logTrinityCatalogVerbose=Ta);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{rg(),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 pg(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 sm)t.facade&&Object.assign(e,t.facade);return e}()));const n=km.manager;for(const e of function(){const e=[];for(const t of sm)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 sm)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(ug.register(new Om),ug.register(new Dm),ug.register(new Fm),ug.register(new qm),ug.register(new Um),ug.register(new Sm),ug.register(new jm),ug.register(new Wm),ug.register(new Vm),ug.register(new Lm),ug.register(new Km),ug.register(new Gm),ug.register(new Ym),ug.register(new zm),ug.register(new Jm),ug.register(new Qm),ug.register(new Zm),ug.register(new Hm),ug.register(new za),ug.register(new Bm),r){const e=am(),t=n.getActiveModules();for(const n of t){const t=e[n];t&&(ug.register(t()),console.log(`[Punica] Shell module registered: ${n}`))}}ug.register(new Em),console.log(`[Punica] Module registry initialized with ${ug.getAll().length} modules`),await ug.bootstrapAll(),console.log("[Punica] Module bootstrap completed")}catch(e){throw console.error("[Punica] CRITICAL: Bootstrap failed:",e?.message??e,e?.stack),e}}async function fg(){try{console.log("[Punica] Starting system..."),await ug.startAll(),ug.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:ig}}),console.log("[Punica] System started successfully"),Ca()}catch(e){throw console.error("[Punica] CRITICAL: System start failed:",e?.message??e,e?.stack),e}}om({moduleFactories:{"flow.shell":()=>new $m}});var hg=Object.freeze({__proto__:null,StdioTransport:class{#Ot;#Dt;#jt;#Ft=null;#qt=null;#Bt=null;#Ut=null;#Vt=null;#Wt=new Map;#Kt=1;#Gt="";constructor(e,t=[],n={}){this.#Ot=e,this.#Dt=t,this.#jt=n}async connect(){const e=globalThis.api?.mcp?.stdio;e?await this.#Yt(e):await this.#zt()}async#Yt(e){this.#Bt=e;const{sessionId:t}=await e.spawn({command:this.#Ot,args:this.#Dt,env:this.#jt});this.#qt=t,this.#Ut=e.onData(e=>{e.sessionId===t&&this.#Jt(e.chunk)}),this.#Vt=e.onExit(e=>{if(e.sessionId!==t)return;const n=new Error(e.error??`MCP stdio process exited (${e.code})`);for(const{reject:e}of this.#Wt.values())e(n);this.#Wt.clear()})}async#zt(){const e=await import(
2
+ /* webpackIgnore: true */"child_process"),t=globalThis,n=t.process?.env??{};this.#Ft=e.spawn(this.#Ot,this.#Dt,{env:{...n,...this.#jt},stdio:["pipe","pipe","inherit"]}),this.#Ft.stdout.setEncoding("utf8"),this.#Ft.stdout.on("data",e=>{this.#Jt(e)}),this.#Ft.on("error",e=>{for(const{reject:t}of this.#Wt.values())t(e);this.#Wt.clear()})}#Jt(e){let t;for(this.#Gt+=e;-1!==(t=this.#Gt.indexOf("\n"));){const e=this.#Gt.slice(0,t).trim();this.#Gt=this.#Gt.slice(t+1),e&&this.#Ht(e)}}notify(e,t={}){const n=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";this.#Qt(n)}async request(e,t={}){const n=this.#Kt++;return new Promise((r,i)=>{this.#Wt.set(n,{resolve:r,reject:i});const s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+"\n";try{this.#Qt(s)}catch(e){this.#Wt.delete(n),i(e instanceof Error?e:new Error(String(e)))}})}#Qt(e){if(this.#Bt&&this.#qt)this.#Bt.write(this.#qt,e);else{if(!this.#Ft?.stdin)throw new Error("MCP stdio transport is not connected");this.#Ft.stdin.write(e)}}close(){this.#Ut?.(),this.#Vt?.(),this.#Ut=null,this.#Vt=null,this.#Bt&&this.#qt&&this.#Bt.close(this.#qt),this.#Ft?.kill(),this.#Ft=null,this.#qt=null,this.#Bt=null;for(const{reject:e}of this.#Wt.values())e(new Error("MCP stdio transport closed"));this.#Wt.clear()}#Ht(e){let t;try{t=JSON.parse(e)}catch{return}const n=this.#Wt.get(t.id);n&&(this.#Wt.delete(t.id),t.error?n.reject(new Error(t.error.message??"MCP error")):n.resolve(t.result))}}});var mg=Object.freeze({__proto__:null,StreamableHttpTransport:class{#Zt;#Xt;#Kt=1;#qt;constructor(e,t={}){this.#Zt=e.replace(/\/$/,""),this.#Xt=t}async connect(){const e=await fetch(`${this.#Zt}/sse`,{headers:{...this.#Xt,Accept:"text/event-stream"}});if(!e.ok)throw new Error(`MCP SSE connect failed: ${e.status} ${e.statusText}`);this.#qt=e.headers.get("mcp-session-id")??void 0}notify(e,t={}){this.#en({jsonrpc:"2.0",method:e,params:t})}async request(e,t={}){const n=this.#Kt++,r=await this.#en({jsonrpc:"2.0",id:n,method:e,params:t});if(r.error)throw new Error(r.error.message??"MCP error");return r.result}async#en(e){const t={...this.#Xt,"Content-Type":"application/json",Accept:"application/json"};this.#qt&&(t["mcp-session-id"]=this.#qt);const n=await fetch(`${this.#Zt}/messages`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw new Error(`MCP request failed: ${n.status} ${n.statusText}`);return await n.json()}close(){this.#qt=void 0}}});var gg=Object.freeze({__proto__:null,parseYamlMcpConfig:function(e){return Ga(Kd(e))}});export{ot as COMMAND_IDS,st as MODULE_NAMES,e as ModuleLifecycleState,km as Profile,pg as bootstrap,bm as emitShellEvent,up as enterHeadlessScope,dp as exitHeadlessScope,cg as extensions,lg as flow,vm as getProfileValidator,dg as initialize,pp as isHeadlessScope,np as isMacPlatform,sg as kernel,rp as parseKeyChord,om as registerShell,fp as runInHeadlessScope,ag as runtime,wm as setProfileValidator,og as shell,fg as start,ig as version};
3
3
  //# sourceMappingURL=index.bundle.esm.js.map