comet-dsh-plugin 0.0.0-stage → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +176 -0
- package/README.md +152 -2
- package/client.js +349 -0
- package/cordis.patch.yml +4 -0
- package/icon.png +0 -0
- package/index.js +183 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +58 -4
- package/rules/comet-workflow-guard.md +65 -0
- package/rules/migration-assets.json +218 -0
- package/server/comet-plugin-setup.mjs +192 -0
- package/skills/comet/SKILL.md +37 -0
- package/skills/comet/agents/openai.yaml +3 -0
- package/skills/comet/reference/change-walkthrough.md +77 -0
- package/skills/comet/reference/edit-review.md +26 -0
- package/skills/comet/reference/host-check.md +11 -0
- package/skills/comet/reference/platform-execution.md +34 -0
- package/skills/comet/reference/task-learning.md +39 -0
- package/skills/comet/runtime/classic/checks.yaml +6 -0
- package/skills/comet/runtime/classic/guardrails.yaml +13 -0
- package/skills/comet/runtime/classic/skill.yaml +122 -0
- package/skills/comet/scripts/comet-archive.mjs +310 -0
- package/skills/comet/scripts/comet-check.mjs +179 -0
- package/skills/comet/scripts/comet-entry-runtime.mjs +151 -0
- package/skills/comet/scripts/comet-env.mjs +15 -0
- package/skills/comet/scripts/comet-guard.mjs +335 -0
- package/skills/comet/scripts/comet-handoff.mjs +289 -0
- package/skills/comet/scripts/comet-hook-guard.mjs +295 -0
- package/skills/comet/scripts/comet-hook-router-guard.mjs +629 -0
- package/skills/comet/scripts/comet-hook-router.mjs +17 -0
- package/skills/comet/scripts/comet-intent.mjs +181 -0
- package/skills/comet/scripts/comet-plugin-hook.mjs +213 -0
- package/skills/comet/scripts/comet-resume-probe.mjs +205 -0
- package/skills/comet/scripts/comet-runtime.mjs +572 -0
- package/skills/comet/scripts/comet-state.mjs +381 -0
- package/skills/comet/scripts/comet-yaml-validate.mjs +182 -0
- package/skills/comet-any/SKILL.md +47 -0
- package/skills/comet-any/agents/openai.yaml +5 -0
- package/skills/comet-any/reference/sdk-creation.md +100 -0
- package/skills/comet-archive/SKILL.md +28 -0
- package/skills/comet-archive/agents/openai.yaml +5 -0
- package/skills/comet-archive/reference/compat.md +188 -0
- package/skills/comet-build/SKILL.md +35 -0
- package/skills/comet-build/agents/openai.yaml +5 -0
- package/skills/comet-build/reference/compat.md +191 -0
- package/skills/comet-classic/SKILL.md +98 -0
- package/skills/comet-classic/agents/openai.yaml +3 -0
- package/skills/comet-classic/reference/auto-transition.md +34 -0
- package/skills/comet-classic/reference/classic-layout.md +36 -0
- package/skills/comet-classic/reference/comet-yaml-fields.md +82 -0
- package/skills/comet-classic/reference/context-recovery.md +128 -0
- package/skills/comet-classic/reference/debug-gate.md +30 -0
- package/skills/comet-classic/reference/decision-point.md +109 -0
- package/skills/comet-classic/reference/dirty-worktree.md +59 -0
- package/skills/comet-classic/reference/file-structure.md +32 -0
- package/skills/comet-classic/reference/intent-frame.md +132 -0
- package/skills/comet-classic/reference/scripts.md +144 -0
- package/skills/comet-classic/reference/sdk-methods.md +136 -0
- package/skills/comet-classic/reference/subagent-dispatch.md +75 -0
- package/skills/comet-classic/reference/workspace.md +23 -0
- package/skills/comet-design/SKILL.md +25 -0
- package/skills/comet-design/agents/openai.yaml +5 -0
- package/skills/comet-design/reference/compat.md +191 -0
- package/skills/comet-hotfix/SKILL.md +46 -0
- package/skills/comet-hotfix/agents/openai.yaml +5 -0
- package/skills/comet-hotfix/reference/compat.md +240 -0
- package/skills/comet-memory/SKILL.md +68 -0
- package/skills/comet-memory/agents/openai.yaml +5 -0
- package/skills/comet-native/SKILL.md +139 -0
- package/skills/comet-native/agents/openai.yaml +3 -0
- package/skills/comet-native/reference/artifacts.md +118 -0
- package/skills/comet-native/reference/clarification.md +120 -0
- package/skills/comet-native/reference/commands.md +321 -0
- package/skills/comet-native/reference/edit-review.md +26 -0
- package/skills/comet-native/reference/recovery.md +64 -0
- package/skills/comet-native/reference/workspace.md +70 -0
- package/skills/comet-native/scripts/comet-native-archive.mjs +475 -0
- package/skills/comet-native/scripts/comet-native-cancel.mjs +461 -0
- package/skills/comet-native/scripts/comet-native-doctor.mjs +475 -0
- package/skills/comet-native/scripts/comet-native-hook-guard.mjs +470 -0
- package/skills/comet-native/scripts/comet-native-init.mjs +465 -0
- package/skills/comet-native/scripts/comet-native-new.mjs +478 -0
- package/skills/comet-native/scripts/comet-native-next.mjs +470 -0
- package/skills/comet-native/scripts/comet-native-root.mjs +472 -0
- package/skills/comet-native/scripts/comet-native-runtime.mjs +525 -0
- package/skills/comet-native/scripts/comet-native-select.mjs +468 -0
- package/skills/comet-native/scripts/comet-native-show.mjs +462 -0
- package/skills/comet-native/scripts/comet-native-spec.mjs +468 -0
- package/skills/comet-native/scripts/comet-native-status.mjs +467 -0
- package/skills/comet-native/scripts/comet-native-transfer.mjs +466 -0
- package/skills/comet-open/SKILL.md +265 -0
- package/skills/comet-open/agents/openai.yaml +5 -0
- package/skills/comet-open/reference/batch-changes.md +51 -0
- package/skills/comet-review/SKILL.md +121 -0
- package/skills/comet-review/agents/openai.yaml +5 -0
- package/skills/comet-tweak/SKILL.md +49 -0
- package/skills/comet-tweak/agents/openai.yaml +5 -0
- package/skills/comet-tweak/reference/compat.md +232 -0
- package/skills/comet-verify/SKILL.md +30 -0
- package/skills/comet-verify/agents/openai.yaml +5 -0
- package/skills/comet-verify/reference/compat.md +202 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var aI=Object.create;var rf=Object.defineProperty;var cI=Object.getOwnPropertyDescriptor;var lI=Object.getOwnPropertyNames;var uI=Object.getPrototypeOf,dI=Object.prototype.hasOwnProperty;var Nc=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Le=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},fI=(e,t)=>{for(var r in t)rf(e,r,{get:t[r],enumerable:!0})},pI=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of lI(t))!dI.call(e,i)&&i!==r&&rf(e,i,{get:()=>t[i],enumerable:!(n=cI(t,i))||n.enumerable});return e};var bt=(e,t,r)=>(r=e!=null?aI(uI(e)):{},pI(t||!e||!e.__esModule?rf(r,"default",{value:e,enumerable:!0}):r,e));function $c(e){return e.charCodeAt(0)===65279?e.slice(1):e}var nf=Le(()=>{"use strict"});async function sf(e=2e3){return process.stdin.isTTY?{text:""}:!Number.isFinite(e)||e<1?{text:null}:process.stdin.readableEnded?{text:""}:await new Promise(t=>{let r=!1,n=0,i=[],s=setTimeout(()=>o({text:null}),Math.ceil(e)),o=d=>{r||(r=!0,clearTimeout(s),process.stdin.removeListener("data",c),process.stdin.removeListener("end",l),process.stdin.removeListener("close",f),process.stdin.removeListener("error",a),process.stdin.pause(),t(d))},c=d=>{let p=Buffer.isBuffer(d)?d:Buffer.from(d),u=1048576-n;if(u<=0){o({text:null});return}let m=p.subarray(0,u);i.push(m),n+=m.length,p.length>m.length&&o({text:null})},l=()=>o({text:Buffer.concat(i,n).toString("utf8")}),f=()=>{process.stdin.readableEnded||o({text:null})},a=()=>o({text:null});process.stdin.on("data",c),process.stdin.once("end",l),process.stdin.once("close",f),process.stdin.once("error",a),s.unref(),process.stdin.resume()})}var of=Le(()=>{"use strict"});import ey from"node:path";import{fileURLToPath as mI}from"node:url";function ys(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function jc(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function wI(e){for(let t of["tool_name","toolName","tool","name"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}return null}function yI(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!ey.isAbsolute(r.trim())))return r.trim()}}function vI(e){for(let t of["session_id","sessionId","conversation_id","conversationId"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim().slice(0,256)}}function kI(e){for(let t of["hook_event_name","hookEventName","event_name","eventName"]){let r=e[t];if(typeof r=="string"&&r.trim())return jc(r)}}function bI(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function RI(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function SI(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return RI(e[t]);return e}function qc(e){let t=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of r)for(let i of e.matchAll(n)){let s=i[1]?.trim();s&&s!=="/dev/null"&&t.push(s)}return t}function Po(e){return[...new Set(e.flatMap(t=>{let r=t.trim();if(!r)return[];if(/^file:/iu.test(r))try{return[mI(r)]}catch{return[r]}return/^[A-Za-z]:/u.test(r)?[r]:/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(r)?[]:[r]}))]}function bi(e,t){if(typeof t=="string"){let r=t.trim();r&&e.push(r);return}if(Array.isArray(t)){for(let r of t)bi(e,r);return}if(ys(t)){for(let r of af)bi(e,t[r]);for(let r of ty)bi(e,t[r]);for(let r of ry)bi(e,t[r])}}function CI(e,t){let r=[],n=[t,e].filter(ys);for(let i of n){for(let s of af)bi(r,i[s]);for(let s of ty)bi(r,i[s]);for(let s of ry)bi(r,i[s]);for(let s of ny){let o=i[s];typeof o=="string"&&r.push(...qc(o))}}return typeof t=="string"&&r.push(...qc(t)),r}function Dc(e){if(typeof e=="string"&&e.startsWith("*** Begin Patch")&&/^[- +].+/mu.test(e))return qc(e).map(i=>({path:i,patch:e}));if(!ys(e))return[];for(let i of ny)if(typeof e[i]=="string")return Dc(e[i]);let t=af.map(i=>e[i]).find(i=>typeof i=="string");if(typeof t!="string")return[];if(typeof e.content=="string")return[{path:t,content:e.content}];let r=Array.isArray(e.edits)?e.edits:[e],n=[];for(let i of r){if(!ys(i))return[];let s=i.old_string??i.oldString,o=i.new_string??i.newString;if(typeof s!="string"||!s||typeof o!="string")return[];n.push({oldText:s,newText:o,replaceAll:i.replace_all===!0})}return n.length?[{path:t,replacements:n}]:[]}function iy(e,t){if(t?.trim()){let u=Po([t]);return{intent:u.length>0?"write":"non-write",targets:u,toolName:null}}if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse($c(e))}catch{let u=qc(e);if(u.length>0){let m=Po(u);return{intent:m.length>0?"write":"non-write",targets:m,toolName:"apply_patch",...Dc(e).length?{writes:Dc(e)}:{}}}return{intent:"unknown",targets:[],toolName:null}}if(!ys(r))return{intent:"unknown",targets:[],toolName:null};let n=wI(r),i=SI(r),s=n&&jc(n)==="applypatch"&&ys(i)&&typeof i.command=="string"?{...i,patch:i.command}:i,o=CI(r,s),c=Po(o),l=Dc(s),f=yI(r),a=f?ey.resolve(f):void 0,d=f!==a?f:void 0,p=vI(r);if(kI(r)==="beforeagentstart"){let u=bI(r);return{intent:"context",targets:[],toolName:null,...u?{task:u}:{},...a?{cwd:a}:{},...d?{rawCwd:d}:{},...p?{sessionId:p}:{}}}return o.length>0&&c.length===0?{intent:"non-write",targets:c,toolName:n,...a?{cwd:a}:{},...d?{rawCwd:d}:{},...p?{sessionId:p}:{}}:n&&hI.has(jc(n))?{intent:c.length>0?"write":"unknown",targets:c,toolName:n,...l.length?{writes:l}:{},...a?{cwd:a}:{},...d?{rawCwd:d}:{},...p?{sessionId:p}:{}}:n&&gI.has(jc(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{},...d?{rawCwd:d}:{},...p?{sessionId:p}:{}}:n?{intent:"unknown",targets:c,toolName:n,...a?{cwd:a}:{},...d?{rawCwd:d}:{},...p?{sessionId:p}:{}}:{intent:c.length>0?"write":"unknown",targets:c,toolName:null,...a?{cwd:a}:{},...d?{rawCwd:d}:{},...p?{sessionId:p}:{}}}var hI,gI,af,ty,ry,ny,cf=Le(()=>{"use strict";nf();of();hI=new Set(["applypatch","create","createfile","deletefile","edit","editfile","multiedit","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),gI=new Set(["glob","grep","listfiles","read","readfile","search","view"]),af=["file_path","filePath","path","target_file","targetFile"],ty=["file_paths","filePaths","paths","files","targets"],ry=["operations","edits"],ny=["patch","diff","patchText","patch_text","changes"]});import{AsyncLocalStorage as EI}from"node:async_hooks";function Lc(){let e=lf.getStore();return e?.active?e:null}function sy(){Lc()?.entries.clear()}async function oy(e){if(Lc()!==null)return e();let t={entries:new Map,active:!0};return lf.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function Pn(e){return lf.run({entries:new Map,active:!1},e)}function ay(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function je(e,t){return(...r)=>{let n=Lc();if(n===null)return t(...r);let i=ay(`async:${e}`,r),s=n.entries.get(i);if(s)return s.value;let o=t(...r).catch(c=>{throw n.entries.get(i)?.value===o&&n.entries.delete(i),c});return n.entries.set(i,{value:o}),o}}function Vr(e,t){return(...r)=>{let n=Lc();if(n===null)return t(...r);let i=ay(`sync:${e}`,r),s=n.entries.get(i);if(s)return s.value;let o=t(...r);return n.entries.set(i,{value:o}),o}}var lf,nr=Le(()=>{"use strict";lf=new EI});function On(e){return e!==0&&e!==0n&&e!=="0"}function Mc(e,t){return On(e.dev)&&On(t.dev)&&On(e.ino)&&On(t.ino)}function ar(e,t){let r=On(e.dev)&&On(t.dev);if(r&&e.dev!==t.dev)return!1;let n=On(e.ino)&&On(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var To=Le(()=>{"use strict"});import{constants as Tn,promises as Vt}from"fs";import{createHash as NI}from"node:crypto";function ff(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Fc(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function $n(e){return{dev:e.dev,ino:e.ino,birthtime:ff(e)}}function $I(e,t){let r=$n(e),n=$n(t);return Mc(r,n)?ar(r,n):ar(r,n)&&ff(e)===ff(t)&&Fc(e)===Fc(t)&&e.size===t.size}function Nn(e,t){let r=n=>"mtimeNs"in n?n.mtimeNs:n.mtimeMs;return $I(e,t)&&e.size===t.size&&e.mode===t.mode&&r(e)===r(t)&&Fc(e)===Fc(t)}async function vs(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,s=await Vt.lstat(e,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new mt("not-regular-file",`${n} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new mt("too-large",`${n} exceeds ${t} bytes`);let o=await Vt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:$n(s)});let c=process.platform==="win32"?Tn.O_RDONLY:Tn.O_RDONLY|Tn.O_NOFOLLOW|Tn.O_NONBLOCK,l;try{l=await Vt.open(e,c)}catch(f){throw f.code==="ELOOP"?new mt("not-regular-file",`${n} must be a regular file`,{cause:f}):f}try{let[f,a,d]=await Promise.all([l.stat({bigint:i}),Vt.lstat(e,{bigint:i}),Vt.realpath(e)]);if(!f.isFile()||!a.isFile()||a.isSymbolicLink()||d!==o||!Nn(s,f)||!Nn(s,a))throw new mt("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:$n(f)}),await r.hooks?.afterOpen?.();let p=[],u=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-u,{bytesRead:R}=await l.read(m,0,Math.min(m.length,b),null);if(R===0)break;if(u+=R,u>t)throw new mt("too-large",`${n} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,R)))}let h=Buffer.concat(p,u);if(await r.hooks?.beforeFinalCheck?.(),process.platform==="win32"){let b=0;for(;;){let{bytesRead:R}=await l.read(m,0,Math.min(m.length,u+1-b),b);if(R===0&&b===u)break;if(R===0||b+R>u||!m.subarray(0,R).equals(h.subarray(b,b+R)))throw new mt("changed",`${n} changed while reading`);b+=R}}let[g,w,k]=await Promise.all([l.stat({bigint:i}),Vt.lstat(e,{bigint:i}),Vt.realpath(e)]);if(!w.isFile()||w.isSymbolicLink()||k!==o||!Nn(s,g)||!Nn(s,w))throw new mt("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:k,identity:$n(g)}),{bytes:h,stat:g,realPath:k}}finally{await l.close()}}async function dy(e,t={}){let r=t.label??"file",n=t.bigint===!0,i=await Vt.lstat(e,{bigint:n});if(!i.isFile()||i.isSymbolicLink())throw new mt("not-regular-file",`${r} must be a regular file`);let s=await Vt.realpath(e);await t.verify?.("pre-open",{realPath:s,identity:$n(i)});let o=process.platform==="win32"?Tn.O_RDONLY:Tn.O_RDONLY|Tn.O_NOFOLLOW|Tn.O_NONBLOCK,c;try{c=await Vt.open(e,o)}catch(l){throw l.code==="ELOOP"?new mt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,a]=await Promise.all([c.stat({bigint:n}),Vt.lstat(e,{bigint:n}),Vt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||a!==s||!Nn(i,l)||!Nn(i,f))throw new mt("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:a,identity:$n(l)}),await t.hooks?.afterOpen?.();let d=t.algorithm??"sha256",p=await uy(c,d);if(await t.hooks?.beforeFinalCheck?.(),process.platform==="win32"&&await uy(c,d)!==p)throw new mt("changed",`${r} changed while reading`);let[u,m,h]=await Promise.all([c.stat({bigint:n}),Vt.lstat(e,{bigint:n}),Vt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||h!==s||!Nn(i,u)||!Nn(i,m))throw new mt("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:$n(u)}),{digest:p,stat:u,realPath:h}}finally{await c.close()}}async function uy(e,t){let r=NI(t),n=Buffer.allocUnsafe(64*1024),i=0;for(;;){let{bytesRead:s}=await e.read(n,0,n.length,i);if(s===0)break;r.update(n.subarray(0,s)),i+=s}return r.digest("hex")}var mt,Ri=Le(()=>{"use strict";To();mt=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{promises as hf}from"node:fs";async function gf(e,t){let r;for(let n=0;n<=mf.length;n+=1)try{return await e()}catch(i){r=i;let s=i.code;if(n===mf.length||!DI.has(s??""))throw i;await new Promise(o=>setTimeout(o,mf[n]))}throw r}async function wf(e,t){await gf(()=>hf.rename(e,t),`rename ${t}`)}async function yf(e){await gf(()=>hf.unlink(e),`unlink ${e}`)}async function Hc(e,t){await gf(()=>hf.link(e,t),`link ${t}`)}var DI,mf,my=Le(()=>{"use strict";DI=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),mf=[50,100,200]});import{randomUUID as hy}from"crypto";import{constants as qI,promises as Ve}from"fs";import Ge from"path";async function vf(e,t){try{return await Hc(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await Ve.copyFile(e,t,qI.COPYFILE_EXCL),{linked:!1}}function Ci(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}function Bc(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function LI(e,t){return ar(e,Bc(t))}function Si(e,t){return ar(Bc(e),Bc(t))}function gy(e,t){return Si(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Vc(e){let t=await Ve.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Ve.realpath(e),...Bc(t)}}async function Rt(e){for(let t of e){let r=await Ve.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!LI(t,r)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function WI(e,t,r){let[n,i]=await Promise.all([Ve.lstat(e),Ve.realpath(e),Rt(r)]);if(!n.isFile()||n.isSymbolicLink()||!Si(n,t)||!Ci(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function wy(e,t){let r=await kf(e,t);if(r)return r;let n=Ge.resolve(e),i=Ge.resolve(t);if(!Ci(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let s=[await Vc(n)],o=Ge.relative(n,i).split(Ge.sep).filter(Boolean),c=n;for(let l of o){await Rt(s),c=Ge.join(c,l);try{await Ve.mkdir(c)}catch(a){if(a.code!=="EEXIST")throw a}let f=await Vc(c);if(!Ci(s[0].realPath,f.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${c}`);s.push(f)}return await Rt(s),s}async function kf(e,t){let r=Ge.resolve(e),n=Ge.resolve(t);if(!Ci(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await Vc(r)],s=Ge.relative(r,n).split(Ge.sep).filter(Boolean),o=r;for(let c of s){o=Ge.join(o,c);try{let l=await Vc(o);if(!Ci(i[0].realPath,l.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(l)}catch(l){if(l.code==="ENOENT")return null;throw l}}return await Rt(i),i}async function bf(e){let t;try{t=await Ve.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function MI(e,t,r){let n=Ge.dirname(e),i=await wy(r.containedRoot,n),s=Ge.join(n,`.${Ge.basename(e)}.${hy()}.tmp`),o,c,l;try{await r.beforeTemporaryOpen?.(),o=await Ve.open(s,"wx"),c=await o.stat();let[f,a]=await Promise.all([Ve.lstat(s),Ve.realpath(s)]);if(await Rt(i),!f.isFile()||f.isSymbolicLink()||!Si(c,f)||!Ci(i[0].realPath,a))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),l=await o.stat(),!Si(c,l))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Contained atomic write temporary file was not written");l=await WI(s,l,i),await r.beforeCommit?.(),await Rt(i);let d=await Ve.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!l||!gy(d,l))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(r.requireAtomicPublication?await Hc(s,e):await vf(s,e),await Ve.unlink(s)):await wf(s,e),await bf(n)}catch(f){await o?.close();try{await Rt(i),await Ve.rm(s,{force:!0})}catch{}throw f}}async function Te(e,t,r){await MI(e,t,r)}async function yy(e,t,r){let n=await kf(r.containedRoot,Ge.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await wy(r.containedRoot,Ge.dirname(t)),s=await Ve.lstat(e);if(!s.isFile()||s.isSymbolicLink())throw new Error("Contained link source must be a regular file");let o=Ge.join(Ge.dirname(t),`.${Ge.basename(t)}.${hy()}.tmp`);try{await Rt(n),await Rt(i),await Hc(e,o),await r.beforeCommit?.(),await Rt(n),await Rt(i);let c=await Ve.lstat(o),l=await Ve.lstat(e);if(!c.isFile()||c.isSymbolicLink()||!l.isFile()||l.isSymbolicLink()||!Si(s,l)||!Si(l,c)||s.size!==l.size||s.mtimeMs!==l.mtimeMs)throw new Error("Contained link source changed before publication");let f=await Ve.lstat(t).catch(a=>{if(a.code==="ENOENT")return null;throw a});f?.isFile()&&!f.isSymbolicLink()&&Si(l,f)?await yf(o):await wf(o,t),await bf(Ge.dirname(t)),await Rt(n),await Rt(i)}catch(c){try{await Rt(i),await Ve.unlink(o)}catch{}throw c}}async function zr(e,t){let r=Ge.dirname(e),n=await kf(t.containedRoot,r);if(!n)return!1;let i,s;try{i=await Ve.lstat(e),s=await Ve.realpath(e)}catch(l){if(l.code==="ENOENT")return!1;throw l}if(!i.isFile()||i.isSymbolicLink()||!Ci(n[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Rt(n);let[o,c]=await Promise.all([Ve.lstat(e),Ve.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!gy(i,o)||c!==s)throw new Error("Contained file removal target changed before removal");return await yf(e),await Rt(n),await bf(r),!0}var jt=Le(()=>{"use strict";my();To()});var ke=x(ht=>{"use strict";var Rf=Symbol.for("yaml.alias"),vy=Symbol.for("yaml.document"),Uc=Symbol.for("yaml.map"),ky=Symbol.for("yaml.pair"),Sf=Symbol.for("yaml.scalar"),zc=Symbol.for("yaml.seq"),cn=Symbol.for("yaml.node.type"),FI=e=>!!e&&typeof e=="object"&&e[cn]===Rf,HI=e=>!!e&&typeof e=="object"&&e[cn]===vy,BI=e=>!!e&&typeof e=="object"&&e[cn]===Uc,VI=e=>!!e&&typeof e=="object"&&e[cn]===ky,by=e=>!!e&&typeof e=="object"&&e[cn]===Sf,UI=e=>!!e&&typeof e=="object"&&e[cn]===zc;function Ry(e){if(e&&typeof e=="object")switch(e[cn]){case Uc:case zc:return!0}return!1}function zI(e){if(e&&typeof e=="object")switch(e[cn]){case Rf:case Uc:case Sf:case zc:return!0}return!1}var KI=e=>(by(e)||Ry(e))&&!!e.anchor;ht.ALIAS=Rf;ht.DOC=vy;ht.MAP=Uc;ht.NODE_TYPE=cn;ht.PAIR=ky;ht.SCALAR=Sf;ht.SEQ=zc;ht.hasAnchor=KI;ht.isAlias=FI;ht.isCollection=Ry;ht.isDocument=HI;ht.isMap=BI;ht.isNode=zI;ht.isPair=VI;ht.isScalar=by;ht.isSeq=UI});var No=x(Cf=>{"use strict";var ct=ke(),Ut=Symbol("break visit"),Sy=Symbol("skip children"),Kr=Symbol("remove node");function Kc(e,t){let r=Cy(t);ct.isDocument(e)?ks(null,e.contents,r,Object.freeze([e]))===Kr&&(e.contents=null):ks(null,e,r,Object.freeze([]))}Kc.BREAK=Ut;Kc.SKIP=Sy;Kc.REMOVE=Kr;function ks(e,t,r,n){let i=Ey(e,t,r,n);if(ct.isNode(i)||ct.isPair(i))return Ay(e,n,i),ks(e,i,r,n);if(typeof i!="symbol"){if(ct.isCollection(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){let o=ks(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===Ut)return Ut;o===Kr&&(t.items.splice(s,1),s-=1)}}}else if(ct.isPair(t)){n=Object.freeze(n.concat(t));let s=ks("key",t.key,r,n);if(s===Ut)return Ut;s===Kr&&(t.key=null);let o=ks("value",t.value,r,n);if(o===Ut)return Ut;o===Kr&&(t.value=null)}}return i}async function Gc(e,t){let r=Cy(t);ct.isDocument(e)?await bs(null,e.contents,r,Object.freeze([e]))===Kr&&(e.contents=null):await bs(null,e,r,Object.freeze([]))}Gc.BREAK=Ut;Gc.SKIP=Sy;Gc.REMOVE=Kr;async function bs(e,t,r,n){let i=await Ey(e,t,r,n);if(ct.isNode(i)||ct.isPair(i))return Ay(e,n,i),bs(e,i,r,n);if(typeof i!="symbol"){if(ct.isCollection(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){let o=await bs(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===Ut)return Ut;o===Kr&&(t.items.splice(s,1),s-=1)}}}else if(ct.isPair(t)){n=Object.freeze(n.concat(t));let s=await bs("key",t.key,r,n);if(s===Ut)return Ut;s===Kr&&(t.key=null);let o=await bs("value",t.value,r,n);if(o===Ut)return Ut;o===Kr&&(t.value=null)}}return i}function Cy(e){return typeof e=="object"&&(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 Ey(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(ct.isMap(t))return r.Map?.(e,t,n);if(ct.isSeq(t))return r.Seq?.(e,t,n);if(ct.isPair(t))return r.Pair?.(e,t,n);if(ct.isScalar(t))return r.Scalar?.(e,t,n);if(ct.isAlias(t))return r.Alias?.(e,t,n)}function Ay(e,t,r){let n=t[t.length-1];if(ct.isCollection(n))n.items[e]=r;else if(ct.isPair(n))e==="key"?n.key=r:n.value=r;else if(ct.isDocument(n))n.contents=r;else{let i=ct.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Cf.visit=Kc;Cf.visitAsync=Gc});var Ef=x(_y=>{"use strict";var xy=ke(),GI=No(),JI={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},YI=e=>e.replace(/[!,[\]{}]/g,t=>JI[t]),$o=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return r(6,`Unsupported YAML version ${s}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+YI(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&xy.isNode(t.contents)){let s={};GI.visit(t.contents,(o,c)=>{xy.isNode(c)&&c.tag&&(s[c.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(c=>c.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`
|
|
5
|
+
`)}};$o.defaultYaml={explicit:!1,version:"1.2"};$o.defaultTags={"!!":"tag:yaml.org,2002:"};_y.Directives=$o});var Jc=x(jo=>{"use strict";var Iy=ke(),XI=No();function QI(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Py(e){let t=new Set;return XI.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function Oy(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function ZI(e,t){let r=[],n=new Map,i=null;return{onAnchor:s=>{r.push(s),i??(i=Py(e));let o=Oy(t,i);return i.add(o),o},setAnchors:()=>{for(let s of r){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(Iy.isScalar(o.node)||Iy.isCollection(o.node)))o.node.anchor=o.anchor;else{let c=new Error("Failed to resolve repeated object (this should not happen)");throw c.source=s,c}}},sourceObjects:n}}jo.anchorIsValid=QI;jo.anchorNames=Py;jo.createNodeAnchors=ZI;jo.findNewAnchor=Oy});var Af=x(Ty=>{"use strict";function Do(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;i<s;++i){let o=n[i],c=Do(e,n,String(i),o);c===void 0?delete n[i]:c!==o&&(n[i]=c)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let s=n.get(i),o=Do(e,n,i,s);o===void 0?n.delete(i):o!==s&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let s=Do(e,n,i,i);s===void 0?n.delete(i):s!==i&&(n.delete(i),n.add(s))}else for(let[i,s]of Object.entries(n)){let o=Do(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}Ty.applyReviver=Do});var Dn=x($y=>{"use strict";var eP=ke();function Ny(e,t,r){if(Array.isArray(e))return e.map((n,i)=>Ny(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!eP.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=s=>{n.res=s,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}$y.toJS=Ny});var Yc=x(Dy=>{"use strict";var tP=Af(),jy=ke(),rP=Dn(),xf=class{constructor(t){Object.defineProperty(this,jy.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:s}={}){if(!jy.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=rP.toJS(this,"",o);if(typeof i=="function")for(let{count:l,res:f}of o.anchors.values())i(f,l);return typeof s=="function"?tP.applyReviver(s,{"":c},"",c):c}};Dy.NodeBase=xf});var qo=x(qy=>{"use strict";var nP=Jc(),iP=No(),Rs=ke(),sP=Yc(),oP=Dn(),_f=class extends sP.NodeBase{constructor(t){super(Rs.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],iP.visit(t,{Node:(s,o)=>{(Rs.isAlias(o)||Rs.hasAnchor(o))&&n.push(o)}}),r&&(r.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=r,o=this.resolve(i,r);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let c=n.get(o);if(c||(oP.toJS(o,null,r),c=n.get(o)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(s>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Xc(i,o,n)),c.count*c.aliasCount>s)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return c.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(nP.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${i} `}return i}};function Xc(e,t,r){if(Rs.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(Rs.isCollection(t)){let n=0;for(let i of t.items){let s=Xc(e,i,r);s>n&&(n=s)}return n}else if(Rs.isPair(t)){let n=Xc(e,t.key,r),i=Xc(e,t.value,r);return Math.max(n,i)}return 1}qy.Alias=_f});var tt=x(If=>{"use strict";var aP=ke(),cP=Yc(),lP=Dn(),uP=e=>!e||typeof e!="function"&&typeof e!="object",qn=class extends cP.NodeBase{constructor(t){super(aP.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:lP.toJS(this.value,t,r)}toString(){return String(this.value)}};qn.BLOCK_FOLDED="BLOCK_FOLDED";qn.BLOCK_LITERAL="BLOCK_LITERAL";qn.PLAIN="PLAIN";qn.QUOTE_DOUBLE="QUOTE_DOUBLE";qn.QUOTE_SINGLE="QUOTE_SINGLE";If.Scalar=qn;If.isScalarValue=uP});var Lo=x(Wy=>{"use strict";var dP=qo(),Ei=ke(),Ly=tt(),fP="tag:yaml.org,2002:";function pP(e,t,r){if(t){let n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function mP(e,t,r){if(Ei.isDocument(e)&&(e=e.contents),Ei.isNode(e))return e;if(Ei.isPair(e)){let d=r.schema[Ei.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:c}=r,l;if(n&&e&&typeof e=="object"){if(l=c.get(e),l)return l.anchor??(l.anchor=i(e)),new dP.Alias(l.anchor);l={anchor:null,node:null},c.set(e,l)}t?.startsWith("!!")&&(t=fP+t.slice(2));let f=pP(e,t,o.tags);if(!f){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Ly.Scalar(e);return l&&(l.node=d),d}f=e instanceof Map?o[Ei.MAP]:Symbol.iterator in Object(e)?o[Ei.SEQ]:o[Ei.MAP]}s&&(s(f),delete r.onTagObj);let a=f?.createNode?f.createNode(r.schema,e,r):typeof f?.nodeClass?.from=="function"?f.nodeClass.from(r.schema,e,r):new Ly.Scalar(e);return t?a.tag=t:f.default||(a.tag=f.tag),l&&(l.node=a),a}Wy.createNode=mP});var Zc=x(Qc=>{"use strict";var hP=Lo(),Gr=ke(),gP=Yc();function Pf(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return hP.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var My=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Of=class extends gP.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>Gr.isNode(n)||Gr.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(My(t))this.add(r);else{let[n,...i]=t,s=this.get(n,!0);if(Gr.isCollection(s))s.addIn(i,r);else if(s===void 0&&this.schema)this.set(n,Pf(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(Gr.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,s=this.get(n,!0);return i.length===0?!r&&Gr.isScalar(s)?s.value:s:Gr.isCollection(s)?s.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Gr.isPair(r))return!1;let n=r.value;return n==null||t&&Gr.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return Gr.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let s=this.get(n,!0);if(Gr.isCollection(s))s.setIn(i,r);else if(s===void 0&&this.schema)this.set(n,Pf(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};Qc.Collection=Of;Qc.collectionFromPath=Pf;Qc.isEmptyPath=My});var Wo=x(el=>{"use strict";var wP=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Tf(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var yP=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?Tf(r,t):r.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+Tf(r,t):(e.endsWith(" ")?"":" ")+r;el.indentComment=Tf;el.lineComment=yP;el.stringifyComment=wP});var Hy=x(Mo=>{"use strict";var vP="flow",Nf="block",tl="quoted";function kP(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:c}={}){if(!i||i<0)return e;i<s&&(s=0);let l=Math.max(1+s,1+i-t.length);if(e.length<=l)return e;let f=[],a={},d=i-t.length;typeof n=="number"&&(n>i-Math.max(2,s)?f.push(0):d=i-n);let p,u,m=!1,h=-1,g=-1,w=-1;r===Nf&&(h=Fy(e,h,t.length),h!==-1&&(d=h+l));for(let b;b=e[h+=1];){if(r===tl&&b==="\\"){switch(g=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===`
|
|
9
|
+
`)r===Nf&&(h=Fy(e,h,t.length)),d=h+t.length+l,p=void 0;else{if(b===" "&&u&&u!==" "&&u!==`
|
|
10
|
+
`&&u!==" "){let R=e[h+1];R&&R!==" "&&R!==`
|
|
11
|
+
`&&R!==" "&&(p=h)}if(h>=d)if(p)f.push(p),d=p+l,p=void 0;else if(r===tl){for(;u===" "||u===" ";)u=b,b=e[h+=1],m=!0;let R=h>w+1?h-2:g-1;if(a[R])return e;f.push(R),a[R]=!0,d=R+l,p=void 0}else m=!0}u=b}if(m&&c&&c(),f.length===0)return e;o&&o();let k=e.slice(0,f[0]);for(let b=0;b<f.length;++b){let R=f[b],E=f[b+1]||e.length;R===0?k=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(r===tl&&a[R]&&(k+=`${e[R]}\\`),k+=`
|
|
13
|
+
${t}${e.slice(R+1,E)}`)}return k}function Fy(e,t,r){let n=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+r)s=e[++t];else{do s=e[++t];while(s&&s!==`
|
|
14
|
+
`);n=t,i=t+1,s=e[i]}return n}Mo.FOLD_BLOCK=Nf;Mo.FOLD_FLOW=vP;Mo.FOLD_QUOTED=tl;Mo.foldFlowLines=kP});var Ho=x(By=>{"use strict";var _r=tt(),Ln=Hy(),nl=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),il=e=>/^(%|---|\.\.\.)/m.test(e);function bP(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`
|
|
15
|
+
`){if(s-o>n)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Fo(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(il(e)?" ":""),o="",c=0;for(let l=0,f=r[l];f;f=r[++l])if(f===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(c,l)+"\\ ",l+=1,c=l,f="\\"),f==="\\")switch(r[l+1]){case"u":{o+=r.slice(c,l);let a=r.substr(l+2,4);switch(a){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:a.substr(0,2)==="00"?o+="\\x"+a.substr(2):o+=r.substr(l,6)}l+=5,c=l+1}break;case"n":if(n||r[l+2]==='"'||r.length<i)l+=1;else{for(o+=r.slice(c,l)+`
|
|
16
|
+
|
|
17
|
+
`;r[l+2]==="\\"&&r[l+3]==="n"&&r[l+4]!=='"';)o+=`
|
|
18
|
+
`,l+=2;o+=s,r[l+2]===" "&&(o+="\\"),l+=1,c=l+1}break;default:l+=1}return o=c?o+r.slice(c):r,n?o:Ln.foldFlowLines(o,s,Ln.FOLD_QUOTED,nl(t,!1))}function $f(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Fo(e,t);let r=t.indent||(il(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?n:Ln.foldFlowLines(n,r,Ln.FOLD_FLOW,nl(t,!1))}function Ss(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=Fo;else{let i=e.includes('"'),s=e.includes("'");i&&!s?n=$f:s&&!i?n=Fo:n=r?$f:Fo}return n(e,t)}var jf;try{jf=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{jf=/\n+(?!\n|$)/g}function rl({comment:e,type:t,value:r},n,i,s){let{blockQuote:o,commentString:c,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(r))return Ss(r,n);let f=n.indent||(n.forceBlockIndent||il(r)?" ":""),a=o==="literal"?!0:o==="folded"||t===_r.Scalar.BLOCK_FOLDED?!1:t===_r.Scalar.BLOCK_LITERAL?!0:!bP(r,l,f.length);if(!r)return a?`|
|
|
24
|
+
`:`>
|
|
25
|
+
`;let d,p;for(p=r.length;p>0;--p){let E=r[p-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let u=r.substring(p),m=u.indexOf(`
|
|
27
|
+
`);m===-1?d="-":r===u||m!==u.length-1?(d="+",s&&s()):d="",u&&(r=r.slice(0,-u.length),u[u.length-1]===`
|
|
28
|
+
`&&(u=u.slice(0,-1)),u=u.replace(jf,`$&${f}`));let h=!1,g,w=-1;for(g=0;g<r.length;++g){let E=r[g];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)w=g;else break}let k=r.substring(0,w<g?w+1:g);k&&(r=r.substring(k.length),k=k.replace(/\n+/g,`$&${f}`));let R=(h?f?"2":"1":"")+d;if(e&&(R+=" "+c(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!a){let E=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`),O=!1,z=nl(n,!0);o!=="folded"&&t!==_r.Scalar.BLOCK_FOLDED&&(z.onOverflow=()=>{O=!0});let D=Ln.foldFlowLines(`${k}${E}${u}`,f,Ln.FOLD_BLOCK,z);if(!O)return`>${R}
|
|
31
|
+
${f}${D}`}return r=r.replace(/\n+/g,`$&${f}`),`|${R}
|
|
32
|
+
${f}${k}${r}${u}`}function RP(e,t,r,n){let{type:i,value:s}=e,{actualString:o,implicitKey:c,indent:l,indentStep:f,inFlow:a}=t;if(c&&s.includes(`
|
|
33
|
+
`)||a&&/[[\]{},]/.test(s))return Ss(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return c||a||!s.includes(`
|
|
34
|
+
`)?Ss(s,t):rl(e,t,r,n);if(!c&&!a&&i!==_r.Scalar.PLAIN&&s.includes(`
|
|
35
|
+
`))return rl(e,t,r,n);if(il(s)){if(l==="")return t.forceBlockIndent=!0,rl(e,t,r,n);if(c&&l===f)return Ss(s,t)}let d=s.replace(/\n+/g,`$&
|
|
36
|
+
${l}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:u,tags:m}=t.doc.schema;if(m.some(p)||u?.some(p))return Ss(s,t)}return c?d:Ln.foldFlowLines(d,l,Ln.FOLD_FLOW,nl(t,!1))}function SP(e,t,r,n){let{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:c}=e;c!==_r.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(c=_r.Scalar.QUOTE_DOUBLE);let l=a=>{switch(a){case _r.Scalar.BLOCK_FOLDED:case _r.Scalar.BLOCK_LITERAL:return i||s?Ss(o.value,t):rl(o,t,r,n);case _r.Scalar.QUOTE_DOUBLE:return Fo(o.value,t);case _r.Scalar.QUOTE_SINGLE:return $f(o.value,t);case _r.Scalar.PLAIN:return RP(o,t,r,n);default:return null}},f=l(c);if(f===null){let{defaultKeyType:a,defaultStringType:d}=t.options,p=i&&a||d;if(f=l(p),f===null)throw new Error(`Unsupported default string type ${p}`)}return f}By.stringifyString=SP});var Bo=x(Df=>{"use strict";var CP=Jc(),Wn=ke(),EP=Wo(),AP=Ho();function xP(e,t){let r=Object.assign({blockQuote:!0,commentString:EP.stringifyComment,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,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function _P(e,t){if(t.tag){let i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(Wn.isScalar(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function IP(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],s=(Wn.isScalar(e)||Wn.isCollection(e))&&e.anchor;s&&CP.anchorIsValid(s)&&(r.add(s),i.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function PP(e,t,r,n){if(Wn.isPair(e))return e.toString(t,r,n);if(Wn.isAlias(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,s=Wn.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>i=l});i??(i=_P(t.doc.schema.tags,s));let o=IP(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let c=typeof i.stringify=="function"?i.stringify(s,t,r,n):Wn.isScalar(s)?AP.stringifyString(s,t,r,n):s.toString(t,r,n);return o?Wn.isScalar(s)||c[0]==="{"||c[0]==="["?`${o} ${c}`:`${o}
|
|
37
|
+
${t.indent}${c}`:c}Df.createStringifyContext=xP;Df.stringify=PP});var Ky=x(zy=>{"use strict";var ln=ke(),Vy=tt(),Uy=Bo(),Vo=Wo();function OP({key:e,value:t},r,n,i){let{allNullValues:s,doc:o,indent:c,indentStep:l,options:{commentString:f,indentSeq:a,simpleKeys:d}}=r,p=ln.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(ln.isCollection(e)||!ln.isNode(e)&&typeof e=="object"){let z="With simple keys, collection cannot be used as a key value";throw new Error(z)}}let u=!d&&(!e||p&&t==null&&!r.inFlow||ln.isCollection(e)||(ln.isScalar(e)?e.type===Vy.Scalar.BLOCK_FOLDED||e.type===Vy.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!u&&(d||!s),indent:c+l});let m=!1,h=!1,g=Uy.stringify(e,r,()=>m=!0,()=>h=!0);if(!u&&!r.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");u=!0}if(r.inFlow){if(s||t==null)return m&&n&&n(),g===""?"?":u?`? ${g}`:g}else if(s&&!d||t==null&&u)return g=`? ${g}`,p&&!m?g+=Vo.lineComment(g,r.indent,f(p)):h&&i&&i(),g;m&&(p=null),u?(p&&(g+=Vo.lineComment(g,r.indent,f(p))),g=`? ${g}
|
|
38
|
+
${c}:`):(g=`${g}:`,p&&(g+=Vo.lineComment(g,r.indent,f(p))));let w,k,b;ln.isNode(t)?(w=!!t.spaceBefore,k=t.commentBefore,b=t.comment):(w=!1,k=null,b=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!u&&!p&&ln.isScalar(t)&&(r.indentAtStart=g.length+1),h=!1,!a&&l.length>=2&&!r.inFlow&&!u&&ln.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let R=!1,E=Uy.stringify(t,r,()=>R=!0,()=>h=!0),O=" ";if(p||w||k){if(O=w?`
|
|
39
|
+
`:"",k){let z=f(k);O+=`
|
|
40
|
+
${Vo.indentComment(z,r.indent)}`}E===""&&!r.inFlow?O===`
|
|
41
|
+
`&&b&&(O=`
|
|
42
|
+
|
|
43
|
+
`):O+=`
|
|
44
|
+
${r.indent}`}else if(!u&&ln.isCollection(t)){let z=E[0],D=E.indexOf(`
|
|
45
|
+
`),G=D!==-1,J=r.inFlow??t.flow??t.items.length===0;if(G||!J){let te=!1;if(G&&(z==="&"||z==="!")){let Z=E.indexOf(" ");z==="&"&&Z!==-1&&Z<D&&E[Z+1]==="!"&&(Z=E.indexOf(" ",Z+1)),(Z===-1||D<Z)&&(te=!0)}te||(O=`
|
|
46
|
+
${r.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(O="");return g+=O+E,r.inFlow?R&&n&&n():b&&!R?g+=Vo.lineComment(g,r.indent,f(b)):h&&i&&i(),g}zy.stringifyPair=OP});var Lf=x(qf=>{"use strict";var Gy=Nc("process");function TP(e,...t){e==="debug"&&console.log(...t)}function NP(e,t){(e==="debug"||e==="warn")&&(typeof Gy.emitWarning=="function"?Gy.emitWarning(t):console.warn(t))}qf.debug=TP;qf.warn=NP});var ll=x(cl=>{"use strict";var al=ke(),Jy=tt(),sl="<<",ol={identify:e=>e===sl||typeof e=="symbol"&&e.description===sl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Jy.Scalar(Symbol(sl)),{addToJSMap:Yy}),stringify:()=>sl},$P=(e,t)=>(ol.identify(t)||al.isScalar(t)&&(!t.type||t.type===Jy.Scalar.PLAIN)&&ol.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===ol.tag&&r.default);function Yy(e,t,r){let n=Xy(e,r);if(al.isSeq(n))for(let i of n.items)Wf(e,t,i);else if(Array.isArray(n))for(let i of n)Wf(e,t,i);else Wf(e,t,n)}function Wf(e,t,r){let n=Xy(e,r);if(!al.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Xy(e,t){return e&&al.isAlias(t)?t.resolve(e.doc,e):t}cl.addMergeToJSMap=Yy;cl.isMergeKey=$P;cl.merge=ol});var Ff=x(ev=>{"use strict";var jP=Lf(),Qy=ll(),DP=Bo(),Zy=ke(),Mf=Dn();function qP(e,t,{key:r,value:n}){if(Zy.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(Qy.isMergeKey(e,r))Qy.addMergeToJSMap(e,t,n);else{let i=Mf.toJS(r,"",e);if(t instanceof Map)t.set(i,Mf.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let s=LP(r,i,e),o=Mf.toJS(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function LP(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Zy.isNode(e)&&r?.doc){let n=DP.createStringifyContext(r.doc,{});n.anchors=new Set;for(let s of r.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),jP.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}ev.addPairToJSMap=qP});var Mn=x(Hf=>{"use strict";var tv=Lo(),WP=Ky(),MP=Ff(),ul=ke();function FP(e,t,r){let n=tv.createNode(e,void 0,r),i=tv.createNode(t,void 0,r);return new dl(n,i)}var dl=class e{constructor(t,r=null){Object.defineProperty(this,ul.NODE_TYPE,{value:ul.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return ul.isNode(r)&&(r=r.clone(t)),ul.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return MP.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?WP.stringifyPair(this,t,r,n):JSON.stringify(this)}};Hf.Pair=dl;Hf.createPair=FP});var Bf=x(nv=>{"use strict";var Ai=ke(),rv=Bo(),fl=Wo();function HP(e,t,r){return(t.inFlow??e.flow?VP:BP)(e,t,r)}function BP({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:c}){let{indent:l,options:{commentString:f}}=r,a=Object.assign({},r,{indent:s,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(Ai.isNode(h))!d&&h.spaceBefore&&p.push(""),pl(r,p,h.commentBefore,d),h.comment&&(g=h.comment);else if(Ai.isPair(h)){let k=Ai.isNode(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&p.push(""),pl(r,p,k.commentBefore,d))}d=!1;let w=rv.stringify(h,a,()=>g=null,()=>d=!0);g&&(w+=fl.lineComment(w,s,f(g))),d&&g&&(d=!1),p.push(n+w)}let u;if(p.length===0)u=i.start+i.end;else{u=p[0];for(let m=1;m<p.length;++m){let h=p[m];u+=h?`
|
|
48
|
+
${l}${h}`:`
|
|
49
|
+
`}}return e?(u+=`
|
|
50
|
+
`+fl.indentComment(f(e),l),c&&c()):d&&o&&o(),u}function VP({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:c}}=t;n+=s;let l=Object.assign({},t,{indent:n,inFlow:!0,type:null}),f=!1,a=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(Ai.isNode(h))h.spaceBefore&&d.push(""),pl(t,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Ai.isPair(h)){let k=Ai.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),pl(t,d,k.commentBefore,!1),k.comment&&(f=!0));let b=Ai.isNode(h.value)?h.value:null;b?(b.comment&&(g=b.comment),b.commentBefore&&(f=!0)):h.value==null&&k?.comment&&(g=k.comment)}g&&(f=!0);let w=rv.stringify(h,l,()=>g=null);f||(f=d.length>a||w.includes(`
|
|
51
|
+
`)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(f||(f=d.reduce((k,b)=>k+b.length+2,2)+(w.length+2)>t.options.lineWidth)),f&&(w+=",")),g&&(w+=fl.lineComment(w,n,c(g))),d.push(w),a=d.length}let{start:p,end:u}=r;if(d.length===0)return p+u;if(!f){let m=d.reduce((h,g)=>h+g.length+2,2);f=t.options.lineWidth>0&&m>t.options.lineWidth}if(f){let m=p;for(let h of d)m+=h?`
|
|
52
|
+
${s}${i}${h}`:`
|
|
53
|
+
`;return`${m}
|
|
54
|
+
${i}${u}`}else return`${p}${o}${d.join(" ")}${o}${u}`}function pl({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=fl.indentComment(t(n),e);r.push(s.trimStart())}}nv.stringifyCollection=HP});var Hn=x(Uf=>{"use strict";var UP=Bf(),zP=Ff(),KP=Zc(),Fn=ke(),ml=Mn(),GP=tt();function Uo(e,t){let r=Fn.isScalar(t)?t.value:t;for(let n of e)if(Fn.isPair(n)&&(n.key===t||n.key===r||Fn.isScalar(n.key)&&n.key.value===r))return n}var Vf=class extends KP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Fn.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:s}=n,o=new this(t),c=(l,f)=>{if(typeof s=="function")f=s.call(r,l,f);else if(Array.isArray(s)&&!s.includes(l))return;(f!==void 0||i)&&o.items.push(ml.createPair(l,f,n))};if(r instanceof Map)for(let[l,f]of r)c(l,f);else if(r&&typeof r=="object")for(let l of Object.keys(r))c(l,r[l]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let n;Fn.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new ml.Pair(t,t?.value):n=new ml.Pair(t.key,t.value);let i=Uo(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Fn.isScalar(i.value)&&GP.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(c=>s(n,c)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let r=Uo(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=Uo(this.items,t)?.value;return(!r&&Fn.isScalar(i)?i.value:i)??void 0}has(t){return!!Uo(this.items,t)}set(t,r){this.add(new ml.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let s of this.items)zP.addPairToJSMap(r,i,s);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Fn.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),UP.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};Uf.YAMLMap=Vf;Uf.findPair=Uo});var Cs=x(sv=>{"use strict";var JP=ke(),iv=Hn(),YP={collection:"map",default:!0,nodeClass:iv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return JP.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>iv.YAMLMap.from(e,t,r)};sv.map=YP});var Bn=x(ov=>{"use strict";var XP=Lo(),QP=Bf(),ZP=Zc(),gl=ke(),eO=tt(),tO=Dn(),zf=class extends ZP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(gl.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=hl(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=hl(t);if(typeof n!="number")return;let i=this.items[n];return!r&&gl.isScalar(i)?i.value:i}has(t){let r=hl(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=hl(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];gl.isScalar(i)&&eO.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let s of this.items)n.push(tO.toJS(s,String(i++),r));return n}toString(t,r,n){return t?QP.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let c of r){if(typeof i=="function"){let l=r instanceof Set?c:String(o++);c=i.call(r,l,c)}s.items.push(XP.createNode(c,void 0,n))}}return s}};function hl(e){let t=gl.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}ov.YAMLSeq=zf});var Es=x(cv=>{"use strict";var rO=ke(),av=Bn(),nO={collection:"seq",default:!0,nodeClass:av.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return rO.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>av.YAMLSeq.from(e,t,r)};cv.seq=nO});var zo=x(lv=>{"use strict";var iO=Ho(),sO={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),iO.stringifyString(e,t,r,n)}};lv.string=sO});var wl=x(fv=>{"use strict";var uv=tt(),dv={identify:e=>e==null,createNode:()=>new uv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new uv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&dv.test.test(e)?e:t.options.nullStr};fv.nullTag=dv});var Kf=x(mv=>{"use strict";var oO=tt(),pv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new oO.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&pv.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};mv.boolTag=pv});var As=x(hv=>{"use strict";function aO({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let c=t-(s.length-o-1);for(;c-- >0;)s+="0"}return s}hv.stringifyNumber=aO});var Jf=x(yl=>{"use strict";var cO=tt(),Gf=As(),lO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Gf.stringifyNumber},uO={identify:e=>typeof e=="number",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){let t=Number(e.value);return isFinite(t)?t.toExponential():Gf.stringifyNumber(e)}},dO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new cO.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Gf.stringifyNumber};yl.float=dO;yl.floatExp=uO;yl.floatNaN=lO});var Xf=x(kl=>{"use strict";var gv=As(),vl=e=>typeof e=="bigint"||Number.isInteger(e),Yf=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function wv(e,t,r){let{value:n}=e;return vl(n)&&n>=0?r+n.toString(t):gv.stringifyNumber(e)}var fO={identify:e=>vl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Yf(e,2,8,r),stringify:e=>wv(e,8,"0o")},pO={identify:vl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Yf(e,0,10,r),stringify:gv.stringifyNumber},mO={identify:e=>vl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Yf(e,2,16,r),stringify:e=>wv(e,16,"0x")};kl.int=pO;kl.intHex=mO;kl.intOct=fO});var vv=x(yv=>{"use strict";var hO=Cs(),gO=wl(),wO=Es(),yO=zo(),vO=Kf(),Qf=Jf(),Zf=Xf(),kO=[hO.map,wO.seq,yO.string,gO.nullTag,vO.boolTag,Zf.intOct,Zf.int,Zf.intHex,Qf.floatNaN,Qf.floatExp,Qf.float];yv.schema=kO});var Rv=x(bv=>{"use strict";var bO=tt(),RO=Cs(),SO=Es();function kv(e){return typeof e=="bigint"||Number.isInteger(e)}var bl=({value:e})=>JSON.stringify(e),CO=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:bl},{identify:e=>e==null,createNode:()=>new bO.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:bl},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:bl},{identify:kv,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>kv(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:bl}],EO={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},AO=[RO.map,SO.seq].concat(CO,EO);bv.schema=AO});var tp=x(Sv=>{"use strict";var Ko=Nc("buffer"),ep=tt(),xO=Ho(),_O={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ko.Buffer=="function")return Ko.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,s){if(!r)return"";let o=r,c;if(typeof Ko.Buffer=="function")c=o instanceof Ko.Buffer?o.toString("base64"):Ko.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let f=0;f<o.length;++f)l+=String.fromCharCode(o[f]);c=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=ep.Scalar.BLOCK_LITERAL),t!==ep.Scalar.QUOTE_DOUBLE){let l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),f=Math.ceil(c.length/l),a=new Array(f);for(let d=0,p=0;d<f;++d,p+=l)a[d]=c.substr(p,l);c=a.join(t===ep.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return xO.stringifyString({comment:e,type:t,value:c},n,i,s)}};Sv.binary=_O});var Cl=x(Sl=>{"use strict";var Rl=ke(),rp=Mn(),IO=tt(),PO=Bn();function Cv(e,t){if(Rl.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!Rl.isPair(n)){if(Rl.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new rp.Pair(new IO.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
56
|
+
${i.key.commentBefore}`:n.commentBefore),n.comment){let s=i.value??i.key;s.comment=s.comment?`${n.comment}
|
|
57
|
+
${s.comment}`:n.comment}n=i}e.items[r]=Rl.isPair(n)?n:new rp.Pair(n)}}else t("Expected a sequence for this tag");return e}function Ev(e,t,r){let{replacer:n}=r,i=new PO.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(s++),o));let c,l;if(Array.isArray(o))if(o.length===2)c=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let f=Object.keys(o);if(f.length===1)c=f[0],l=o[c];else throw new TypeError(`Expected tuple with one key, not ${f.length} keys`)}else c=o;i.items.push(rp.createPair(c,l,r))}return i}var OO={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Cv,createNode:Ev};Sl.createPairs=Ev;Sl.pairs=OO;Sl.resolvePairs=Cv});var sp=x(ip=>{"use strict";var Av=ke(),np=Dn(),Go=Hn(),TO=Bn(),xv=Cl(),xi=class e extends TO.YAMLSeq{constructor(){super(),this.add=Go.YAMLMap.prototype.add.bind(this),this.delete=Go.YAMLMap.prototype.delete.bind(this),this.get=Go.YAMLMap.prototype.get.bind(this),this.has=Go.YAMLMap.prototype.has.bind(this),this.set=Go.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let s,o;if(Av.isPair(i)?(s=np.toJS(i.key,"",r),o=np.toJS(i.value,s,r)):s=np.toJS(i,"",r),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(t,r,n){let i=xv.createPairs(t,r,n),s=new this;return s.items=i.items,s}};xi.tag="tag:yaml.org,2002:omap";var NO={collection:"seq",identify:e=>e instanceof Map,nodeClass:xi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=xv.resolvePairs(e,t),n=[];for(let{key:i}of r.items)Av.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new xi,r)},createNode:(e,t,r)=>xi.from(e,t,r)};ip.YAMLOMap=xi;ip.omap=NO});var Tv=x(op=>{"use strict";var _v=tt();function Iv({value:e,source:t},r){return t&&(e?Pv:Ov).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Pv={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new _v.Scalar(!0),stringify:Iv},Ov={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new _v.Scalar(!1),stringify:Iv};op.falseTag=Ov;op.trueTag=Pv});var Nv=x(El=>{"use strict";var $O=tt(),ap=As(),jO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ap.stringifyNumber},DO={identify:e=>typeof e=="number",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){let t=Number(e.value);return isFinite(t)?t.toExponential():ap.stringifyNumber(e)}},qO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new $O.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:ap.stringifyNumber};El.float=qO;El.floatExp=DO;El.floatNaN=jO});var jv=x(Yo=>{"use strict";var $v=As(),Jo=e=>typeof e=="bigint"||Number.isInteger(e);function Al(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return i==="-"?BigInt(-1)*o:o}let s=parseInt(e,r);return i==="-"?-1*s:s}function cp(e,t,r){let{value:n}=e;if(Jo(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return $v.stringifyNumber(e)}var LO={identify:Jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Al(e,2,2,r),stringify:e=>cp(e,2,"0b")},WO={identify:Jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Al(e,1,8,r),stringify:e=>cp(e,8,"0")},MO={identify:Jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Al(e,0,10,r),stringify:$v.stringifyNumber},FO={identify:Jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Al(e,2,16,r),stringify:e=>cp(e,16,"0x")};Yo.int=MO;Yo.intBin=LO;Yo.intHex=FO;Yo.intOct=WO});var up=x(lp=>{"use strict";var Il=ke(),xl=Mn(),_l=Hn(),_i=class e extends _l.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Il.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new xl.Pair(t.key,null):r=new xl.Pair(t,null),_l.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=_l.findPair(this.items,t);return!r&&Il.isPair(n)?Il.isScalar(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=_l.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new xl.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),s.items.push(xl.createPair(o,null,n));return s}};_i.tag="tag:yaml.org,2002:set";var HO={collection:"map",identify:e=>e instanceof Set,nodeClass:_i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>_i.from(e,t,r),resolve(e,t){if(Il.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new _i,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};lp.YAMLSet=_i;lp.set=HO});var fp=x(Pl=>{"use strict";var BO=As();function dp(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=o=>t?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,c)=>o*i(60)+i(c),i(0));return r==="-"?i(-1)*s:s}function Dv(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return BO.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(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))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var VO={identify:e=>typeof e=="bigint"||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:r})=>dp(e,r),stringify:Dv},UO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>dp(e,!1),stringify:Dv},qv={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){let t=e.match(qv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,s,o,c]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,f=Date.UTC(r,n-1,i,s||0,o||0,c||0,l),a=t[8];if(a&&a!=="Z"){let d=dp(a,!1);Math.abs(d)<30&&(d*=60),f-=6e4*d}return new Date(f)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Pl.floatTime=UO;Pl.intTime=VO;Pl.timestamp=qv});var Mv=x(Wv=>{"use strict";var zO=Cs(),KO=wl(),GO=Es(),JO=zo(),YO=tp(),Lv=Tv(),pp=Nv(),Ol=jv(),XO=ll(),QO=sp(),ZO=Cl(),e0=up(),mp=fp(),t0=[zO.map,GO.seq,JO.string,KO.nullTag,Lv.trueTag,Lv.falseTag,Ol.intBin,Ol.intOct,Ol.int,Ol.intHex,pp.floatNaN,pp.floatExp,pp.float,YO.binary,XO.merge,QO.omap,ZO.pairs,e0.set,mp.intTime,mp.floatTime,mp.timestamp];Wv.schema=t0});var Yv=x(wp=>{"use strict";var Vv=Cs(),r0=wl(),Uv=Es(),n0=zo(),i0=Kf(),hp=Jf(),gp=Xf(),s0=vv(),o0=Rv(),zv=tp(),Xo=ll(),Kv=sp(),Gv=Cl(),Fv=Mv(),Jv=up(),Tl=fp(),Hv=new Map([["core",s0.schema],["failsafe",[Vv.map,Uv.seq,n0.string]],["json",o0.schema],["yaml11",Fv.schema],["yaml-1.1",Fv.schema]]),Bv={binary:zv.binary,bool:i0.boolTag,float:hp.float,floatExp:hp.floatExp,floatNaN:hp.floatNaN,floatTime:Tl.floatTime,int:gp.int,intHex:gp.intHex,intOct:gp.intOct,intTime:Tl.intTime,map:Vv.map,merge:Xo.merge,null:r0.nullTag,omap:Kv.omap,pairs:Gv.pairs,seq:Uv.seq,set:Jv.set,timestamp:Tl.timestamp},a0={"tag:yaml.org,2002:binary":zv.binary,"tag:yaml.org,2002:merge":Xo.merge,"tag:yaml.org,2002:omap":Kv.omap,"tag:yaml.org,2002:pairs":Gv.pairs,"tag:yaml.org,2002:set":Jv.set,"tag:yaml.org,2002:timestamp":Tl.timestamp};function c0(e,t,r){let n=Hv.get(t);if(n&&!e)return r&&!n.includes(Xo.merge)?n.concat(Xo.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let s=Array.from(Hv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)i=i.concat(s);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(Xo.merge)),i.reduce((s,o)=>{let c=typeof o=="string"?Bv[o]:o;if(!c){let l=JSON.stringify(o),f=Object.keys(Bv).map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${f}`)}return s.includes(c)||s.push(c),s},[])}wp.coreKnownTags=a0;wp.getTags=c0});var kp=x(Xv=>{"use strict";var yp=ke(),l0=Cs(),u0=Es(),d0=zo(),Nl=Yv(),f0=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,vp=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:c}){this.compat=Array.isArray(t)?Nl.getTags(t,"compat"):t?Nl.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Nl.coreKnownTags:{},this.tags=Nl.getTags(r,this.name,n),this.toStringOptions=c??null,Object.defineProperty(this,yp.MAP,{value:l0.map}),Object.defineProperty(this,yp.SCALAR,{value:d0.string}),Object.defineProperty(this,yp.SEQ,{value:u0.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?f0:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Xv.Schema=vp});var Zv=x(Qv=>{"use strict";var p0=ke(),bp=Bo(),Qo=Wo();function m0(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(r.push(l),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=bp.createStringifyContext(e,t),{commentString:s}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let l=s(e.commentBefore);r.unshift(Qo.indentComment(l,""))}let o=!1,c=null;if(e.contents){if(p0.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let a=s(e.contents.commentBefore);r.push(Qo.indentComment(a,""))}i.forceBlockIndent=!!e.comment,c=e.contents.comment}let l=c?void 0:()=>o=!0,f=bp.stringify(e.contents,i,()=>c=null,l);c&&(f+=Qo.lineComment(f,"",s(c))),(f[0]==="|"||f[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${f}`:r.push(f)}else r.push(bp.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let l=s(e.comment);l.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(Qo.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=e.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||c)&&r[r.length-1]!==""&&r.push(""),r.push(Qo.indentComment(s(l),"")))}return r.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}Qv.stringifyDocument=m0});var Zo=x(ek=>{"use strict";var h0=qo(),xs=Zc(),cr=ke(),g0=Mn(),w0=Dn(),y0=kp(),v0=Zv(),Rp=Jc(),k0=Af(),b0=Lo(),Sp=Ef(),Cp=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,cr.NODE_TYPE,{value:cr.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Sp.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[cr.NODE_TYPE]:{value:cr.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=cr.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){_s(this.contents)&&this.contents.add(t)}addIn(t,r){_s(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=Rp.anchorNames(this);t.anchor=!r||n.has(r)?Rp.findNewAnchor(r||"a",n):r}return new h0.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let g=k=>typeof k=="number"||k instanceof String||k instanceof Number,w=r.filter(g).map(String);w.length>0&&(r=r.concat(w)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:c,keepUndefined:l,onTagObj:f,tag:a}=n??{},{onAnchor:d,setAnchors:p,sourceObjects:u}=Rp.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:f,replacer:i,schema:this.schema,sourceObjects:u},h=b0.createNode(t,a,m);return c&&cr.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,n={}){let i=this.createNode(t,null,n),s=this.createNode(r,null,n);return new g0.Pair(i,s)}delete(t){return _s(this.contents)?this.contents.delete(t):!1}deleteIn(t){return xs.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):_s(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return cr.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return xs.isEmptyPath(t)?!r&&cr.isScalar(this.contents)?this.contents.value:this.contents:cr.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return cr.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return xs.isEmptyPath(t)?this.contents!==void 0:cr.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=xs.collectionFromPath(this.schema,[t],r):_s(this.contents)&&this.contents.set(t,r)}setIn(t,r){xs.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=xs.collectionFromPath(this.schema,Array.from(t),r):_s(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Sp.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Sp.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new y0.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let c={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=w0.toJS(this.contents,r??"",c);if(typeof s=="function")for(let{count:f,res:a}of c.anchors.values())s(a,f);return typeof o=="function"?k0.applyReviver(o,{"":l},"",l):l}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return v0.stringifyDocument(this,t)}};function _s(e){if(cr.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ek.Document=Cp});var ra=x(ta=>{"use strict";var ea=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Ep=class extends ea{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Ap=class extends ea{constructor(t,r,n){super("YAMLWarning",t,r,n)}},R0=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(c=>t.linePos(c));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let c=Math.min(s-39,o.length-79);o="…"+o.substring(c),s-=c-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,s))){let c=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);c.length>80&&(c=c.substring(0,79)+`…
|
|
61
|
+
`),o=c+o}if(/[^ ]/.test(o)){let c=1,l=r.linePos[1];l?.line===n&&l.col>i&&(c=Math.max(1,Math.min(l.col-i,80-s)));let f=" ".repeat(s)+"^".repeat(c);r.message+=`:
|
|
62
|
+
|
|
63
|
+
${o}
|
|
64
|
+
${f}
|
|
65
|
+
`}};ta.YAMLError=ea;ta.YAMLParseError=Ep;ta.YAMLWarning=Ap;ta.prettifyError=R0});var na=x(tk=>{"use strict";function S0(e,{flow:t,indicator:r,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:c}){let l=!1,f=c,a=c,d="",p="",u=!1,m=!1,h=null,g=null,w=null,k=null,b=null,R=null,E=null;for(let D of e)switch(m&&(D.type!=="space"&&D.type!=="newline"&&D.type!=="comma"&&s(D.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(f&&D.type!=="comment"&&D.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),D.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&D.source.includes(" ")&&(h=D),a=!0;break;case"comment":{a||s(D,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let G=D.source.substring(1)||" ";d?d+=p+G:d=G,p="",f=!1;break}case"newline":f?d?d+=D.source:(!R||r!=="seq-item-ind")&&(l=!0):p+=D.source,f=!0,u=!0,(g||w)&&(k=D),a=!0;break;case"anchor":g&&s(D,"MULTIPLE_ANCHORS","A node can have at most one anchor"),D.source.endsWith(":")&&s(D.offset+D.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=D,E??(E=D.offset),f=!1,a=!1,m=!0;break;case"tag":{w&&s(D,"MULTIPLE_TAGS","A node can have at most one tag"),w=D,E??(E=D.offset),f=!1,a=!1,m=!0;break}case r:(g||w)&&s(D,"BAD_PROP_ORDER",`Anchors and tags must be after the ${D.source} indicator`),R&&s(D,"UNEXPECTED_TOKEN",`Unexpected ${D.source} in ${t??"collection"}`),R=D,f=r==="seq-item-ind"||r==="explicit-key-ind",a=!1;break;case"comma":if(t){b&&s(D,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=D,f=!1,a=!1;break}default:s(D,"UNEXPECTED_TOKEN",`Unexpected ${D.type} token`),f=!1,a=!1}let O=e[e.length-1],z=O?O.offset+O.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(f&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:R,spaceBefore:l,comment:d,hasNewline:u,anchor:g,tag:w,newlineAfterProp:k,end:z,start:E??z}}tk.resolveProps=S0});var $l=x(rk=>{"use strict";function xp(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(xp(t.key)||xp(t.value))return!0}return!1;default:return!0}}rk.containsNewline=xp});var _p=x(nk=>{"use strict";var C0=$l();function E0(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&C0.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}nk.flowIndentCheck=E0});var Ip=x(sk=>{"use strict";var ik=ke();function A0(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||ik.isScalar(s)&&ik.isScalar(o)&&s.value===o.value;return t.some(s=>i(s.key,r))}sk.mapIncludes=A0});var dk=x(uk=>{"use strict";var ok=Mn(),x0=Hn(),ak=na(),_0=$l(),ck=_p(),I0=Ip(),lk="All mapping items must start at the same column";function P0({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??x0.YAMLMap,c=new o(r.schema);r.atRoot&&(r.atRoot=!1);let l=n.offset,f=null;for(let a of n.items){let{start:d,key:p,sep:u,value:m}=a,h=ak.resolveProps(d,{indicator:"explicit-key-ind",next:p??u?.[0],offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!h.found;if(g){if(p&&(p.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&i(l,"BAD_INDENT",lk)),!h.anchor&&!h.tag&&!u){f=h.end,h.comment&&(c.comment?c.comment+=`
|
|
67
|
+
`+h.comment:c.comment=h.comment);continue}(h.newlineAfterProp||_0.containsNewline(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(l,"BAD_INDENT",lk);r.atKey=!0;let w=h.end,k=p?e(r,p,h,i):t(r,w,d,null,h,i);r.schema.compat&&ck.flowIndentCheck(n.indent,p,i),r.atKey=!1,I0.mapIncludes(r,c.items,k)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let b=ak.resolveProps(u??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=b.end,b.found){g&&(m?.type==="block-map"&&!b.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<b.found.offset-1024&&i(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let R=m?e(r,m,b,i):t(r,l,u,null,b,i);r.schema.compat&&ck.flowIndentCheck(n.indent,m,i),l=R.range[2];let E=new ok.Pair(k,R);r.options.keepSourceTokens&&(E.srcToken=a),c.items.push(E)}else{g&&i(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(k.comment?k.comment+=`
|
|
68
|
+
`+b.comment:k.comment=b.comment);let R=new ok.Pair(k);r.options.keepSourceTokens&&(R.srcToken=a),c.items.push(R)}}return f&&f<l&&i(f,"IMPOSSIBLE","Map comment with trailing content"),c.range=[n.offset,l,f??l],c}uk.resolveBlockMap=P0});var pk=x(fk=>{"use strict";var O0=Bn(),T0=na(),N0=_p();function $0({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??O0.YAMLSeq,c=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let l=n.offset,f=null;for(let{start:a,value:d}of n.items){let p=T0.resolveProps(a,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?i(p.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{f=p.end,p.comment&&(c.comment=p.comment);continue}let u=d?e(r,d,p,i):t(r,p.end,a,null,p,i);r.schema.compat&&N0.flowIndentCheck(n.indent,d,i),l=u.range[2],c.items.push(u)}return c.range=[n.offset,l,f??l],c}fk.resolveBlockSeq=$0});var Is=x(mk=>{"use strict";function j0(e,t,r,n){let i="";if(e){let s=!1,o="";for(let c of e){let{source:l,type:f}=c;switch(f){case"space":s=!0;break;case"comment":{r&&!s&&n(c,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let a=l.substring(1)||" ";i?i+=o+a:i=a,o="";break}case"newline":i&&(o+=l),s=!0;break;default:n(c,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}t+=l.length}}return{comment:i,offset:t}}mk.resolveEnd=j0});var yk=x(wk=>{"use strict";var D0=ke(),q0=Mn(),hk=Hn(),L0=Bn(),W0=Is(),gk=na(),M0=$l(),F0=Ip(),Pp="Block collections are not allowed within flow collections",Op=e=>e&&(e.type==="block-map"||e.type==="block-seq");function H0({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=n.start.source==="{",c=o?"flow map":"flow sequence",l=s?.nodeClass??(o?hk.YAMLMap:L0.YAMLSeq),f=new l(r.schema);f.flow=!0;let a=r.atRoot;a&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let w=n.items[g],{start:k,key:b,sep:R,value:E}=w,O=gk.resolveProps(k,{flow:c,indicator:"explicit-key-ind",next:b??R?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!R&&!E){g===0&&O.comma?i(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`):g<n.items.length-1&&i(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${c}`),O.comment&&(f.comment?f.comment+=`
|
|
69
|
+
`+O.comment:f.comment=O.comment),d=O.end;continue}!o&&r.options.strict&&M0.containsNewline(b)&&i(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)O.comma&&i(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`);else if(O.comma||i(O.start,"MISSING_CHAR",`Missing , between ${c} items`),O.comment){let z="";e:for(let D of k)switch(D.type){case"comma":case"space":break;case"comment":z=D.source.substring(1);break e;default:break e}if(z){let D=f.items[f.items.length-1];D0.isPair(D)&&(D=D.value??D.key),D.comment?D.comment+=`
|
|
70
|
+
`+z:D.comment=z,O.comment=O.comment.substring(z.length+1)}}if(!o&&!R&&!O.found){let z=E?e(r,E,O,i):t(r,O.end,R,null,O,i);f.items.push(z),d=z.range[2],Op(E)&&i(z.range,"BLOCK_IN_FLOW",Pp)}else{r.atKey=!0;let z=O.end,D=b?e(r,b,O,i):t(r,z,k,null,O,i);Op(b)&&i(D.range,"BLOCK_IN_FLOW",Pp),r.atKey=!1;let G=gk.resolveProps(R??[],{flow:c,indicator:"map-value-ind",next:E,offset:D.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(G.found){if(!o&&!O.found&&r.options.strict){if(R)for(let Z of R){if(Z===G.found)break;if(Z.type==="newline"){i(Z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}O.start<G.found.offset-1024&&i(G.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?i(E,"MISSING_CHAR",`Missing space after : in ${c}`):i(G.start,"MISSING_CHAR",`Missing , or : between ${c} items`));let J=E?e(r,E,G,i):G.found?t(r,G.end,R,null,G,i):null;J?Op(E)&&i(J.range,"BLOCK_IN_FLOW",Pp):G.comment&&(D.comment?D.comment+=`
|
|
71
|
+
`+G.comment:D.comment=G.comment);let te=new q0.Pair(D,J);if(r.options.keepSourceTokens&&(te.srcToken=w),o){let Z=f;F0.mapIncludes(r,Z.items,D)&&i(z,"DUPLICATE_KEY","Map keys must be unique"),Z.items.push(te)}else{let Z=new hk.YAMLMap(r.schema);Z.flow=!0,Z.items.push(te);let we=(J??D).range;Z.range=[D.range[0],we[1],we[2]],f.items.push(Z)}d=J?J.range[2]:G.end}}let p=o?"}":"]",[u,...m]=n.end,h=d;if(u?.source===p)h=u.offset+u.source.length;else{let g=c[0].toUpperCase()+c.substring(1),w=a?`${g} must end with a ${p}`:`${g} in block collection must be sufficiently indented and end with a ${p}`;i(d,a?"MISSING_CHAR":"BAD_INDENT",w),u&&u.source.length!==1&&m.unshift(u)}if(m.length>0){let g=W0.resolveEnd(m,h,r.options.strict,i);g.comment&&(f.comment?f.comment+=`
|
|
72
|
+
`+g.comment:f.comment=g.comment),f.range=[n.offset,h,g.offset]}else f.range=[n.offset,h,h];return f}wk.resolveFlowCollection=H0});var kk=x(vk=>{"use strict";var B0=ke(),V0=tt(),U0=Hn(),z0=Bn(),K0=dk(),G0=pk(),J0=yk();function Tp(e,t,r,n,i,s){let o=r.type==="block-map"?K0.resolveBlockMap(e,t,r,n,s):r.type==="block-seq"?G0.resolveBlockSeq(e,t,r,n,s):J0.resolveFlowCollection(e,t,r,n,s),c=o.constructor;return i==="!"||i===c.tagName?(o.tag=c.tagName,o):(i&&(o.tag=i),o)}function Y0(e,t,r,n,i){let s=n.tag,o=s?t.directives.tagName(s.source,p=>i(s,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:u}=n,m=p&&s?p.offset>s.offset?p:s:p??s;m&&(!u||u.offset<m.offset)&&i(m,"MISSING_CHAR","Missing newline after block sequence props")}let c=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!s||!o||o==="!"||o===U0.YAMLMap.tagName&&c==="map"||o===z0.YAMLSeq.tagName&&c==="seq")return Tp(e,t,r,i,o);let l=t.schema.tags.find(p=>p.tag===o&&p.collection===c);if(!l){let p=t.schema.knownTags[o];if(p?.collection===c)t.schema.tags.push(Object.assign({},p,{default:!1})),l=p;else return p?i(s,"BAD_COLLECTION_TYPE",`${p.tag} used for ${c} collection, but expects ${p.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Tp(e,t,r,i,o)}let f=Tp(e,t,r,i,o,l),a=l.resolve?.(f,p=>i(s,"TAG_RESOLVE_FAILED",p),t.options)??f,d=B0.isNode(a)?a:new V0.Scalar(a);return d.range=f.range,d.tag=o,l?.format&&(d.format=l.format),d}vk.composeCollection=Y0});var $p=x(bk=>{"use strict";var Np=tt();function X0(e,t,r){let n=t.offset,i=Q0(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?Np.Scalar.BLOCK_FOLDED:Np.Scalar.BLOCK_LITERAL,o=t.source?Z0(t.source):[],c=o.length;for(let h=o.length-1;h>=0;--h){let g=o[h][1];if(g===""||g==="\r")c=h;else break}if(c===0){let h=i.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:h,type:s,comment:i.comment,range:[n,g,g]}}let l=t.indent+i.indent,f=t.offset+i.length,a=0;for(let h=0;h<c;++h){let[g,w]=o[h];if(w===""||w==="\r")i.indent===0&&g.length>l&&(l=g.length);else{g.length<l&&r(f+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=g.length),a=h,l===0&&!e.atRoot&&r(f,"BAD_INDENT","Block scalar values in collections must be indented");break}f+=g.length+w.length+1}for(let h=o.length-1;h>=c;--h)o[h][0].length>l&&(c=h+1);let d="",p="",u=!1;for(let h=0;h<a;++h)d+=o[h][0].slice(l)+`
|
|
74
|
+
`;for(let h=a;h<c;++h){let[g,w]=o[h];f+=g.length+w.length+1;let k=w[w.length-1]==="\r";if(k&&(w=w.slice(0,-1)),w&&g.length<l){let R=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(f-w.length-(k?2:1),"BAD_INDENT",R),g=""}s===Np.Scalar.BLOCK_LITERAL?(d+=p+g.slice(l)+w,p=`
|
|
75
|
+
`):g.length>l||w[0]===" "?(p===" "?p=`
|
|
76
|
+
`:!u&&p===`
|
|
77
|
+
`&&(p=`
|
|
78
|
+
|
|
79
|
+
`),d+=p+g.slice(l)+w,p=`
|
|
80
|
+
`,u=!0):w===""?p===`
|
|
81
|
+
`?d+=`
|
|
82
|
+
`:p=`
|
|
83
|
+
`:(d+=p+w,p=" ",u=!1)}switch(i.chomp){case"-":break;case"+":for(let h=c;h<o.length;++h)d+=`
|
|
84
|
+
`+o[h][0].slice(l);d[d.length-1]!==`
|
|
85
|
+
`&&(d+=`
|
|
86
|
+
`);break;default:d+=`
|
|
87
|
+
`}let m=n+i.length+t.source.length;return{value:d,type:s,comment:i.comment,range:[n,m,m]}}function Q0({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],s=i[0],o=0,c="",l=-1;for(let p=1;p<i.length;++p){let u=i[p];if(!c&&(u==="-"||u==="+"))c=u;else{let m=Number(u);!o&&m?o=m:l===-1&&(l=e+p)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let f=!1,a="",d=i.length;for(let p=1;p<t.length;++p){let u=t[p];switch(u.type){case"space":f=!0;case"newline":d+=u.source.length;break;case"comment":r&&!f&&n(u,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=u.source.length,a=u.source.substring(1);break;case"error":n(u,"UNEXPECTED_TOKEN",u.message),d+=u.source.length;break;default:{let m=`Unexpected token in block scalar header: ${u.type}`;n(u,"UNEXPECTED_TOKEN",m);let h=u.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:s,indent:o,chomp:c,comment:a,length:d}}function Z0(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),s=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)s.push([t[o],t[o+1]]);return s}bk.resolveBlockScalar=X0});var Dp=x(Sk=>{"use strict";var jp=tt(),eT=Is();function tT(e,t,r){let{offset:n,type:i,source:s,end:o}=e,c,l,f=(p,u,m)=>r(n+p,u,m);switch(i){case"scalar":c=jp.Scalar.PLAIN,l=rT(s,f);break;case"single-quoted-scalar":c=jp.Scalar.QUOTE_SINGLE,l=nT(s,f);break;case"double-quoted-scalar":c=jp.Scalar.QUOTE_DOUBLE,l=iT(s,f);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let a=n+s.length,d=eT.resolveEnd(o,a,t,r);return{value:l,type:c,comment:d.comment,range:[n,a,d.offset]}}function rT(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Rk(e)}function nT(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Rk(e.slice(1,-1)).replace(/''/g,"'")}function Rk(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
|
+
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],s=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)n[1]===""?s===`
|
|
90
|
+
`?i+=s:s=`
|
|
91
|
+
`:(i+=s+n[1],s=" "),o=r.lastIndex;let c=/[ \t]*(.*)/sy;return c.lastIndex=o,n=c.exec(e),i+s+(n?.[1]??"")}function iT(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
|
|
92
|
+
`))if(i===`
|
|
93
|
+
`){let{fold:s,offset:o}=sT(e,n);r+=s,n=o}else if(i==="\\"){let s=e[++n],o=oT[s];if(o)r+=o;else if(s===`
|
|
94
|
+
`)for(s=e[n+1];s===" "||s===" ";)s=e[++n+1];else if(s==="\r"&&e[n+1]===`
|
|
95
|
+
`)for(s=e[++n+1];s===" "||s===" ";)s=e[++n+1];else if(s==="x"||s==="u"||s==="U"){let c=s==="x"?2:s==="u"?4:8;r+=aT(e,n+1,c,t),n+=c}else{let c=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),r+=c}}else if(i===" "||i===" "){let s=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&e[n+2]===`
|
|
97
|
+
`)&&(r+=n>s?e.slice(s,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function sT(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
|
|
98
|
+
`||n==="\r")&&!(n==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)n===`
|
|
100
|
+
`&&(r+=`
|
|
101
|
+
`),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var oT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function aT(e,t,r,n){let i=e.substr(t,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let c=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}Sk.resolveFlowScalar=tT});var Ak=x(Ek=>{"use strict";var Ii=ke(),Ck=tt(),cT=$p(),lT=Dp();function uT(e,t,r,n){let{value:i,type:s,comment:o,range:c}=t.type==="block-scalar"?cT.resolveBlockScalar(e,t,n):lT.resolveFlowScalar(t,e.options.strict,n),l=r?e.directives.tagName(r.source,d=>n(r,"TAG_RESOLVE_FAILED",d)):null,f;e.options.stringKeys&&e.atKey?f=e.schema[Ii.SCALAR]:l?f=dT(e.schema,i,l,r,n):t.type==="scalar"?f=fT(e,i,t,n):f=e.schema[Ii.SCALAR];let a;try{let d=f.resolve(i,p=>n(r??t,"TAG_RESOLVE_FAILED",p),e.options);a=Ii.isScalar(d)?d:new Ck.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);n(r??t,"TAG_RESOLVE_FAILED",p),a=new Ck.Scalar(i)}return a.range=c,a.source=i,s&&(a.type=s),l&&(a.tag=l),f.format&&(a.format=f.format),o&&(a.comment=o),a}function dT(e,t,r,n,i){if(r==="!")return e[Ii.SCALAR];let s=[];for(let c of e.tags)if(!c.collection&&c.tag===r)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if(c.test?.test(t))return c;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Ii.SCALAR])}function fT({atKey:e,directives:t,schema:r},n,i,s){let o=r.tags.find(c=>(c.default===!0||e&&c.default==="key")&&c.test?.test(n))||r[Ii.SCALAR];if(r.compat){let c=r.compat.find(l=>l.default&&l.test?.test(n))??r[Ii.SCALAR];if(o.tag!==c.tag){let l=t.tagString(o.tag),f=t.tagString(c.tag),a=`Value may be parsed as either ${l} or ${f}`;s(i,"TAG_RESOLVE_FAILED",a,!0)}}return o}Ek.composeScalar=uT});var _k=x(xk=>{"use strict";function pT(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}xk.emptyScalarPosition=pT});var Ok=x(Lp=>{"use strict";var mT=qo(),hT=ke(),gT=kk(),Ik=Ak(),wT=Is(),yT=_k(),vT={composeNode:Pk,composeEmptyNode:qp};function Pk(e,t,r,n){let i=e.atKey,{spaceBefore:s,comment:o,anchor:c,tag:l}=r,f,a=!0;switch(t.type){case"alias":f=kT(e,t,n),(c||l)&&n(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":f=Ik.composeScalar(e,t,l,n),c&&(f.anchor=c.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{f=gT.composeCollection(vT,e,t,r,n),c&&(f.anchor=c.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),a=!1}}return f??(f=qp(e,t.offset,void 0,null,r,n)),c&&f.anchor===""&&n(c,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!hT.isScalar(f)||typeof f.value!="string"||f.tag&&f.tag!=="tag:yaml.org,2002:str")&&n(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(f.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?f.comment=o:f.commentBefore=o),e.options.keepSourceTokens&&a&&(f.srcToken=t),f}function qp(e,t,r,n,{spaceBefore:i,comment:s,anchor:o,tag:c,end:l},f){let a={type:"scalar",offset:yT.emptyScalarPosition(t,r,n),indent:-1,source:""},d=Ik.composeScalar(e,a,c,f);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&f(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=l),d}function kT({options:e},{offset:t,source:r,end:n},i){let s=new mT.Alias(r.substring(1));s.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,c=wT.resolveEnd(n,o,e.strict,i);return s.range=[t,o,c.offset],c.comment&&(s.comment=c.comment),s}Lp.composeEmptyNode=qp;Lp.composeNode=Pk});var $k=x(Nk=>{"use strict";var bT=Zo(),Tk=Ok(),RT=Is(),ST=na();function CT(e,t,{offset:r,start:n,value:i,end:s},o){let c=Object.assign({_directives:t},e),l=new bT.Document(void 0,c),f={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},a=ST.resolveProps(n,{indicator:"doc-start",next:i??s?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});a.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!a.hasNewline&&o(a.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?Tk.composeNode(f,i,a,o):Tk.composeEmptyNode(f,a.end,n,null,a,o);let d=l.contents.range[2],p=RT.resolveEnd(s,d,!1,o);return p.comment&&(l.comment=p.comment),l.range=[r,d,p.offset],l}Nk.composeDoc=CT});var Mp=x(qk=>{"use strict";var ET=Nc("process"),AT=Ef(),xT=Zo(),ia=ra(),jk=ke(),_T=$k(),IT=Is();function sa(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Dk(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let s=e[i];switch(s[0]){case"#":t+=(t===""?"":n?`
|
|
103
|
+
|
|
104
|
+
`:`
|
|
105
|
+
`)+(s.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var Wp=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,s)=>{let o=sa(r);s?this.warnings.push(new ia.YAMLWarning(o,n,i)):this.errors.push(new ia.YAMLParseError(o,n,i))},this.directives=new AT.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=Dk(this.prelude);if(n){let s=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${n}`:n;else if(i||t.directives.docStart||!s)t.commentBefore=n;else if(jk.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];jk.isPair(o)&&(o=o.key);let c=o.commentBefore;o.commentBefore=c?`${n}
|
|
107
|
+
${c}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n}
|
|
108
|
+
${o}`:n}}if(r){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Dk(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(ET.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let s=sa(t);s[0]+=r,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=_T.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new ia.YAMLParseError(sa(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new ia.YAMLParseError(sa(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=IT.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new ia.YAMLParseError(sa(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new xT.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};qk.Composer=Wp});var Mk=x(jl=>{"use strict";var PT=$p(),OT=Dp(),TT=ra(),Lk=Ho();function NT(e,t=!0,r){if(e){let n=(i,s,o)=>{let c=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(c,s,o);else throw new TT.YAMLParseError([c,c+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return OT.resolveFlowScalar(e,t,n);case"block-scalar":return PT.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function $T(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,c=Lk.stringifyString({type:o,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
110
|
+
`}];switch(c[0]){case"|":case">":{let f=c.indexOf(`
|
|
111
|
+
`),a=c.substring(0,f),d=c.substring(f+1)+`
|
|
112
|
+
`,p=[{type:"block-scalar-header",offset:s,indent:n,source:a}];return Wk(p,l)||p.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:s,indent:n,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:s,indent:n,source:c,end:l};case"'":return{type:"single-quoted-scalar",offset:s,indent:n,source:c,end:l};default:return{type:"scalar",offset:s,indent:n,source:c,end:l}}}function jT(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=r,c="indent"in e?e.indent:null;if(n&&typeof c=="number"&&(c+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let f=e.props[0];if(f.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=f.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=Lk.stringifyString({type:o,value:t},{implicitKey:i||c===null,indent:c!==null&&c>0?" ".repeat(c):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":DT(e,l);break;case'"':Fp(e,l,"double-quoted-scalar");break;case"'":Fp(e,l,"single-quoted-scalar");break;default:Fp(e,l,"scalar")}}function DT(e,t){let r=t.indexOf(`
|
|
114
|
+
`),n=t.substring(0,r),i=t.substring(r+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=n,e.source=i}else{let{offset:s}=e,o="indent"in e?e.indent:-1,c=[{type:"block-scalar-header",offset:s,indent:o,source:n}];Wk(c,"end"in e?e.end:void 0)||c.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:c,source:i})}}function Wk(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Fp(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let s of n)s.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}jl.createScalarToken=$T;jl.resolveAsScalar=NT;jl.setScalarValue=jT});var Hk=x(Fk=>{"use strict";var qT=e=>"type"in e?ql(e):Dl(e);function ql(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ql(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Dl(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Dl(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Dl(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Dl({start:e,key:t,sep:r,value:n}){let i="";for(let s of e)i+=s.source;if(t&&(i+=ql(t)),r)for(let s of r)i+=s.source;return n&&(i+=ql(n)),i}Fk.stringify=qT});var zk=x(Uk=>{"use strict";var Hp=Symbol("break visit"),LT=Symbol("skip children"),Bk=Symbol("remove item");function Pi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Vk(Object.freeze([]),e,t)}Pi.BREAK=Hp;Pi.SKIP=LT;Pi.REMOVE=Bk;Pi.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let s=r?.[n];if(s&&"items"in s)r=s.items[i];else return}return r};Pi.parentCollection=(e,t)=>{let r=Pi.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Vk(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let c=Vk(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof c=="number")o=c-1;else{if(c===Hp)return Hp;c===Bk&&(s.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}Uk.visit=Pi});var Ll=x(zt=>{"use strict";var Bp=Mk(),WT=Hk(),MT=zk(),Vp="\uFEFF",Up="",zp="",Kp="",FT=e=>!!e&&"items"in e,HT=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function BT(e){switch(e){case Vp:return"<BOM>";case Up:return"<DOC>";case zp:return"<FLOW_END>";case Kp:return"<SCALAR>";default:return JSON.stringify(e)}}function VT(e){switch(e){case Vp:return"byte-order-mark";case Up:return"doc-mode";case zp:return"flow-error-end";case Kp:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
|
+
`:case`\r
|
|
119
|
+
`: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" ":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}zt.createScalarToken=Bp.createScalarToken;zt.resolveAsScalar=Bp.resolveAsScalar;zt.setScalarValue=Bp.setScalarValue;zt.stringify=WT.stringify;zt.visit=MT.visit;zt.BOM=Vp;zt.DOCUMENT=Up;zt.FLOW_END=zp;zt.SCALAR=Kp;zt.isCollection=FT;zt.isScalar=HT;zt.prettyToken=BT;zt.tokenType=VT});var Yp=x(Gk=>{"use strict";var oa=Ll();function Ir(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Kk=new Set("0123456789ABCDEFabcdef"),UT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wl=new Set(",[]{}"),zT=new Set(` ,[]{}
|
|
121
|
+
\r `),Gp=e=>!e||zT.has(e),Jp=class{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(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
|
+
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
|
|
124
|
+
`||!i&&!this.atEnd)return t+n+1}return r===`
|
|
125
|
+
`||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Ir(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){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 t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===oa.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let s=t[n-1];if(s===" "||s===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let s=t[r-1];if(s===" "||s===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield oa.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Ir(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ir(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ir(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);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(Gp),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&Ir(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield oa.FLOW_END,yield*this.parseLineStart();let s=0;for(;i[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),i[s]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Gp),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ir(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let s=0;for(;this.buffer[r-1-s]==="\\";)s+=1;if(s%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
|
|
127
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let s=this.continueScalar(i+1);if(s===-1)break;i=n.indexOf(`
|
|
128
|
+
`,s)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ir(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":r+=1;break;case`
|
|
129
|
+
`:t=s,r=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
|
+
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
132
|
+
`;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let s=t-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let c=s;for(;o===" ";)o=this.buffer[--s];if(o===`
|
|
133
|
+
`&&s>=this.pos&&s+1+r>c)t=s;else break}while(!0);return yield oa.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(Ir(s)||t&&Wl.has(s))break;r=n}else if(Ir(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===`
|
|
134
|
+
`?(n+=1,i=`
|
|
135
|
+
`,s=this.buffer[n+1]):r=n),s==="#"||t&&Wl.has(s))break;if(i===`
|
|
136
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&Wl.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield oa.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Gp),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(Ir(n)||r&&Wl.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Ir(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(UT.has(r))r=this.buffer[++t];else if(r==="%"&&Kk.has(this.buffer[t+1])&&Kk.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Gk.Lexer=Jp});var Qp=x(Jk=>{"use strict";var Xp=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let s=r+n>>1;this.lineStarts[s]<t?r=s+1:n=s}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};Jk.LineCounter=Xp});var em=x(eb=>{"use strict";var KT=Nc("process"),Yk=Ll(),GT=Yp();function Vn(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Xk(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 Zk(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 Ml(e){switch(e.type){case"document":return e.start;case"block-map":{let 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 Ps(e){if(e.length===0)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(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Fl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function Qk(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Vn(t.start,"explicit-key-ind")&&!Vn(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Zk(t.value)?t.value.end?Fl(t.value.end,t.sep):t.value.end=t.sep:Fl(t.start,t.sep),delete t.sep)}var Zp=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new GT.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,KT.env.LOG_TOKENS&&console.log("|",Yk.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Yk.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.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(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Qk(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Xk(i.start)===-1&&(r.indent===0||i.start.every(s=>s.type!=="comment"||s.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Xk(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Ml(this.peek(2)),n=Ps(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
139
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Fl(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&r.sep&&!r.value){let o=[];for(let c=0;c<r.sep.length;++c){let l=r.sep[c];switch(l.type){case"newline":o.push(c);break;case"space":break;case"comment":l.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Vn(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Zk(r.key)&&!Vn(r.sep,"newline")){let o=Ps(r.start),c=r.key,l=r.sep;l.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:c,sep:l}]})}else s.length>0?r.sep=r.sep.concat(s,this.sourceToken):r.sep.push(this.sourceToken);else if(Vn(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ps(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:s,key:null,sep:[this.sourceToken]}):Vn(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||r.value?(t.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Vn(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Fl(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Vn(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=Ml(n),s=Ps(i);Qk(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let c={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=c}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){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;let r=Ml(t),n=Ps(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Ml(t),n=Ps(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){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:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};eb.Parser=Zp});var sb=x(ca=>{"use strict";var tb=Mp(),JT=Zo(),aa=ra(),YT=Lf(),XT=ke(),QT=Qp(),rb=em();function nb(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new QT.LineCounter||null,prettyErrors:t}}function ZT(e,t={}){let{lineCounter:r,prettyErrors:n}=nb(t),i=new rb.Parser(r?.addNewLine),s=new tb.Composer(t),o=Array.from(s.compose(i.parse(e)));if(n&&r)for(let c of o)c.errors.forEach(aa.prettifyError(e,r)),c.warnings.forEach(aa.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function ib(e,t={}){let{lineCounter:r,prettyErrors:n}=nb(t),i=new rb.Parser(r?.addNewLine),s=new tb.Composer(t),o=null;for(let c of s.compose(i.parse(e),!0,e.length))if(!o)o=c;else if(o.options.logLevel!=="silent"){o.errors.push(new aa.YAMLParseError(c.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(aa.prettifyError(e,r)),o.warnings.forEach(aa.prettifyError(e,r))),o}function eN(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=ib(e,r);if(!i)return null;if(i.warnings.forEach(s=>YT.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function tN(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return XT.isDocument(e)&&!n?e.toString(r):new JT.Document(e,n,r).toString(r)}ca.parse=eN;ca.parseAllDocuments=ZT;ca.parseDocument=ib;ca.stringify=tN});var Dt=x(_e=>{"use strict";var rN=Mp(),nN=Zo(),iN=kp(),tm=ra(),sN=qo(),Un=ke(),oN=Mn(),aN=tt(),cN=Hn(),lN=Bn(),uN=Ll(),dN=Yp(),fN=Qp(),pN=em(),Hl=sb(),ob=No();_e.Composer=rN.Composer;_e.Document=nN.Document;_e.Schema=iN.Schema;_e.YAMLError=tm.YAMLError;_e.YAMLParseError=tm.YAMLParseError;_e.YAMLWarning=tm.YAMLWarning;_e.Alias=sN.Alias;_e.isAlias=Un.isAlias;_e.isCollection=Un.isCollection;_e.isDocument=Un.isDocument;_e.isMap=Un.isMap;_e.isNode=Un.isNode;_e.isPair=Un.isPair;_e.isScalar=Un.isScalar;_e.isSeq=Un.isSeq;_e.Pair=oN.Pair;_e.Scalar=aN.Scalar;_e.YAMLMap=cN.YAMLMap;_e.YAMLSeq=lN.YAMLSeq;_e.CST=uN;_e.Lexer=dN.Lexer;_e.LineCounter=fN.LineCounter;_e.Parser=pN.Parser;_e.parse=Hl.parse;_e.parseAllDocuments=Hl.parseAllDocuments;_e.parseDocument=Hl.parseDocument;_e.stringify=Hl.stringify;_e.visit=ob.visit;_e.visitAsync=ob.visitAsync});import zn from"path";function hN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||zn.posix.isAbsolute(r)||zn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function la(e){let t=hN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function gb(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function rt(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||zn.posix.isAbsolute(n)||zn.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let i=n.split("/");if(i.some(s=>s===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(s=>s===""||s==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function Kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wb(e,t,r){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function gN(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function fb(e,t,r){let n=gN(e,t,r);if(n>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return n}function wN(e){if(e===void 0)return;let t=Kn(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,s=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let c=Kn(t.cleanup,"native.pending_root_move.cleanup"),l=c.kind,f=c.state,a=c.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(f!=="prepared"&&f!=="quarantined"&&f!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof a!="string"||!/^[a-f0-9]{64}$/u.test(a))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:l,state:f,manifestHash:a}}return{id:r,fromArtifactRoot:la(n),toArtifactRoot:la(i),stage:s,...o?{cleanup:o}:{}}}function yN(e){if(e===void 0)return;let t=Kn(e,"native.finish");if(t.pull_request===void 0)return{};let r=Kn(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let n=r.command.map((s,o)=>{if(typeof s!="string"||s.trim().length===0||s.length>4096||/[\0\r\n]/u.test(s))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return s});if(zn.posix.isAbsolute(n[0])||zn.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??mN;if(!Number.isSafeInteger(i)||i<1||i>db)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${db}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function vN(e,t={}){let r=Kn(e,"native"),n=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=r.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??pb;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let c=r.max_parallel_children===void 0?mb:r.max_parallel_children;if(!Number.isSafeInteger(c)||c<1)throw new Error("native.max_parallel_children must be a positive integer");let l=r.document_writes??"allow";if(l!=="allow"&&l!=="revert")throw new Error("native.document_writes must be allow or revert");let f=wN(r.pending_root_move),a=yN(r.finish);return{artifact_root:la(n),language:wb(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:s,max_verify_failures:o,max_parallel_children:c,...l==="revert"?{document_writes:l}:{},...a?{finish:a}:{},...f?{pending_root_move:f}:{}}}function yb(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>ub)throw new Error(`${t} must be an integer between 1 and ${ub} milliseconds`);return e}function kN(e){let t=Kn(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=t.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");t.check_timeout_ms!==void 0&&yb(t.check_timeout_ms,"classic.check_timeout_ms");let s=t.document_evidence??"neutral";if(s!=="neutral"&&s!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:gb(t.artifact_layout),language:wb(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...s==="strict"?{document_evidence:s}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function bN(e){let r=Kn(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>rt(n,`hook.allow_paths[${i}]`)))]}}function RN(e){if(e===void 0)return{...Bl};let t=Kn(e,"memory"),r=t.learning??Bl.learning,n=t.retrieval??Bl.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof n!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:n}}function rm(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function SN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||zn.posix.isAbsolute(r)||zn.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>ab)throw new Error(`${t} exceeds ${ab} characters`);let n=0;for(let i=0;i<r.length;i+=1)r[i]==="?"?n+=1:r[i]==="*"&&(n+=1,r[i+1]==="*"&&(i+=1));if(n>cb)throw new Error(`${t} contains more than ${cb} wildcard tokens`);return r}function CN(e){let t=rm(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let n={include:[...new Set(r.map((i,s)=>SN(i,`knowledge.local.include[${s}]`)))],max_file_mb:fb(t.max_file_mb,lb.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:fb(t.max_total_mb,lb.max_total_mb,"knowledge.local.max_total_mb")};if(n.max_file_mb>n.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return n}function EN(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function AN(e){let t=rm(e,"knowledge.remote"),r=EN(t.endpoint),n=t.token_env;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(n)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=t.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let s=t.timeout_ms??5e3;if(typeof s!="number"||!Number.isSafeInteger(s)||s<100||s>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...n===void 0?{}:{token_env:n},...i===void 0?{}:{scope:i},timeout_ms:s}}function xN(e){if(e===void 0)return{...hb};let t=rm(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let n=t.local===void 0?void 0:CN(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:AN(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...n?{local:n}:{},remote:i}}function vb(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function _N(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function IN(e,t,r,n,i,s,o,c){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!c.allowPartialProject&&e.native!==void 0)||c.allowPartialProject&&!l)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=e.workflows??[e.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(p=>p!=="native"&&p!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(a)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,change_walkthrough:vb(e.change_walkthrough),...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...s?{classic:s}:{}}}function kb(e){let t=(0,lr.parseDocument)(e),r=n=>{let i=(0,lr.isAlias)(n)?n.resolve(t):n;return(0,lr.isScalar)(i)?i.value:void 0};return(0,lr.isMap)(t.contents)&&t.contents.items.some(({key:n,value:i})=>r(n)==="schema"&&r(i)==="comet.project.v1")}function dn(e,t={}){let r=(0,lr.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0,change_walkthrough:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,s=_N(i.ambient_resume),o=vb(i.change_walkthrough),c=i.hook===void 0?void 0:bN(i.hook),l=RN(i.memory),f=xN(i.knowledge),a=i.native===void 0?void 0:vN(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=i.classic===void 0?void 0:kN(i.classic),p=IN(i,c,l,f,a,d,s,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:p,ambient_resume:s,change_walkthrough:o,memory:l,knowledge:f,...c?{hook:c}:{},...a?{native:a}:{},...d?{classic:d}:{}}}function nm(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,change_walkthrough:!0,memory:{...Bl},knowledge:{...hb},native:{artifact_root:la(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:pb,max_parallel_children:mb}}}var lr,un,ab,cb,pb,mb,Bl,lb,hb,ub,mN,db,qt=Le(()=>{"use strict";lr=bt(Dt(),1),un=Number.MAX_SAFE_INTEGER,ab=1024,cb=64,pb=5,mb=2,Bl={learning:!0,retrieval:!0},lb={include:[],max_file_mb:1,max_total_mb:32},hb={provider:"local"},ub=36e5,mN=12e4,db=6e5});import{promises as Kt}from"fs";import Ie from"path";import{AsyncLocalStorage as PN}from"node:async_hooks";async function ua(e,t,r={}){let n=Ie.resolve(e),i=await sm(n,t),s=new Map,o=!1,c=p=>[p.dev,p.ino,p.mode,p.birthtimeNs,p.mtimeNs,p.ctimeNs].join(":"),l=p=>[p.dev,p.ino,p.mode,p.birthtimeNs].join(":"),f=async(p,u)=>JSON.stringify((await Kt.readdir(p,{withFileTypes:!0})).filter(m=>!u(m)).map(m=>[m.name,m.isDirectory(),m.isSymbolicLink()]).sort((m,h)=>String(m[0]).localeCompare(String(h[0]),"en"))),a=p=>{let u=s.get(p);return u||(u=(async()=>{let m=await Kt.lstat(p,{bigint:!0});if(!m.isDirectory()||m.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Ie.relative(n,p)||"."}`);let h=await Kt.realpath(p);if(!Os(i,h))throw new Error(`${t} resolves outside the project root`);let g=r.ignoredDirectoryEntries?.(Ie.relative(n,p).replaceAll("\\","/")||".");return{stat:m,real:h,...g?{ignoreEntry:g,namespace:await f(p,g)}:{}}})(),u=u.catch(m=>{throw s.delete(p),m}),s.set(p,u)),u};await a(n);let d=async p=>{if(o)throw new Error(`${t} read session is already finished`);let u=rt(p,t),m=n;for(let h of u.split("/").slice(0,-1))m=Ie.join(m,h),await a(m);return Ie.resolve(n,...u.split("/"))};return{observePath:d,async observeDirectory(p){let u=await d(p);return await a(u),u},async stat(p){let u=await d(p),m=await Kt.lstat(u,{bigint:!0});if(!m.isFile()||m.isSymbolicLink())throw new Error(`${t} must be a real file: ${p}`);return{target:u,stat:m}},async hash(p){let u=await d(p);return dy(u,{bigint:!0,label:`${t} ${p}`,verify:async(m,h)=>{if(!Os(i,h.realPath))throw new Error(`${t} resolves outside the project root`);let g=n,w=[n];for(let k of Ie.relative(n,Ie.dirname(u)).split(Ie.sep).filter(Boolean))g=Ie.join(g,k),w.push(g);for(let k of w){let b=await s.get(k),R=await Kt.lstat(k,{bigint:!0});if(!R.isDirectory()||R.isSymbolicLink()||l(R)!==l(b.stat))throw new Error(`${t} directory changed while reading: ${Ie.relative(n,k)||"."}`)}}})},async read(p,u,m={}){let h=await d(p);return vs(h,u,{...m,label:`${t} ${p}`,verify:async(g,w)=>{if(!Os(i,w.realPath))throw new Error(`${t} resolves outside the project root`);if(r.deferDirectoryChecks)return;let k=n,b=[n];for(let R of Ie.relative(n,Ie.dirname(h)).split(Ie.sep).filter(Boolean))k=Ie.join(k,R),b.push(k);for(let R of b){let E=await s.get(R),O=await Kt.lstat(R,{bigint:!0});if(!O.isDirectory()||O.isSymbolicLink()||l(O)!==l(E.stat))throw new Error(`${t} directory changed while reading: ${Ie.relative(n,R)||"."}`)}}})},async finish(p={}){if(o)throw new Error(`${t} read session is already finished`);o=!0;let u=[];for(let[m,h]of s){let g=await h,w=await Kt.lstat(m,{bigint:!0});if(!w.isDirectory()||w.isSymbolicLink()||l(g.stat)!==l(w)||!p.allowDirectoryContentChanges&&c(g.stat)!==c(w)&&(!g.ignoreEntry||await f(m,g.ignoreEntry)!==g.namespace)||await Kt.realpath(m)!==g.real)throw new Error(`${t} directory changed while observing: ${Ie.relative(n,m)||"."}`);c(g.stat)!==c(w)&&u.push(Ie.relative(n,m).replaceAll("\\","/")||".")}return{changedDirectories:u}}}}function bb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Os(e,t){let r=Ie.relative(e,t);return r===""||!Ie.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ie.sep}`)}async function sm(e,t){let r=Ie.resolve(e),n=await Rb(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Sb(r)}async function Cb(e,t,r,n){let i=e;for(let s=0;s<r.length;s++){i=Ie.join(i,r[s]);let o;try{o=await Rb(i)}catch(f){if(bb(f))return{exists:!1,kind:"missing"};throw f}if(o.isSymbolicLink()){let f=Ie.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} crosses a symbolic link or junction at ${f}`)}let c=s===r.length-1;if(!c&&!o.isDirectory()){let f=Ie.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} ancestor ${f} must be a real directory`)}if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await Sb(i);if(!TN(t,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Eb(e,t,r){let n=rt(t,r.label),i=Ie.resolve(e),s=await sm(i,r.label),o=n.split("/"),c=Ie.resolve(i,...o);if(!Os(i,c))throw new Error(`${r.label} must stay inside the project root`);let l=await Cb(i,s,o,r);return{projectRoot:i,target:c,relative:n,exists:l.exists,kind:l.kind}}async function U(e,t,r){if(r.expected===void 0)return Eb(e,t,r);try{return await NN(e,t,r.expected)}catch(n){throw n instanceof Error&&n.message.includes("Protected project path")&&(n.message=n.message.replaceAll("Protected project path",r.label)),n}}async function gt(e,t,r){let n=rt(t,r.label),i=Ie.resolve(e),s=await sm(i,r.label),o=n.split("/"),c=i;for(let l of o){c=Ie.join(c,l);let f;try{f=await Kt.lstat(c)}catch(p){if(!bb(p))throw p;try{await Kt.mkdir(c)}catch(u){if(u.code!=="EEXIST")throw u}f=await Kt.lstat(c)}let a=Ie.relative(i,c).replaceAll("\\","/");if(f.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${a}`);if(!f.isDirectory())throw new Error(`${r.label} directory ${a} must be a real directory`);let d=await Kt.realpath(c);if(!Os(s,d))throw new Error(`${r.label} resolves outside the project root`)}return await Cb(i,s,o,{label:r.label,expected:"directory"}),c}async function om(e,t,r){return(await U(e,t,{...r,expected:"file"})).exists}async function Ab(e,t,r,n){let i=!n.hooks&&!n.bigint?ON.getStore():void 0;if(i){let c=Ie.resolve(e),l=i.get(c);return l||(l=ua(c,n.label,{deferDirectoryChecks:!0}).catch(f=>{throw i.delete(c),f}),i.set(c,l)),(await l).read(t,r,n)}let s=await ua(e,n.label),o=await s.read(t,r,n);return await s.finish({allowDirectoryContentChanges:!0}),o}async function ae(e,t,r,n){if(n.hooks||n.bigint)return Ab(e,t,r,n);try{return await $N(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(im)&&(i.message=i.message.replaceAll(im,n.label)),i}}var ON,Rb,Sb,TN,NN,im,$N,ye=Le(()=>{"use strict";Ri();qt();nr();ON=new PN;Rb=je("protectedChainLstat",e=>Kt.lstat(e)),Sb=je("protectedChainRealpath",e=>Kt.realpath(e)),TN=Vr("protectedChainInside",Os);NN=je("protectedInspectPath",(e,t,r)=>Eb(e,t,{label:"Protected project path",expected:r}));im="Cached protected project read",$N=je("protectedReadFile",(e,t,r)=>Ab(e,t,r,{label:im}))});import{promises as Ts}from"fs";import Gt from"path";function Kl(e,t){let r=Gt.relative(e,t);return r===""||r!==".."&&!r.startsWith(`..${Gt.sep}`)&&!Gt.isAbsolute(r)}function qb(e,t){return Gt.isAbsolute(t)?t:`${e}${Gt.sep}${t}`}async function um(e){let t=qb(process.cwd(),e),r=c=>c.split(process.platform==="win32"?/[\\/]+/u:/\/+/u),n=Gt.parse(t).root,i=await Ts.realpath(n),s=r(t.slice(n.length)),o=0;for(;s.length>0;){let c=s.shift();if(!c||c===".")continue;if(c===".."){i=Gt.dirname(i);continue}let l=Gt.join(i,c),f;try{f=await Ts.lstat(l)}catch(a){if(a.code!=="ENOENT")throw a;if(s.includes("..")){i=l;continue}return Gt.join(l,...s)}if(f.isSymbolicLink()){if(s.includes(".."))throw new Error("Hook 目标经过链接后返回父级;请使用规范物理路径");if(++o>40)throw new Error("Hook 目标链接解析超过 40 层,无法安全确定归属");let a=await Ts.readlink(l);if(Gt.isAbsolute(a)){let d=Gt.parse(a).root;i=await Ts.realpath(d),s=[...r(a.slice(d.length)),...s]}else s=[...r(a),...s];continue}if(s.length>0&&!f.isDirectory())throw new Error("Hook 目标的中间路径不是目录;请使用规范物理路径");i=await Ts.realpath(l)}return i}async function Lb(e,t){let r=Gt.resolve(e),n=Gt.resolve(t);if(Kl(r,n))return!0;let[i,s]=await Promise.all([um(r),um(t)]);return i!==null&&s!==null&&Kl(i,s)}async function Gl(e,t){let r=Gt.resolve(e),n=await Ts.realpath(r),i=[],s=[];for(let o of Po(t)){let c=qb(r,o),l=await um(c);((l?Kl(n,l):Kl(r,c))?i:s).push(o)}return{projectTargets:i,externalTargets:s}}var dm=Le(()=>{"use strict";cf()});import{createHash as BN}from"crypto";function VN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fn(e,t={}){return(await Jl(e,t)).document}async function UN(e){try{return(await ae(e,fa,un,{label:fa})).bytes}catch(t){if(VN(t))return null;throw t}}function zN(e){return e?{exists:!0,sha256:BN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Jl(e,t={}){let r=await UN(e);return{source:r?.toString("utf8")??null,document:r?dn(r.toString("utf8"),t):null,identity:zN(r)}}async function fm(e){return(await fn(e))?.config??null}var fa,pn=Le(()=>{"use strict";qt();ye();fa=".comet/config.yaml"});import lt from"path";function GN(e,t){let r=lt.relative(e,t);return r===""||!lt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${lt.sep}`)}function JN(e,t){let r=lt.isAbsolute(t)?lt.resolve(t):lt.resolve(e,t),n=lt.relative(lt.resolve(e),r);return n===""||lt.isAbsolute(n)||n===".."||n.startsWith(`..${lt.sep}`)?null:n.replaceAll("\\","/")}function Wb(e){return process.platform==="win32"?e.toLowerCase():e}async function pm(e,t,r=[]){let n=lt.isAbsolute(t)?lt.resolve(t):lt.resolve(e,t),i=lt.resolve(e);if(!GN(i,n))return null;let s=JN(e,t);if(!s)return null;let c=(await KN(e)).allow_paths.find(d=>{let p=Wb(s),u=Wb(d);return p===u||p.startsWith(`${u}/`)});if(!c)return null;let l=await Gl(e,[t]),f=lt.isAbsolute(t)?t:`${i}${lt.sep}${t}`;if(l.projectTargets.length!==1)return null;let a=[lt.join(i,".git"),lt.join(i,".comet"),...r];for(let d of a)if(await Lb(lt.resolve(d),f))return null;return`${s} (configured Hook allow path: ${c})`}var KN,mm=Le(()=>{"use strict";nr();pn();dm();KN=je("hookWritePolicy",async e=>(await fm(e))?.hook??{allow_paths:[]})});var wK,ym=Le(()=>{"use strict";jt();pn();ye();wK=Number.MAX_SAFE_INTEGER});var Zl=Le(()=>{"use strict";jt();qt();pn();ye();ym()});var eu=Le(()=>{"use strict"});var eR=Le(()=>{"use strict"});var bm=Le(()=>{"use strict";eu()});var tR=Le(()=>{"use strict";eu();bm()});function b$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function R$(e){let t=(0,rR.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new Error(`Invalid global Comet config: ${t.errors[0].message}`);let r=t.toJS();if(r==null)return{};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid global Comet config: root must be a mapping");return r}function iR(e){let t={...e};if(delete t.change_walkthrough,e.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let r=e.native?(({pending_root_move:n,...i})=>i)(e.native):void 0;return{...t,schema:"comet.global.v1",...r?{native:r}:{}}}function S$(e){let t=dn(JSON.stringify({...e,schema:"comet.project.v1"})).config;if(!t)throw new Error("Invalid global Comet config: workflow template is incomplete");return iR(t)}function C$(e){let t=dn(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t.native&&!t.classic)return null;let r=t.native?"native":"classic",n=t.native?.language??t.classic?.language??"en",i=nm(t.native?.artifact_root??"docs",n);return{schema:"comet.global.v1",default_workflow:r,workflows:[r],ambient_resume:t.ambient_resume,...t.native?{native:{...i.native,...t.native}}:{},...t.classic?{classic:t.classic}:{}}}function sR(e){let t=R$(e);if(Object.keys(t).length===0)return null;if(t.schema===void 0)return C$(e);if(t.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return S$(t)}async function Rm(e){try{let t=await ae(e,nR,un,{label:"global Comet config"});return sR(t.bytes.toString("utf8"))}catch(t){if(b$(t))return null;throw t}}var rR,nR,Sm=Le(()=>{"use strict";rR=bt(Dt(),1);jt();qt();ye();nR=".comet/config.yaml"});var GK,oR=Le(()=>{"use strict";jt();ye();GK=Number.MAX_SAFE_INTEGER});import{promises as E$}from"node:fs";import A$ from"node:path";function ru(e){return A$.join(e,".comet","current-change.json")}function x$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function aR(e){return e===null||typeof e=="string"}function _$(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!x$(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!aR(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:tu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==tu)throw new Error(`current change selection schema must be ${tu}`);if(t.workflow!=="native"&&t.workflow!=="classic"&&t.workflow!=="application")throw new Error("current change selection workflow must be native, classic or application");if(t.workflow==="application"&&(typeof t.applicationId!="string"||!t.applicationId.trim()||t.branch!==null))throw new Error("application selection requires applicationId and a null branch");if(t.workflow!=="application"&&t.applicationId!==void 0)throw new Error("built-in selection cannot retain another application identity");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!aR(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function js(e){let t;try{let n=ru(e),{bytes:i}=await vs(n,cR,{label:"current change selection"});t=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",..._$(t)}}async function Cm(e){await E$.rm(ru(e),{force:!0})}async function nu(e,t,r){let n=await js(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==r?!1:(await Cm(e),!0)}var tu,cR,I$,ga=Le(()=>{"use strict";nr();Ri();tu="comet.selection.v2",cR=Number.MAX_SAFE_INTEGER;I$=je("readCometCurrentSelection",e=>js(e))});var uR=Le(()=>{"use strict";eu();jt();eR();tR();qt();Sm();ye();pn();Zl();oR();mm();ga();ym();bm()});import{TextDecoder as P$}from"util";function dR(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function O$(e,t){try{return new P$("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t} is not valid UTF-8`,{cause:r})}}async function Em(e,t,r,n,i={}){try{let s=await ae(e,t,r,{label:n,hooks:i.hooks});return{result:s,text:O$(s,n)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function $i(e,t,r,n,i={}){return(await Em(e,t,r,n,i))?.text??null}async function ji(e,t,r,n,i,s={}){if(Buffer.byteLength(r,"utf8")>n)throw new Error(`${i} exceeds ${n} bytes`);let o=await Em(e,t,n,i),c=await U(e,t,{label:i,expected:"file"});await Te(c.target,r,{containedRoot:c.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let l=await Em(e,t,n,i);if(!(!o&&!l)){if(!o||!l)throw new Error(`${i} changed before commit`);if(o.result.realPath!==l.result.realPath||!ar(dR(o.result.stat),dR(l.result.stat))||o.text!==l.text)throw new Error(`${i} changed before commit`)}}})}async function fR(e,t,r,n,i,s={}){let o=await $i(e,t,n,i);await ji(e,t,`${o??""}${r}`,n,i,s)}async function iu(e,t,r,n={}){let i=await U(e,t,{label:r,expected:"file"});return i.exists?zr(i.target,{containedRoot:i.projectRoot,beforeRemove:n.beforeRemove}):!1}var Am=Le(()=>{"use strict";uR();To()});var hR={};fI(hR,{RUN_STATE_FILE:()=>su,applyRunStateToDocument:()=>xm,readRunState:()=>va,removeRunState:()=>ka,runStateFromDocument:()=>Di,writeRunState:()=>qi});import T$ from"path";function ya(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function wa(e,t){let r=ya(e,t);if(T$.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function N$(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(r))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function Di(e){if(!e.run_id)return null;let t=ya(e,"run_id"),r=ya(e,"skill"),n=ya(e,"skill_version"),i=ya(e,"skill_hash"),s=wa(e,"pending_ref"),o=wa(e,"trajectory_ref"),c=wa(e,"context_ref"),l=wa(e,"artifacts_ref"),f=wa(e,"checkpoint_ref"),a=Number(e.iteration);if(!Number.isInteger(a)||a<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:n,skillHash:i,orchestration:e.orchestration,currentStep:pR(e,"current_step"),iteration:a,pending:pR(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:c,artifactsRef:l,checkpointRef:f,status:e.run_status,retries:N$(e)}}function xm(e,t){t?e.run_id=t.runId:delete e.run_id}function $$(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,currentStep:e.currentStep,iteration:e.iteration,pending:e.pending,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,status:e.status,retries:e.retries}}function j$(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)};return Di(t)}async function va(e,t={}){let r=await $i(e,su,mR,"Run state",t);if(r===null)return null;let n=JSON.parse(r);return j$(n)}async function qi(e,t,r={}){await ji(e,su,JSON.stringify($$(t),null,2),mR,"Run state",r)}async function ka(e,t={}){await iu(e,su,"Run state",t)}var pR,su,mR,ou=Le(()=>{"use strict";Am();pR=(e,t)=>{let r=e[t];return r==null?null:String(r)};su=".comet/run-state.json",mR=Number.MAX_SAFE_INTEGER});var Da=x(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.regexpCode=Ae.getEsmExportName=Ae.getProperty=Ae.safeStringify=Ae.stringify=Ae.strConcat=Ae.addCodeArg=Ae.str=Ae._=Ae.nil=Ae._Code=Ae.Name=Ae.IDENTIFIER=Ae._CodeOrName=void 0;var $a=class{};Ae._CodeOrName=$a;Ae.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fi=class extends $a{constructor(t){if(super(),!Ae.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ae.Name=Fi;var gr=class extends $a{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Fi&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ae._Code=gr;Ae.nil=new gr("");function eS(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Gm(r,t[n]),r.push(e[++n]);return new gr(r)}Ae._=eS;var Km=new gr("+");function tS(e,...t){let r=[ja(e[0])],n=0;for(;n<t.length;)r.push(Km),Gm(r,t[n]),r.push(Km,ja(e[++n]));return Nj(r),new gr(r)}Ae.str=tS;function Gm(e,t){t instanceof gr?e.push(...t._items):t instanceof Fi?e.push(t):e.push(Dj(t))}Ae.addCodeArg=Gm;function Nj(e){let t=1;for(;t<e.length-1;){if(e[t]===Km){let r=$j(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function $j(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Fi||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Fi))return`"${e}${t.slice(1)}`}function jj(e,t){return t.emptyStr()?e:e.emptyStr()?t:tS`${e}${t}`}Ae.strConcat=jj;function Dj(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:ja(Array.isArray(e)?e.join(","):e)}function qj(e){return new gr(ja(e))}Ae.stringify=qj;function ja(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ae.safeStringify=ja;function Lj(e){return typeof e=="string"&&Ae.IDENTIFIER.test(e)?new gr(`.${e}`):eS`[${e}]`}Ae.getProperty=Lj;function Wj(e){if(typeof e=="string"&&Ae.IDENTIFIER.test(e))return new gr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Ae.getEsmExportName=Wj;function Mj(e){return new gr(e.toString())}Ae.regexpCode=Mj});var Xm=x(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.ValueScope=Xt.ValueScopeName=Xt.Scope=Xt.varKinds=Xt.UsedValueState=void 0;var Yt=Da(),Jm=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Su;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Su||(Xt.UsedValueState=Su={}));Xt.varKinds={const:new Yt.Name("const"),let:new Yt.Name("let"),var:new Yt.Name("var")};var Cu=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Yt.Name?t:this.name(t)}name(t){return new Yt.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Xt.Scope=Cu;var Eu=class extends Yt.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Yt._)`.${new Yt.Name(r)}[${n}]`}};Xt.ValueScopeName=Eu;var Fj=(0,Yt._)`\n`,Ym=class extends Cu{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Fj:Yt.nil}}get(){return this._scope}name(t){return new Eu(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:s}=i,o=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[s];if(c){let a=c.get(o);if(a)return a}else c=this._values[s]=new Map;c.set(o,i);let l=this._scope[s]||(this._scope[s]=[]),f=l.length;return l[f]=r.ref,i.setValue(r,{property:s,itemIndex:f}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Yt._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let s=Yt.nil;for(let o in t){let c=t[o];if(!c)continue;let l=n[o]=n[o]||new Map;c.forEach(f=>{if(l.has(f))return;l.set(f,Su.Started);let a=r(f);if(a){let d=this.opts.es5?Xt.varKinds.var:Xt.varKinds.const;s=(0,Yt._)`${s}${d} ${f} = ${a};${this.opts._n}`}else if(a=i?.(f))s=(0,Yt._)`${s}${a}${this.opts._n}`;else throw new Jm(f);l.set(f,Su.Completed)})}return s}};Xt.ValueScope=Ym});var pe=x(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.or=de.and=de.not=de.CodeGen=de.operators=de.varKinds=de.ValueScopeName=de.ValueScope=de.Scope=de.Name=de.regexpCode=de.stringify=de.getProperty=de.nil=de.strConcat=de.str=de._=void 0;var ve=Da(),jr=Xm(),ei=Da();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return ei._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return ei.str}});Object.defineProperty(de,"strConcat",{enumerable:!0,get:function(){return ei.strConcat}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return ei.nil}});Object.defineProperty(de,"getProperty",{enumerable:!0,get:function(){return ei.getProperty}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return ei.stringify}});Object.defineProperty(de,"regexpCode",{enumerable:!0,get:function(){return ei.regexpCode}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return ei.Name}});var Iu=Xm();Object.defineProperty(de,"Scope",{enumerable:!0,get:function(){return Iu.Scope}});Object.defineProperty(de,"ValueScope",{enumerable:!0,get:function(){return Iu.ValueScope}});Object.defineProperty(de,"ValueScopeName",{enumerable:!0,get:function(){return Iu.ValueScopeName}});Object.defineProperty(de,"varKinds",{enumerable:!0,get:function(){return Iu.varKinds}});de.operators={GT:new ve._Code(">"),GTE:new ve._Code(">="),LT:new ve._Code("<"),LTE:new ve._Code("<="),EQ:new ve._Code("==="),NEQ:new ve._Code("!=="),NOT:new ve._Code("!"),OR:new ve._Code("||"),AND:new ve._Code("&&"),ADD:new ve._Code("+")};var vn=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Qm=class extends vn{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?jr.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=zs(this.rhs,t,r)),this}get names(){return this.rhs instanceof ve._CodeOrName?this.rhs.names:{}}},Au=class extends vn{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof ve.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=zs(this.rhs,t,r),this}get names(){let t=this.lhs instanceof ve.Name?{}:{...this.lhs.names};return _u(t,this.rhs)}},Zm=class extends Au{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},eh=class extends vn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},th=class extends vn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},rh=class extends vn{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},nh=class extends vn{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=zs(this.code,t,r),this}get names(){return this.code instanceof ve._CodeOrName?this.code.names:{}}},qa=class extends vn{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(t,r)||(Hj(t,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Vi(t,r.names),{})}},kn=class extends qa{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ih=class extends qa{},Us=class extends kn{};Us.kind="else";var Hi=class e extends kn{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Us(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(rS(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=zs(this.condition,t,r),this}get names(){let t=super.names;return _u(t,this.condition),this.else&&Vi(t,this.else.names),t}};Hi.kind="if";var Bi=class extends kn{};Bi.kind="for";var sh=class extends Bi{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=zs(this.iteration,t,r),this}get names(){return Vi(super.names,this.iteration.names)}},oh=class extends Bi{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?jr.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${r} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=_u(super.names,this.from);return _u(t,this.to)}},xu=class extends Bi{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=zs(this.iterable,t,r),this}get names(){return Vi(super.names,this.iterable.names)}},La=class extends kn{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};La.kind="func";var Wa=class extends qa{render(t){return"return "+super.render(t)}};Wa.kind="return";var ah=class extends kn{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Vi(t,this.catch.names),this.finally&&Vi(t,this.finally.names),t}},Ma=class extends kn{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Ma.kind="catch";var Fa=class extends kn{render(t){return"finally"+super.render(t)}};Fa.kind="finally";var ch=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
143
|
+
`:""},this._extScope=t,this._scope=new jr.Scope({parent:t}),this._nodes=[new ih]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let s=this._scope.toName(r);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new Qm(t,s,n)),s}const(t,r,n){return this._def(jr.varKinds.const,t,r,n)}let(t,r,n){return this._def(jr.varKinds.let,t,r,n)}var(t,r,n){return this._def(jr.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Au(t,r,n))}add(t,r){return this._leafNode(new Zm(t,de.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==ve.nil&&this._leafNode(new nh(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,ve.addCodeArg)(r,i));return r.push("}"),new ve._Code(r)}if(t,r,n){if(this._blockNode(new Hi(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Hi(t))}else(){return this._elseNode(new Us)}endIf(){return this._endBlockNode(Hi,Us)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new sh(t),r)}forRange(t,r,n,i,s=this.opts.es5?jr.varKinds.var:jr.varKinds.let){let o=this._scope.toName(t);return this._for(new oh(s,o,r,n),()=>i(o))}forOf(t,r,n,i=jr.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let o=r instanceof ve.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ve._)`${o}.length`,c=>{this.var(s,(0,ve._)`${o}[${c}]`),n(s)})}return this._for(new xu("of",i,s,r),()=>n(s))}forIn(t,r,n,i=this.opts.es5?jr.varKinds.var:jr.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,ve._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new xu("in",i,s,r),()=>n(s))}endFor(){return this._endBlockNode(Bi)}label(t){return this._leafNode(new eh(t))}break(t){return this._leafNode(new th(t))}return(t){let r=new Wa;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Wa)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new ah;if(this._blockNode(i),this.code(t),r){let s=this.name("e");this._currNode=i.catch=new Ma(s),r(s)}return n&&(this._currNode=i.finally=new Fa,this.code(n)),this._endBlockNode(Ma,Fa)}throw(t){return this._leafNode(new rh(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=ve.nil,n,i){return this._blockNode(new La(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(La)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Hi))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};de.CodeGen=ch;function Vi(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function _u(e,t){return t instanceof ve._CodeOrName?Vi(e,t.names):e}function zs(e,t,r){if(e instanceof ve.Name)return n(e);if(!i(e))return e;return new ve._Code(e._items.reduce((s,o)=>(o instanceof ve.Name&&(o=n(o)),o instanceof ve._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=r[s.str];return o===void 0||t[s.str]!==1?s:(delete t[s.str],o)}function i(s){return s instanceof ve._Code&&s._items.some(o=>o instanceof ve.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function Hj(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function rS(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,ve._)`!${lh(e)}`}de.not=rS;var Bj=nS(de.operators.AND);function Vj(...e){return e.reduce(Bj)}de.and=Vj;var Uj=nS(de.operators.OR);function zj(...e){return e.reduce(Uj)}de.or=zj;function nS(e){return(t,r)=>t===ve.nil?r:r===ve.nil?t:(0,ve._)`${lh(t)} ${e} ${lh(r)}`}function lh(e){return e instanceof ve.Name?e:(0,ve._)`(${e})`}});var Re=x(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.checkStrictMode=me.getErrorPath=me.Type=me.useFunc=me.setEvaluated=me.evaluatedPropsToName=me.mergeEvaluated=me.eachItem=me.unescapeJsonPointer=me.escapeJsonPointer=me.escapeFragment=me.unescapeFragment=me.schemaRefOrVal=me.schemaHasRulesButRef=me.schemaHasRules=me.checkUnknownRules=me.alwaysValidSchema=me.toHash=void 0;var De=pe(),Kj=Da();function Gj(e){let t={};for(let r of e)t[r]=!0;return t}me.toHash=Gj;function Jj(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(oS(e,t),!aS(t,e.self.RULES.all))}me.alwaysValidSchema=Jj;function oS(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let s in t)i[s]||uS(e,`unknown keyword: "${s}"`)}me.checkUnknownRules=oS;function aS(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}me.schemaHasRules=aS;function Yj(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}me.schemaHasRulesButRef=Yj;function Xj({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,De._)`${r}`}return(0,De._)`${e}${t}${(0,De.getProperty)(n)}`}me.schemaRefOrVal=Xj;function Qj(e){return cS(decodeURIComponent(e))}me.unescapeFragment=Qj;function Zj(e){return encodeURIComponent(dh(e))}me.escapeFragment=Zj;function dh(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=dh;function cS(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=cS;function eD(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}me.eachItem=eD;function iS({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,s,o,c)=>{let l=o===void 0?s:o instanceof De.Name?(s instanceof De.Name?e(i,s,o):t(i,s,o),o):s instanceof De.Name?(t(i,o,s),s):r(s,o);return c===De.Name&&!(l instanceof De.Name)?n(i,l):l}}me.mergeEvaluated={props:iS({mergeNames:(e,t,r)=>e.if((0,De._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,De._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,De._)`${r} || {}`).code((0,De._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,De._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,De._)`${r} || {}`),fh(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:lS}),items:iS({mergeNames:(e,t,r)=>e.if((0,De._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,De._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,De._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,De._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function lS(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,De._)`{}`);return t!==void 0&&fh(e,r,t),r}me.evaluatedPropsToName=lS;function fh(e,t,r){Object.keys(r).forEach(n=>e.assign((0,De._)`${t}${(0,De.getProperty)(n)}`,!0))}me.setEvaluated=fh;var sS={};function tD(e,t){return e.scopeValue("func",{ref:t,code:sS[t.code]||(sS[t.code]=new Kj._Code(t.code))})}me.useFunc=tD;var uh;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(uh||(me.Type=uh={}));function rD(e,t,r){if(e instanceof De.Name){let n=t===uh.Num;return r?n?(0,De._)`"[" + ${e} + "]"`:(0,De._)`"['" + ${e} + "']"`:n?(0,De._)`"/" + ${e}`:(0,De._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,De.getProperty)(e).toString():"/"+dh(e)}me.getErrorPath=rD;function uS(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}me.checkStrictMode=uS});var bn=x(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var Ct=pe(),nD={data:new Ct.Name("data"),valCxt:new Ct.Name("valCxt"),instancePath:new Ct.Name("instancePath"),parentData:new Ct.Name("parentData"),parentDataProperty:new Ct.Name("parentDataProperty"),rootData:new Ct.Name("rootData"),dynamicAnchors:new Ct.Name("dynamicAnchors"),vErrors:new Ct.Name("vErrors"),errors:new Ct.Name("errors"),this:new Ct.Name("this"),self:new Ct.Name("self"),scope:new Ct.Name("scope"),json:new Ct.Name("json"),jsonPos:new Ct.Name("jsonPos"),jsonLen:new Ct.Name("jsonLen"),jsonPart:new Ct.Name("jsonPart")};ph.default=nD});var Ha=x(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.extendErrors=Et.resetErrorsCount=Et.reportExtraError=Et.reportError=Et.keyword$DataError=Et.keywordError=void 0;var Se=pe(),Pu=Re(),Mt=bn();Et.keywordError={message:({keyword:e})=>(0,Se.str)`must pass "${e}" keyword validation`};Et.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Se.str)`"${e}" keyword must be ${t} ($data)`:(0,Se.str)`"${e}" keyword is invalid ($data)`};function iD(e,t=Et.keywordError,r,n){let{it:i}=e,{gen:s,compositeRule:o,allErrors:c}=i,l=pS(e,t,r);n??(o||c)?dS(s,l):fS(i,(0,Se._)`[${l}]`)}Et.reportError=iD;function sD(e,t=Et.keywordError,r){let{it:n}=e,{gen:i,compositeRule:s,allErrors:o}=n,c=pS(e,t,r);dS(i,c),s||o||fS(n,Mt.default.vErrors)}Et.reportExtraError=sD;function oD(e,t){e.assign(Mt.default.errors,t),e.if((0,Se._)`${Mt.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Se._)`${Mt.default.vErrors}.length`,t),()=>e.assign(Mt.default.vErrors,null)))}Et.resetErrorsCount=oD;function aD({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",i,Mt.default.errors,c=>{e.const(o,(0,Se._)`${Mt.default.vErrors}[${c}]`),e.if((0,Se._)`${o}.instancePath === undefined`,()=>e.assign((0,Se._)`${o}.instancePath`,(0,Se.strConcat)(Mt.default.instancePath,s.errorPath))),e.assign((0,Se._)`${o}.schemaPath`,(0,Se.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,Se._)`${o}.schema`,r),e.assign((0,Se._)`${o}.data`,n))})}Et.extendErrors=aD;function dS(e,t){let r=e.const("err",t);e.if((0,Se._)`${Mt.default.vErrors} === null`,()=>e.assign(Mt.default.vErrors,(0,Se._)`[${r}]`),(0,Se._)`${Mt.default.vErrors}.push(${r})`),e.code((0,Se._)`${Mt.default.errors}++`)}function fS(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,Se._)`new ${e.ValidationError}(${t})`):(r.assign((0,Se._)`${n}.errors`,t),r.return(!1))}var Ui={keyword:new Se.Name("keyword"),schemaPath:new Se.Name("schemaPath"),params:new Se.Name("params"),propertyName:new Se.Name("propertyName"),message:new Se.Name("message"),schema:new Se.Name("schema"),parentSchema:new Se.Name("parentSchema")};function pS(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Se._)`{}`:cD(e,t,r)}function cD(e,t,r={}){let{gen:n,it:i}=e,s=[lD(i,r),uD(e,r)];return dD(e,t,s),n.object(...s)}function lD({errorPath:e},{instancePath:t}){let r=t?(0,Se.str)`${e}${(0,Pu.getErrorPath)(t,Pu.Type.Str)}`:e;return[Mt.default.instancePath,(0,Se.strConcat)(Mt.default.instancePath,r)]}function uD({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,Se.str)`${t}/${e}`;return r&&(i=(0,Se.str)`${i}${(0,Pu.getErrorPath)(r,Pu.Type.Str)}`),[Ui.schemaPath,i]}function dD(e,{params:t,message:r},n){let{keyword:i,data:s,schemaValue:o,it:c}=e,{opts:l,propertyName:f,topSchemaRef:a,schemaPath:d}=c;n.push([Ui.keyword,i],[Ui.params,typeof t=="function"?t(e):t||(0,Se._)`{}`]),l.messages&&n.push([Ui.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([Ui.schema,o],[Ui.parentSchema,(0,Se._)`${a}${d}`],[Mt.default.data,s]),f&&n.push([Ui.propertyName,f])}});var hS=x(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.boolOrEmptySchema=Ks.topBoolOrEmptySchema=void 0;var fD=Ha(),pD=pe(),mD=bn(),hD={message:"boolean schema is false"};function gD(e){let{gen:t,schema:r,validateName:n}=e;r===!1?mS(e,!1):typeof r=="object"&&r.$async===!0?t.return(mD.default.data):(t.assign((0,pD._)`${n}.errors`,null),t.return(!0))}Ks.topBoolOrEmptySchema=gD;function wD(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),mS(e)):r.var(t,!0)}Ks.boolOrEmptySchema=wD;function mS(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,fD.reportError)(i,hD,void 0,t)}});var mh=x(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.getRules=Gs.isJSONType=void 0;var yD=["string","number","integer","boolean","null","object","array"],vD=new Set(yD);function kD(e){return typeof e=="string"&&vD.has(e)}Gs.isJSONType=kD;function bD(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Gs.getRules=bD});var hh=x(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.shouldUseRule=ti.shouldUseGroup=ti.schemaHasRulesForType=void 0;function RD({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&gS(e,n)}ti.schemaHasRulesForType=RD;function gS(e,t){return t.rules.some(r=>wS(e,r))}ti.shouldUseGroup=gS;function wS(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}ti.shouldUseRule=wS});var Ba=x(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.reportTypeError=At.checkDataTypes=At.checkDataType=At.coerceAndCheckDataType=At.getJSONTypes=At.getSchemaTypes=At.DataType=void 0;var SD=mh(),CD=hh(),ED=Ha(),ce=pe(),yS=Re(),Js;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Js||(At.DataType=Js={}));function AD(e){let t=vS(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}At.getSchemaTypes=AD;function vS(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(SD.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}At.getJSONTypes=vS;function xD(e,t){let{gen:r,data:n,opts:i}=e,s=_D(t,i.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,CD.schemaHasRulesForType)(e,t[0]));if(o){let c=wh(t,n,i.strictNumbers,Js.Wrong);r.if(c,()=>{s.length?ID(e,t,s):yh(e)})}return o}At.coerceAndCheckDataType=xD;var kS=new Set(["string","number","integer","boolean","null"]);function _D(e,t){return t?e.filter(r=>kS.has(r)||t==="array"&&r==="array"):[]}function ID(e,t,r){let{gen:n,data:i,opts:s}=e,o=n.let("dataType",(0,ce._)`typeof ${i}`),c=n.let("coerced",(0,ce._)`undefined`);s.coerceTypes==="array"&&n.if((0,ce._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,ce._)`${i}[0]`).assign(o,(0,ce._)`typeof ${i}`).if(wh(t,i,s.strictNumbers),()=>n.assign(c,i))),n.if((0,ce._)`${c} !== undefined`);for(let f of r)(kS.has(f)||f==="array"&&s.coerceTypes==="array")&&l(f);n.else(),yh(e),n.endIf(),n.if((0,ce._)`${c} !== undefined`,()=>{n.assign(i,c),PD(e,c)});function l(f){switch(f){case"string":n.elseIf((0,ce._)`${o} == "number" || ${o} == "boolean"`).assign(c,(0,ce._)`"" + ${i}`).elseIf((0,ce._)`${i} === null`).assign(c,(0,ce._)`""`);return;case"number":n.elseIf((0,ce._)`${o} == "boolean" || ${i} === null
|
|
144
|
+
|| (${o} == "string" && ${i} && ${i} == +${i})`).assign(c,(0,ce._)`+${i}`);return;case"integer":n.elseIf((0,ce._)`${o} === "boolean" || ${i} === null
|
|
145
|
+
|| (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(c,(0,ce._)`+${i}`);return;case"boolean":n.elseIf((0,ce._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(c,!1).elseIf((0,ce._)`${i} === "true" || ${i} === 1`).assign(c,!0);return;case"null":n.elseIf((0,ce._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(c,null);return;case"array":n.elseIf((0,ce._)`${o} === "string" || ${o} === "number"
|
|
146
|
+
|| ${o} === "boolean" || ${i} === null`).assign(c,(0,ce._)`[${i}]`)}}}function PD({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,ce._)`${t} !== undefined`,()=>e.assign((0,ce._)`${t}[${r}]`,n))}function gh(e,t,r,n=Js.Correct){let i=n===Js.Correct?ce.operators.EQ:ce.operators.NEQ,s;switch(e){case"null":return(0,ce._)`${t} ${i} null`;case"array":s=(0,ce._)`Array.isArray(${t})`;break;case"object":s=(0,ce._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o((0,ce._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return(0,ce._)`typeof ${t} ${i} ${e}`}return n===Js.Correct?s:(0,ce.not)(s);function o(c=ce.nil){return(0,ce.and)((0,ce._)`typeof ${t} == "number"`,c,r?(0,ce._)`isFinite(${t})`:ce.nil)}}At.checkDataType=gh;function wh(e,t,r,n){if(e.length===1)return gh(e[0],t,r,n);let i,s=(0,yS.toHash)(e);if(s.array&&s.object){let o=(0,ce._)`typeof ${t} != "object"`;i=s.null?o:(0,ce._)`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else i=ce.nil;s.number&&delete s.integer;for(let o in s)i=(0,ce.and)(i,gh(o,t,r,n));return i}At.checkDataTypes=wh;var OD={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,ce._)`{type: ${e}}`:(0,ce._)`{type: ${t}}`};function yh(e){let t=TD(e);(0,ED.reportError)(t,OD)}At.reportTypeError=yh;function TD(e){let{gen:t,data:r,schema:n}=e,i=(0,yS.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var RS=x(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});Ou.assignDefaults=void 0;var Ys=pe(),ND=Re();function $D(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)bS(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,s)=>bS(e,s,i.default))}Ou.assignDefaults=$D;function bS(e,t,r){let{gen:n,compositeRule:i,data:s,opts:o}=e;if(r===void 0)return;let c=(0,Ys._)`${s}${(0,Ys.getProperty)(t)}`;if(i){(0,ND.checkStrictMode)(e,`default is ignored for: ${c}`);return}let l=(0,Ys._)`${c} === undefined`;o.useDefaults==="empty"&&(l=(0,Ys._)`${l} || ${c} === null || ${c} === ""`),n.if(l,(0,Ys._)`${c} = ${(0,Ys.stringify)(r)}`)}});var wr=x($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.validateUnion=$e.validateArray=$e.usePattern=$e.callValidateCode=$e.schemaProperties=$e.allSchemaProperties=$e.noPropertyInData=$e.propertyInData=$e.isOwnProperty=$e.hasPropFunc=$e.reportMissingProp=$e.checkMissingProp=$e.checkReportMissingProp=void 0;var We=pe(),vh=Re(),ri=bn(),jD=Re();function DD(e,t){let{gen:r,data:n,it:i}=e;r.if(bh(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,We._)`${t}`},!0),e.error()})}$e.checkReportMissingProp=DD;function qD({gen:e,data:t,it:{opts:r}},n,i){return(0,We.or)(...n.map(s=>(0,We.and)(bh(e,t,s,r.ownProperties),(0,We._)`${i} = ${s}`)))}$e.checkMissingProp=qD;function LD(e,t){e.setParams({missingProperty:t},!0),e.error()}$e.reportMissingProp=LD;function SS(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,We._)`Object.prototype.hasOwnProperty`})}$e.hasPropFunc=SS;function kh(e,t,r){return(0,We._)`${SS(e)}.call(${t}, ${r})`}$e.isOwnProperty=kh;function WD(e,t,r,n){let i=(0,We._)`${t}${(0,We.getProperty)(r)} !== undefined`;return n?(0,We._)`${i} && ${kh(e,t,r)}`:i}$e.propertyInData=WD;function bh(e,t,r,n){let i=(0,We._)`${t}${(0,We.getProperty)(r)} === undefined`;return n?(0,We.or)(i,(0,We.not)(kh(e,t,r))):i}$e.noPropertyInData=bh;function CS(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}$e.allSchemaProperties=CS;function MD(e,t){return CS(t).filter(r=>!(0,vh.alwaysValidSchema)(e,t[r]))}$e.schemaProperties=MD;function FD({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},c,l,f){let a=f?(0,We._)`${e}, ${t}, ${n}${i}`:t,d=[[ri.default.instancePath,(0,We.strConcat)(ri.default.instancePath,s)],[ri.default.parentData,o.parentData],[ri.default.parentDataProperty,o.parentDataProperty],[ri.default.rootData,ri.default.rootData]];o.opts.dynamicRef&&d.push([ri.default.dynamicAnchors,ri.default.dynamicAnchors]);let p=(0,We._)`${a}, ${r.object(...d)}`;return l!==We.nil?(0,We._)`${c}.call(${l}, ${p})`:(0,We._)`${c}(${p})`}$e.callValidateCode=FD;var HD=(0,We._)`new RegExp`;function BD({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,s=i(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,We._)`${i.code==="new RegExp"?HD:(0,jD.useFunc)(e,i)}(${r}, ${n})`})}$e.usePattern=BD;function VD(e){let{gen:t,data:r,keyword:n,it:i}=e,s=t.name("valid");if(i.allErrors){let c=t.let("valid",!0);return o(()=>t.assign(c,!1)),c}return t.var(s,!0),o(()=>t.break()),s;function o(c){let l=t.const("len",(0,We._)`${r}.length`);t.forRange("i",0,l,f=>{e.subschema({keyword:n,dataProp:f,dataPropType:vh.Type.Num},s),t.if((0,We.not)(s),c)})}}$e.validateArray=VD;function UD(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,vh.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((l,f)=>{let a=e.subschema({keyword:n,schemaProp:f,compositeRule:!0},c);t.assign(o,(0,We._)`${o} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,We.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}$e.validateUnion=UD});var xS=x(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.validateKeywordUsage=Qr.validSchemaType=Qr.funcKeywordCode=Qr.macroKeywordCode=void 0;var Ft=pe(),zi=bn(),zD=wr(),KD=Ha();function GD(e,t){let{gen:r,keyword:n,schema:i,parentSchema:s,it:o}=e,c=t.macro.call(o.self,i,s,o),l=AS(r,n,c);o.opts.validateSchema!==!1&&o.self.validateSchema(c,!0);let f=r.name("valid");e.subschema({schema:c,schemaPath:Ft.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}Qr.macroKeywordCode=GD;function JD(e,t){var r;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:c,it:l}=e;XD(l,t);let f=!c&&t.compile?t.compile.call(l.self,s,o,l):t.validate,a=AS(n,i,f),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)h(),t.modifying&&ES(e),g(()=>e.error());else{let w=t.async?u():m();t.modifying&&ES(e),g(()=>YD(e,w))}}function u(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Ft._)`await `),k=>n.assign(d,!1).if((0,Ft._)`${k} instanceof ${l.ValidationError}`,()=>n.assign(w,(0,Ft._)`${k}.errors`),()=>n.throw(k))),w}function m(){let w=(0,Ft._)`${a}.errors`;return n.assign(w,null),h(Ft.nil),w}function h(w=t.async?(0,Ft._)`await `:Ft.nil){let k=l.opts.passContext?zi.default.this:zi.default.self,b=!("compile"in t&&!c||t.schema===!1);n.assign(d,(0,Ft._)`${w}${(0,zD.callValidateCode)(e,a,k,b)}`,t.modifying)}function g(w){var k;n.if((0,Ft.not)((k=t.valid)!==null&&k!==void 0?k:d),w)}}Qr.funcKeywordCode=JD;function ES(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ft._)`${n.parentData}[${n.parentDataProperty}]`))}function YD(e,t){let{gen:r}=e;r.if((0,Ft._)`Array.isArray(${t})`,()=>{r.assign(zi.default.vErrors,(0,Ft._)`${zi.default.vErrors} === null ? ${t} : ${zi.default.vErrors}.concat(${t})`).assign(zi.default.errors,(0,Ft._)`${zi.default.vErrors}.length`),(0,KD.extendErrors)(e)},()=>e.error())}function XD({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function AS(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ft.stringify)(r)})}function QD(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Qr.validSchemaType=QD;function ZD({schema:e,opts:t,self:r,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Qr.validateKeywordUsage=ZD});var IS=x(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.extendSubschemaMode=ni.extendSubschemaData=ni.getSubschema=void 0;var Zr=pe(),_S=Re();function e1(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return r===void 0?{schema:c,schemaPath:(0,Zr._)`${e.schemaPath}${(0,Zr.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Zr._)`${e.schemaPath}${(0,Zr.getProperty)(t)}${(0,Zr.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,_S.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}ni.getSubschema=e1;function t1(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(r!==void 0){let{errorPath:f,dataPathArr:a,opts:d}=t,p=c.let("data",(0,Zr._)`${t.data}${(0,Zr.getProperty)(r)}`,!0);l(p),e.errorPath=(0,Zr.str)`${f}${(0,_S.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Zr._)`${r}`,e.dataPathArr=[...a,e.parentDataProperty]}if(i!==void 0){let f=i instanceof Zr.Name?i:c.let("data",i,!0);l(f),o!==void 0&&(e.propertyName=o)}s&&(e.dataTypes=s);function l(f){e.data=f,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,f]}}ni.extendSubschemaData=t1;function r1(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}ni.extendSubschemaMode=r1});var Rh=x((y4,PS)=>{"use strict";PS.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var TS=x((v4,OS)=>{"use strict";var ii=OS.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Tu(t,n,i,e,"",e)};ii.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ii.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ii.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ii.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Tu(e,t,r,n,i,s,o,c,l,f){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,s,o,c,l,f);for(var a in n){var d=n[a];if(Array.isArray(d)){if(a in ii.arrayKeywords)for(var p=0;p<d.length;p++)Tu(e,t,r,d[p],i+"/"+a+"/"+p,s,i,a,n,p)}else if(a in ii.propsKeywords){if(d&&typeof d=="object")for(var u in d)Tu(e,t,r,d[u],i+"/"+a+"/"+n1(u),s,i,a,n,u)}else(a in ii.keywords||e.allKeys&&!(a in ii.skipKeywords))&&Tu(e,t,r,d,i+"/"+a,s,i,a,n)}r(n,i,s,o,c,l,f)}}function n1(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Va=x(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.getSchemaRefs=Qt.resolveUrl=Qt.normalizeId=Qt._getFullPath=Qt.getFullPath=Qt.inlineRef=void 0;var i1=Re(),s1=Rh(),o1=TS(),a1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function c1(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Sh(e):t?NS(e)<=t:!1}Qt.inlineRef=c1;var l1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Sh(e){for(let t in e){if(l1.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Sh)||typeof r=="object"&&Sh(r))return!0}return!1}function NS(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!a1.has(r)&&(typeof e[r]=="object"&&(0,i1.eachItem)(e[r],n=>t+=NS(n)),t===1/0))return 1/0}return t}function $S(e,t="",r){r!==!1&&(t=Xs(t));let n=e.parse(t);return jS(e,n)}Qt.getFullPath=$S;function jS(e,t){return e.serialize(t).split("#")[0]+"#"}Qt._getFullPath=jS;var u1=/#\/?$/;function Xs(e){return e?e.replace(u1,""):""}Qt.normalizeId=Xs;function d1(e,t,r){return r=Xs(r),e.resolve(t,r)}Qt.resolveUrl=d1;var f1=/^[a-z_][-a-z0-9._]*$/i;function p1(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Xs(e[r]||t),s={"":i},o=$S(n,i,!1),c={},l=new Set;return o1(e,{allKeys:!0},(d,p,u,m)=>{if(m===void 0)return;let h=o+p,g=s[m];typeof d[r]=="string"&&(g=w.call(this,d[r])),k.call(this,d.$anchor),k.call(this,d.$dynamicAnchor),s[p]=g;function w(b){let R=this.opts.uriResolver.resolve;if(b=Xs(g?R(g,b):b),l.has(b))throw a(b);l.add(b);let E=this.refs[b];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?f(d,E.schema,b):b!==Xs(h)&&(b[0]==="#"?(f(d,c[b],b),c[b]=d):this.refs[b]=h),b}function k(b){if(typeof b=="string"){if(!f1.test(b))throw new Error(`invalid anchor "${b}"`);w.call(this,`#${b}`)}}}),c;function f(d,p,u){if(p!==void 0&&!s1(d,p))throw a(u)}function a(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Qt.getSchemaRefs=p1});var Ka=x(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.getData=si.KeywordCxt=si.validateFunctionCode=void 0;var MS=hS(),DS=Ba(),Eh=hh(),Nu=Ba(),m1=RS(),za=xS(),Ch=IS(),ee=pe(),se=bn(),h1=Va(),Rn=Re(),Ua=Ha();function g1(e){if(BS(e)&&(VS(e),HS(e))){v1(e);return}FS(e,()=>(0,MS.topBoolOrEmptySchema)(e))}si.validateFunctionCode=g1;function FS({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},s){i.code.es5?e.func(t,(0,ee._)`${se.default.data}, ${se.default.valCxt}`,n.$async,()=>{e.code((0,ee._)`"use strict"; ${qS(r,i)}`),y1(e,i),e.code(s)}):e.func(t,(0,ee._)`${se.default.data}, ${w1(i)}`,n.$async,()=>e.code(qS(r,i)).code(s))}function w1(e){return(0,ee._)`{${se.default.instancePath}="", ${se.default.parentData}, ${se.default.parentDataProperty}, ${se.default.rootData}=${se.default.data}${e.dynamicRef?(0,ee._)`, ${se.default.dynamicAnchors}={}`:ee.nil}}={}`}function y1(e,t){e.if(se.default.valCxt,()=>{e.var(se.default.instancePath,(0,ee._)`${se.default.valCxt}.${se.default.instancePath}`),e.var(se.default.parentData,(0,ee._)`${se.default.valCxt}.${se.default.parentData}`),e.var(se.default.parentDataProperty,(0,ee._)`${se.default.valCxt}.${se.default.parentDataProperty}`),e.var(se.default.rootData,(0,ee._)`${se.default.valCxt}.${se.default.rootData}`),t.dynamicRef&&e.var(se.default.dynamicAnchors,(0,ee._)`${se.default.valCxt}.${se.default.dynamicAnchors}`)},()=>{e.var(se.default.instancePath,(0,ee._)`""`),e.var(se.default.parentData,(0,ee._)`undefined`),e.var(se.default.parentDataProperty,(0,ee._)`undefined`),e.var(se.default.rootData,se.default.data),t.dynamicRef&&e.var(se.default.dynamicAnchors,(0,ee._)`{}`)})}function v1(e){let{schema:t,opts:r,gen:n}=e;FS(e,()=>{r.$comment&&t.$comment&&zS(e),C1(e),n.let(se.default.vErrors,null),n.let(se.default.errors,0),r.unevaluated&&k1(e),US(e),x1(e)})}function k1(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,ee._)`${r}.evaluated`),t.if((0,ee._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,ee._)`${e.evaluated}.props`,(0,ee._)`undefined`)),t.if((0,ee._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,ee._)`${e.evaluated}.items`,(0,ee._)`undefined`))}function qS(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,ee._)`/*# sourceURL=${r} */`:ee.nil}function b1(e,t){if(BS(e)&&(VS(e),HS(e))){R1(e,t);return}(0,MS.boolOrEmptySchema)(e,t)}function HS({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function BS(e){return typeof e.schema!="boolean"}function R1(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&zS(e),E1(e),A1(e);let s=n.const("_errs",se.default.errors);US(e,s),n.var(t,(0,ee._)`${s} === ${se.default.errors}`)}function VS(e){(0,Rn.checkUnknownRules)(e),S1(e)}function US(e,t){if(e.opts.jtd)return LS(e,[],!1,t);let r=(0,DS.getSchemaTypes)(e.schema),n=(0,DS.coerceAndCheckDataType)(e,r);LS(e,r,!n,t)}function S1(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Rn.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function C1(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Rn.checkStrictMode)(e,"default is ignored in the schema root")}function E1(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,h1.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function A1(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function zS({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let s=r.$comment;if(i.$comment===!0)e.code((0,ee._)`${se.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,ee.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,ee._)`${se.default.self}.opts.$comment(${s}, ${o}, ${c}.schema)`)}}function x1(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:s}=e;r.$async?t.if((0,ee._)`${se.default.errors} === 0`,()=>t.return(se.default.data),()=>t.throw((0,ee._)`new ${i}(${se.default.vErrors})`)):(t.assign((0,ee._)`${n}.errors`,se.default.vErrors),s.unevaluated&&_1(e),t.return((0,ee._)`${se.default.errors} === 0`))}function _1({gen:e,evaluated:t,props:r,items:n}){r instanceof ee.Name&&e.assign((0,ee._)`${t}.props`,r),n instanceof ee.Name&&e.assign((0,ee._)`${t}.items`,n)}function LS(e,t,r,n){let{gen:i,schema:s,data:o,allErrors:c,opts:l,self:f}=e,{RULES:a}=f;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Rn.schemaHasRulesButRef)(s,a))){i.block(()=>GS(e,"$ref",a.all.$ref.definition));return}l.jtd||I1(e,t),i.block(()=>{for(let p of a.rules)d(p);d(a.post)});function d(p){(0,Eh.shouldUseGroup)(s,p)&&(p.type?(i.if((0,Nu.checkDataType)(p.type,o,l.strictNumbers)),WS(e,p),t.length===1&&t[0]===p.type&&r&&(i.else(),(0,Nu.reportTypeError)(e)),i.endIf()):WS(e,p),c||i.if((0,ee._)`${se.default.errors} === ${n||0}`))}}function WS(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,m1.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,Eh.shouldUseRule)(n,s)&&GS(e,s.keyword,s.definition,t.type)})}function I1(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P1(e,t),e.opts.allowUnionTypes||O1(e,t),T1(e,e.dataTypes))}function P1(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{KS(e.dataTypes,r)||Ah(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),$1(e,t)}}function O1(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ah(e,"use allowUnionTypes to allow union type keyword")}function T1(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Eh.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>N1(t,o))&&Ah(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function N1(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function KS(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function $1(e,t){let r=[];for(let n of e.dataTypes)KS(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ah(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Rn.checkStrictMode)(e,t,e.opts.strictTypes)}var $u=class{constructor(t,r,n){if((0,za.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Rn.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",JS(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,za.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",se.default.errors))}result(t,r,n){this.failResult((0,ee.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,ee.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,ee._)`${r} !== undefined && (${(0,ee.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?Ua.reportExtraError:Ua.reportError)(this,this.def.error,r)}$dataError(){(0,Ua.reportError)(this,this.def.$dataError||Ua.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ua.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=ee.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=ee.nil,r=ee.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,ee.or)((0,ee._)`${i} === undefined`,r)),t!==ee.nil&&n.assign(t,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==ee.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:s}=this;return(0,ee.or)(o(),c());function o(){if(n.length){if(!(r instanceof ee.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,ee._)`${(0,Nu.checkDataTypes)(l,r,s.opts.strictNumbers,Nu.DataType.Wrong)}`}return ee.nil}function c(){if(i.validateSchema){let l=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,ee._)`!${l}(${r})`}return ee.nil}}subschema(t,r){let n=(0,Ch.getSubschema)(this.it,t);(0,Ch.extendSubschemaData)(n,this.it,t),(0,Ch.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return b1(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Rn.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Rn.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,ee.Name)),!0}};si.KeywordCxt=$u;function GS(e,t,r,n){let i=new $u(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,za.funcKeywordCode)(i,r):"macro"in r?(0,za.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,za.funcKeywordCode)(i,r)}var j1=/^\/(?:[^~]|~0|~1)*$/,D1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function JS(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,s;if(e==="")return se.default.rootData;if(e[0]==="/"){if(!j1.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,s=se.default.rootData}else{let f=D1.exec(e);if(!f)throw new Error(`Invalid JSON-pointer: ${e}`);let a=+f[1];if(i=f[2],i==="#"){if(a>=t)throw new Error(l("property/index",a));return n[t-a]}if(a>t)throw new Error(l("data",a));if(s=r[t-a],!i)return s}let o=s,c=i.split("/");for(let f of c)f&&(s=(0,ee._)`${s}${(0,ee.getProperty)((0,Rn.unescapeJsonPointer)(f))}`,o=(0,ee._)`${o} && ${s}`);return o;function l(f,a){return`Cannot access ${f} ${a} levels up, current level is ${t}`}}si.getData=JS});var ju=x(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var xh=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};_h.default=xh});var Ga=x(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var Ih=Va(),Ph=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ih.resolveUrl)(t,r,n),this.missingSchema=(0,Ih.normalizeId)((0,Ih.getFullPath)(t,this.missingRef))}};Oh.default=Ph});var qu=x(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.resolveSchema=yr.getCompilingSchema=yr.resolveRef=yr.compileSchema=yr.SchemaEnv=void 0;var Dr=pe(),q1=ju(),Ki=bn(),qr=Va(),YS=Re(),L1=Ka(),Qs=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,qr.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};yr.SchemaEnv=Qs;function Nh(e){let t=XS.call(this,e);if(t)return t;let r=(0,qr.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Dr.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),c;e.$async&&(c=o.scopeValue("Error",{ref:q1.default,code:(0,Dr._)`require("ajv/dist/runtime/validation_error").default`}));let l=o.scopeName("validate");e.validateName=l;let f={gen:o,allErrors:this.opts.allErrors,data:Ki.default.data,parentData:Ki.default.parentData,parentDataProperty:Ki.default.parentDataProperty,dataNames:[Ki.default.data],dataPathArr:[Dr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Dr.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Dr.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Dr._)`""`,opts:this.opts,self:this},a;try{this._compilations.add(e),(0,L1.validateFunctionCode)(f),o.optimize(this.opts.code.optimize);let d=o.toString();a=`${o.scopeRefs(Ki.default.scope)}return ${d}`,this.opts.code.process&&(a=this.opts.code.process(a,e));let u=new Function(`${Ki.default.self}`,`${Ki.default.scope}`,a)(this,this.scope.get());if(this.scope.value(l,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async&&(u.$async=!0),this.opts.code.source===!0&&(u.source={validateName:l,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=f;u.evaluated={props:m instanceof Dr.Name?void 0:m,items:h instanceof Dr.Name?void 0:h,dynamicProps:m instanceof Dr.Name,dynamicItems:h instanceof Dr.Name},u.source&&(u.source.evaluated=(0,Dr.stringify)(u.evaluated))}return e.validate=u,e}catch(d){throw delete e.validate,delete e.validateName,a&&this.logger.error("Error compiling schema, function code:",a),d}finally{this._compilations.delete(e)}}yr.compileSchema=Nh;function W1(e,t,r){var n;r=(0,qr.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let s=H1.call(this,e,r);if(s===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;o&&(s=new Qs({schema:o,schemaId:c,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=M1.call(this,s)}yr.resolveRef=W1;function M1(e){return(0,qr.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Nh.call(this,e)}function XS(e){for(let t of this._compilations)if(F1(t,e))return t}yr.getCompilingSchema=XS;function F1(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function H1(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Du.call(this,e,t)}function Du(e,t){let r=this.opts.uriResolver.parse(t),n=(0,qr._getFullPath)(this.opts.uriResolver,r),i=(0,qr.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Th.call(this,r,e);let s=(0,qr.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let c=Du.call(this,e,o);return typeof c?.schema!="object"?void 0:Th.call(this,r,c)}if(typeof o?.schema=="object"){if(o.validate||Nh.call(this,o),s===(0,qr.normalizeId)(t)){let{schema:c}=o,{schemaId:l}=this.opts,f=c[l];return f&&(i=(0,qr.resolveUrl)(this.opts.uriResolver,i,f)),new Qs({schema:c,schemaId:l,root:e,baseId:i})}return Th.call(this,r,o)}}yr.resolveSchema=Du;var B1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Th(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,YS.unescapeFragment)(c)];if(l===void 0)return;r=l;let f=typeof r=="object"&&r[this.opts.schemaId];!B1.has(c)&&f&&(t=(0,qr.resolveUrl)(this.opts.uriResolver,t,f))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,YS.schemaHasRulesButRef)(r,this.RULES)){let c=(0,qr.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Du.call(this,n,c)}let{schemaId:o}=this.opts;if(s=s||new Qs({schema:r,schemaId:o,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var QS=x((E4,V1)=>{V1.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Wh=x((A4,oC)=>{"use strict";var U1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jh=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),z1=RegExp.prototype.test.bind(/^\d*$/u),Gi=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Dh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),eC=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),qh=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),K1=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Zt=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Zt[t]="%"+e[t>>4]+e[t&15]}function xt(e){return e<2048?Zt[192|e>>6]+Zt[128|e&63]:e<65536?Zt[224|e>>12]+Zt[128|e>>6&63]+Zt[128|e&63]:Zt[240|e>>18]+Zt[128|e>>12&63]+Zt[128|e>>6&63]+Zt[128|e&63]}function G1(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var J1=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Y1=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),X1=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Q1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Z1(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!X1(e[t])){if(e[t]==="%"&&t+2<e.length&&Gi(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function ZS(e){let t=-1,r=0,n=-1,i=0;for(let c=0;c<e.length;c++)e[c]==="0"?(n===-1&&(n=c),i++,i>r&&(r=i,t=n)):(n=-1,i=0);if(r<2)return e.join(":");let s=e.slice(0,t).join(":"),o=e.slice(t+r).join(":");return s+"::"+o}function eq(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=r.concat(n),s=0;for(let c=0;c<i.length;c++){let l=i[c];if(l==="")return;if(l.indexOf(".")!==-1){if(c!==i.length-1||t!==-1&&n.length===0||!jh(l))return;s+=2;continue}if(!J1(l))return;i[c]=parseInt(l,16).toString(16),s++}if(t===-1)return s!==8?void 0:ZS(i);if(s>=8)return;let o=i.slice(0,r.length);for(let c=s;c<8;c++)o.push("0");for(let c=r.length;c<i.length;c++)o.push(i[c]);return ZS(o)}function $h(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&Y1(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(tq(n,":")<2)return{host:e,isIPV6:!1,error:t};let i="",s=n.indexOf("%");if(s!==-1){let c=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(i=n.slice(s+c),!Z1(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,s)}let o=eq(n);return o===void 0?{host:e,isIPV6:!1,error:!0}:{host:o+(i?"%"+i:""),escapedHost:o+(i?"%25"+i:""),isIPV6:!0}}function tq(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function tC(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function rq(e){if(e===""||e[0]==="/")return tC(e);let t=e.split("/"),r=t.length-1,n=[],i=!1;for(let s=0;s<=r;s++){let o=t[s];o==="."||o===".."?(o===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),i=s===r):n.push(o)}return i&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var nq={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},iq=/[@/?#:]/g,sq=/[@/?#]/g;function rC(e,t){let r=t?sq:iq;return r.lastIndex=0,e.replace(r,n=>nq[n])}function nC(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(Gi(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));t&&Dh(o)?r+=o:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function oq(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Gi(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Dh(o)?t+=o:t+="%"+s,r+=2;continue}}if(eC(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=sC(i)?n:Zt[i];else if(i<55296||i>57343)t+=xt(i);else if(i<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=xt(65536+(i-55296<<10)+(s-56320)),r++):t+=xt(65533)}else t+=xt(65533)}}return t}function aq(e,t=!1){let r="",n=t&&e[0]!=="/";for(let i=0;i<e.length;i++){let s=e[i];if(s==="%"&&i+2<e.length){let o=e.slice(i+1,i+3);if(Gi(o)){r+="%"+o.toUpperCase(),i+=2;continue}}if(s==="/"&&(n=!1),eC(s)&&(s!==":"||!n))r+=s;else{let o=e.charCodeAt(i);if(o<128)r+=Zt[o];else if(o<55296||o>57343)r+=xt(o);else if(o<=56319&&i+1<e.length){let c=e.charCodeAt(i+1);c>=56320&&c<=57343?(r+=xt(65536+(o-55296<<10)+(c-56320)),i++):r+=xt(65533)}else r+=xt(65533)}}return r}function Lh(e,t){let r="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="%"&&n+2<e.length){let s=e.slice(n+1,n+3);if(Gi(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{let s=e.charCodeAt(n);if(s<128)r+=Zt[s];else if(s<55296||s>57343)r+=xt(s);else if(s<=56319&&n+1<e.length){let o=e.charCodeAt(n+1);o>=56320&&o<=57343?(r+=xt(65536+(s-55296<<10)+(o-56320)),n++):r+=xt(65533)}else r+=xt(65533)}}return r}function iC(e){return Lh(e,K1)}function cq(e){return Lh(e,qh)}function lq(e){return Lh(e,qh)}function sC(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function uq(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Gi(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));Dh(o)?t+=o:t+="%"+s,r+=2;continue}}if(qh(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=sC(i)?n:Zt[i];else if(i<55296||i>57343)t+=xt(i);else if(i<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=xt(65536+(i-55296<<10)+(s-56320)),r++):t+=xt(65533)}else t+=xt(65533)}}return t}function dq(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Gi(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function fq(e){let t=[];if(e.userinfo!==void 0&&(t.push(iC(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!jh(r)){let n=$h(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=nC(r,!0),n=$h(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=rC(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!z1(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}oC.exports={nonSimpleDomain:Q1,recomposeAuthority:fq,reescapeHostDelimiters:rC,normalizePercentEncoding:nC,normalizePathEncoding:oq,serializePathEncoding:aq,normalizeQueryFragmentEncoding:uq,encodeUserinfo:iC,encodeQuery:cq,encodeFragment:lq,escapePreservingEscapes:dq,removeDotSegments:tC,removeDotSegmentsRelative:rq,isIPv4:jh,isUUID:U1,normalizeIPv6:$h,stringArrayToHexStripped:G1}});var dC=x((x4,uC)=>{"use strict";var{isUUID:pq}=Wh(),mq=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,hq=["http","https","ws","wss","urn","urn:uuid"];function gq(e){return hq.indexOf(e)!==-1}function Mh(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function aC(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function cC(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function wq(e){return e.secure=Mh(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function yq(e){if((e.port===(Mh(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function vq(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(mq);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,s=Fh(i);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function kq(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,s=Fh(i);s&&(e=s.serialize(e,t));let o=e,c=e.nss;return o.path=`${n||t.nid}:${c}`,t.skipEscape=!0,o}function bq(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!pq(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Rq(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var lC={scheme:"http",domainHost:!0,parse:aC,serialize:cC},Sq={scheme:"https",domainHost:lC.domainHost,parse:aC,serialize:cC},Lu={scheme:"ws",domainHost:!0,parse:wq,serialize:yq},Cq={scheme:"wss",domainHost:Lu.domainHost,parse:Lu.parse,serialize:Lu.serialize},Eq={scheme:"urn",parse:vq,serialize:kq,skipNormalize:!0},Aq={scheme:"urn:uuid",parse:bq,serialize:Rq,skipNormalize:!0},Wu={http:lC,https:Sq,ws:Lu,wss:Cq,urn:Eq,"urn:uuid":Aq};Object.setPrototypeOf(Wu,null);function Fh(e){return e&&(Wu[e]||Wu[e.toLowerCase()])||void 0}uC.exports={wsIsSecure:Mh,SCHEMES:Wu,isValidSchemeName:gq,getSchemeHandler:Fh}});var AC=x((_4,Vu)=>{"use strict";var{normalizeIPv6:gC,removeDotSegments:Ya,removeDotSegmentsRelative:wC,recomposeAuthority:xq,normalizePercentEncoding:Hh,normalizePathEncoding:_q,serializePathEncoding:fC,normalizeQueryFragmentEncoding:pC,encodeQuery:Iq,encodeFragment:Pq,reescapeHostDelimiters:Oq,isIPv4:yC,nonSimpleDomain:Tq}=Wh(),{SCHEMES:vC,getSchemeHandler:Bh}=dC(),kC=/^[A-Za-z][A-Za-z0-9+.-]*$/u,bC="URI scheme is malformed.",Mu="URI host is malformed.",Nq=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function mC(e){let t=String(e);if(!kC.test(t))throw new TypeError(bC);return t}function $q(e,t){return typeof e=="string"?e=Bq(e,t):typeof e=="object"&&(e=Hu(Ji(e,t),t)),e}function jq(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:f}=Fu(e,n),{parsed:a,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:u,malformedHost:m,malformedScheme:h}=Fu(t,n);if(s||d||o||p||c||u||l||m||f||h)throw new Error(i.error||a.error||"URI is malformed.");let g=RC(i,a,n,!0),w=Bh(r&&r.scheme||g.scheme),k=g.host,b=k!==void 0&&k!==""&&(yC(k)||gC(k).isIPV6);if(CC(g,r||{},w,b))throw new Error(Mu);SC(g,r||{},w,b);let R=k&&k.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(k);if(g.error&&!R)throw new Error(g.error);return n.skipEscape=!0,Ji(g,n)}function RC(e,t,r,n){let i={};if(n||(e=Hu(Ji(e,r),r),t=Hu(Ji(t,r),r)),r=r||{},!r.tolerant&&t.scheme)i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Ya(t.path||""),i.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Ya(t.path||""),i.query=t.query;else{if(!t.path)i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query;else{if(t.path[0]==="/")i.path=Ya(t.path);else{let s=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;s&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=e.scheme===void 0&&!s&&i.path[0]!=="/"?wC(i.path):Ya(i.path)}i.query=t.query}i.userinfo=e.userinfo,i.host=e.host,i.port=e.port}i.scheme=e.scheme}return i.fragment=t.fragment,i}function Dq(e,t,r){let n=hC(e,r),i=hC(t,r);return n!==void 0&&i!==void 0&&n===i}function Ji(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[];r.scheme&&(r.scheme=mC(r.scheme));let s=Bh(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let o=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,c=(r.scheme===void 0||n.reference==="suffix")&&!o,l=!n.skipEscape&&c;r.path!==void 0&&(n.skipEscape?r.path=Hh(r.path):r.path=fC(r.path,l)),n.reference!=="suffix"&&r.scheme&&(r.scheme=mC(r.scheme),i.push(r.scheme,":"));let f=xq(r);if(f!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(f),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=c&&a[0]!=="/"?wC(a):Ya(a)),c&&(a=fC(a,!0)),f===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",Iq(r.query)),r.fragment!==void 0&&i.push("#",Pq(r.fragment)),i.join("")}var qq=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Lq=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Wq=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function Mq(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Ja(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function Bu(e){return e[0]==="["&&e[e.length-1]==="]"}function Fq(e){let t=e[4];return Ja(e[3])||t!==void 0&&!Bu(t)&&Ja(t)||Ja(e[6])||Ja(e[7])||Ja(e[8])}function SC(e,t,r,n){if(CC(e,t,r,n))return e.error=e.error||Mu,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Bu(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&Tq(e.host)){let i;try{i=new URL("http://"+e.host)}catch(s){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!Hq(i))return e.error=e.error||Mu,!0;e.host=i.hostname}return!1}function CC(e,t,r,n){return!!(e.host&&n===!1&&!Bu(e.host)&&(t.domainHost||r&&r.domainHost)&&Nq.test(e.host))}function Hq(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Fu(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1,o=!1,c=!1,l=!1,f=!1,a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let d=e.match(Lq);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let p=e.match(Wq);if(p!==null){let m=p[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let u=e.match(qq);if(u){n.scheme=u[1],n.userinfo=u[3],n.host=u[4],n.port=parseInt(u[5],10),n.path=u[6]||"",n.query=u[7],n.fragment=u[8],n.scheme!==void 0&&(kC.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||bC,f=!0)),s=Fq(u),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=u[5]);let m=Mq(n,u);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(yC(n.host)===!1){let w=Bu(n.host),k=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,b=gC(n.host);a=b.isIPV6||b.isIPVFuture===!0,l=k&&(!w||b.error===!0),n.host=a?b.host:b.host.toLowerCase(),l&&(n.error=n.error||Mu,i=!0)}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=Bh(r.scheme||n.scheme);if(l||(c=SC(n,r,h,a)),e.indexOf("%")!==-1&&n.host!==void 0&&!l){let g=a?n.host:Hh(n.host,!0);a||(g=Hh(g.toLowerCase())),n.host=a||r.scheme!=="null"?Oq(g,a):g}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=_q(n.path)),n.query&&(n.query=pC(n.query)),n.fragment&&(n.fragment=pC(n.fragment))),h&&h.parse&&(h.parse(n,r),h===vC.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:c,malformedScheme:f}}function Hu(e,t){return Fu(e,t).parsed}function Bq(e,t){return EC(e,t).normalized}function EC(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}=Fu(e,t);return{normalized:n||i||s||o||c?e:Ji(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}}function hC(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Ji(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:c,malformedScheme:l}=EC(r,t);return i||s||o||c||l?void 0:n}var Vh={SCHEMES:vC,normalize:$q,resolve:jq,resolveComponent:RC,equal:Dq,serialize:Ji,parse:Hu};Vu.exports=Vh;Vu.exports.default=Vh;Vu.exports.fastUri=Vh});var _C=x(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var xC=AC();xC.code='require("ajv/dist/runtime/uri").default';Uh.default=xC});var DC=x(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.CodeGen=yt.Name=yt.nil=yt.stringify=yt.str=yt._=yt.KeywordCxt=void 0;var Vq=Ka();Object.defineProperty(yt,"KeywordCxt",{enumerable:!0,get:function(){return Vq.KeywordCxt}});var Zs=pe();Object.defineProperty(yt,"_",{enumerable:!0,get:function(){return Zs._}});Object.defineProperty(yt,"str",{enumerable:!0,get:function(){return Zs.str}});Object.defineProperty(yt,"stringify",{enumerable:!0,get:function(){return Zs.stringify}});Object.defineProperty(yt,"nil",{enumerable:!0,get:function(){return Zs.nil}});Object.defineProperty(yt,"Name",{enumerable:!0,get:function(){return Zs.Name}});Object.defineProperty(yt,"CodeGen",{enumerable:!0,get:function(){return Zs.CodeGen}});var Uq=ju(),NC=Ga(),zq=mh(),Xa=qu(),Kq=pe(),Qa=Va(),Uu=Ba(),Kh=Re(),IC=QS(),Gq=_C(),$C=(e,t)=>new RegExp(e,t);$C.code="new RegExp";var Jq=["removeAdditional","useDefaults","coerceTypes"],Yq=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Xq={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Qq={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},PC=200;function Zq(e){var t,r,n,i,s,o,c,l,f,a,d,p,u,m,h,g,w,k,b,R,E,O,z,D,G;let J=e.strict,te=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=te===!0||te===void 0?1:te||0,we=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:$C,K=(i=e.uriResolver)!==null&&i!==void 0?i:Gq.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:J)!==null&&o!==void 0?o:!0,strictNumbers:(l=(c=e.strictNumbers)!==null&&c!==void 0?c:J)!==null&&l!==void 0?l:!0,strictTypes:(a=(f=e.strictTypes)!==null&&f!==void 0?f:J)!==null&&a!==void 0?a:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:J)!==null&&p!==void 0?p:"log",strictRequired:(m=(u=e.strictRequired)!==null&&u!==void 0?u:J)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Z,regExp:we}:{optimize:Z,regExp:we},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:PC,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:PC,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(k=e.messages)!==null&&k!==void 0?k:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(E=e.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(O=e.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(z=e.validateFormats)!==null&&z!==void 0?z:!0,unicodeRegExp:(D=e.unicodeRegExp)!==null&&D!==void 0?D:!0,int32range:(G=e.int32range)!==null&&G!==void 0?G:!0,uriResolver:K}}var Za=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...Zq(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Kq.ValueScope({scope:{},prefixes:Yq,es5:r,lines:n}),this.logger=sL(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,zq.getRules)(),OC.call(this,Xq,t,"NOT SUPPORTED"),OC.call(this,Qq,t,"DEPRECATED","warn"),this._metaOpts=nL.call(this),t.formats&&tL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&rL.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),eL.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=IC;n==="id"&&(i={...IC},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(a,d){await s.call(this,a.$schema);let p=this._addSchema(a,d);return p.validate||o.call(this,p)}async function s(a){a&&!this.getSchema(a)&&await i.call(this,{$ref:a},!0)}async function o(a){try{return this._compileSchemaEnv(a)}catch(d){if(!(d instanceof NC.default))throw d;return c.call(this,d),await l.call(this,d.missingSchema),o.call(this,a)}}function c({missingSchema:a,missingRef:d}){if(this.refs[a])throw new Error(`AnySchema ${a} is loaded but ${d} cannot be resolved`)}async function l(a){let d=await f.call(this,a);this.refs[a]||await s.call(this,d.$schema),this.refs[a]||this.addSchema(d,a,r)}async function f(a){let d=this._loading[a];if(d)return d;try{return await(this._loading[a]=n(a))}finally{delete this._loading[a]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,n,i);return this}let s;if(typeof t=="object"){let{schemaId:o}=this.opts;if(s=t[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return r=(0,Qa.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(t){let r;for(;typeof(r=TC.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Xa.SchemaEnv({schema:{},schemaId:n});if(r=Xa.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=TC.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Qa.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(aL.call(this,n,r),!r)return(0,Kh.eachItem)(n,s=>zh.call(this,s)),this;lL.call(this,r);let i={...r,type:(0,Uu.getJSONTypes)(r.type),schemaType:(0,Uu.getJSONTypes)(r.schemaType)};return(0,Kh.eachItem)(n,i.type.length===0?s=>zh.call(this,s,i):s=>i.type.forEach(o=>zh.call(this,s,i,o))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(s=>s.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let s=i.split("/").slice(1),o=t;for(let c of s)o=o[c];for(let c in n){let l=n[c];if(typeof l!="object")continue;let{$data:f}=l.definition,a=o[c];f&&a&&(o[c]=jC(a))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:c}=this.opts;if(typeof t=="object")o=t[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(t);if(l!==void 0)return l;n=(0,Qa.normalizeId)(o||n);let f=Qa.getSchemaRefs.call(this,t,n);return l=new Xa.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:f}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),i&&this.validateSchema(t,!0),l}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Xa.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Xa.compileSchema.call(this,t)}finally{this.opts=r}}};Za.ValidationError=Uq.default;Za.MissingRefError=NC.default;yt.default=Za;function OC(e,t,r,n="error"){for(let i in e){let s=i;s in t&&this.logger[n](`${r}: option ${i}. ${e[s]}`)}}function TC(e){return e=(0,Qa.normalizeId)(e),this.schemas[e]||this.refs[e]}function eL(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function tL(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function rL(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function nL(){let e={...this.opts};for(let t of Jq)delete e[t];return e}var iL={log(){},warn(){},error(){}};function sL(e){if(e===!1)return iL;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var oL=/^[a-z_$][a-z0-9_$:-]*$/i;function aL(e,t){let{RULES:r}=this;if((0,Kh.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!oL.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function zh(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:l})=>l===r);if(o||(o={type:r,rules:[]},s.rules.push(o)),s.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,Uu.getJSONTypes)(t.type),schemaType:(0,Uu.getJSONTypes)(t.schemaType)}};t.before?cL.call(this,o,c,t.before):o.rules.push(c),s.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function cL(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function lL(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=jC(t)),e.validateSchema=this.compile(t,!0))}var uL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jC(e){return{anyOf:[e,uL]}}});var qC=x(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var dL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Gh.default=dL});var FC=x(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.callRef=Yi.getValidate=void 0;var fL=Ga(),LC=wr(),er=pe(),eo=bn(),WC=qu(),zu=Re(),pL={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:s,validateName:o,opts:c,self:l}=n,{root:f}=s;if((r==="#"||r==="#/")&&i===f.baseId)return d();let a=WC.resolveRef.call(l,f,i,r);if(a===void 0)throw new fL.default(n.opts.uriResolver,i,r);if(a instanceof WC.SchemaEnv)return p(a);return u(a);function d(){if(s===f)return Ku(e,o,s,s.$async);let m=t.scopeValue("root",{ref:f});return Ku(e,(0,er._)`${m}.validate`,f,f.$async)}function p(m){let h=MC(e,m);Ku(e,h,m,m.$async)}function u(m){let h=t.scopeValue("schema",c.code.source===!0?{ref:m,code:(0,er.stringify)(m)}:{ref:m}),g=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:er.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(w),e.ok(g)}}};function MC(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,er._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Yi.getValidate=MC;function Ku(e,t,r,n){let{gen:i,it:s}=e,{allErrors:o,schemaEnv:c,opts:l}=s,f=l.passContext?eo.default.this:er.nil;n?a():d();function a(){if(!c.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,er._)`await ${(0,LC.callValidateCode)(e,t,f)}`),u(t),o||i.assign(m,!0)},h=>{i.if((0,er._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),p(h),o||i.assign(m,!1)}),e.ok(m)}function d(){e.result((0,LC.callValidateCode)(e,t,f),()=>u(t),()=>p(t))}function p(m){let h=(0,er._)`${m}.errors`;i.assign(eo.default.vErrors,(0,er._)`${eo.default.vErrors} === null ? ${h} : ${eo.default.vErrors}.concat(${h})`),i.assign(eo.default.errors,(0,er._)`${eo.default.vErrors}.length`)}function u(m){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=zu.mergeEvaluated.props(i,g.props,s.props));else{let w=i.var("props",(0,er._)`${m}.evaluated.props`);s.props=zu.mergeEvaluated.props(i,w,s.props,er.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=zu.mergeEvaluated.items(i,g.items,s.items));else{let w=i.var("items",(0,er._)`${m}.evaluated.items`);s.items=zu.mergeEvaluated.items(i,w,s.items,er.Name)}}}Yi.callRef=Ku;Yi.default=pL});var HC=x(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var mL=qC(),hL=FC(),gL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",mL.default,hL.default];Jh.default=gL});var BC=x(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var Gu=pe(),oi=Gu.operators,Ju={maximum:{okStr:"<=",ok:oi.LTE,fail:oi.GT},minimum:{okStr:">=",ok:oi.GTE,fail:oi.LT},exclusiveMaximum:{okStr:"<",ok:oi.LT,fail:oi.GTE},exclusiveMinimum:{okStr:">",ok:oi.GT,fail:oi.LTE}},wL={message:({keyword:e,schemaCode:t})=>(0,Gu.str)`must be ${Ju[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Gu._)`{comparison: ${Ju[e].okStr}, limit: ${t}}`},yL={keyword:Object.keys(Ju),type:"number",schemaType:"number",$data:!0,error:wL,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Gu._)`${r} ${Ju[t].fail} ${n} || isNaN(${r})`)}};Yh.default=yL});var VC=x(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var ec=pe(),vL={message:({schemaCode:e})=>(0,ec.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,ec._)`{multipleOf: ${e}}`},kL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:vL,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),c=s?(0,ec._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,ec._)`${o} !== parseInt(${o})`;e.fail$data((0,ec._)`(${n} === 0 || (${o} = ${r}/${n}, ${c}))`)}};Xh.default=kL});var Zh=x(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});function UC(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}Qh.default=UC;UC.code='require("ajv/dist/runtime/ucs2length").default'});var zC=x(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});var Xi=pe(),bL=Re(),RL=Zh(),SL={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Xi.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Xi._)`{limit: ${e}}`},CL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:SL,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,s=t==="maxLength"?Xi.operators.GT:Xi.operators.LT,o=i.opts.unicode===!1?(0,Xi._)`${r}.length`:(0,Xi._)`${(0,bL.useFunc)(e.gen,RL.default)}(${r})`;e.fail$data((0,Xi._)`${o} ${s} ${n}`)}};eg.default=CL});var KC=x(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var EL=wr(),AL=Re(),to=pe(),xL={message:({schemaCode:e})=>(0,to.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,to._)`{pattern: ${e}}`},_L={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xL,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:s,it:o}=e,c=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=o.opts.code,f=l.code==="new RegExp"?(0,to._)`new RegExp`:(0,AL.useFunc)(t,l),a=t.let("valid");t.try(()=>t.assign(a,(0,to._)`${f}(${s}, ${c}).test(${r})`),()=>t.assign(a,!1)),e.fail$data((0,to._)`!${a}`)}else{let l=(0,EL.usePattern)(e,i);e.fail$data((0,to._)`!${l}.test(${r})`)}}};tg.default=_L});var GC=x(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var tc=pe(),IL={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,tc.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,tc._)`{limit: ${e}}`},PL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:IL,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?tc.operators.GT:tc.operators.LT;e.fail$data((0,tc._)`Object.keys(${r}).length ${i} ${n}`)}};rg.default=PL});var JC=x(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var rc=wr(),nc=pe(),OL=Re(),TL={message:({params:{missingProperty:e}})=>(0,nc.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,nc._)`{missingProperty: ${e}}`},NL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:TL,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:s,it:o}=e,{opts:c}=o;if(!s&&r.length===0)return;let l=r.length>=c.loopRequired;if(o.allErrors?f():a(),c.strictRequired){let u=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(u?.[h]===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,OL.checkStrictMode)(o,w,o.opts.strictRequired)}}function f(){if(l||s)e.block$data(nc.nil,d);else for(let u of r)(0,rc.checkReportMissingProp)(e,u)}function a(){let u=t.let("missing");if(l||s){let m=t.let("valid",!0);e.block$data(m,()=>p(u,m)),e.ok(m)}else t.if((0,rc.checkMissingProp)(e,r,u)),(0,rc.reportMissingProp)(e,u),t.else()}function d(){t.forOf("prop",n,u=>{e.setParams({missingProperty:u}),t.if((0,rc.noPropertyInData)(t,i,u,c.ownProperties),()=>e.error())})}function p(u,m){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(m,(0,rc.propertyInData)(t,i,u,c.ownProperties)),t.if((0,nc.not)(m),()=>{e.error(),t.break()})},nc.nil)}}};ng.default=NL});var YC=x(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var ic=pe(),$L={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,ic.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,ic._)`{limit: ${e}}`},jL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$L,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?ic.operators.GT:ic.operators.LT;e.fail$data((0,ic._)`${r}.length ${i} ${n}`)}};ig.default=jL});var Yu=x(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var XC=Rh();XC.code='require("ajv/dist/runtime/equal").default';sg.default=XC});var QC=x(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var og=Ba(),vt=pe(),DL=Re(),qL=Yu(),LL={message:({params:{i:e,j:t}})=>(0,vt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,vt._)`{i: ${e}, j: ${t}}`},WL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:LL,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:s,schemaCode:o,it:c}=e;if(!n&&!i)return;let l=t.let("valid"),f=s.items?(0,og.getSchemaTypes)(s.items):[];e.block$data(l,a,(0,vt._)`${o} === false`),e.ok(l);function a(){let m=t.let("i",(0,vt._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(l,!0),t.if((0,vt._)`${m} > 1`,()=>(d()?p:u)(m,h))}function d(){return f.length>0&&!f.some(m=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),w=(0,og.checkDataTypes)(f,g,c.opts.strictNumbers,og.DataType.Wrong),k=t.const("indices",(0,vt._)`{}`);t.for((0,vt._)`;${m}--;`,()=>{t.let(g,(0,vt._)`${r}[${m}]`),t.if(w,(0,vt._)`continue`),f.length>1&&t.if((0,vt._)`typeof ${g} == "string"`,(0,vt._)`${g} += "_"`),t.if((0,vt._)`typeof ${k}[${g}] == "number"`,()=>{t.assign(h,(0,vt._)`${k}[${g}]`),e.error(),t.assign(l,!1).break()}).code((0,vt._)`${k}[${g}] = ${m}`)})}function u(m,h){let g=(0,DL.useFunc)(t,qL.default),w=t.name("outer");t.label(w).for((0,vt._)`;${m}--;`,()=>t.for((0,vt._)`${h} = ${m}; ${h}--;`,()=>t.if((0,vt._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(l,!1).break(w)})))}}};ag.default=WL});var ZC=x(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var cg=pe(),ML=Re(),FL=Yu(),HL={message:"must be equal to constant",params:({schemaCode:e})=>(0,cg._)`{allowedValue: ${e}}`},BL={keyword:"const",$data:!0,error:HL,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,cg._)`!${(0,ML.useFunc)(t,FL.default)}(${r}, ${i})`):e.fail((0,cg._)`${s} !== ${r}`)}};lg.default=BL});var eE=x(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var sc=pe(),VL=Re(),UL=Yu(),zL={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,sc._)`{allowedValues: ${e}}`},KL={keyword:"enum",schemaType:"array",$data:!0,error:zL,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:s,it:o}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let c=i.length>=o.opts.loopEnum,l,f=()=>l??(l=(0,VL.useFunc)(t,UL.default)),a;if(c||n)a=t.let("valid"),e.block$data(a,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let u=t.const("vSchema",s);a=(0,sc.or)(...i.map((m,h)=>p(u,h)))}e.pass(a);function d(){t.assign(a,!1),t.forOf("v",s,u=>t.if((0,sc._)`${f()}(${r}, ${u})`,()=>t.assign(a,!0).break()))}function p(u,m){let h=i[m];return typeof h=="object"&&h!==null?(0,sc._)`${f()}(${r}, ${u}[${m}])`:(0,sc._)`${r} === ${h}`}}};ug.default=KL});var tE=x(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var GL=BC(),JL=VC(),YL=zC(),XL=KC(),QL=GC(),ZL=JC(),eW=YC(),tW=QC(),rW=ZC(),nW=eE(),iW=[GL.default,JL.default,YL.default,XL.default,QL.default,ZL.default,eW.default,tW.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rW.default,nW.default];dg.default=iW});var pg=x(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.validateAdditionalItems=void 0;var Qi=pe(),fg=Re(),sW={message:({params:{len:e}})=>(0,Qi.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Qi._)`{limit: ${e}}`},oW={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:sW,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,fg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}rE(e,n)}};function rE(e,t){let{gen:r,schema:n,data:i,keyword:s,it:o}=e;o.items=!0;let c=r.const("len",(0,Qi._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Qi._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,fg.alwaysValidSchema)(o,n)){let f=r.var("valid",(0,Qi._)`${c} <= ${t.length}`);r.if((0,Qi.not)(f),()=>l(f)),e.ok(f)}function l(f){r.forRange("i",t.length,c,a=>{e.subschema({keyword:s,dataProp:a,dataPropType:fg.Type.Num},f),o.allErrors||r.if((0,Qi.not)(f),()=>r.break())})}}oc.validateAdditionalItems=rE;oc.default=oW});var mg=x(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.validateTuple=void 0;var nE=pe(),Xu=Re(),aW=wr(),cW={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return iE(e,"additionalItems",t);r.items=!0,!(0,Xu.alwaysValidSchema)(r,t)&&e.ok((0,aW.validateArray)(e))}};function iE(e,t,r=e.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:c}=e;a(i),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Xu.mergeEvaluated.items(n,r.length,c.items));let l=n.name("valid"),f=n.const("len",(0,nE._)`${s}.length`);r.forEach((d,p)=>{(0,Xu.alwaysValidSchema)(c,d)||(n.if((0,nE._)`${f} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},l)),e.ok(l))});function a(d){let{opts:p,errSchemaPath:u}=c,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Xu.checkStrictMode)(c,g,p.strictTuples)}}}ac.validateTuple=iE;ac.default=cW});var sE=x(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var lW=mg(),uW={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,lW.validateTuple)(e,"items")};hg.default=uW});var aE=x(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var oE=pe(),dW=Re(),fW=wr(),pW=pg(),mW={message:({params:{len:e}})=>(0,oE.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,oE._)`{limit: ${e}}`},hW={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mW,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,dW.alwaysValidSchema)(n,t)&&(i?(0,pW.validateAdditionalItems)(e,i):e.ok((0,fW.validateArray)(e)))}};gg.default=hW});var cE=x(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var vr=pe(),Qu=Re(),gW={message:({params:{min:e,max:t}})=>t===void 0?(0,vr.str)`must contain at least ${e} valid item(s)`:(0,vr.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,vr._)`{minContains: ${e}}`:(0,vr._)`{minContains: ${e}, maxContains: ${t}}`},wW={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:gW,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e,o,c,{minContains:l,maxContains:f}=n;s.opts.next?(o=l===void 0?1:l,c=f):o=1;let a=t.const("len",(0,vr._)`${i}.length`);if(e.setParams({min:o,max:c}),c===void 0&&o===0){(0,Qu.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&o>c){(0,Qu.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Qu.alwaysValidSchema)(s,r)){let h=(0,vr._)`${a} >= ${o}`;c!==void 0&&(h=(0,vr._)`${h} && ${a} <= ${c}`),e.pass(h);return}s.items=!0;let d=t.name("valid");c===void 0&&o===1?u(d,()=>t.if(d,()=>t.break())):o===0?(t.let(d,!0),c!==void 0&&t.if((0,vr._)`${i}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);u(h,()=>t.if(h,()=>m(g)))}function u(h,g){t.forRange("i",0,a,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Qu.Type.Num,compositeRule:!0},h),g()})}function m(h){t.code((0,vr._)`${h}++`),c===void 0?t.if((0,vr._)`${h} >= ${o}`,()=>t.assign(d,!0).break()):(t.if((0,vr._)`${h} > ${c}`,()=>t.assign(d,!1).break()),o===1?t.assign(d,!0):t.if((0,vr._)`${h} >= ${o}`,()=>t.assign(d,!0)))}}};wg.default=wW});var dE=x(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.validateSchemaDeps=en.validatePropertyDeps=en.error=void 0;var yg=pe(),yW=Re(),cc=wr();en.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,yg.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,yg._)`{property: ${e},
|
|
147
|
+
missingProperty: ${n},
|
|
148
|
+
depsCount: ${t},
|
|
149
|
+
deps: ${r}}`};var vW={keyword:"dependencies",type:"object",schemaType:"object",error:en.error,code(e){let[t,r]=kW(e);lE(e,t),uE(e,r)}};function kW({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function lE(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let c=t[o];if(c.length===0)continue;let l=(0,cc.propertyInData)(r,n,o,i.opts.ownProperties);e.setParams({property:o,depsCount:c.length,deps:c.join(", ")}),i.allErrors?r.if(l,()=>{for(let f of c)(0,cc.checkReportMissingProp)(e,f)}):(r.if((0,yg._)`${l} && (${(0,cc.checkMissingProp)(e,c,s)})`),(0,cc.reportMissingProp)(e,s),r.else())}}en.validatePropertyDeps=lE;function uE(e,t=e.schema){let{gen:r,data:n,keyword:i,it:s}=e,o=r.name("valid");for(let c in t)(0,yW.alwaysValidSchema)(s,t[c])||(r.if((0,cc.propertyInData)(r,n,c,s.opts.ownProperties),()=>{let l=e.subschema({keyword:i,schemaProp:c},o);e.mergeValidEvaluated(l,o)},()=>r.var(o,!0)),e.ok(o))}en.validateSchemaDeps=uE;en.default=vW});var pE=x(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var fE=pe(),bW=Re(),RW={message:"property name must be valid",params:({params:e})=>(0,fE._)`{propertyName: ${e.propertyName}}`},SW={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RW,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,bW.alwaysValidSchema)(i,r))return;let s=t.name("valid");t.forIn("key",n,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,fE.not)(s),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(s)}};vg.default=SW});var bg=x(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var Zu=wr(),Lr=pe(),CW=bn(),ed=Re(),EW={message:"must NOT have additional properties",params:({params:e})=>(0,Lr._)`{additionalProperty: ${e.additionalProperty}}`},AW={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:EW,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:c,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,ed.alwaysValidSchema)(o,r))return;let f=(0,Zu.allSchemaProperties)(n.properties),a=(0,Zu.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Lr._)`${s} === ${CW.default.errors}`);function d(){t.forIn("key",i,g=>{!f.length&&!a.length?m(g):t.if(p(g),()=>m(g))})}function p(g){let w;if(f.length>8){let k=(0,ed.schemaRefOrVal)(o,n.properties,"properties");w=(0,Zu.isOwnProperty)(t,k,g)}else f.length?w=(0,Lr.or)(...f.map(k=>(0,Lr._)`${g} === ${k}`)):w=Lr.nil;return a.length&&(w=(0,Lr.or)(w,...a.map(k=>(0,Lr._)`${(0,Zu.usePattern)(e,k)}.test(${g})`))),(0,Lr.not)(w)}function u(g){t.code((0,Lr._)`delete ${i}[${g}]`)}function m(g){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){u(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,ed.alwaysValidSchema)(o,r)){let w=t.name("valid");l.removeAdditional==="failing"?(h(g,w,!1),t.if((0,Lr.not)(w),()=>{e.reset(),u(g)})):(h(g,w),c||t.if((0,Lr.not)(w),()=>t.break()))}}function h(g,w,k){let b={keyword:"additionalProperties",dataProp:g,dataPropType:ed.Type.Str};k===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,w)}}};kg.default=AW});var gE=x(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var xW=Ka(),mE=wr(),Rg=Re(),hE=bg(),_W={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&hE.default.code(new xW.KeywordCxt(s,hE.default,"additionalProperties"));let o=(0,mE.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Rg.mergeEvaluated.props(t,(0,Rg.toHash)(o),s.props));let c=o.filter(d=>!(0,Rg.alwaysValidSchema)(s,r[d]));if(c.length===0)return;let l=t.name("valid");for(let d of c)f(d)?a(d):(t.if((0,mE.propertyInData)(t,i,d,s.opts.ownProperties)),a(d),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(l);function f(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function a(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};Sg.default=_W});var kE=x(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var wE=wr(),td=pe(),yE=Re(),vE=Re(),IW={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:s}=e,{opts:o}=s,c=(0,wE.allSchemaProperties)(r),l=c.filter(h=>(0,yE.alwaysValidSchema)(s,r[h]));if(c.length===0||l.length===c.length&&(!s.opts.unevaluated||s.props===!0))return;let f=o.strictSchema&&!o.allowMatchingProperties&&i.properties,a=t.name("valid");s.props!==!0&&!(s.props instanceof td.Name)&&(s.props=(0,vE.evaluatedPropsToName)(t,s.props));let{props:d}=s;p();function p(){for(let h of c)f&&u(h),s.allErrors?m(h):(t.var(a,!0),m(h),t.if(a))}function u(h){for(let g in f)new RegExp(h).test(g)&&(0,yE.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,g=>{t.if((0,td._)`${(0,wE.usePattern)(e,h)}.test(${g})`,()=>{let w=l.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:vE.Type.Str},a),s.opts.unevaluated&&d!==!0?t.assign((0,td._)`${d}[${g}]`,!0):!w&&!s.allErrors&&t.if((0,td.not)(a),()=>t.break())})})}}};Cg.default=IW});var bE=x(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var PW=Re(),OW={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,PW.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Eg.default=OW});var RE=x(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var TW=wr(),NW={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:TW.validateUnion,error:{message:"must match a schema in anyOf"}};Ag.default=NW});var SE=x(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var rd=pe(),$W=Re(),jW={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,rd._)`{passingSchemas: ${e.passing}}`},DW={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:jW,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=t.let("valid",!1),c=t.let("passing",null),l=t.name("_valid");e.setParams({passing:c}),t.block(f),e.result(o,()=>e.reset(),()=>e.error(!0));function f(){s.forEach((a,d)=>{let p;(0,$W.alwaysValidSchema)(i,a)?t.var(l,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&t.if((0,rd._)`${l} && ${o}`).assign(o,!1).assign(c,(0,rd._)`[${c}, ${d}]`).else(),t.if(l,()=>{t.assign(o,!0),t.assign(c,d),p&&e.mergeEvaluated(p,rd.Name)})})}}};xg.default=DW});var CE=x(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var qW=Re(),LW={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((s,o)=>{if((0,qW.alwaysValidSchema)(n,s))return;let c=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(c)})}};_g.default=LW});var xE=x(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var nd=pe(),AE=Re(),WW={message:({params:e})=>(0,nd.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,nd._)`{failingKeyword: ${e.ifClause}}`},MW={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:WW,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,AE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=EE(n,"then"),s=EE(n,"else");if(!i&&!s)return;let o=t.let("valid",!0),c=t.name("_valid");if(l(),e.reset(),i&&s){let a=t.let("ifClause");e.setParams({ifClause:a}),t.if(c,f("then",a),f("else",a))}else i?t.if(c,f("then")):t.if((0,nd.not)(c),f("else"));e.pass(o,()=>e.error(!0));function l(){let a=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);e.mergeEvaluated(a)}function f(a,d){return()=>{let p=e.subschema({keyword:a},c);t.assign(o,c),e.mergeValidEvaluated(p,o),d?t.assign(d,(0,nd._)`${a}`):e.setParams({ifClause:a})}}}};function EE(e,t){let r=e.schema[t];return r!==void 0&&!(0,AE.alwaysValidSchema)(e,r)}Ig.default=MW});var _E=x(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var FW=Re(),HW={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,FW.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Pg.default=HW});var IE=x(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var BW=pg(),VW=sE(),UW=mg(),zW=aE(),KW=cE(),GW=dE(),JW=pE(),YW=bg(),XW=gE(),QW=kE(),ZW=bE(),eM=RE(),tM=SE(),rM=CE(),nM=xE(),iM=_E();function sM(e=!1){let t=[ZW.default,eM.default,tM.default,rM.default,nM.default,iM.default,JW.default,YW.default,GW.default,XW.default,QW.default];return e?t.push(VW.default,zW.default):t.push(BW.default,UW.default),t.push(KW.default),t}Og.default=sM});var PE=x(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var Ze=pe(),oM={message:({schemaCode:e})=>(0,Ze.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Ze._)`{format: ${e}}`},aM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oM,code(e,t){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:c}=e,{opts:l,errSchemaPath:f,schemaEnv:a,self:d}=c;if(!l.validateFormats)return;i?p():u();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=r.const("fDef",(0,Ze._)`${m}[${o}]`),g=r.let("fType"),w=r.let("format");r.if((0,Ze._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Ze._)`${h}.type || "string"`).assign(w,(0,Ze._)`${h}.validate`),()=>r.assign(g,(0,Ze._)`"string"`).assign(w,h)),e.fail$data((0,Ze.or)(k(),b()));function k(){return l.strictSchema===!1?Ze.nil:(0,Ze._)`${o} && !${w}`}function b(){let R=a.$async?(0,Ze._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,Ze._)`${w}(${n})`,E=(0,Ze._)`(typeof ${w} == "function" ? ${R} : ${w}.test(${n}))`;return(0,Ze._)`${w} && ${w} !== true && ${g} === ${t} && !${E}`}}function u(){let m=d.formats[s];if(!m){k();return}if(m===!0)return;let[h,g,w]=b(m);h===t&&e.pass(R());function k(){if(l.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${f}"`}}function b(E){let O=E instanceof RegExp?(0,Ze.regexpCode)(E):l.code.formats?(0,Ze._)`${l.code.formats}${(0,Ze.getProperty)(s)}`:void 0,z=r.scopeValue("formats",{key:s,ref:E,code:O});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ze._)`${z}.validate`]:["string",E,z]}function R(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!a.$async)throw new Error("async format in sync schema");return(0,Ze._)`await ${w}(${n})`}return typeof g=="function"?(0,Ze._)`${w}(${n})`:(0,Ze._)`${w}.test(${n})`}}}};Tg.default=aM});var OE=x(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var cM=PE(),lM=[cM.default];Ng.default=lM});var TE=x(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.contentVocabulary=ro.metadataVocabulary=void 0;ro.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ro.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var $E=x($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var uM=HC(),dM=tE(),fM=IE(),pM=OE(),NE=TE(),mM=[uM.default,dM.default,(0,fM.default)(),pM.default,NE.metadataVocabulary,NE.contentVocabulary];$g.default=mM});var DE=x(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});id.DiscrError=void 0;var jE;(function(e){e.Tag="tag",e.Mapping="mapping"})(jE||(id.DiscrError=jE={}))});var LE=x(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var no=pe(),jg=DE(),qE=qu(),hM=Ga(),gM=Re(),wM={message:({params:{discrError:e,tagName:t}})=>e===jg.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,no._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},yM={keyword:"discriminator",type:"object",schemaType:"object",error:wM,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:s}=e,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let l=t.let("valid",!1),f=t.const("tag",(0,no._)`${r}${(0,no.getProperty)(c)}`);t.if((0,no._)`typeof ${f} == "string"`,()=>a(),()=>e.error(!1,{discrError:jg.DiscrError.Tag,tag:f,tagName:c})),e.ok(l);function a(){let u=p();t.if(!1);for(let m in u)t.elseIf((0,no._)`${f} === ${m}`),t.assign(l,d(u[m]));t.else(),e.error(!1,{discrError:jg.DiscrError.Mapping,tag:f,tagName:c}),t.endIf()}function d(u){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:u},m);return e.mergeEvaluated(h,no.Name),m}function p(){var u;let m={},h=w(i),g=!0;for(let R=0;R<o.length;R++){let E=o[R];if(E?.$ref&&!(0,gM.schemaHasRulesButRef)(E,s.self.RULES)){let z=E.$ref;if(E=qE.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,z),E instanceof qE.SchemaEnv&&(E=E.schema),E===void 0)throw new hM.default(s.opts.uriResolver,s.baseId,z)}let O=(u=E?.properties)===null||u===void 0?void 0:u[c];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);g=g&&(h||w(E)),k(O,R)}if(!g)throw new Error(`discriminator: "${c}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(c)}function k(R,E){if(R.const)b(R.const,E);else if(R.enum)for(let O of R.enum)b(O,E);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function b(R,E){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${c}" values must be unique strings`);m[R]=E}}}};Dg.default=yM});var WE=x((g6,vM)=>{vM.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var FE=x((Me,qg)=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.MissingRefError=Me.ValidationError=Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=Me.Ajv=void 0;var kM=DC(),bM=$E(),RM=LE(),ME=WE(),SM=["/properties"],sd="http://json-schema.org/draft-07/schema",io=class extends kM.default{_addVocabularies(){super._addVocabularies(),bM.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(RM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(ME,SM):ME;this.addMetaSchema(t,sd,!1),this.refs["http://json-schema.org/schema"]=sd}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(sd)?sd:void 0)}};Me.Ajv=io;qg.exports=Me=io;qg.exports.Ajv=io;Object.defineProperty(Me,"__esModule",{value:!0});Me.default=io;var CM=Ka();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return CM.KeywordCxt}});var so=pe();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return so._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return so.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return so.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return so.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return so.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return so.CodeGen}});var EM=ju();Object.defineProperty(Me,"ValidationError",{enumerable:!0,get:function(){return EM.default}});var AM=Ga();Object.defineProperty(Me,"MissingRefError",{enumerable:!0,get:function(){return AM.default}})});nf();cf();nr();of();import{promises as tf}from"fs";import Nt from"path";import{promises as fy}from"node:fs";import jI from"node:path";nr();import{createHash as AI}from"node:crypto";import{lstatSync as Oo,readFileSync as xI,realpathSync as cy}from"node:fs";import _I from"node:os";import $t from"node:path";function uf(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function Wc(e){return process.platform==="win32"?cy.native(e):cy(e)}var II=Vr("workspaceIdentity",OI);function PI(e){return II(e)}function OI(e){let t=Wc($t.resolve(e)),r=Oo(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=uf(r),i=(l,f)=>({projectRoot:t,workspaceId:AI("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,l,f])).digest("hex")}),s=$t.join(t,".git"),o,c;try{let l=Oo(s);if(l.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${s}`);if(l.isDirectory())o=Wc(s),c=uf(Oo(o,{bigint:!0}));else if(l.isFile()){let f=/^gitdir: (.+)\r?\n?$/u.exec(xI(s,"utf8"));if(!f)throw new Error(`工作区 .git 文件格式无效:${s}`);o=Wc($t.resolve(t,f[1].trim()));let a=Oo(o,{bigint:!0});if(!a.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${o}`);c=uf(a)}else throw new Error(`工作区 .git 类型无效:${s}`)}catch(l){if(l.code!=="ENOENT")throw l;try{Oo(s)}catch(f){if(f.code==="ENOENT")return i(s,null);throw f}throw l}return i(o,c)}function ly(e){let t=$t.dirname(e);if(t===e)return e;try{return $t.join(Wc(t),$t.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return $t.join(ly(t),$t.basename(e))}}var TI=Vr("workspaceRuntimeParent",ly);function df(e){let t=PI(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!$t.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=TI(r??$t.join(_I.homedir(),".comet")),i=$t.relative(t.projectRoot,n);if(i===""||!$t.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${$t.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let s=$t.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:s,runtimeRoot:$t.join(s,"runtime")}}function pt(e){return df(e).runtimeRoot}Ri();async function jn(e){return pt(e)}async function pf(e){return[pt(e)]}async function py(e){let t=jI.dirname(e);if(t!==e){await py(t);try{await fy.mkdir(e,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}}let r=await fy.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function Ur(e){let t=pt(e);return await py(t),t}nr();jt();Ri();ye();import{promises as jN}from"node:fs";import{AsyncLocalStorage as DN}from"node:async_hooks";import Pr from"node:path";var da="comet.change-owner.v1",_b=["native","classic-full","classic-hotfix","classic-tweak"],qN=je("changeOwnerRuntimeRoots",e=>pf(e)),Ib=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Or(e,t,r="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!Ib.test(t))throw new Error(`Invalid change name: ${t}`);return`${r==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function cm(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Change runtime owner must be a JSON object");let n=e,i=n.schema===da&&n.workflow===t&&n.change===r,s=n.format==="compat"&&Object.keys(n).length===4,o=n.format==="sdk"&&Object.keys(n).length===6&&n.runId===r&&(typeof n.application=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(n.application)&&!_b.includes(n.application)||(t==="native"?n.application==="native":n.application==="classic-full"||n.application==="classic-hotfix"||n.application==="classic-tweak"));if(!i||!s&&!o)throw new Error(`Invalid change runtime owner for ${t}/${r}`);return n}async function Vl(e,t,r,n){let i;try{({bytes:i}=await ae(e,t,Number.MAX_SAFE_INTEGER,{label:"change runtime owner"}))}catch(o){if(o.code==="ENOENT")return null;throw o}let s;try{s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error(`Invalid change runtime owner JSON for ${r}/${n}`)}return cm(s,r,n)}function Pb(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function Ob(e,t){return Or(e,t),`change-owner-records/${e}/${t}.json`}async function lm(e,t,r){let n;try{n=await ae(e,Ob(t,r),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(s){if(s.code==="ENOENT")return null;throw s}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{throw new Error(`Invalid canonical Runtime owner for ${t}/${r}`)}return{owner:cm(i,t,r),identity:Pb(n.stat)}}async function Tb(e,t,r){let n=await ua(e,"change owner bindings"),i=async c=>{try{let{stat:l}=await n.stat(Or(t,r,c));return Pb(l)}catch(l){if(l.code==="ENOENT")return null;throw l}},s=await i("active"),o=await i("history");return await n.finish({allowDirectoryContentChanges:!0}),{active:s,history:o}}async function LN(e,t,r=!1){let n=await Tb(e,t.workflow,t.change);if(n.active===null&&n.history===null)return;if(n.active!==null&&n.history!==null)throw new Error(`Conflicting or missing Runtime owner for ${t.workflow}/${t.change}`);let i=r?null:await lm(e,t.workflow,t.change);if(i?.identity&&i.identity===(n.active??n.history))return;let s=Ob(t.workflow,t.change);await gt(e,Pr.posix.dirname(s),{label:"canonical change runtime owners"});let o=Or(t.workflow,t.change,n.active?"active":"history");try{await yy(Pr.join(e,o),Pr.join(e,s),{containedRoot:e})}catch(c){if(!["ENOTSUP","EOPNOTSUPP"].includes(c.code??""))throw c}}async function WN(e,t,r){let n;try{n=await lm(e,t,r)}catch(s){if(s instanceof mt&&s.reason==="changed")return null;throw s}if(!n?.identity)return null;let i=await Tb(e,t,r);return i.active===n.identity&&i.history===null||i.history===n.identity&&i.active===null?n:null}var Oi=new DN,Nb=Vr("verifiedOwnerBatchResults",()=>new Map),$b=(e,t,r)=>`${JSON.stringify([e,t])}\0${r}`;async function jb(e){let t=Oi.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??qN(e)}async function Db(e,t,r=!1){let n=Oi.getStore();if(n?.active&&e.every(s=>n.roots.has(s)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let s=await Oi.run(i,()=>Pn(()=>r?oy(t):t())),o=Nb();for(let c of o.keys())[...i.projects].some(l=>c.startsWith(l+"\0"))&&o.delete(c);for(let[c,l]of i.owners)o.set(c,l);return s}finally{i.active=!1}}async function am(e,t,r){let n=await WN(e,t,r);return n?n.owner:Db([e],async()=>{let i=await Vl(e,Or(t,r),t,r),s=await Vl(e,Or(t,r,"history"),t,r);if(i&&s)throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);return i??s})}async function Ul(e,t,r,n={}){if(Or(t,r),!n.readOnly)return Oi.run(null,()=>Pn(async()=>am(await jn(e),t,r)));let[i,s]=await jb(e),o=Pr.parse(i).root,l=(await U(o,Pr.relative(o,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await am(i,t,r):null,f=s?await am(s,t,r):null;if(l&&f&&JSON.stringify(Object.entries(l).sort())!==JSON.stringify(Object.entries(f).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${r}`);return l??f}async function xb(e,t,r,n={}){let i=await Ul(e,t,r,n),s=i?.format==="sdk"?i:null,o=Oi.getStore();return n.readOnly&&o?.active&&o.owners.set($b(e,t,r),s),s}async function Tr(e,t,r,n={}){if(!n.readOnly||Oi.getStore()?.active)return xb(e,t,r,n);let i=Nb(),s=$b(e,t,r);if(i.has(s))return i.get(s);let o=xb(e,t,r,n).catch(c=>{throw i.get(s)===o&&i.delete(s),c});return i.set(s,o),o}async function MN(e,t,r,n=!1){Or(t,"validate");let i=r.readOnly?await jb(e):[await jn(e)],s=async()=>{let o={active:new Set,history:new Set};for(let c of i)for(let l of["active","history"]){let f=Pr.parse(c).root,a=Pr.posix.dirname(Or(t,"validate",l)),d=await U(f,Pr.relative(f,Pr.join(c,a)).replaceAll("\\","/"),{label:`${t} ${l} change runtime owners`,expected:"directory"});if(!d.exists)continue;let p=await jN.readdir(d.target,{withFileTypes:!0});for(let u of p){if(u.isFile()&&/^\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.json\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/u.test(u.name))continue;if(t==="classic"&&l==="active"){let h=/^([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\.lock(?:\.([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(?:tmp|removed))?$/u;if(u.isFile()&&h.test(u.name)||u.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(u.name))continue}if(!u.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${u.name}`);let m=u.name.slice(0,-5);if(!u.isFile()||!Ib.test(m))throw new Error(`Invalid ${t} change runtime owner entry: ${u.name}`);o[l].add(m)}}return o};return n?s():Db(i,s)}var Bz=je("changeOwnerPartitions",MN);async function FN(e,t,r){return sy(),Oi.run(null,()=>Pn(async()=>{let n=await Ur(e);return Or(t.workflow,t.change),r(n)}))}async function HN(e,t,r={}){let n=Or(t.workflow,t.change),i=cm(t,t.workflow,t.change);return FN(e,i,async s=>{if(await Vl(s,Or(t.workflow,t.change,"history"),t.workflow,t.change))throw new Error(`Change ${t.workflow}/${t.change} is in history; restore its active owner before registering`);await gt(s,Pr.posix.dirname(n),{label:"change runtime owner directory"});try{await Te(Pr.join(s,...n.split("/")),`${JSON.stringify(i)}
|
|
150
|
+
`,{containedRoot:s,exclusive:!0,requireAtomicPublication:!0})}catch(c){if(c.code!=="EEXIST")throw c;let l=await Vl(s,n,t.workflow,t.change);if(JSON.stringify(l)!==JSON.stringify(i))throw new Error(`Change ${t.workflow}/${t.change} is already bound to another Runtime`,{cause:c})}return(r.canonical||await lm(s,t.workflow,t.change))&&await LN(s,i),i})}function zl(e,t,r={}){return HN(e,t,r)}dm();mm();function hm(e){let t=e.replaceAll("\\","/");return/(?:^|\/)(?:AGENTS|CLAUDE|GEMINI|QWEN|SKILL)\.md$/iu.test(t)||/(?:^|\/)(?:\.agents|\.claude|\.codex|\.cursor|\.windsurf|\.kiro|\.superpowers)(?:\/|$)/iu.test(t)||/(?:^|\/)assets\/skills(?:-[^/]+)?\//iu.test(t)||/(?:^|\/)\.github\/(?:instructions|prompts)\//iu.test(t)||/(?:^|\/)copilot-instructions\.md$/iu.test(t)}var YN=new Set([".md",".markdown"]);function Mb(e,t){let r=Yl(e),n=Yl(t).replace(/\/+$/u,"");if(!r.startsWith(`${n}/`))return!1;let i=r.slice(n.length+1).split("/");return(i.length===2||i.length===3&&i[0]==="archive")&&i.at(-1)==="walkthrough.html"}var XN=new Set([".md",".markdown",".rst",".txt"]),QN=new Set(["docs","doc","documentation",".github"]),ZN=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function Yl(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function e$(e,t){for(let r of t){let n=Yl(r).replace(/\/+$/u,"");if(n&&(e===n||e.startsWith(`${n}/`)))return!0}return!1}function Fb(e,t=[]){let r=Yl(e);if(hm(r)||!r||r.endsWith("/")||e$(r,t))return!1;let n=r.split("/"),i=n[n.length-1],s=i.lastIndexOf("."),o=s===-1?"":i.slice(s).toLowerCase();return n.length===1?YN.has(o)||ZN.some(c=>c.test(i)):QN.has(n[0])&&XN.has(o)}nr();import{promises as t$}from"node:fs";import gm from"node:path";var Hb="comet-state.yaml",Xl=".comet.yaml",Ns=[Hb,Xl],pa=class extends Error{};function ma(e){return Ns.some(t=>t===e)}async function r$(e,t={}){let r=[],n=[];for(let i of Ns)try{let s=await t$.lstat(gm.join(e,i));r.push(i),(!s.isFile()||s.isSymbolicLink())&&n.push(i)}catch(s){if(s.code!=="ENOENT")throw s}if(r.length>1)throw new pa(`Classic state files are ambiguous in ${e}: ${Ns.join(" and ")} both exist; preserve both files and resolve the conflict before continuing`);if(n.length)throw new Error(`Classic state must be a regular file, not a symlink or directory: ${gm.join(e,n[0])}`);return gm.join(e,r[0]??t.defaultFileName??Hb)}var n$=je("classicStateFile",(e,t)=>r$(e,t));async function fe(e,t={}){return n$(e,t)}import{AsyncLocalStorage as Ub}from"node:async_hooks";import{performance as Bb}from"node:perf_hooks";var i$=0,s$=0,wm=new Ub,Vb=new Ub;async function zb(e,t=r=>{let n=r.completed===void 0?"":`:${r.completed}${r.total===void 0?"":`/${r.total}`} 项`;process.stderr.write(`[Comet] ${r.label}${n},已用 ${Math.floor(r.elapsedMs/1e3)} 秒
|
|
151
|
+
`)}){if(Vb.getStore())return e();let r={label:"执行工作流命令"},n=Date.now(),i=setInterval(()=>{try{t({...r,elapsedMs:Date.now()-n})}catch{}},5e3);i.unref?.();try{return await Vb.run(r,e)}finally{clearInterval(i)}}function o$(e=0){i$+=1,s$+=e;for(let t of wm.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}async function Kb(e){let t={gitCommands:0,gitDurationMs:0};return{result:await wm.run([...wm.getStore()??[],t],e),metrics:t}}function Jr(e){let t=Bb.now();try{return e()}finally{o$(Bb.now()-t)}}var Dm=bt(Dt(),1);nr();import{execFileSync as jm}from"child_process";import{promises as pj}from"fs";import mj from"path";nr();import{randomUUID as rj}from"node:crypto";ye();import{promises as Qb}from"fs";import Ye from"path";import f$ from"os";import{promises as a$}from"fs";async function Ql(e){try{return await a$.access(e),!0}catch(t){if(c$(t))return!1;throw t}}function c$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}qt();pn();Zl();ye();var $s=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},Ti=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="ClassicProjectConfigError"}},Yb=".comet/config.yaml";function km(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ha(e,t){let r=Ye.resolve(e),n=t==="docs"?Ye.join(r,"docs"):r,i=Ye.join(n,"openspec"),s=Ye.join(r,"docs","superpowers");return{projectRoot:r,artifactLayout:t,openSpecBase:n,openSpecRoot:i,changesDir:Ye.join(i,"changes"),archiveDir:Ye.join(i,"changes","archive"),specsDir:Ye.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:Ye.join(s,"specs"),superpowersPlansDir:Ye.join(s,"plans"),superpowersReportsDir:Ye.join(s,"reports")}}async function Zb(e){let t=await fn(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new $s;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new $s("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function mn(e,t){return ha(e,t??await Zb(e))}async function p$(e){try{return await Qb.lstat(e),!0}catch(t){if(km(t))return!1;throw t}}async function m$(e,t){let r=await mn(e,t),n=r.artifactLayout==="legacy"?"docs":"legacy",i=ha(e,n).openSpecRoot,[s,o]=await Promise.all([U(r.projectRoot,be(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),p$(i)]),c=s.exists;return{paths:r,configuredRootExists:c,alternateRoot:i,alternateRootExists:o,dualRoots:c&&o}}async function h$(e){let t=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let r of t){let n=be(e.projectRoot,r);await U(e.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function wt(e,t){let r=await m$(e,t);if(await h$(r.paths),!r.configuredRootExists){let n=be(r.paths.projectRoot,r.paths.openSpecRoot),i=be(r.paths.projectRoot,r.alternateRoot);throw new $s(`Configured Classic OpenSpec root is missing: ${n} (alternate ${i} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function Ni(e,t){let r=Ye.join(Ye.resolve(e),".comet","classic-root-move.json");if(await Ql(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let n=await wt(e,t);if(!await Ql(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${be(n.projectRoot,n.openSpecRoot)}`);return n}async function ut(e){let t=Ye.resolve(e),r=null;try{(await Qb.lstat(t)).isDirectory()||(t=Ye.dirname(t))}catch(s){if(!km(s))throw s}let n=t,i=Ye.resolve(f$.homedir());for(;;){Ye.basename(t)==="openspec"&&(r=Ye.dirname(t));let s=!1,o=t===i&&t!==n,c=null;if(!o)try{let{bytes:f}=await ae(t,Yb,un,{label:Yb});c=f.toString("utf8")}catch(f){if(!km(f))throw f}if(c!==null)try{let f=dn(c,{allowPartialProject:!0,allowMissingNativeFields:!0}).value;s=!!f&&typeof f=="object"&&!Array.isArray(f)&&(f.schema==="comet.project.v1"||f.default_workflow!==void 0||f.native!==void 0)}catch(f){if(t===n)throw new Ti(f);if(kb(c))throw new Ti(f)}if(s||await Ql(Ye.join(t,".git")))return t;let l=Ye.dirname(t);if(l===t)return r??Ye.resolve(e);t=l}}function be(e,t){return Ye.relative(Ye.resolve(e),t).replaceAll("\\","/")}ou();var Pm=["full","hotfix","tweak"],Li=1,Om=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u,Tm=`# comet-execution: managed-run
|
|
152
|
+
`;function ir(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}var wR=["open","design","build","verify","archive"],D$=["en","zh-CN"],q$=["off","beta"],L$=["subagent-driven-development","executing-plans","direct","autonomous"],W$=["plan-ready"],M$=["confirmed"],F$=["tdd","direct"],H$=["off","standard","thorough"],B$=["current","branch","worktree"],V$=["light","full"],U$=["pending","pass","fail"],z$=["pending","handled"],K$=["pending","confirmed"],Gn=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","check_epoch","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],ba=["change_id","run_id","run_checkpoint","application_checkpoint"],yR=new Set([...Gn,...ba]),G$=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function _m(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ds(e,t){let r=e[t];if(r==null||r==="")return null;if(typeof r!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return r}function Lt(e,t,r,n=!0){let i=e[t];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="string"||!r.includes(i))throw new Error(`Invalid Classic state: ${t} must be one of ${r.join(", ")}${n?" or null":""}`);return i}function Im(e,t,r=!0){let n=e[t];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof n!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return n}function gR(e,t,r=0){let n=e[t];if(n==null||n==="")return r;if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return n}function au(e,t){let r=Ds(e,t);if(r===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return r}function J$(e,t){let r=Ds(e,t);if(r!==null&&!/^[a-f0-9]{64}$/u.test(r))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return r}function Y$(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==Li)throw new Error(`Invalid Classic state: classic_migration must be ${Li}`);return t}function X$(e){if(!Gn.some(r=>_m(e,r)))return null;for(let r of G$)if(!_m(e,r))return null;return{workflow:Lt(e,"workflow",Pm,!1),language:Lt(e,"language",D$),phase:Lt(e,"phase",wR,!1),contextCompression:Lt(e,"context_compression",q$),buildMode:Lt(e,"build_mode",L$),buildPause:Lt(e,"build_pause",W$),subagentDispatch:Lt(e,"subagent_dispatch",M$),tddMode:Lt(e,"tdd_mode",F$),reviewMode:Lt(e,"review_mode",H$),isolation:Lt(e,"isolation",B$),boundBranch:Ds(e,"bound_branch"),verifyMode:Lt(e,"verify_mode",V$),autoTransition:Im(e,"auto_transition"),baseRef:Ds(e,"base_ref"),designDoc:au(e,"design_doc"),plan:au(e,"plan"),verifyResult:Lt(e,"verify_result",U$,!1),verifyFailures:gR(e,"verify_failures"),..._m(e,"check_epoch")?{checkEpoch:gR(e,"check_epoch")}:{},verificationReport:au(e,"verification_report"),branchStatus:Lt(e,"branch_status",z$),createdAt:Ds(e,"created_at"),verifiedAt:Ds(e,"verified_at"),archiveConfirmation:Lt(e,"archive_confirmation",K$),archived:Im(e,"archived",!1),directOverride:Im(e,"direct_override"),handoffContext:au(e,"handoff_context"),handoffHash:J$(e,"handoff_hash"),classicProfile:Lt(e,"classic_profile",Pm),classicMigration:Y$(e)}}function ur(e,t){if(e.change_id!==void 0&&(typeof e.change_id!="string"||!Om.test(e.change_id)))throw new Error("Invalid Classic state: change_id must be an immutable UUID");let r=t??null;if(r===null&&t===void 0&&e.run_id&&e.skill)try{r=Di(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:n})}return{classic:X$(e),run:r,unknownKeys:Object.keys(e).filter(n=>!yR.has(n))}}function vR(e){let t=e.workflow,r=e.phase,n=e.archived,i=e.design_doc;return{workflow:typeof t=="string"&&Pm.includes(t)?t:null,phase:typeof r=="string"&&wR.includes(r)?r:null,archived:n===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(e).filter(s=>!yR.has(s))}}function cu(e){return{workflow:e.workflow,language:e.language,phase:e.phase,context_compression:e.contextCompression,build_mode:e.buildMode,build_pause:e.buildPause,subagent_dispatch:e.subagentDispatch,tdd_mode:e.tddMode,review_mode:e.reviewMode,isolation:e.isolation,bound_branch:e.boundBranch,verify_mode:e.verifyMode,auto_transition:e.autoTransition,base_ref:e.baseRef,design_doc:e.designDoc,plan:e.plan,verify_result:e.verifyResult,verify_failures:e.verifyFailures,...e.checkEpoch===void 0?{}:{check_epoch:e.checkEpoch},verification_report:e.verificationReport,branch_status:e.branchStatus,created_at:e.createdAt,verified_at:e.verifiedAt,archive_confirmation:e.archiveConfirmation,archived:e.archived,direct_override:e.directOverride,handoff_context:e.handoffContext,handoff_hash:e.handoffHash,classic_profile:e.classicProfile,classic_migration:e.classicMigration}}ye();var kR=bt(Dt(),1);jt();ye();import{createHash as Q$,randomUUID as Z$}from"node:crypto";import xe from"node:path";var Nm=new Set(["run-state.json","pending-action.json","trajectory.jsonl","context.md","artifacts.json","checkpoint.json","coordination.json","subagent-progress.md"]);function lu(e){let t=Q$("sha256").update(e).digest("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}async function bR(e,t){let r=await fe(t),n=xe.relative(e,r).replaceAll("\\","/"),i=null;try{i=(await ae(e,n,Number.MAX_SAFE_INTEGER,{label:"Classic change identity"})).bytes.toString("utf8")}catch(c){if(c.code!=="ENOENT")throw c}if(i===null)throw Object.assign(new Error("Classic state file does not exist"),{code:"ENOENT"});let s=(0,kR.parseDocument)(i,{uniqueKeys:!0});if(s.errors.length)throw new Error(`Invalid Classic state document: ${s.errors[0].message}`);let o=s.get("change_id");if(o!==void 0&&(typeof o!="string"||!Om.test(o)))throw new Error("Invalid Classic change_id: expected an immutable UUID");return{source:i,document:s,id:o}}async function ej(e,t){let r=await fe(t),n=xe.relative(e,r).replaceAll("\\","/"),i=()=>bR(e,t),s=await i();if(s.id)return s.id;let{source:o,document:c}=s,l=c.get("run_id"),f=typeof l=="string"&&l?lu(`classic-run:${l}`):Z$();return c.get("archived")===!0||xe.basename(xe.dirname(t))==="archive"?typeof l=="string"&&l?f:lu(`classic-archive:${n}`):(c.set("change_id",f),await Te(r,c.toString(),{containedRoot:e,exclusive:o===null,beforeCommit:async()=>{if((await i()).source!==o)throw new Error("Classic state changed while assigning its instance identity")}}),f)}async function $m(e,t,r={}){let n=t??await ut(e),i;try{i=await bR(n,e)}catch(m){if(m.code==="ENOENT")return null;throw m}let{document:s,id:o}=i,c=xe.relative(n,e).replaceAll("\\","/"),l=s.get("run_id"),f=s.get("archived")===!0||xe.basename(xe.dirname(e))==="archive",a=o??(typeof l=="string"&&l?lu(`classic-run:${l}`):f?lu(`classic-archive:${c}`):null);if(!a)return e;let d=pt(n),p=xe.parse(d).root;if(!(await U(p,xe.relative(p,d).replaceAll("\\","/"),{label:"Classic read-only Runtime root",expected:"directory"})).exists)return r.includeMissing?xe.join(d,"classic-changes",a):e;let u=await U(d,`classic-changes/${a}`,{label:"Classic read-only Run directory",expected:"directory"});return u.exists||r.includeMissing?u.target:e}async function Ee(e,t){return tj(e,t)}async function tj(e,t){let r=t??await ut(e),n=xe.relative(r,e).replaceAll("\\","/");if(n&&!(await U(r,n,{label:"Classic change directory",expected:"directory"})).exists)throw Object.assign(new Error("Classic change directory does not exist"),{code:"ENOENT"});await fe(e);let i=await Ur(r),s=await ej(r,e),o=xe.join(i,"classic-changes",s);return await gt(i,xe.relative(i,o),{label:"Classic local Run directory"}),o}async function Ra(e,t,r={}){let n=pt(e),i=xe.relative(n,t);if(i===""||!i.startsWith(`..${xe.sep}`)&&i!==".."&&!xe.isAbsolute(i))return r.readOnly?{root:xe.dirname(n),target:t}:(await Ur(e),{root:n,target:t});let s=xe.relative(xe.resolve(e),t).replaceAll("\\","/");if(s.startsWith(".comet/runtime/"))return{root:n,target:xe.join(n,s.slice(15))};let o=/^(?:(.*)\/)?\.comet\/([^/]+)(\/.*)?$/u.exec(s);if(!o||!Nm.has(o[2]))return null;if(r.readOnly){let p=xe.parse(n).root;if(!(await U(p,xe.relative(p,xe.join(n,"classic-changes")),{label:"Classic local records",expected:"directory"})).exists)return null}let c=o[1]??"";if(!(await U(e,xe.relative(e,await fe(xe.join(e,c))),{label:"Classic local change identity",expected:"file"})).exists)return null;let f=xe.join(e,c),a=r.readOnly?await $m(f,e,{includeMissing:!0}):await Ee(f,e);if(!a||r.readOnly&&a===f)return null;let d=xe.relative(n,a);if(xe.isAbsolute(d)||d===".."||d.startsWith(`..${xe.sep}`))throw new Error("Classic Runtime workspace changed while resolving a change-local target");return{root:r.readOnly?xe.dirname(n):n,target:xe.join(a,".comet",o[2],o[3]??"")}}ye();var Ea=bt(Dt(),1);jt();ye();import Yr from"path";import{AsyncLocalStorage as nj}from"node:async_hooks";ou();var RR=new nj,Sa=".comet-state-transaction.json";async function Nr(e,t){let r=await Ee(e);return RR.getStore()===r?t():RR.run(r,async()=>(await CR(e),t()))}async function Ca(e,t){let r=t===Sa?await Ee(e):e;try{return(await ae(r,t,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}}function ij(e){if(e===null)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic transaction Run");let t=e,r=Di({run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:t.retries});if(!r)throw new Error("Invalid Classic transaction Run identity");return r}async function CR(e){let t=await Ca(e,Sa);if(t===null)return;let r=JSON.parse(t);if(!r||r.schema!=="comet.classic.state-transaction.v1"||r.beforeYaml!==null&&typeof r.beforeYaml!="string"||typeof r.afterYaml!="string")throw new Error("Invalid Classic state transaction");let n=await fe(e),i=r.stateFile??Xl;if(typeof i!="string"||!ma(i)||Yr.basename(n)!==i)throw new Error("Classic state transaction belongs to a different state filename; preserve files for recovery");let s=await Ca(e,i);if(s!==r.beforeYaml&&s!==r.afterYaml)throw new Error("Classic state transaction conflicts with current YAML; preserve files for recovery");let o=ij(s===r.afterYaml?r.afterRun:r.beforeRun);if(await fe(e)!==n)throw new Error("Classic state filename changed during transaction recovery");o?await qi(await Ee(e),o):await ka(await Ee(e));let c=await Ee(e);await zr(Yr.join(c,Sa),{containedRoot:c})}function ER(e,t){if(t&&e.run_id!==t.runId)throw new Error("Classic local Run identity differs from .comet.yaml; preserve both records and restore the matching Runtime history");if(!t&&e.run_id&&!e.skill&&e.run_checkpoint===void 0)throw new Error("Classic local Run history is missing; restore the matching workspace Runtime backup before continuing")}function Jn(e){let t=e.toJS();if(t===null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic state document: root must be a mapping");return t}function SR(e,t,r){e.get(t)!==r&&e.set(t,r)}function AR(e,t){if(t.classic)for(let[r,n]of Object.entries(cu(t.classic)))r==="auto_transition"&&n===null&&!e.has(r)||SR(e,r,n);else for(let r of Gn)e.delete(r);xm(e.toJS(),t.run),t.run?SR(e,"run_id",t.run.runId):e.delete("run_id")}function sj(e){let t=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let r of t)e.delete(r)}function xR(e){let t=!1;for(let r of["build_command","verify_command"])e.has(r)&&(e.delete(r),t=!0);return t}async function uu(e){let t;try{t=(await ae(Yr.dirname(e),Yr.basename(e),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(n){if(n.code!=="ENOENT")throw n;return new Ea.Document({})}let r=(0,Ea.parseDocument)(t);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return Jn(r),r}var oj=je("classicStateProjection",e=>aj(e));async function dr(e,t={}){return t.migrate===!1?oj(e):Nr(e,()=>cj(e,t))}async function aj(e){let t=await $m(e);if(t===null)return ur({});if((await U(t,Sa,{label:"Classic state transaction",expected:"file"})).exists)throw new Error("Classic state transaction is incomplete; use an explicit state operation to recover it");let r=await uu(await fe(e));xR(r);let n=Jn(r),i=await va(t);return!i&&n.run_id&&n.skill&&(i=Di(n)),ER(n,i),ur(n,i)}async function cj(e,t){let r=t.migrate!==!1,n=await fe(e),i=await uu(n),s=Jn(i),o=xR(i);o&&(s=Jn(i));let c=await va(await Ee(e));if(ER(s,c),!c&&s.run_id&&s.skill){let{runStateFromDocument:l}=await Promise.resolve().then(()=>(ou(),hR));c=l(s),c&&r&&(await qi(await Ee(e),c),sj(i),o=!0)}return o&&r&&await Te(n,i.toString(),{containedRoot:e}),ur(Jn(i),c)}async function _R(e){let t=await uu(await fe(e));return vR(Jn(t))}async function qs(e,t,r={}){let n=await fe(e,{defaultFileName:Xl});if(await Ca(e,Yr.basename(n))===null){let i=new Ea.Document({change_id:rj()});AR(i,{...t,unknownKeys:t.unknownKeys??[]}),ur(Jn(i),t.run??null);let s=await ut(e),o=await Ur(s),c=await gt(o,`classic-changes/${i.get("change_id")}`,{label:"Classic initial Run"});t.run&&await qi(c,t.run),await Te(n,i.toString(),{containedRoot:e,exclusive:!0,beforeCommit:r.beforeCommit});return}return Nr(e,()=>lj(e,t,r))}async function lj(e,t,r){let n=await fe(e),i=await Ca(e,Yr.basename(n));if(i!==null&&ir(i))throw new Error("Classic managed Run state is owned by the SDK; compat writes are not allowed");let s=await uu(n);s.has("change_id")||s.set("change_id",Yr.basename(await Ee(e)));let o=s.get("check_epoch")??0;if(typeof o=="number"&&o>(t.classic?.checkEpoch??0))throw new Error("Classic state changed during this operation; reload before retrying");AR(s,{...t,unknownKeys:t.unknownKeys??[]}),ur(Jn(s),t.run??null);let c=await Ca(e,Yr.basename(n)),l=s.toString();if(c===l){await r.beforeCommit?.(),t.run?await qi(await Ee(e),t.run):await ka(await Ee(e));return}let f=await Ee(e),a=Yr.join(f,Sa);await Te(a,JSON.stringify({schema:"comet.classic.state-transaction.v1",stateFile:Yr.basename(n),beforeYaml:c,afterYaml:l,beforeRun:await va(await Ee(e)),afterRun:t.run}),{containedRoot:f});try{t.run?await qi(await Ee(e),t.run):await ka(await Ee(e)),await Te(n,l,{containedRoot:e,beforeCommit:r.beforeCommit})}catch(d){throw await CR(e).catch(()=>{}),d}await zr(a,{containedRoot:f}).catch(()=>{})}import Ls from"path";import{AsyncLocalStorage as uj}from"node:async_hooks";jt();qt();ye();var Aa=Number.MAX_SAFE_INTEGER,dj=new uj;async function fj(e,t){let r=dj.getStore();if(!r||r.root!==Ls.resolve(e))return null;let n=rt(t,"Classic proposal source"),i=r.files.get(n);return i||(i=r.session.read(n,Aa),r.files.set(n,i)),i}async function du(e,t,r,n=!1){let i=Ls.resolve(e),s=Ls.isAbsolute(t)?Ls.resolve(t):Ls.resolve(i,t),o=await Ra(i,s,{readOnly:!n});o&&(i=o.root,s=o.target);let c=Ls.relative(i,s).replaceAll("\\","/");return{root:i,relative:rt(c,r),target:s}}async function hn(e,t,r){let n=await du(e,t,r.label,r.migrate);return U(n.root,n.relative,r)}async function Wt(e,t,r){try{return(await hn(e,t,{label:r.label,expected:r.expected??"any"})).exists}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yn(e,t,r,n){return await Wt(e,t,{label:r,expected:"file"})?(await IR(e,t,{label:r,hooks:n})).byteLength>0:!1}async function Pe(e,t,r){return(await IR(e,t,r)).toString("utf8")}async function IR(e,t,r){let n=await du(e,t,r.label);if(!r.hooks){let i=await fj(n.root,n.relative);if(i){if(i.bytes.length>(r.maxBytes??Aa))throw new Error(`${r.label} exceeds the read limit`);return i.bytes}}return(await ae(n.root,n.relative,r.maxBytes??Aa,{label:r.label,hooks:r.hooks})).bytes}async function fu(e,t,r){let n=await du(e,t,r,!0);return gt(n.root,n.relative,{label:r})}async function Wi(e,t,r,n){let i=await du(e,t,n.label,!0);await U(i.root,i.relative,{label:n.label,expected:"file"}),await Te(i.target,r,{containedRoot:i.root,beforeTemporaryOpen:n.beforeTemporaryOpen,beforeCommit:n.beforeCommit,exclusive:n.exclusive})}jt();ye();function fr(e){let t={cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0};try{let r=Jr(()=>jm("git",["rev-parse","--abbrev-ref","HEAD"],t).trim());if(r&&r!=="HEAD")return r}catch{}try{return Jr(()=>jm("git",["symbolic-ref","--quiet","--short","HEAD"],t).trim())||null}catch{return null}}var hj=Vr("liveGitBranch",e=>fr(e));function Xn(e){try{return Jr(()=>jm("git",["rev-parse","--is-inside-work-tree"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())==="true"}catch{return!1}}var gj=Vr("isGitWorkTree",e=>Xn(e)),wj=["current","branch","worktree"];function xa(e){return wj.includes(e)}function gn(e){return xa(e.isolation)?e.boundBranch===null&&e.currentBranch===null&&e.gitWorkTree===!1?{status:"not-applicable"}:e.boundBranch===null?e.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:e.currentBranch}:e.currentBranch===e.boundBranch?{status:"ok"}:{status:"drift",boundBranch:e.boundBranch,currentBranch:e.currentBranch}:{status:"not-applicable"}}async function _a(e,t){return t.heal?Nr(e,()=>PR(e,t)):PR(e,t)}async function PR(e,t){let r=await fe(e),n=(0,Dm.parseDocument)(await pj.readFile(r,"utf8"),{uniqueKeys:!1});if(n.errors.length>0)throw new Error(`Invalid .comet.yaml: ${n.errors[0].message}`);let i=n.toJS()??{},s=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,c=xa(s),l=hj(t.cwd),f=c&&o===null&&l===null?gj(t.cwd):!0,a=gn({isolation:s,boundBranch:o,currentBranch:l,gitWorkTree:f});return a.status==="needs-heal"&&t.heal?(await yj(e,a.branch),{status:"healed",branch:a.branch,bindingRequired:c,currentBranch:l}):{...a,bindingRequired:c,currentBranch:l}}async function yj(e,t){return Nr(e,()=>vj(e,t))}async function vj(e,t){let r=await fe(e),n=(await ae(e,mj.basename(r),Aa,{label:"Classic branch binding"})).bytes.toString("utf8"),i=(0,Dm.parseDocument)(n,{uniqueKeys:!1});if(i.errors.length)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);i.set("bound_branch",t),await Te(r,i.toString(),{containedRoot:e})}function kj(e){return e??"detached HEAD"}function Ws(e,t,r){return`change '${e}' is bound to branch '${t}', but current branch is '${kj(r)}'. Next: switch to branch '${t}' and rerun, or run comet state rebind ${e} after the user explicitly confirms this branch should take over the change`}function Ms(e){return`change '${e}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}ga();nr();import{randomUUID as Tj}from"node:crypto";import{types as bj}from"node:util";import{createHash as Rj}from"node:crypto";var OR=new WeakMap,TR=new WeakMap;function NR(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=TR.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&TR.set(e,n),n}function Sj(e,t,r){let n=new WeakMap,i=w=>{let k=n.get(w);if(k)return k;let b=Array.isArray(w)?[...w]:{...w};return n.set(w,b),b},s=i(e),o=[],c=[],l=[],f=new Map,a=new Map,d=new WeakMap,p=new Map,u=new Map,m=new Map,h=w=>{let k=w&&typeof w=="object"?d.get(w):void 0;if(k!==void 0)return k;let b=NR(w,r);return k=f.get(b),k===void 0&&(k=o.length,o.push(w),f.set(b,k)),w&&typeof w=="object"&&d.set(w,k),k},g=w=>{let k=m.get(w);if(k!==void 0)return k;let b=w.base===void 0?void 0:g(w.base),R=c.length;return c.push({...b===void 0?{}:{base:b},entries:w.entries.map(([E,O])=>[E,h(O)]),removed:[...w.removed]}),m.set(w,R),R};for(let w of t){let k=s,b=e;for(let G of w.path.slice(0,-1)){b=b[G];let J=i(b);Object.defineProperty(k,G,{value:J,enumerable:!0,writable:!0,configurable:!0}),k=J}let R=w.path.at(-1),E=k[R];if(!E||typeof E!="object"||Array.isArray(E))continue;if(r?.(E)){let G=OR.get(E);if(!G){let J=E,te=u.get(w.group),Z=Object.entries(J),we=te?Z.filter(([ze,P])=>!Object.hasOwn(te.source,ze)||h(te.source[ze])!==h(P)):Z,K=te?Object.keys(te.source).filter(ze=>!Object.hasOwn(J,ze)):[],ne=te&&we.length+K.length<Z.length;G={...ne?{base:te.node}:{},entries:ne?we:Z,removed:ne?K:[]},OR.set(E,G)}u.set(w.group,{source:E,node:G}),l.push({path:w.path,map:g(G)}),Object.defineProperty(k,R,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let O=new Map;for(let[G,J]of Object.entries(E)){let te=J&&typeof J=="object"?d.get(J):void 0;if(te===void 0){let Z=NR(J,r);te=f.get(Z),te===void 0&&(te=o.length,o.push(J),f.set(Z,te)),J&&typeof J=="object"&&d.set(J,te)}O.set(G,te)}let z=JSON.stringify([...O]),D=a.get(z);if(D===void 0){let G=p.get(w.group),J=[...O].filter(([we,K])=>G?.entries.get(we)!==K),te=G?[...G.entries.keys()].filter(we=>!O.has(we)):[],Z=G&&J.length+te.length<O.size;D=c.length,c.push({...Z?{base:G.id}:{},entries:Z?J:[...O],removed:Z?te:[]}),a.set(z,D)}p.set(w.group,{id:D,entries:O}),l.push({path:w.path,map:D}),Object.defineProperty(k,R,{value:{},enumerable:!0,writable:!0,configurable:!0})}return l.length?{record:s,pool:{version:1,values:o,maps:c,bindings:l}}:{record:s}}function Cj(){let e=[],t=s=>s===null?0:e[s].height,r=(s,o,c,l)=>{let f=e.length;return e.push({key:s,value:o,left:c,right:l,height:1+Math.max(t(c),t(l))}),f},n=(s,o,c,l)=>{if(t(c)>t(l)+1){let f=e[c];if(t(f.left)>=t(f.right))return r(f.key,f.value,f.left,r(s,o,f.right,l));let a=e[f.right];return r(a.key,a.value,r(f.key,f.value,f.left,a.left),r(s,o,a.right,l))}if(t(l)>t(c)+1){let f=e[l];if(t(f.right)>=t(f.left))return r(f.key,f.value,r(s,o,c,f.left),f.right);let a=e[f.left];return r(a.key,a.value,r(s,o,c,a.left),r(f.key,f.value,a.right,f.right))}return r(s,o,c,l)},i=(s,o,c)=>{if(s===null)return c===void 0?null:r(o,c,null,null);let l=e[s];if(o<l.key){let a=i(l.left,o,c);return a===l.left?s:n(l.key,l.value,a,l.right)}if(o>l.key){let a=i(l.right,o,c);return a===l.right?s:n(l.key,l.value,l.left,a)}if(c!==void 0)return c===l.value?s:r(o,c,l.left,l.right);if(l.left===null)return l.right;if(l.right===null)return l.left;let f=e[l.right];for(;f.left!==null;)f=e[f.left];return n(f.key,f.value,l.left,i(l.right,f.key,void 0))};return{nodes:e,set:i}}function jR(e){let{nodes:t,set:r}=Cj(),n=[];for(let l of e.maps){let f=l.base===void 0?null:n[l.base];for(let a of l.removed)f=r(f,a,void 0);for(let[a,d]of l.entries)f=r(f,a,d);n.push(f)}let i=[],s=new Map,o=l=>{if(l===null)return null;let f=s.get(l);if(f!==void 0)return f;let a=t[l],d=o(a.left),p=o(a.right),u=i.length;return i.push({...a,left:d,right:p}),s.set(l,u),u},c=n.map(o);return{version:3,values:e.values,nodes:i,maps:c,bindings:e.bindings}}function DR(e,t,r){let n=Sj(e,t,r);return{record:n.record,...n.pool?{pool:jR(n.pool)}:{}}}var wn=new WeakMap,Ia=new WeakMap;function*pu(e,t=e.root){if(t===null)return;let r=e.pool.nodes[t];yield*pu(e,r.left),yield[r.key,e.pool.values[r.value]],yield*pu(e,r.right)}function Ej(e){let t=n=>{let i=e.root;for(;i!==null;){let s=e.pool.nodes[i];if(n===s.key)return s.value;i=n<s.key?s.left:s.right}},r=new Proxy({},{ownKeys:()=>[...pu(e)].map(([n])=>n),get:(n,i)=>typeof i=="string"?e.pool.values[t(i)??-1]:void 0,has:(n,i)=>typeof i=="string"&&t(i)!==void 0,getOwnPropertyDescriptor:(n,i)=>typeof i=="string"&&t(i)!==void 0?{value:e.pool.values[t(i)],enumerable:!0,configurable:!0,writable:!1}:void 0,set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1});return wn.set(r,e),r}var Xe=e=>{throw new Error(e)},Fs=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;function qR(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return Xe("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(s=>!["version","values","maps","bindings"].includes(s))&&Xe("JSON 引用池字段无效"),i.maps.forEach((s,o)=>{(!s||!Array.isArray(s.entries)||!Array.isArray(s.removed)||s.base!==void 0&&!Fs(s.base,o)||Object.keys(s).some(l=>!["base","entries","removed"].includes(l)))&&Xe("JSON 映射引用无效");let c=new Set;for(let l of s.removed)(typeof l!="string"||c.has(l))&&Xe("JSON 删除键无效"),c.add(l);for(let l of s.entries)(!Array.isArray(l)||l.length!==2||typeof l[0]!="string"||!Fs(l[1],i.values.length)||c.has(l[0]))&&Xe("JSON 值引用无效"),c.add(l[0])}),qR(jR(i))}let r=e;if(r.version!==3||!Array.isArray(r.nodes)||Object.keys(r).some(i=>!["version","values","maps","bindings","nodes"].includes(i)))return Xe("JSON 引用池版本或字段无效");let n=[];return r.nodes.forEach((i,s)=>{(!i||typeof i.key!="string"||!Fs(i.value,r.values.length)||![i.left,i.right].every(l=>l===null||Fs(l,s))||Object.keys(i).some(l=>!["key","value","left","right","height"].includes(l)))&&Xe("JSON 树引用无效");let o=i.left===null?void 0:r.nodes[i.left],c=i.right===null?void 0:r.nodes[i.right];(i.height!==1+Math.max(o?.height??0,c?.height??0)||Math.abs((o?.height??0)-(c?.height??0))>1||i.left!==null&&n[i.left].max>=i.key||i.right!==null&&n[i.right].min<=i.key)&&Xe("JSON 树顺序或平衡无效"),n.push({min:i.left===null?i.key:n[i.left].min,max:i.right===null?i.key:n[i.right].max})}),r.maps.some(i=>i!==null&&!Fs(i,r.nodes.length))&&Xe("JSON 映射根无效"),r}function Aj(e,t){let r=(m,h=0,g=new Set)=>{if(h>64&&Xe("JSON 数据嵌套过深"),!(m===null||typeof m=="string"||typeof m=="boolean"||typeof m=="number"&&Number.isFinite(m))){if(typeof m!="object"||m===null||bj.isProxy(m)||g.has(m))return Xe("JSON 数据无效");Object.getPrototypeOf(m)!==Object.prototype&&Object.getPrototypeOf(m)!==null&&!Array.isArray(m)&&Xe("JSON 数据必须为普通对象"),g.add(m);for(let w of Reflect.ownKeys(m)){if(Array.isArray(m)&&w==="length")continue;let k=Object.getOwnPropertyDescriptor(m,w);(typeof w!="string"||!k.enumerable||!("value"in k))&&Xe("JSON 数据不能包含访问器"),r(k.value,h+1,g)}Array.isArray(m)&&Object.keys(m).length!==m.length&&Xe("JSON 数组不能稀疏"),g.delete(m)}};r(e),r(t);let n=qR(structuredClone(t)),i=structuredClone(e),s={validatedNodes:n.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},o=new Set,c=new Set,l=new Set,f=new Map;for(let m of n.bindings){(!m||!Array.isArray(m.path)||m.path.length<1||m.path.length>16||m.path.some(k=>typeof k!="string"||["__proto__","constructor","prototype"].includes(k))||!Fs(m.map,n.maps.length)||Object.keys(m).some(k=>!["path","map"].includes(k)))&&Xe("JSON 池绑定无效");let h=JSON.stringify(m.path);(c.has(h)||m.path.some((k,b)=>o.has(JSON.stringify(m.path.slice(0,b+1)))))&&Xe("JSON 池绑定重复或重叠"),o.add(h),m.path.forEach((k,b)=>c.add(JSON.stringify(m.path.slice(0,b+1))));let g=i;for(let k of m.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,k))&&Xe("JSON 池绑定缺失"),g=g[k];let w=m.path.at(-1);(!g||!Object.hasOwn(g,w)||!g[w]||typeof g[w]!="object"||Array.isArray(g[w])||Object.keys(g[w]).length)&&Xe("JSON 池绑定必须替换空对象"),Object.defineProperty(g,w,{value:Ej({pool:n,root:n.maps[m.map],stats:s,checked:l,origins:f}),enumerable:!0,writable:!0,configurable:!0})}let a=new WeakMap,d=new Map,p=m=>{if(!m||typeof m!="object")return 0;let h=a.get(m);if(h!==void 0)return h;let g=wn.get(m),w=b=>{if(b===null)return 0;let R=d.get(b);if(R!==void 0)return R;let E=n.nodes[b],O=Math.max(1+p(n.values[E.value]),w(E.left),w(E.right));return d.set(b,O),O},k=g?w(g.root):Object.values(m).reduce((b,R)=>Math.max(b,1+p(R)),0);return a.set(m,k),k};p(i)>64&&Xe("JSON 逻辑数据嵌套超过 64 层"),Pa(n),Pa(i);let u=m=>{if(!(!m||typeof m!="object"||wn.has(m)||Ia.has(m))){Ia.set(m,s);for(let h of Object.values(m))u(h)}};return u(i),{value:i,stats:s,materialize:(m=[])=>Jt(m.reduce((h,g)=>h?.[g],i)),hash:()=>St(i)}}function Pa(e){let t=new WeakSet,r=n=>{if(!(!n||typeof n!="object"||wn.has(n)||t.has(n))){t.add(n);for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(e),e}function Jt(e){if(e===null||typeof e!="object")return e;let t=wn.get(e);if(t){t.stats.materializedMaps++;let r=[...pu(t)];return t.stats.materializedEntries+=r.length,Object.fromEntries(r.map(([n,i])=>[n,Jt(i)]))}return Array.isArray(e)?e.map(Jt):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Jt(n)]))}function mu(e,t){let r=wn.get(e);if(!r){for(let[i,s]of Object.entries(e))t(i,s);return}r.stats.validationResultMaps++;let n=i=>{if(i===null||r.checked.has(i))return;let s=r.pool.nodes[i];n(s.left),t(s.key,r.pool.values[s.value]),r.stats.validationEntries++,n(s.right),r.checked.add(i)};n(r.root)}function hu(e,t,r){let n=wn.get(e),i=(c,l)=>{let f=l.sequence;return t.get(f)!==c&&Xe("WorkflowRun 结果来源不一致"),f};if(!n){for(let[c,l]of Object.entries(e))i(c,l)>=r&&Xe("WorkflowRun 结果序号无效");return}let s=n.origins.get(t);s||(s=new Map,n.origins.set(t,s));let o=c=>{if(c===null)return 0;let l=s.get(c);if(l!==void 0)return l;let f=n.pool.nodes[c],a=Math.max(i(f.key,n.pool.values[f.value]),o(f.left),o(f.right));return s.set(c,a),a};o(n.root)>=r&&Xe("WorkflowRun 结果序号无效")}function xj(e){return Object.keys(e).sort((t,r)=>{let n=i=>String(Number(i))===i&&Number.isInteger(Number(i))&&Number(i)>=0&&Number(i)<4294967295;return n(t)||n(r)?n(t)&&n(r)?Number(t)-Number(r):n(t)?-1:1:t<r?-1:t>r?1:0})}var $R=new WeakMap;function St(e,t={}){let r=Rj("sha256"),n=e&&typeof e=="object"?Ia.get(e):void 0,i=f=>{if(!f||typeof f!="object")return;let a=wn.get(f)?.stats??Ia.get(f);if(a)return a;for(let d of Object.values(f)){let p=i(d);if(p)return p}};n??=i(e);let s=n&&t.cachePrefixes!==!1?$R.get(n):void 0;n&&!s&&t.cachePrefixes!==!1&&(s={root:{hash:r.copy(),next:new Map},size:0},$R.set(n,s));let o=s?.root,c=f=>{let a=Buffer.byteLength(f);n&&(n.logicalHashBytes+=a);let d=o?.next.get(f);if(d){r=d.hash.copy(),o=d;return}if(r.update(f),n&&(n.hashBytes+=a),o&&s&&s.size<1e5){let p={hash:r.copy(),next:new Map};o.next.set(f,p),o=p,s.size++}else o=void 0},l=f=>{if(f===null||typeof f!="object"){c(JSON.stringify(f));return}if(Array.isArray(f)){c("["),f.forEach((a,d)=>{d&&c(","),l(a)}),c("]");return}c("{"),xj(f).forEach((a,d)=>{d&&c(","),c(JSON.stringify(a)+":"),l(f[a])}),c("}")};return l(e),r.digest("hex")}function Oa(e){return Ia.get(e)??wn.get(e)?.stats}function gu(e,t,r=!0){let n=Aj(e,t);return r?n.materialize():n.value}var LR=Object.freeze({STORE_WRITER_FENCED:"inspect-run",STORE_INDEX_CORRUPT:"repair-storage",STORE_INDEX_EPOCH_CHANGED:"inspect-run",STORE_BUSY:"inspect-run",SCOPE_HELD:"inspect-run",INVALID_VALIDATION:"restore-definition",ACTION_ACTIVE:"reconcile-execution",ACTION_ALREADY_ADVANCED:"inspect-run",ACTION_ALREADY_CLAIMED:"inspect-run",ACTION_IN_FLIGHT:"reconcile-execution",ACTION_NOT_FOUND:"inspect-run",ACTION_NOT_PENDING:"inspect-run",ACTION_NOT_RUNNING:"inspect-run",ACTION_TERMINAL:"inspect-run",CAPABILITY_REQUIRED:"correct-input",CHILD_DEPTH_LIMIT:"restore-definition",CHILD_MANAGED:"inspect-run",COMMAND_CONFLICT:"correct-input",COMMAND_DISPATCH_FAILED:"manual-review",COMMAND_NOT_FOUND:"inspect-run",COMMAND_REJECTED:"correct-input",COMMAND_VALIDATION_ERROR:"manual-review",COMMAND_VALIDATOR_UNAVAILABLE:"restore-definition",DECISION_CONFLICT:"inspect-run",DUPLICATE_COMMAND_VALIDATOR:"restore-definition",DUPLICATE_EVIDENCE_VALIDATOR:"restore-definition",DUPLICATE_EXECUTOR:"restore-definition",DUPLICATE_STATE_VALIDATOR:"restore-definition",DUPLICATE_TRANSITION_HANDLER:"restore-definition",DUPLICATE_VALIDATOR:"restore-definition",DUPLICATE_WORKFLOW:"restore-definition",EVIDENCE_INVALIDATION_UNAVAILABLE:"restore-definition",EVIDENCE_KIND_MISMATCH:"correct-input",EVIDENCE_REJECTED:"correct-input",EVIDENCE_STEP_CHANGED:"restore-definition",EVIDENCE_STILL_VALID:"inspect-run",EVIDENCE_VALIDATOR_UNAVAILABLE:"restore-definition",EVIDENCE_WAIT_NOT_FOUND:"inspect-run",EVIDENCE_WAIT_RESOLVED:"inspect-run",EXECUTION_UNKNOWN:"reconcile-execution",EXECUTOR_UNAVAILABLE:"restore-definition",EXECUTOR_UNSUPPORTED:"correct-input",INITIAL_STATE_CONFLICT:"correct-input",INITIAL_STATE_INVALID:"correct-input",INITIAL_STATE_REQUIRED:"correct-input",INVALID_ACTION:"correct-input",INVALID_COMMAND:"correct-input",INVALID_DECISION:"correct-input",INVALID_EVIDENCE:"correct-input",INVALID_JOIN:"correct-input",INVALID_JSON:"correct-input",INVALID_OUTCOME:"correct-input",INVALID_REQUEST:"correct-input",INVALID_RUN:"correct-input",INVALID_WORKFLOW:"correct-input",OUTCOME_ALREADY_RECORDED:"inspect-run",OUTCOME_CONFLICT:"inspect-outcome",OUTCOME_PROCESSING_ERROR:"inspect-outcome",OUTCOME_REJECTED:"inspect-outcome",OUTPUT_INVALID:"inspect-outcome",PROPOSAL_INPUT_MISSING:"correct-input",RECONCILIATION_REQUIRED:"reconcile-execution",REQUEST_ABORTED:"inspect-run",REVISION_CONFLICT:"inspect-run",RUN_CANCELLED:"inspect-run",RUN_CONFLICT:"correct-input",RUN_FAILED:"inspect-run",RUN_NOT_FOUND:"inspect-run",RUN_STATE_INVALID:"restore-definition",RUN_TERMINAL:"inspect-run",STALE_ACTION:"inspect-run",STALE_PROPOSAL:"review-proposal",STATE_VALIDATOR_UNAVAILABLE:"restore-definition",STORE_ATOMIC_PUBLICATION_UNSUPPORTED:"repair-storage",STORE_CHANGED_DIRECTORY:"repair-storage",STORE_CORRUPT_RECORD:"repair-storage",STORE_INVALID_ENTRY:"repair-storage",STORE_INVALID_REVISION:"repair-storage",STORE_INVALID_ROOT:"repair-storage",STORE_INVALID_RUN_ID:"repair-storage",STORE_MISSING_REVISION:"repair-storage",TRANSITION_HANDLER_UNAVAILABLE:"restore-definition",TRANSITION_STATE_INVALID:"restore-definition",TRANSITION_TARGET_INVALID:"restore-definition",TRANSITION_UNAVAILABLE:"restore-definition",UNSUPPORTED_PROTOCOL:"restore-definition",VALIDATOR_UNAVAILABLE:"restore-definition",WAIT_NOT_FOUND:"inspect-run",WORKFLOW_CHANGED:"restore-definition",WORKFLOW_UNAVAILABLE:"restore-definition"}),v=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.name="RuntimeProtocolError",this.recovery=Object.hasOwn(LR,r)?LR[r]:"manual-review"}code;recovery};import{createHash as _j}from"node:crypto";import{types as Ij}from"node:util";var qm=new WeakMap,WR=new WeakMap;function pr(e){return qm.has(e)}function wu(e,t=!0,r=!1,n=!1){let i=new Set,s=new WeakMap;function o(c,l){if(l>64)throw new v("INVALID_JSON","数据嵌套超过 64 层");if(c===null||typeof c=="string"||typeof c=="boolean")return r?JSON.stringify(c):c;if(typeof c=="number"&&Number.isFinite(c))return r?JSON.stringify(c):c===0?0:c;if(typeof c!="object"||c===null)throw new v("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(c))throw new v("INVALID_JSON","数据包含循环引用");if(Ij.isProxy(c))throw new v("INVALID_JSON","仅接受无执行行为的 JSON 数据");let f=qm.get(c);if(!t&&!r&&f!==void 0){if(l+f>64)throw new v("INVALID_JSON","数据嵌套超过 64 层");return s.set(c,{value:c,height:f}),c}let a=s.get(c);if(a){if(l+a.height>64)throw new v("INVALID_JSON","数据嵌套超过 64 层");return t?Oe(a.value):r?a.value:c}i.add(c);let d=0,p=m=>m&&typeof m=="object"?s.get(m)?.height??0:0,u=m=>(s.set(c,{value:m,height:d}),n&&(Object.freeze(c),qm.set(c,d)),m);try{if(Array.isArray(c)){if(Reflect.ownKeys(c).length!==c.length+1)throw new v("INVALID_JSON","数组不能包含空洞或额外属性");let w=[];for(let k=0;k<c.length;k+=1){let b=Object.getOwnPropertyDescriptor(c,String(k));if(!b||!("value"in b))throw new v("INVALID_JSON","数组元素必须是普通数据");let R=o(b.value,l+1);d=Math.max(d,1+p(b.value)),(t||r)&&w.push(R)}return u(r?`[${w.join(",")}]`:t?w:c)}let m=Object.getPrototypeOf(c);if(m!==Object.prototype&&m!==null)throw new v("INVALID_JSON","仅接受普通 JSON 对象");let h=[],g=Reflect.ownKeys(c);(t||r)&&g.sort((w,k)=>{let b=String(w),R=String(k),E=String(Number(b))===b&&Number.isInteger(Number(b))&&Number(b)>=0&&Number(b)<4294967295,O=String(Number(R))===R&&Number.isInteger(Number(R))&&Number(R)>=0&&Number(R)<4294967295;return E||O?E&&O?Number(b)-Number(R):E?-1:1:b<R?-1:b>R?1:0});for(let w of g){let k=Object.getOwnPropertyDescriptor(c,w);if(typeof w!="string"||!k.enumerable||!("value"in k))throw new v("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let b=o(k.value,l+1);d=Math.max(d,1+p(k.value)),(t||r)&&h.push([w,b])}return u(r?`{${h.map(([w,k])=>`${JSON.stringify(w)}:${k}`).join(",")}}`:t?Object.fromEntries(h):c)}finally{i.delete(c)}}return o(e,0)}function yn(e){return wu(e,!1,!0)}function Je(e){return wu(e)}function Oe(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(Oe(e[n]));return r}let t={};for(let r of Object.keys(e)){let n=Oe(e[r]);r==="__proto__"?Object.defineProperty(t,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):t[r]=n}return t}function mr(e){wu(e,!1)}function j(e){let t=e!==null&&typeof e=="object"&&pr(e),r=t?WR.get(e):void 0;if(r!==void 0)return r;let n=_j("sha256").update(yn(e)).digest("hex");return t&&WR.set(e,n),n}function Mi(e){return wu(e,!1,!1,!0),e}function dt(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new v("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function Xr(e){return pr(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Lm(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new v("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Wm(e){return["succeeded","failed","cancelled"].includes(e.status)}function MR(e){return FR(e,e.input)}function FR(e,t,r){for(let o of["id","runId","stepId","type"])dt(e[o],o);e.ref!==void 0&&dt(e.ref,"ref");let n=e.attempt??1;if(!Number.isSafeInteger(n)||n<1)throw new v("INVALID_ACTION","attempt 必须是正安全整数");let i=e.retry??"manual";if(!["idempotent","reconcile","manual"].includes(i))throw new v("INVALID_ACTION","retry 策略无效");let s=e.requiredCapabilities??[];for(let o of s)dt(o,"requiredCapabilities");return{protocolVersion:1,id:e.id,runId:e.runId,stepId:e.stepId,type:e.type,...e.ref===void 0?{}:{ref:e.ref},attempt:n,input:t,inputHash:r??j(t),status:"pending",retry:i,requiredCapabilities:[...new Set(s)],receipts:[],reconciliations:[]}}function HR(e,t){Lm(e,t.attempt,t.inputHash),dt(t.executorId,"executorId"),dt(t.token,"token"),t.sessionId!==void 0&&dt(t.sessionId,"sessionId");let r={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if(j(e.claim)===j(r)&&e.status==="running")return Xr(e);throw new v("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new v("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...Xr(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Mm(e,t){if(t=yu(t),dt(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new v("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&dt(t.event,"event");let r=j(t),n=e.rejectedOutcomes?.find(s=>s.outcome.outcomeId===t.outcomeId);if(n)throw j(n.outcome)!==r?new v("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new v(n.code,n.reason);let i=e.receipts.find(s=>s.outcomeId===t.outcomeId);if(i){if(i.hash!==r)throw new v("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:Xr(e),duplicate:!0}}if(Lm(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new v("STALE_ACTION","结果不属于当前 Action");if(Wm(e))throw new v("ACTION_TERMINAL","Action 已终止,不能接受新结果");if(!e.claim||!["running","unknown"].includes(e.status))throw new v("ACTION_NOT_RUNNING","Action 尚未交给执行者");if(t.claimToken!==e.claim.token)throw new v("STALE_ACTION","结果不属于当前执行者的领取记录");for(let s of t.artifacts??[])if(dt(s.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(s.sha256))throw new v("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...Xr(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function BR(e,t){if(dt(t,"reason"),!["running","unknown"].includes(e.status))throw new v("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...Xr(e),status:"unknown",reason:t}}function VR(e,t){if(e.rejectedOutcomes?.some(n=>n.outcome.attempt===e.attempt))throw new v("OUTCOME_ALREADY_RECORDED","当前执行尝试已记录结果,不能声明未执行并重试;请核对并修正同一次结果");if(!["failed","unknown"].includes(e.status))throw new v("ACTION_ACTIVE","仅失败或待核对的 Action 可以重试");if((e.retry!=="idempotent"||e.status==="unknown")&&!t)throw new v("RECONCILIATION_REQUIRED","先核对外部执行结果;不能把断连当作未执行");let r=Xr(e);if(t){if(t.resolution!=="not-executed"||t.evidence===null)throw new v("RECONCILIATION_REQUIRED","需要明确的未执行结论与核对证据");r.reconciliations.push({attempt:e.attempt,resolution:"not-executed",evidence:Je(t.evidence)})}if(!Number.isSafeInteger(e.attempt+1))throw new v("INVALID_ACTION","执行尝试次数溢出");return r.attempt+=1,r.status="pending",delete r.claim,delete r.executionOrigin,delete r.executionStop,delete r.cancellation,delete r.outcome,delete r.reason,r}function Fm(e,t){return dt(t,"reason"),Wm(e)?Xr(e):{...Xr(e),status:"cancelled",reason:t}}function UR(e,t){$r(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])dt(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new v("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Lm(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new v("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function Hm(e,t){if(UR(e,t),e.status!=="cancelled")throw new v("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&j(e.cancellation)!==j(t))throw new v("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Xr(e),cancellation:structuredClone(t)}}function Bm(e,t){if(UR(e,t),!Wm(e))throw new v("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&j(e.executionStop)!==j(t))throw new v("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Xr(e),executionStop:structuredClone(t)}}function $r(e,t,r="INVALID_ACTION"){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!t.includes(n)))throw new v(r,"执行记录包含无效结构或未知字段")}function yu(e){let t=Je(e),r=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if($r(t,[...r,"artifacts","summary","event"],"INVALID_OUTCOME"),r.some(n=>!Object.hasOwn(t,n)))throw new v("INVALID_OUTCOME","执行结果缺少身份、绑定或 output 字段");for(let n of["actionId","inputHash","claimToken","outcomeId"])if(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096)throw new v("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(typeof t.attempt!="number"||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new v("INVALID_OUTCOME","attempt 必须是正安全整数");if(t.status!=="succeeded"&&t.status!=="failed")throw new v("INVALID_OUTCOME","status 必须是 succeeded 或 failed");for(let n of["summary","event"])if(t[n]!==void 0&&(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096))throw new v("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(t.artifacts!==void 0){if(!Array.isArray(t.artifacts))throw new v("INVALID_OUTCOME","产物引用必须是数组");for(let n of t.artifacts)if($r(n,["uri","sha256"],"INVALID_OUTCOME"),typeof n.uri!="string"||!n.uri.trim()||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/.test(n.sha256))throw new v("INVALID_OUTCOME","产物引用必须包含 URI 与 SHA-256")}return t}function vu(e,t){if($r(e,["protocolVersion","id","runId","stepId","type","ref","attempt","input","inputHash","status","retry","requiredCapabilities","claim","outcome","receipts","rejectedOutcomes","reconciliations","reason","cancellation","executionOrigin","executionStop"]),e.protocolVersion!==1)throw new v("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Action 协议版本");if(!Array.isArray(e.requiredCapabilities)||!Array.isArray(e.receipts)||!Array.isArray(e.reconciliations))throw new v("INVALID_ACTION","Action 缺少能力、结果或核对记录");let r=e,n=FR(r,r.input,t);if(r.inputHash!==n.inputHash||r.retry!==n.retry||r.attempt!==n.attempt)throw new v("INVALID_ACTION","Action 输入绑定或执行参数不完整");if(!["pending","running","unknown","succeeded","failed","cancelled"].includes(r.status))throw new v("INVALID_ACTION","Action 状态无效");if(r.reason!==void 0&&dt(r.reason,"reason"),r.claim!==void 0&&($r(r.claim,["executorId","sessionId","token"]),dt(r.claim.executorId,"executorId"),dt(r.claim.token,"token"),r.claim.sessionId!==void 0&&dt(r.claim.sessionId,"sessionId")),r.status==="pending"&&r.claim||["running","unknown","succeeded","failed"].includes(r.status)&&!r.claim)throw new v("INVALID_ACTION","Action 状态与执行归属不一致");if(r.executionOrigin!==void 0&&($r(r.executionOrigin,["workflow"]),$r(r.executionOrigin.workflow,["id","version","hash"]),dt(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),dt(r.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!r.claim||!/^[a-f0-9]{64}$/u.test(r.executionOrigin.workflow.hash)))throw new v("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");r.cancellation!==void 0&&Hm({...r,input:null},r.cancellation),r.executionStop!==void 0&&Bm({...r,input:null},r.executionStop);let i=new Set;for(let o of r.receipts){if($r(o,["outcomeId","hash"]),dt(o.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(o.hash)||i.has(o.outcomeId))throw new v("INVALID_ACTION","结果记录的标识或摘要无效");i.add(o.outcomeId)}if(r.rejectedOutcomes!==void 0){if(!Array.isArray(r.rejectedOutcomes))throw new v("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let o=new Set;for(let c of r.rejectedOutcomes){if($r(c,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(c.code))throw new v("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof c.reason!="string"||!c.reason.trim())throw new v("INVALID_ACTION","Action 的拒绝结果缺少原因");let l=yu(c.outcome),f=r.receipts.find(a=>a.outcomeId===l.outcomeId);if(o.has(l.outcomeId)||!f||f.hash!==j(l)||l.actionId!==r.id||l.inputHash!==r.inputHash||l.attempt>r.attempt||l.attempt===r.attempt&&r.claim?.token!==l.claimToken)throw new v("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");o.add(l.outcomeId)}}let s=new Set;for(let o of r.reconciliations){if($r(o,["attempt","resolution","evidence"]),!Number.isSafeInteger(o.attempt)||o.attempt<1||o.attempt>=r.attempt||s.has(o.attempt)||o.resolution!=="not-executed"||o.evidence===null||o.evidence===void 0)throw new v("INVALID_ACTION","核对记录与执行尝试不一致");s.add(o.attempt)}if(r.status==="succeeded"||r.status==="failed"){if($r(r.outcome,["actionId","attempt","inputHash","claimToken","outcomeId","status","output","artifacts","summary","event"]),r.outcome.status!==r.status||r.outcome.output===void 0)throw new v("INVALID_ACTION","终态 Action 缺少匹配的结果");let o=r.receipts.find(c=>c.outcomeId===r.outcome.outcomeId);if(!o||o.hash!==j(r.outcome))throw new v("INVALID_ACTION","终态结果与已接受摘要不一致");Mm({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new v("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}function Vm(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}var JR=new WeakSet,YR=new WeakSet,Um=new WeakSet,zR=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"];function X(e){throw new v("INVALID_RUN",e)}function nt(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&X(`${t} 必须是 JSON 对象`),e}function hr(e,t,r){for(let n of Object.keys(e))t.includes(n)||X(`${r} 包含不支持的字段:${n}`)}function Ne(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&X(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Hs(e,t,r=0){return(!Number.isSafeInteger(e)||e<r)&&X(`${t} 必须是大于等于 ${r} 的安全整数`),e}function Qn(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&X(`${t} 必须是 SHA-256 摘要`),e}function KR(e,t,r=!1){let n=nt(e,t);hr(n,r?["id","version","hash"]:["id","version"],t);let i={id:Ne(n.id,`${t}.id`),version:Ne(n.version,`${t}.version`)};return r&&(i.hash=Qn(n.hash,`${t}.hash`)),i}function Ta(e,t,r){let n=nt(e,t);if(!r&&pr(n)&&YR.has(n))return n;let i=(s,o)=>{Ne(s,`${t} step id`);let c=nt(o,`${t}.${s}`);hr(c,["sequence","value"],`${t}.${s}`),(!Object.hasOwn(c,"sequence")||!Object.hasOwn(c,"value"))&&X(`${t}.${s} 缺少 sequence 或 value`),Hs(c.sequence,`${t}.${s}.sequence`,1)};if(r)r.visitResults(n,i);else for(let[s,o]of Object.entries(n))i(s,o);return n}function GR(e,t,r){let n=nt(e,t);return hr(n,["from","to","results","activation"],t),(!Object.hasOwn(n,"from")||!Object.hasOwn(n,"to")||!Object.hasOwn(n,"results"))&&X(`${t} 缺少 from、to 或 results`),{from:n.from===null?null:Ne(n.from,`${t}.from`),to:Ne(n.to,`${t}.to`),results:Ta(n.results,`${t}.results`,r),...Object.hasOwn(n,"activation")?{activation:n.activation}:{}}}function ku(e,t,r,n){let i=`${t}:`;e.startsWith(i)||X(`${r} 不属于当前 Run`);let s=e.slice(i.length);/^[1-9][0-9]*$/.test(s)||X(`${r} 的步骤序号无效`);let o=Number(s);return(!Number.isSafeInteger(o)||o>n)&&X(`${r} 的步骤序号超出 Run 范围`),o}function Pj(e,t,r,n){let i=nt(e,"Wait");hr(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let d of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,d)||X(`Wait 缺少 ${d}`);let s=Ne(i.id,"Wait.id"),o=Ne(i.stepId,"Wait.stepId"),c=Hs(i.sequence,"Wait.sequence",1);(c>r||ku(s,t,"Wait.id",r)!==c)&&X("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||X("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&X("Wait.choices 必须是非空数组");let l=i.choices.map(d=>Ne(d,"Wait.choices"));new Set(l).size!==l.length&&X("Wait.choices 不能重复");let f=Qn(i.proposalHash,"Wait.proposalHash");j(i.proposal)!==f&&X("Wait.proposal 与 proposalHash 不一致");let a={id:s,stepId:o,sequence:c,status:i.status,proposal:i.proposal,proposalHash:f,choices:l,results:Ta(i.results,"Wait.results",n)};if(i.decision!==void 0){let d=nt(i.decision,"Wait.decision");hr(d,["id","choice","proposalHash","reason"],"Wait.decision"),d.reason!==void 0&&!Vm(d.reason)&&X("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let p={id:Ne(d.id,"Wait.decision.id"),choice:Ne(d.choice,"Wait.decision.choice"),proposalHash:Qn(d.proposalHash,"Wait.decision.proposalHash"),...d.reason===void 0?{}:{reason:d.reason}};(i.status!=="resolved"||!l.includes(p.choice)||p.proposalHash!==f)&&X("Wait.decision 与 Wait 状态、选择或提案不一致"),a.decision=p}else i.status==="resolved"&&X("已解决的 Wait 必须保存对应 decision");return a}function Oj(e,t,r,n){let i=nt(e,"EvidenceWait");hr(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let s=Ne(i.id,"EvidenceWait.id"),o=Hs(i.sequence,"EvidenceWait.sequence",1);(o>r||ku(s,t,"EvidenceWait.id",r)!==o)&&X("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||X("EvidenceWait.status 无效");let c={id:s,stepId:Ne(i.stepId,"EvidenceWait.stepId"),sequence:o,kind:Ne(i.kind,"EvidenceWait.kind"),status:i.status,results:Ta(i.results,"EvidenceWait.results",n)};if(i.receipt!==void 0){let l=nt(i.receipt,"EvidenceWait.receipt");hr(l,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),c.receipt={ref:Ne(l.ref,"EvidenceWait.receipt.ref"),contentHash:Qn(l.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Ne(l.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let l=nt(i.invalidation,"EvidenceWait.invalidation");hr(l,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),c.invalidation={ref:Ne(l.ref,"EvidenceWait.invalidation.ref"),contentHash:Qn(l.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Ne(l.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Ne(l.reason,"EvidenceWait.invalidation.reason")}}return(c.status==="resolved"!=!!c.receipt||c.status==="invalidated"!=!!c.invalidation)&&X("EvidenceWait.receipt 与状态不一致"),c}function Bs(e,t){let r=nt(Je(e),"WorkflowRun");return Ru(r,t)}function XR(e,t){if(e&&typeof e=="object"&&Um.has(e)&&pr(e)){let r=e;return t!==void 0&&r.runId!==t&&X("WorkflowRun.runId 与存储键不一致"),r}return mr(e),QR(Ru(nt(structuredClone(e),"WorkflowRun"),t))}function Na(e,t,r){return Ru(nt(e,"WorkflowRun"),t,void 0,r)}function bu(e,t){return mr(e),Ru(nt(e,"WorkflowRun"),e.runId,t&&Um.has(t)&&pr(t)?t:void 0),QR(e)}function QR(e){Mi(e),Um.add(e);for(let r of e.actions)JR.add(r);let t=r=>YR.add(r);for(let r of Object.values(e.actionContexts))t(r.results);for(let r of e.waits)t(r.results);for(let r of e.evidenceWaits??[])t(r.results);for(let r of e.ready)t(r.results);for(let r of Object.values(e.joins))for(let n of Object.values(r))for(let i of n)t(i.results);return t(e.outputs),e}function Ru(e,t,r,n){hr(e,zR,"WorkflowRun");for(let P of zR.filter(F=>F!=="reason"&&F!=="state"&&F!=="evidenceWaits"&&F!=="initialStateHash"&&F!=="commands"))Object.hasOwn(e,P)||X(`WorkflowRun 缺少 ${P}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new v("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Ne(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&X("WorkflowRun.runId 与存储键不一致");let s=Hs(e.revision,"WorkflowRun.revision",1),o=Hs(e.sequence,"WorkflowRun.sequence"),c=KR(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||X("WorkflowRun.status 无效"),e.reason!==void 0&&Ne(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||X("WorkflowRun 缺少 input");let l=nt(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(l).length===0&&X("WorkflowRun.definitionHashes 不能为空");for(let[P,F]of Object.entries(l)){let re;try{re=JSON.parse(P)}catch{X("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(re)||re.length!==2||typeof re[0]!="string"||typeof re[1]!="string"||JSON.stringify(re)!==P)&&X("WorkflowRun.definitionHashes 包含非规范的工作流引用"),Qn(F,`WorkflowRun.definitionHashes.${P}`)}let f=JSON.stringify([c.id,c.version]);l[f]!==c.hash&&X("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&X("WorkflowRun.lineage 必须是最多 32 层的数组");let a=e.lineage.map(P=>Ne(P,"WorkflowRun.lineage"));(new Set(a).size!==a.length||a.includes(i))&&X("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&X("WorkflowRun.actions 和 waits 必须是数组");let d=e.actions.map(P=>{let F;try{F=P&&typeof P=="object"&&JR.has(P)&&pr(P)?P:vu(P,n?.hash(P.input))}catch(re){if(re instanceof v&&re.code==="UNSUPPORTED_PROTOCOL")throw re;X(`WorkflowRun.actions 包含无效 Action:${re.message}`)}return F.executionOrigin&&F.executionOrigin.workflow.id!==c.id&&X("Action 执行来源不属于当前工作流"),F.runId!==i&&X(`Action ${F.id} 不属于当前 Run`),new Set(F.requiredCapabilities).size!==F.requiredCapabilities.length&&X(`Action ${F.id} 的 requiredCapabilities 不能重复`),F}),p=new Map(d.map(P=>[P.id,P]));e.commands!==void 0&&!Array.isArray(e.commands)&&X("WorkflowRun.commands 必须是数组");let u=e.commands?.map(P=>{let F=nt(P,"WorkflowRun.commands item");hr(F,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let re={id:Ne(F.id,"WorkflowRun.commands.id"),name:Ne(F.name,"WorkflowRun.commands.name"),inputHash:Qn(F.inputHash,"WorkflowRun.commands.inputHash"),actionId:Ne(F.actionId,"WorkflowRun.commands.actionId")};return p.has(re.actionId)||X("WorkflowRun.commands 指向不存在的 Action"),re});u&&new Set(u.map(P=>P.id)).size!==u.length&&X("WorkflowRun.commands 标识不能重复");let m=e.waits.map(P=>Pj(P,i,o,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&X("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(P=>Oj(P,i,o,n))??[],g=new Map;for(let P of d){let F=ku(P.id,i,"Action.id",o);g.has(F)&&X("WorkflowRun 的步骤序号不能重复"),g.set(F,P.stepId)}for(let P of m)g.has(P.sequence)&&X("WorkflowRun 的步骤序号不能重复"),g.set(P.sequence,P.stepId);for(let P of h)g.has(P.sequence)&&X("WorkflowRun 的步骤序号不能重复"),g.set(P.sequence,P.stepId);g.size!==o&&X("WorkflowRun.sequence 与已激活步骤数量不一致");let w=nt(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(w).length!==d.length&&X("WorkflowRun.actionContexts 必须与 actions 一一对应");let k=new Map,b=r?new Map([...r.actions.map(P=>[r.actionContexts[P.id].sequence,P.stepId]),...r.waits.map(P=>[P.sequence,P.stepId]),...(r.evidenceWaits??[]).map(P=>[P.sequence,P.stepId])]):void 0;if(r&&b&&r.runId===i&&[...b].every(([P,F])=>g.get(P)===F)){let P=(F,re)=>k.set(F,Math.min(k.get(F)??1/0,re));for(let F of Object.values(r.actionContexts))P(F.results,F.sequence);for(let F of r.waits)P(F.results,F.sequence);for(let F of r.evidenceWaits??[])P(F.results,F.sequence);for(let F of r.ready)P(F.results,r.sequence+1);for(let F of Object.values(r.joins))for(let re of Object.values(F))for(let He of re)P(He.results,r.sequence+1);P(r.outputs,r.sequence+1)}let R=new Map;function E(P,F){let re=F??o+1;if(n){n.validateOrigins(P,g,re);return}let He=k.get(P);if(!(He!==void 0&&re>=He&&pr(P))&&!((R.get(P)??1/0)<=re)){R.set(P,re);for(let[C,$]of Object.entries(P))($.sequence>=(F??o+1)||g.get($.sequence)!==C)&&X(`WorkflowRun 结果 ${C} 的序号或来源不一致`)}}for(let P of d){Object.hasOwn(w,P.id)||X(`Action ${P.id} 缺少上下文`);let F=nt(w[P.id],`actionContexts.${P.id}`);hr(F,["sequence","results"],`actionContexts.${P.id}`);let re=Hs(F.sequence,`actionContexts.${P.id}.sequence`,1);re!==ku(P.id,i,"Action.id",o)&&X(`Action ${P.id} 的上下文序号不一致`);let He=Ta(F.results,`actionContexts.${P.id}.results`,n);E(He,re)}for(let P of m)E(P.results,P.sequence);for(let P of h)E(P.results,P.sequence);Array.isArray(e.ready)||X("WorkflowRun.ready 必须是数组");let O=e.ready.map(P=>GR(P,"WorkflowRun.ready token",n));for(let P of O)E(P.results);let z=nt(e.joins,"WorkflowRun.joins"),D=Object.fromEntries(Object.entries(z).map(([P,F])=>{Ne(P,"WorkflowRun.joins step id");let re=nt(F,`WorkflowRun.joins.${P}`),He=Object.fromEntries(Object.entries(re).map(([C,$])=>{Ne(C,"WorkflowRun.joins parent id"),Array.isArray($)||X(`WorkflowRun.joins.${P}.${C} 必须是数组`);let T=$.map(L=>{let H=GR(L,`WorkflowRun.joins.${P}.${C}`,n);return(H.to!==P||H.from!==C)&&X(`WorkflowRun.joins.${P}.${C} 包含错误来源的 token`),E(H.results),H});return[C,T]}));return[P,He]})),G=Ta(e.outputs,"WorkflowRun.outputs",n);E(G),Array.isArray(e.children)||X("WorkflowRun.children 必须是数组");let J=e.children.map(P=>{let F=nt(P,"WorkflowRun.children item");hr(F,["actionId","runId","workflow"],"WorkflowRun.children item");let re=KR(F.workflow,"WorkflowRun.children.workflow"),He=Ne(F.actionId,"WorkflowRun.children.actionId"),C=Ne(F.runId,"WorkflowRun.children.runId"),$=p.get(He);return(!$||$.type!=="child_workflow"||$.ref!==`${re.id}@${re.version}`||C!==`child-${j(He)}`||!Object.hasOwn(l,JSON.stringify([re.id,re.version])))&&X("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:He,runId:C,workflow:re}});(new Set(J.map(P=>P.actionId)).size!==J.length||d.filter(P=>P.type==="child_workflow").length!==J.length)&&X("每个子工作流 Action 必须恰好对应一个 Child Run");let Z=d.some(P=>["pending","running","unknown"].includes(P.status)),we=m.some(P=>P.status==="pending"),K=h.some(P=>P.status==="pending"),ne=Object.values(D).some(P=>Object.values(P).some(F=>F.length>0));return e.status==="running"&&!Z&&O.length===0&&X("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(Z||!we&&!K&&!ne||O.length>0)&&X("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(Z||we||K||ne||O.length>0)&&X("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&X(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:s,workflow:c,definitionHashes:l,...e.initialStateHash===void 0?{}:{initialStateHash:Qn(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:o,actions:d,...u===void 0?{}:{commands:u},actionContexts:w,waits:m,...e.evidenceWaits===void 0?{}:{evidenceWaits:h},ready:O,joins:D,outputs:G,children:J,lineage:a,...e.reason===void 0?{}:{reason:e.reason}}}var ZR=new WeakMap;async function Vs(e,t){let r=await(e.readProjection?e.readProjection(t):e.read(t));if(!r)throw new v("RUN_NOT_FOUND",`找不到工作流实例:${t}`);Oa(r)||(mr(r),r=structuredClone(r),Pa(r));let n="run"in r?r.run:r;if(!n||n.runId!==r.runId||n.revision!==r.revision)throw new v("INVALID_RUN","Run 与存储 envelope 身份不一致");let i;try{i=Na(n,t,{hash:St,visitResults:mu,validateOrigins:hu})}catch(c){throw c instanceof v?c:new v("INVALID_RUN",c instanceof Error?c.message:String(c))}Pa(i);let s=Oa(r);s&&(s.validationActions=i.actions.length,s.validationMaterializedEntries=s.materializedEntries);let o=e.queryScope??ZR.get(e);return o||(o=Tj(),ZR.set(e,o)),Object.freeze({record:r,run:i,scope:o,stats:s,materialize:(c=[])=>Jt(c.reduce((l,f)=>l?.[f],i)),hash:()=>St(i)})}var Zn=e=>{throw new v("INVALID_REQUEST",e)};function zm(e,t){let{run:r,scope:n}=e;["current","summary","history","action","artifact"].includes(t.view)||Zn("query.view 无效");let i={runId:r.runId,revision:r.revision,status:r.status,workflow:r.workflow,sequence:r.sequence},s={actions:r.actions.length,waits:r.waits.length,evidenceWaits:r.evidenceWaits?.length??0},o=r.actions.filter(p=>["pending","running","unknown"].includes(p.status)||p.status==="cancelled"&&p.claim&&!p.executionStop&&!p.cancellation);if(t.view==="summary")return Jt({...i,history:s,pending:{actions:o.length,waits:r.waits.filter(p=>p.status==="pending").length,evidenceWaits:(r.evidenceWaits??[]).filter(p=>p.status==="pending").length}});if(t.view==="current")return Jt({...i,input:r.input,...r.state===void 0?{}:{state:r.state},...r.reason===void 0?{}:{reason:r.reason},actions:o,waits:r.waits.filter(p=>p.status==="pending"),evidenceWaits:(r.evidenceWaits??[]).filter(p=>p.status==="pending"),outputs:r.outputs,history:s});if(t.view==="action"||t.view==="artifact"){let p=r.actions.find(h=>h.id===t.actionId);if(p||Zn("query.actionId 不属于当前 Run"),t.view==="action")return Jt({...i,action:p,context:r.actionContexts[p.id]});let u=(p.outcome?.artifacts??[]).map(h=>({...h,artifactId:j({actionId:p.id,...h})})),m=t.artifactId===void 0?u:u.filter(h=>h.artifactId===t.artifactId);return t.artifactId!==void 0&&!m.length&&Zn("query.artifactId 不属于所选 Action"),Jt({...i,actionId:p.id,artifacts:m})}let c=t.limit??25;(!Number.isSafeInteger(c)||c<1||c>100)&&Zn("query.limit 必须在 1–100 之间");let l=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(l)||Zn("query.filter 无效");let f=j({scope:n,runId:r.runId,revision:r.revision,filter:l}),a=0;if(t.cursor)try{let p=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf8"));(p.binding!==f||!Number.isSafeInteger(p.offset)||p.offset<0||Object.keys(p).some(u=>!["binding","offset"].includes(u)))&&Zn("query.cursor 与当前存储、版本或筛选不匹配"),a=p.offset}catch{Zn("query.cursor 无效或已经过期")}let d=[...l==="all"||l==="actions"?r.actions.map((p,u)=>({kind:"action",sequence:r.actionContexts[p.id].sequence,path:["actions",String(u)]})):[],...l==="all"||l==="waits"?r.waits.map((p,u)=>({kind:"wait",sequence:p.sequence,path:["waits",String(u)]})):[],...l==="all"||l==="evidenceWaits"?(r.evidenceWaits??[]).map((p,u)=>({kind:"evidenceWait",sequence:p.sequence,path:["evidenceWaits",String(u)]})):[]].sort((p,u)=>u.sequence-p.sequence);return a>d.length&&Zn("query.cursor 超出历史范围"),{...Jt(i),records:d.slice(a,a+c).map(p=>({kind:p.kind,sequence:p.sequence,value:e.materialize(p.path)})),total:d.length,...a+c<d.length?{nextCursor:Buffer.from(JSON.stringify({binding:f,offset:a+c})).toString("base64url")}:{}}}import{randomUUID as Hg}from"node:crypto";import{types as Ug}from"node:util";var Wg=bt(FE(),1);var et=bt(Zh(),1),xM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{action:{enum:["local","push","pr"]},commit:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$",type:"string"},prUrl:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},targetBranch:{minLength:1,type:"string"}},required:["action","targetBranch","commit"],type:"object"},r=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),n=et.default.default??et.default;function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.action===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"action"},message:"must have required property 'action'"};a===null?a=[p]:a.push(p),d++}if(s.targetBranch===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};a===null?a=[p]:a.push(p),d++}if(s.commit===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"commit"},message:"must have required property 'commit'"};a===null?a=[p]:a.push(p),d++}for(let p in s)if(!(p==="action"||p==="commit"||p==="prUrl"||p==="remote"||p==="targetBranch")){let u={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[u]:a.push(u),d++}if(s.action!==void 0){let p=s.action;if(!(p==="local"||p==="push"||p==="pr")){let u={instancePath:o+"/action",schemaPath:"#/properties/action/enum",keyword:"enum",params:{allowedValues:t.properties.action.enum},message:"must be equal to one of the allowed values"};a===null?a=[u]:a.push(u),d++}}if(s.commit!==void 0){let p=s.commit;if(typeof p=="string"){if(!r.test(p)){let u={instancePath:o+"/commit",schemaPath:"#/properties/commit/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},message:'must match pattern "^[0-9a-f]{40}(?:[0-9a-f]{24})?$"'};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/commit",schemaPath:"#/properties/commit/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.prUrl!==void 0){let p=s.prUrl;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/prUrl",schemaPath:"#/properties/prUrl/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/prUrl",schemaPath:"#/properties/prUrl/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.remote!==void 0){let p=s.remote;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.targetBranch!==void 0){let p=s.targetBranch;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}}else{let p={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),d++}return i.errors=a,d===0}return e.exports})(),_M=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},autoTransition:{type:["boolean","null"]},baseRef:{type:["string","null"]},boundBranch:{type:["string","null"]},branchStatus:{enum:[null,"pending","handled"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},checkEpoch:{minimum:0,type:"integer"},classicMigration:{enum:[null,1]},classicProfile:{enum:[null,"full","hotfix","tweak"]},contextCompression:{enum:[null,"off","beta"]},createdAt:{type:["string","null"]},designDoc:{type:["string","null"]},directOverride:{type:["boolean","null"]},handoffContext:{type:["string","null"]},handoffHash:{anyOf:[{type:"null"},{pattern:"^[a-f0-9]{64}$",type:"string"}]},isolation:{enum:[null,"current","branch","worktree"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},plan:{type:["string","null"]},reviewMode:{enum:[null,"off","standard","thorough"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},verificationReport:{type:["string","null"]},verifiedAt:{type:["string","null"]},verifyFailures:{minimum:0,type:"integer"},verifyMode:{enum:[null,"light","full"]},verifyResult:{enum:["pending","pass","fail"]},workflow:{enum:["full"]}},required:["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],type:"object"},r=Object.prototype.hasOwnProperty,n=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[u]:a.push(u),d++}if(s.language===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[u]:a.push(u),d++}if(s.phase===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[u]:a.push(u),d++}if(s.contextCompression===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[u]:a.push(u),d++}if(s.buildMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[u]:a.push(u),d++}if(s.buildPause===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[u]:a.push(u),d++}if(s.subagentDispatch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[u]:a.push(u),d++}if(s.tddMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[u]:a.push(u),d++}if(s.reviewMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[u]:a.push(u),d++}if(s.isolation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[u]:a.push(u),d++}if(s.boundBranch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[u]:a.push(u),d++}if(s.verifyMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[u]:a.push(u),d++}if(s.baseRef===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[u]:a.push(u),d++}if(s.designDoc===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[u]:a.push(u),d++}if(s.plan===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[u]:a.push(u),d++}if(s.verifyResult===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[u]:a.push(u),d++}if(s.verifyFailures===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[u]:a.push(u),d++}if(s.verificationReport===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[u]:a.push(u),d++}if(s.branchStatus===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[u]:a.push(u),d++}if(s.createdAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[u]:a.push(u),d++}if(s.verifiedAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[u]:a.push(u),d++}if(s.archiveConfirmation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[u]:a.push(u),d++}if(s.archived===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[u]:a.push(u),d++}if(s.directOverride===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[u]:a.push(u),d++}if(s.handoffContext===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[u]:a.push(u),d++}if(s.handoffHash===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[u]:a.push(u),d++}if(s.classicProfile===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[u]:a.push(u),d++}if(s.classicMigration===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[u]:a.push(u),d++}for(let u in s)if(!r.call(t.properties,u)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(s.archiveConfirmation!==void 0){let u=s.archiveConfirmation;if(!(u===null||u==="pending"||u==="confirmed")){let m={instancePath:o+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.archived!==void 0&&typeof s.archived!="boolean"){let u={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition!==void 0){let u=s.autoTransition;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(s.baseRef!==void 0){let u=s.baseRef;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.boundBranch!==void 0){let u=s.boundBranch;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.branchStatus!==void 0){let u=s.branchStatus;if(!(u===null||u==="pending"||u==="handled")){let m={instancePath:o+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.buildMode!==void 0){let u=s.buildMode;if(!(u===null||u==="subagent-driven-development"||u==="executing-plans"||u==="direct"||u==="autonomous")){let m={instancePath:o+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.buildPause!==void 0){let u=s.buildPause;if(!(u===null||u==="plan-ready")){let m={instancePath:o+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.checkEpoch!==void 0){let u=s.checkEpoch;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.classicMigration!==void 0){let u=s.classicMigration;if(!(u===null||u===1)){let m={instancePath:o+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.classicProfile!==void 0){let u=s.classicProfile;if(!(u===null||u==="full"||u==="hotfix"||u==="tweak")){let m={instancePath:o+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.contextCompression!==void 0){let u=s.contextCompression;if(!(u===null||u==="off"||u==="beta")){let m={instancePath:o+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.createdAt!==void 0){let u=s.createdAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.designDoc!==void 0){let u=s.designDoc;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.directOverride!==void 0){let u=s.directOverride;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(s.handoffContext!==void 0){let u=s.handoffContext;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.handoffHash!==void 0){let u=s.handoffHash,m=d,h=!1,g=d;if(u!==null){let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};a===null?a=[w]:a.push(w),d++}var p=g===d;if(h=h||p,!h){let w=d;if(typeof u=="string"){if(!n.test(u)){let b={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[b]:a.push(b),d++}}else{let b={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[b]:a.push(b),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(s.isolation!==void 0){let u=s.isolation;if(!(u===null||u==="current"||u==="branch"||u==="worktree")){let m={instancePath:o+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.language!==void 0){let u=s.language;if(!(u===null||u==="en"||u==="zh-CN")){let m={instancePath:o+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.phase!==void 0){let u=s.phase;if(!(u==="open"||u==="design"||u==="build"||u==="verify"||u==="archive")){let m={instancePath:o+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.plan!==void 0){let u=s.plan;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.reviewMode!==void 0){let u=s.reviewMode;if(!(u===null||u==="off"||u==="standard"||u==="thorough")){let m={instancePath:o+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.subagentDispatch!==void 0){let u=s.subagentDispatch;if(!(u===null||u==="confirmed")){let m={instancePath:o+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.tddMode!==void 0){let u=s.tddMode;if(!(u===null||u==="tdd"||u==="direct")){let m={instancePath:o+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.verificationReport!==void 0){let u=s.verificationReport;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.verifiedAt!==void 0){let u=s.verifiedAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.verifyFailures!==void 0){let u=s.verifyFailures;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.verifyMode!==void 0){let u=s.verifyMode;if(!(u===null||u==="light"||u==="full")){let m={instancePath:o+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.verifyResult!==void 0){let u=s.verifyResult;if(!(u==="pending"||u==="pass"||u==="fail")){let m={instancePath:o+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.workflow!==void 0&&s.workflow!=="full"){let u={instancePath:o+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}return i.errors=a,d===0}return e.exports})(),IM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},autoTransition:{type:["boolean","null"]},baseRef:{type:["string","null"]},boundBranch:{type:["string","null"]},branchStatus:{enum:[null,"pending","handled"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},checkEpoch:{minimum:0,type:"integer"},classicMigration:{enum:[null,1]},classicProfile:{enum:[null,"full","hotfix","tweak"]},contextCompression:{enum:[null,"off","beta"]},createdAt:{type:["string","null"]},designDoc:{type:["string","null"]},directOverride:{type:["boolean","null"]},handoffContext:{type:["string","null"]},handoffHash:{anyOf:[{type:"null"},{pattern:"^[a-f0-9]{64}$",type:"string"}]},isolation:{enum:[null,"current","branch","worktree"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},plan:{type:["string","null"]},reviewMode:{enum:[null,"off","standard","thorough"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},verificationReport:{type:["string","null"]},verifiedAt:{type:["string","null"]},verifyFailures:{minimum:0,type:"integer"},verifyMode:{enum:[null,"light","full"]},verifyResult:{enum:["pending","pass","fail"]},workflow:{enum:["hotfix","full"]}},required:["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],type:"object"},r=Object.prototype.hasOwnProperty,n=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[u]:a.push(u),d++}if(s.language===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[u]:a.push(u),d++}if(s.phase===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[u]:a.push(u),d++}if(s.contextCompression===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[u]:a.push(u),d++}if(s.buildMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[u]:a.push(u),d++}if(s.buildPause===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[u]:a.push(u),d++}if(s.subagentDispatch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[u]:a.push(u),d++}if(s.tddMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[u]:a.push(u),d++}if(s.reviewMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[u]:a.push(u),d++}if(s.isolation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[u]:a.push(u),d++}if(s.boundBranch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[u]:a.push(u),d++}if(s.verifyMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[u]:a.push(u),d++}if(s.baseRef===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[u]:a.push(u),d++}if(s.designDoc===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[u]:a.push(u),d++}if(s.plan===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[u]:a.push(u),d++}if(s.verifyResult===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[u]:a.push(u),d++}if(s.verifyFailures===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[u]:a.push(u),d++}if(s.verificationReport===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[u]:a.push(u),d++}if(s.branchStatus===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[u]:a.push(u),d++}if(s.createdAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[u]:a.push(u),d++}if(s.verifiedAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[u]:a.push(u),d++}if(s.archiveConfirmation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[u]:a.push(u),d++}if(s.archived===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[u]:a.push(u),d++}if(s.directOverride===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[u]:a.push(u),d++}if(s.handoffContext===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[u]:a.push(u),d++}if(s.handoffHash===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[u]:a.push(u),d++}if(s.classicProfile===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[u]:a.push(u),d++}if(s.classicMigration===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[u]:a.push(u),d++}for(let u in s)if(!r.call(t.properties,u)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(s.archiveConfirmation!==void 0){let u=s.archiveConfirmation;if(!(u===null||u==="pending"||u==="confirmed")){let m={instancePath:o+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.archived!==void 0&&typeof s.archived!="boolean"){let u={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition!==void 0){let u=s.autoTransition;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(s.baseRef!==void 0){let u=s.baseRef;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.boundBranch!==void 0){let u=s.boundBranch;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.branchStatus!==void 0){let u=s.branchStatus;if(!(u===null||u==="pending"||u==="handled")){let m={instancePath:o+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.buildMode!==void 0){let u=s.buildMode;if(!(u===null||u==="subagent-driven-development"||u==="executing-plans"||u==="direct"||u==="autonomous")){let m={instancePath:o+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.buildPause!==void 0){let u=s.buildPause;if(!(u===null||u==="plan-ready")){let m={instancePath:o+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.checkEpoch!==void 0){let u=s.checkEpoch;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.classicMigration!==void 0){let u=s.classicMigration;if(!(u===null||u===1)){let m={instancePath:o+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.classicProfile!==void 0){let u=s.classicProfile;if(!(u===null||u==="full"||u==="hotfix"||u==="tweak")){let m={instancePath:o+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.contextCompression!==void 0){let u=s.contextCompression;if(!(u===null||u==="off"||u==="beta")){let m={instancePath:o+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.createdAt!==void 0){let u=s.createdAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.designDoc!==void 0){let u=s.designDoc;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.directOverride!==void 0){let u=s.directOverride;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(s.handoffContext!==void 0){let u=s.handoffContext;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.handoffHash!==void 0){let u=s.handoffHash,m=d,h=!1,g=d;if(u!==null){let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};a===null?a=[w]:a.push(w),d++}var p=g===d;if(h=h||p,!h){let w=d;if(typeof u=="string"){if(!n.test(u)){let b={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[b]:a.push(b),d++}}else{let b={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[b]:a.push(b),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(s.isolation!==void 0){let u=s.isolation;if(!(u===null||u==="current"||u==="branch"||u==="worktree")){let m={instancePath:o+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.language!==void 0){let u=s.language;if(!(u===null||u==="en"||u==="zh-CN")){let m={instancePath:o+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.phase!==void 0){let u=s.phase;if(!(u==="open"||u==="design"||u==="build"||u==="verify"||u==="archive")){let m={instancePath:o+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.plan!==void 0){let u=s.plan;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.reviewMode!==void 0){let u=s.reviewMode;if(!(u===null||u==="off"||u==="standard"||u==="thorough")){let m={instancePath:o+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.subagentDispatch!==void 0){let u=s.subagentDispatch;if(!(u===null||u==="confirmed")){let m={instancePath:o+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.tddMode!==void 0){let u=s.tddMode;if(!(u===null||u==="tdd"||u==="direct")){let m={instancePath:o+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.verificationReport!==void 0){let u=s.verificationReport;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.verifiedAt!==void 0){let u=s.verifiedAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.verifyFailures!==void 0){let u=s.verifyFailures;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.verifyMode!==void 0){let u=s.verifyMode;if(!(u===null||u==="light"||u==="full")){let m={instancePath:o+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.verifyResult!==void 0){let u=s.verifyResult;if(!(u==="pending"||u==="pass"||u==="fail")){let m={instancePath:o+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.workflow!==void 0){let u=s.workflow;if(!(u==="hotfix"||u==="full")){let m={instancePath:o+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}}else{let u={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}return i.errors=a,d===0}return e.exports})(),PM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},autoTransition:{type:["boolean","null"]},baseRef:{type:["string","null"]},boundBranch:{type:["string","null"]},branchStatus:{enum:[null,"pending","handled"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},checkEpoch:{minimum:0,type:"integer"},classicMigration:{enum:[null,1]},classicProfile:{enum:[null,"full","hotfix","tweak"]},contextCompression:{enum:[null,"off","beta"]},createdAt:{type:["string","null"]},designDoc:{type:["string","null"]},directOverride:{type:["boolean","null"]},handoffContext:{type:["string","null"]},handoffHash:{anyOf:[{type:"null"},{pattern:"^[a-f0-9]{64}$",type:"string"}]},isolation:{enum:[null,"current","branch","worktree"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},plan:{type:["string","null"]},reviewMode:{enum:[null,"off","standard","thorough"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},verificationReport:{type:["string","null"]},verifiedAt:{type:["string","null"]},verifyFailures:{minimum:0,type:"integer"},verifyMode:{enum:[null,"light","full"]},verifyResult:{enum:["pending","pass","fail"]},workflow:{enum:["tweak","full"]}},required:["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],type:"object"},r=Object.prototype.hasOwnProperty,n=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[u]:a.push(u),d++}if(s.language===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[u]:a.push(u),d++}if(s.phase===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[u]:a.push(u),d++}if(s.contextCompression===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[u]:a.push(u),d++}if(s.buildMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[u]:a.push(u),d++}if(s.buildPause===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[u]:a.push(u),d++}if(s.subagentDispatch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[u]:a.push(u),d++}if(s.tddMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[u]:a.push(u),d++}if(s.reviewMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[u]:a.push(u),d++}if(s.isolation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[u]:a.push(u),d++}if(s.boundBranch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[u]:a.push(u),d++}if(s.verifyMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[u]:a.push(u),d++}if(s.baseRef===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[u]:a.push(u),d++}if(s.designDoc===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[u]:a.push(u),d++}if(s.plan===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[u]:a.push(u),d++}if(s.verifyResult===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[u]:a.push(u),d++}if(s.verifyFailures===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[u]:a.push(u),d++}if(s.verificationReport===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[u]:a.push(u),d++}if(s.branchStatus===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[u]:a.push(u),d++}if(s.createdAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[u]:a.push(u),d++}if(s.verifiedAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[u]:a.push(u),d++}if(s.archiveConfirmation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[u]:a.push(u),d++}if(s.archived===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[u]:a.push(u),d++}if(s.directOverride===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[u]:a.push(u),d++}if(s.handoffContext===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[u]:a.push(u),d++}if(s.handoffHash===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[u]:a.push(u),d++}if(s.classicProfile===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[u]:a.push(u),d++}if(s.classicMigration===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[u]:a.push(u),d++}for(let u in s)if(!r.call(t.properties,u)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(s.archiveConfirmation!==void 0){let u=s.archiveConfirmation;if(!(u===null||u==="pending"||u==="confirmed")){let m={instancePath:o+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.archived!==void 0&&typeof s.archived!="boolean"){let u={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition!==void 0){let u=s.autoTransition;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(s.baseRef!==void 0){let u=s.baseRef;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.boundBranch!==void 0){let u=s.boundBranch;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.branchStatus!==void 0){let u=s.branchStatus;if(!(u===null||u==="pending"||u==="handled")){let m={instancePath:o+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.buildMode!==void 0){let u=s.buildMode;if(!(u===null||u==="subagent-driven-development"||u==="executing-plans"||u==="direct"||u==="autonomous")){let m={instancePath:o+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.buildPause!==void 0){let u=s.buildPause;if(!(u===null||u==="plan-ready")){let m={instancePath:o+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.checkEpoch!==void 0){let u=s.checkEpoch;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.classicMigration!==void 0){let u=s.classicMigration;if(!(u===null||u===1)){let m={instancePath:o+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.classicProfile!==void 0){let u=s.classicProfile;if(!(u===null||u==="full"||u==="hotfix"||u==="tweak")){let m={instancePath:o+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.contextCompression!==void 0){let u=s.contextCompression;if(!(u===null||u==="off"||u==="beta")){let m={instancePath:o+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.createdAt!==void 0){let u=s.createdAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.designDoc!==void 0){let u=s.designDoc;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.directOverride!==void 0){let u=s.directOverride;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(s.handoffContext!==void 0){let u=s.handoffContext;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.handoffHash!==void 0){let u=s.handoffHash,m=d,h=!1,g=d;if(u!==null){let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};a===null?a=[w]:a.push(w),d++}var p=g===d;if(h=h||p,!h){let w=d;if(typeof u=="string"){if(!n.test(u)){let b={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[b]:a.push(b),d++}}else{let b={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[b]:a.push(b),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(s.isolation!==void 0){let u=s.isolation;if(!(u===null||u==="current"||u==="branch"||u==="worktree")){let m={instancePath:o+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.language!==void 0){let u=s.language;if(!(u===null||u==="en"||u==="zh-CN")){let m={instancePath:o+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.phase!==void 0){let u=s.phase;if(!(u==="open"||u==="design"||u==="build"||u==="verify"||u==="archive")){let m={instancePath:o+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.plan!==void 0){let u=s.plan;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.reviewMode!==void 0){let u=s.reviewMode;if(!(u===null||u==="off"||u==="standard"||u==="thorough")){let m={instancePath:o+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.subagentDispatch!==void 0){let u=s.subagentDispatch;if(!(u===null||u==="confirmed")){let m={instancePath:o+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.tddMode!==void 0){let u=s.tddMode;if(!(u===null||u==="tdd"||u==="direct")){let m={instancePath:o+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.verificationReport!==void 0){let u=s.verificationReport;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.verifiedAt!==void 0){let u=s.verifiedAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(s.verifyFailures!==void 0){let u=s.verifyFailures;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.verifyMode!==void 0){let u=s.verifyMode;if(!(u===null||u==="light"||u==="full")){let m={instancePath:o+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.verifyResult!==void 0){let u=s.verifyResult;if(!(u==="pending"||u==="pass"||u==="fail")){let m={instancePath:o+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(s.workflow!==void 0){let u=s.workflow;if(!(u==="tweak"||u==="full")){let m={instancePath:o+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}}else{let u={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}return i.errors=a,d===0}return e.exports})(),OM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{archiveDirectory:{minLength:1,type:"string"}},required:["archiveDirectory"],type:"object"},r=et.default.default??et.default;function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.archiveDirectory===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveDirectory"},message:"must have required property 'archiveDirectory'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(d!=="archiveDirectory"){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.archiveDirectory!==void 0){let d=i.archiveDirectory;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/archiveDirectory",schemaPath:"#/properties/archiveDirectory/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/archiveDirectory",schemaPath:"#/properties/archiveDirectory/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),TM=(()=>{let e={exports:{}};e.exports=s,e.exports.default=s;let t={additionalProperties:!1,properties:{baseCommit:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$",type:"string"},deliveryAction:{enum:["local","push","pr"]},deliveryPaths:{items:{minLength:1,type:"string"},type:"array"},prBaseBranch:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},remoteIdentity:{pattern:"^[0-9a-f]{64}$",type:"string"},targetBranch:{minLength:1,type:"string"},verifiedBranch:{minLength:1,type:"string"}},required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],type:"object"},r=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),n=new RegExp("^[0-9a-f]{64}$","u"),i=et.default.default??et.default;function s(o,{instancePath:c="",parentData:l,parentDataProperty:f,rootData:a=o}={}){let d=null,p=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.deliveryAction===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"deliveryAction"},message:"must have required property 'deliveryAction'"};d===null?d=[u]:d.push(u),p++}if(o.targetBranch===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};d===null?d=[u]:d.push(u),p++}if(o.verifiedBranch===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedBranch"},message:"must have required property 'verifiedBranch'"};d===null?d=[u]:d.push(u),p++}if(o.baseCommit===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseCommit"},message:"must have required property 'baseCommit'"};d===null?d=[u]:d.push(u),p++}for(let u in o)if(!(u==="baseCommit"||u==="deliveryAction"||u==="deliveryPaths"||u==="prBaseBranch"||u==="remote"||u==="remoteIdentity"||u==="targetBranch"||u==="verifiedBranch")){let m={instancePath:c,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),p++}if(o.baseCommit!==void 0){let u=o.baseCommit;if(typeof u=="string"){if(!r.test(u)){let m={instancePath:c+"/baseCommit",schemaPath:"#/properties/baseCommit/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},message:'must match pattern "^[0-9a-f]{40}(?:[0-9a-f]{24})?$"'};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/baseCommit",schemaPath:"#/properties/baseCommit/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(o.deliveryAction!==void 0){let u=o.deliveryAction;if(!(u==="local"||u==="push"||u==="pr")){let m={instancePath:c+"/deliveryAction",schemaPath:"#/properties/deliveryAction/enum",keyword:"enum",params:{allowedValues:t.properties.deliveryAction.enum},message:"must be equal to one of the allowed values"};d===null?d=[m]:d.push(m),p++}}if(o.deliveryPaths!==void 0){let u=o.deliveryPaths;if(Array.isArray(u)){let m=u.length;for(let h=0;h<m;h++){let g=u[h];if(typeof g=="string"){if(i(g)<1){let w={instancePath:c+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[w]:d.push(w),p++}}else{let w={instancePath:c+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[w]:d.push(w),p++}}}else{let m={instancePath:c+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};d===null?d=[m]:d.push(m),p++}}if(o.prBaseBranch!==void 0){let u=o.prBaseBranch;if(typeof u=="string"){if(i(u)<1){let m={instancePath:c+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(o.remote!==void 0){let u=o.remote;if(typeof u=="string"){if(i(u)<1){let m={instancePath:c+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(o.remoteIdentity!==void 0){let u=o.remoteIdentity;if(typeof u=="string"){if(!n.test(u)){let m={instancePath:c+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{64}$"},message:'must match pattern "^[0-9a-f]{64}$"'};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(o.targetBranch!==void 0){let u=o.targetBranch;if(typeof u=="string"){if(i(u)<1){let m={instancePath:c+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(o.verifiedBranch!==void 0){let u=o.verifiedBranch;if(typeof u=="string"){if(i(u)<1){let m={instancePath:c+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}}else{let u={instancePath:c,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[u]:d.push(u),p++}return s.errors=d,p===0}return e.exports})(),NM=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={additionalProperties:!1,properties:{boundBranch:{type:["string","null"]},buildMode:{enum:["subagent-driven-development","executing-plans","direct","autonomous"]},directOverride:{type:"boolean"},isolation:{enum:["current","branch","worktree"]},reviewMode:{enum:["off","standard","thorough"]},subagentDispatch:{enum:["confirmed",null]},tddMode:{enum:["tdd","direct"]}},required:["buildMode","tddMode","reviewMode","isolation"],type:"object"};function r(n,{instancePath:i="",parentData:s,parentDataProperty:o,rootData:c=n}={}){let l=null,f=0;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.buildMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};l===null?l=[a]:l.push(a),f++}if(n.tddMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};l===null?l=[a]:l.push(a),f++}if(n.reviewMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};l===null?l=[a]:l.push(a),f++}if(n.isolation===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};l===null?l=[a]:l.push(a),f++}for(let a in n)if(!(a==="boundBranch"||a==="buildMode"||a==="directOverride"||a==="isolation"||a==="reviewMode"||a==="subagentDispatch"||a==="tddMode")){let d={instancePath:i,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:a},message:"must NOT have additional properties"};l===null?l=[d]:l.push(d),f++}if(n.boundBranch!==void 0){let a=n.boundBranch;if(typeof a!="string"&&a!==null){let d={instancePath:i+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};l===null?l=[d]:l.push(d),f++}}if(n.buildMode!==void 0){let a=n.buildMode;if(!(a==="subagent-driven-development"||a==="executing-plans"||a==="direct"||a==="autonomous")){let d={instancePath:i+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};l===null?l=[d]:l.push(d),f++}}if(n.directOverride!==void 0&&typeof n.directOverride!="boolean"){let a={instancePath:i+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};l===null?l=[a]:l.push(a),f++}if(n.isolation!==void 0){let a=n.isolation;if(!(a==="current"||a==="branch"||a==="worktree")){let d={instancePath:i+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};l===null?l=[d]:l.push(d),f++}}if(n.reviewMode!==void 0){let a=n.reviewMode;if(!(a==="off"||a==="standard"||a==="thorough")){let d={instancePath:i+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};l===null?l=[d]:l.push(d),f++}}if(n.subagentDispatch!==void 0){let a=n.subagentDispatch;if(!(a==="confirmed"||a===null)){let d={instancePath:i+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};l===null?l=[d]:l.push(d),f++}}if(n.tddMode!==void 0){let a=n.tddMode;if(!(a==="tdd"||a==="direct")){let d={instancePath:i+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};l===null?l=[d]:l.push(d),f++}}}else{let a={instancePath:i,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};l===null?l=[a]:l.push(a),f++}return r.errors=l,f===0}return e.exports})(),$M=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{checks:{items:{additionalProperties:!1,properties:{name:{minLength:1,type:"string"},note:{minLength:1,type:"string"},result:{enum:["passed","failed","not-run"]}},required:["name","result"],type:"object"},type:"array"},checksReason:{minLength:1,type:"string"},event:{enum:["build-complete","escalation-requested"]},proposal:{minLength:1,type:"string"},requirementsEvidence:{additionalProperties:!1,properties:{contentHash:{pattern:"^[a-f0-9]{64}$",type:"string"},ref:{minLength:1,type:"string"}},required:["ref","contentHash"],type:"object"}},required:["event"],type:"object"},r=et.default.default??et.default,n=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.event===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};a===null?a=[p]:a.push(p),d++}for(let p in s)if(!(p==="checks"||p==="checksReason"||p==="event"||p==="proposal"||p==="requirementsEvidence")){let u={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[u]:a.push(u),d++}if(s.checks!==void 0){let p=s.checks;if(Array.isArray(p)){let u=p.length;for(let m=0;m<u;m++){let h=p[m];if(h&&typeof h=="object"&&!Array.isArray(h)){if(h.name===void 0){let g={instancePath:o+"/checks/"+m,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};a===null?a=[g]:a.push(g),d++}if(h.result===void 0){let g={instancePath:o+"/checks/"+m,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};a===null?a=[g]:a.push(g),d++}for(let g in h)if(!(g==="name"||g==="note"||g==="result")){let w={instancePath:o+"/checks/"+m,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};a===null?a=[w]:a.push(w),d++}if(h.name!==void 0){let g=h.name;if(typeof g=="string"){if(r(g)<1){let w={instancePath:o+"/checks/"+m+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[w]:a.push(w),d++}}else{let w={instancePath:o+"/checks/"+m+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[w]:a.push(w),d++}}if(h.note!==void 0){let g=h.note;if(typeof g=="string"){if(r(g)<1){let w={instancePath:o+"/checks/"+m+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[w]:a.push(w),d++}}else{let w={instancePath:o+"/checks/"+m+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[w]:a.push(w),d++}}if(h.result!==void 0){let g=h.result;if(!(g==="passed"||g==="failed"||g==="not-run")){let w={instancePath:o+"/checks/"+m+"/result",schemaPath:"#/properties/checks/items/properties/result/enum",keyword:"enum",params:{allowedValues:t.properties.checks.items.properties.result.enum},message:"must be equal to one of the allowed values"};a===null?a=[w]:a.push(w),d++}}}else{let g={instancePath:o+"/checks/"+m,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[g]:a.push(g),d++}}}else{let u={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};a===null?a=[u]:a.push(u),d++}}if(s.checksReason!==void 0){let p=s.checksReason;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.event!==void 0){let p=s.event;if(!(p==="build-complete"||p==="escalation-requested")){let u={instancePath:o+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};a===null?a=[u]:a.push(u),d++}}if(s.proposal!==void 0){let p=s.proposal;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.requirementsEvidence!==void 0){let p=s.requirementsEvidence;if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.ref===void 0){let u={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"ref"},message:"must have required property 'ref'"};a===null?a=[u]:a.push(u),d++}if(p.contentHash===void 0){let u={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};a===null?a=[u]:a.push(u),d++}for(let u in p)if(!(u==="contentHash"||u==="ref")){let m={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(p.contentHash!==void 0){let u=p.contentHash;if(typeof u=="string"){if(!n.test(u)){let m={instancePath:o+"/requirementsEvidence/contentHash",schemaPath:"#/properties/requirementsEvidence/properties/contentHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[m]:a.push(m),d++}}else{let m={instancePath:o+"/requirementsEvidence/contentHash",schemaPath:"#/properties/requirementsEvidence/properties/contentHash/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[m]:a.push(m),d++}}if(p.ref!==void 0){let u=p.ref;if(typeof u=="string"){if(r(u)<1){let m={instancePath:o+"/requirementsEvidence/ref",schemaPath:"#/properties/requirementsEvidence/properties/ref/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[m]:a.push(m),d++}}else{let m={instancePath:o+"/requirementsEvidence/ref",schemaPath:"#/properties/requirementsEvidence/properties/ref/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[m]:a.push(m),d++}}}else{let u={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}}}else{let p={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),d++}return i.errors=a,d===0}return e.exports})(),jM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{checks:{items:{additionalProperties:!1,properties:{name:{minLength:1,type:"string"},note:{minLength:1,type:"string"},result:{enum:["passed","failed","not-run"]}},required:["name","result"],type:"object"},type:"array"},checksReason:{minLength:1,type:"string"},event:{enum:["verification-ready","verify-fail"]},reason:{minLength:1,type:"string"},verificationReport:{minLength:1,type:"string"}},required:["event"],type:"object"},r=et.default.default??et.default;function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(!(d==="checks"||d==="checksReason"||d==="event"||d==="reason"||d==="verificationReport")){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.checks!==void 0){let d=i.checks;if(Array.isArray(d)){let p=d.length;for(let u=0;u<p;u++){let m=d[u];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};f===null?f=[h]:f.push(h),a++}if(m.result===void 0){let h={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};f===null?f=[h]:f.push(h),a++}for(let h in m)if(!(h==="name"||h==="note"||h==="result")){let g={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:h},message:"must NOT have additional properties"};f===null?f=[g]:f.push(g),a++}if(m.name!==void 0){let h=m.name;if(typeof h=="string"){if(r(h)<1){let g={instancePath:s+"/checks/"+u+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:s+"/checks/"+u+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.note!==void 0){let h=m.note;if(typeof h=="string"){if(r(h)<1){let g={instancePath:s+"/checks/"+u+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:s+"/checks/"+u+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.result!==void 0){let h=m.result;if(!(h==="passed"||h==="failed"||h==="not-run")){let g={instancePath:s+"/checks/"+u+"/result",schemaPath:"#/properties/checks/items/properties/result/enum",keyword:"enum",params:{allowedValues:t.properties.checks.items.properties.result.enum},message:"must be equal to one of the allowed values"};f===null?f=[g]:f.push(g),a++}}}else{let h={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[h]:f.push(h),a++}}}else{let p={instancePath:s+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};f===null?f=[p]:f.push(p),a++}}if(i.checksReason!==void 0){let d=i.checksReason;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.event!==void 0){let d=i.event;if(!(d==="verification-ready"||d==="verify-fail")){let p={instancePath:s+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};f===null?f=[p]:f.push(p),a++}}if(i.reason!==void 0){let d=i.reason;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/reason",schemaPath:"#/properties/reason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/reason",schemaPath:"#/properties/reason/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.verificationReport!==void 0){let d=i.verificationReport;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/verificationReport",schemaPath:"#/properties/verificationReport/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),DM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{contentHash:{pattern:"^[a-f0-9]{64}$",type:"string"}},required:["contentHash"],type:"object"},r=new RegExp("^[a-f0-9]{64}$","u");function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.contentHash===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(d!=="contentHash"){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.contentHash!==void 0){let d=i.contentHash;if(typeof d=="string"){if(!r.test(d)){let p={instancePath:s+"/contentHash",schemaPath:"#/properties/contentHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/contentHash",schemaPath:"#/properties/contentHash/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),qM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{deliveryPaths:{items:{minLength:1,type:"string"},type:"array"},prBaseBranch:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},summary:{minLength:1,type:"string"},targetBranch:{minLength:1,type:"string"}},required:["targetBranch","summary"],type:"object"},r=et.default.default??et.default;function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.targetBranch===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};f===null?f=[d]:f.push(d),a++}if(i.summary===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"summary"},message:"must have required property 'summary'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(!(d==="deliveryPaths"||d==="prBaseBranch"||d==="remote"||d==="summary"||d==="targetBranch")){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.deliveryPaths!==void 0){let d=i.deliveryPaths;if(Array.isArray(d)){let p=d.length;for(let u=0;u<p;u++){let m=d[u];if(typeof m=="string"){if(r(m)<1){let h={instancePath:s+"/deliveryPaths/"+u,schemaPath:"#/properties/deliveryPaths/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[h]:f.push(h),a++}}else{let h={instancePath:s+"/deliveryPaths/"+u,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[h]:f.push(h),a++}}}else{let p={instancePath:s+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};f===null?f=[p]:f.push(p),a++}}if(i.prBaseBranch!==void 0){let d=i.prBaseBranch;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.remote!==void 0){let d=i.remote;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.summary!==void 0){let d=i.summary;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/summary",schemaPath:"#/properties/summary/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/summary",schemaPath:"#/properties/summary/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.targetBranch!==void 0){let d=i.targetBranch;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),LM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={properties:{buildPause:{enum:["plan-ready"]},plan:{minLength:1,type:"string"}},required:["plan"],type:"object"},r=et.default.default??et.default;function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.plan===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};f===null?f=[d]:f.push(d),a++}if(i.buildPause!==void 0&&i.buildPause!=="plan-ready"){let d={instancePath:s+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};f===null?f=[d]:f.push(d),a++}if(i.plan!==void 0){let d=i.plan;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/plan",schemaPath:"#/properties/plan/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),WM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={properties:{checks:{items:{additionalProperties:!1,properties:{name:{minLength:1,type:"string"},note:{minLength:1,type:"string"},result:{enum:["passed","failed","not-run"]}},required:["name","result"],type:"object"},type:"array"},checksReason:{minLength:1,type:"string"},event:{enum:["build-complete"]}},required:["event"],type:"object"},r=et.default.default??et.default;function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};f===null?f=[d]:f.push(d),a++}if(i.checks!==void 0){let d=i.checks;if(Array.isArray(d)){let p=d.length;for(let u=0;u<p;u++){let m=d[u];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};f===null?f=[h]:f.push(h),a++}if(m.result===void 0){let h={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};f===null?f=[h]:f.push(h),a++}for(let h in m)if(!(h==="name"||h==="note"||h==="result")){let g={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:h},message:"must NOT have additional properties"};f===null?f=[g]:f.push(g),a++}if(m.name!==void 0){let h=m.name;if(typeof h=="string"){if(r(h)<1){let g={instancePath:s+"/checks/"+u+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:s+"/checks/"+u+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.note!==void 0){let h=m.note;if(typeof h=="string"){if(r(h)<1){let g={instancePath:s+"/checks/"+u+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:s+"/checks/"+u+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.result!==void 0){let h=m.result;if(!(h==="passed"||h==="failed"||h==="not-run")){let g={instancePath:s+"/checks/"+u+"/result",schemaPath:"#/properties/checks/items/properties/result/enum",keyword:"enum",params:{allowedValues:t.properties.checks.items.properties.result.enum},message:"must be equal to one of the allowed values"};f===null?f=[g]:f.push(g),a++}}}else{let h={instancePath:s+"/checks/"+u,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[h]:f.push(h),a++}}}else{let p={instancePath:s+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};f===null?f=[p]:f.push(p),a++}}if(i.checksReason!==void 0){let d=i.checksReason;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.event!==void 0&&i.event!=="build-complete"){let d={instancePath:s+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};f===null?f=[d]:f.push(d),a++}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),MM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={properties:{designDoc:{minLength:1,type:"string"}},required:["designDoc"],type:"object"},r=et.default.default??et.default;function n(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.designDoc===void 0){let d={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};f===null?f=[d]:f.push(d),a++}if(i.designDoc!==void 0){let d=i.designDoc;if(typeof d=="string"){if(r(d)<1){let p={instancePath:s+"/designDoc",schemaPath:"#/properties/designDoc/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:s+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),FM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={properties:{handoffContext:{minLength:1,type:"string"},handoffHash:{pattern:"^[a-f0-9]{64}$",type:"string"},proposal:{minLength:1,type:"string"}},required:["proposal"],type:"object"},r=et.default.default??et.default,n=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.proposal===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"proposal"},message:"must have required property 'proposal'"};a===null?a=[p]:a.push(p),d++}if(s.handoffContext!==void 0){let p=s.handoffContext;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.handoffHash!==void 0){let p=s.handoffHash;if(typeof p=="string"){if(!n.test(p)){let u={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.proposal!==void 0){let p=s.proposal;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}}else{let p={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),d++}return i.errors=a,d===0}return e.exports})(),HE=new Map([['{"additionalProperties":false,"properties":{"action":{"enum":["local","push","pr"]},"commit":{"pattern":"^[0-9a-f]{40}(?:[0-9a-f]{24})?$","type":"string"},"prUrl":{"minLength":1,"type":"string"},"remote":{"minLength":1,"type":"string"},"targetBranch":{"minLength":1,"type":"string"}},"required":["action","targetBranch","commit"],"type":"object"}',xM],['{"additionalProperties":false,"properties":{"archiveConfirmation":{"enum":[null,"pending","confirmed"]},"archived":{"type":"boolean"},"autoTransition":{"type":["boolean","null"]},"baseRef":{"type":["string","null"]},"boundBranch":{"type":["string","null"]},"branchStatus":{"enum":[null,"pending","handled"]},"buildMode":{"enum":[null,"subagent-driven-development","executing-plans","direct","autonomous"]},"buildPause":{"enum":[null,"plan-ready"]},"checkEpoch":{"minimum":0,"type":"integer"},"classicMigration":{"enum":[null,1]},"classicProfile":{"enum":[null,"full","hotfix","tweak"]},"contextCompression":{"enum":[null,"off","beta"]},"createdAt":{"type":["string","null"]},"designDoc":{"type":["string","null"]},"directOverride":{"type":["boolean","null"]},"handoffContext":{"type":["string","null"]},"handoffHash":{"anyOf":[{"type":"null"},{"pattern":"^[a-f0-9]{64}$","type":"string"}]},"isolation":{"enum":[null,"current","branch","worktree"]},"language":{"enum":[null,"en","zh-CN"]},"phase":{"enum":["open","design","build","verify","archive"]},"plan":{"type":["string","null"]},"reviewMode":{"enum":[null,"off","standard","thorough"]},"subagentDispatch":{"enum":[null,"confirmed"]},"tddMode":{"enum":[null,"tdd","direct"]},"verificationReport":{"type":["string","null"]},"verifiedAt":{"type":["string","null"]},"verifyFailures":{"minimum":0,"type":"integer"},"verifyMode":{"enum":[null,"light","full"]},"verifyResult":{"enum":["pending","pass","fail"]},"workflow":{"enum":["full"]}},"required":["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],"type":"object"}',_M],['{"additionalProperties":false,"properties":{"archiveConfirmation":{"enum":[null,"pending","confirmed"]},"archived":{"type":"boolean"},"autoTransition":{"type":["boolean","null"]},"baseRef":{"type":["string","null"]},"boundBranch":{"type":["string","null"]},"branchStatus":{"enum":[null,"pending","handled"]},"buildMode":{"enum":[null,"subagent-driven-development","executing-plans","direct","autonomous"]},"buildPause":{"enum":[null,"plan-ready"]},"checkEpoch":{"minimum":0,"type":"integer"},"classicMigration":{"enum":[null,1]},"classicProfile":{"enum":[null,"full","hotfix","tweak"]},"contextCompression":{"enum":[null,"off","beta"]},"createdAt":{"type":["string","null"]},"designDoc":{"type":["string","null"]},"directOverride":{"type":["boolean","null"]},"handoffContext":{"type":["string","null"]},"handoffHash":{"anyOf":[{"type":"null"},{"pattern":"^[a-f0-9]{64}$","type":"string"}]},"isolation":{"enum":[null,"current","branch","worktree"]},"language":{"enum":[null,"en","zh-CN"]},"phase":{"enum":["open","design","build","verify","archive"]},"plan":{"type":["string","null"]},"reviewMode":{"enum":[null,"off","standard","thorough"]},"subagentDispatch":{"enum":[null,"confirmed"]},"tddMode":{"enum":[null,"tdd","direct"]},"verificationReport":{"type":["string","null"]},"verifiedAt":{"type":["string","null"]},"verifyFailures":{"minimum":0,"type":"integer"},"verifyMode":{"enum":[null,"light","full"]},"verifyResult":{"enum":["pending","pass","fail"]},"workflow":{"enum":["hotfix","full"]}},"required":["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],"type":"object"}',IM],['{"additionalProperties":false,"properties":{"archiveConfirmation":{"enum":[null,"pending","confirmed"]},"archived":{"type":"boolean"},"autoTransition":{"type":["boolean","null"]},"baseRef":{"type":["string","null"]},"boundBranch":{"type":["string","null"]},"branchStatus":{"enum":[null,"pending","handled"]},"buildMode":{"enum":[null,"subagent-driven-development","executing-plans","direct","autonomous"]},"buildPause":{"enum":[null,"plan-ready"]},"checkEpoch":{"minimum":0,"type":"integer"},"classicMigration":{"enum":[null,1]},"classicProfile":{"enum":[null,"full","hotfix","tweak"]},"contextCompression":{"enum":[null,"off","beta"]},"createdAt":{"type":["string","null"]},"designDoc":{"type":["string","null"]},"directOverride":{"type":["boolean","null"]},"handoffContext":{"type":["string","null"]},"handoffHash":{"anyOf":[{"type":"null"},{"pattern":"^[a-f0-9]{64}$","type":"string"}]},"isolation":{"enum":[null,"current","branch","worktree"]},"language":{"enum":[null,"en","zh-CN"]},"phase":{"enum":["open","design","build","verify","archive"]},"plan":{"type":["string","null"]},"reviewMode":{"enum":[null,"off","standard","thorough"]},"subagentDispatch":{"enum":[null,"confirmed"]},"tddMode":{"enum":[null,"tdd","direct"]},"verificationReport":{"type":["string","null"]},"verifiedAt":{"type":["string","null"]},"verifyFailures":{"minimum":0,"type":"integer"},"verifyMode":{"enum":[null,"light","full"]},"verifyResult":{"enum":["pending","pass","fail"]},"workflow":{"enum":["tweak","full"]}},"required":["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],"type":"object"}',PM],['{"additionalProperties":false,"properties":{"archiveDirectory":{"minLength":1,"type":"string"}},"required":["archiveDirectory"],"type":"object"}',OM],['{"additionalProperties":false,"properties":{"baseCommit":{"pattern":"^[0-9a-f]{40}(?:[0-9a-f]{24})?$","type":"string"},"deliveryAction":{"enum":["local","push","pr"]},"deliveryPaths":{"items":{"minLength":1,"type":"string"},"type":"array"},"prBaseBranch":{"minLength":1,"type":"string"},"remote":{"minLength":1,"type":"string"},"remoteIdentity":{"pattern":"^[0-9a-f]{64}$","type":"string"},"targetBranch":{"minLength":1,"type":"string"},"verifiedBranch":{"minLength":1,"type":"string"}},"required":["deliveryAction","targetBranch","verifiedBranch","baseCommit"],"type":"object"}',TM],['{"additionalProperties":false,"properties":{"boundBranch":{"type":["string","null"]},"buildMode":{"enum":["subagent-driven-development","executing-plans","direct","autonomous"]},"directOverride":{"type":"boolean"},"isolation":{"enum":["current","branch","worktree"]},"reviewMode":{"enum":["off","standard","thorough"]},"subagentDispatch":{"enum":["confirmed",null]},"tddMode":{"enum":["tdd","direct"]}},"required":["buildMode","tddMode","reviewMode","isolation"],"type":"object"}',NM],['{"additionalProperties":false,"properties":{"checks":{"items":{"additionalProperties":false,"properties":{"name":{"minLength":1,"type":"string"},"note":{"minLength":1,"type":"string"},"result":{"enum":["passed","failed","not-run"]}},"required":["name","result"],"type":"object"},"type":"array"},"checksReason":{"minLength":1,"type":"string"},"event":{"enum":["build-complete","escalation-requested"]},"proposal":{"minLength":1,"type":"string"},"requirementsEvidence":{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"ref":{"minLength":1,"type":"string"}},"required":["ref","contentHash"],"type":"object"}},"required":["event"],"type":"object"}',$M],['{"additionalProperties":false,"properties":{"checks":{"items":{"additionalProperties":false,"properties":{"name":{"minLength":1,"type":"string"},"note":{"minLength":1,"type":"string"},"result":{"enum":["passed","failed","not-run"]}},"required":["name","result"],"type":"object"},"type":"array"},"checksReason":{"minLength":1,"type":"string"},"event":{"enum":["verification-ready","verify-fail"]},"reason":{"minLength":1,"type":"string"},"verificationReport":{"minLength":1,"type":"string"}},"required":["event"],"type":"object"}',jM],['{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"}},"required":["contentHash"],"type":"object"}',DM],['{"additionalProperties":false,"properties":{"deliveryPaths":{"items":{"minLength":1,"type":"string"},"type":"array"},"prBaseBranch":{"minLength":1,"type":"string"},"remote":{"minLength":1,"type":"string"},"summary":{"minLength":1,"type":"string"},"targetBranch":{"minLength":1,"type":"string"}},"required":["targetBranch","summary"],"type":"object"}',qM],['{"properties":{"buildPause":{"enum":["plan-ready"]},"plan":{"minLength":1,"type":"string"}},"required":["plan"],"type":"object"}',LM],['{"properties":{"checks":{"items":{"additionalProperties":false,"properties":{"name":{"minLength":1,"type":"string"},"note":{"minLength":1,"type":"string"},"result":{"enum":["passed","failed","not-run"]}},"required":["name","result"],"type":"object"},"type":"array"},"checksReason":{"minLength":1,"type":"string"},"event":{"enum":["build-complete"]}},"required":["event"],"type":"object"}',WM],['{"properties":{"designDoc":{"minLength":1,"type":"string"}},"required":["designDoc"],"type":"object"}',MM],['{"properties":{"handoffContext":{"minLength":1,"type":"string"},"handoffHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"proposal":{"minLength":1,"type":"string"}},"required":["proposal"],"type":"object"}',FM]]);var HM=128,BE=1024*1024,Zi=new Map,Lg=0;function od(e){let t=yn(e),r=Zi.get(t);if(r)return Zi.delete(t),Zi.set(t,r),r;let i=HE.get(t)??new Wg.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),s={validate:i,errorsText:()=>Wg.Ajv.prototype.errorsText(i.errors)};if(t.length<=BE){for(;Zi.size>=HM||Lg+t.length>BE;){let o=Zi.keys().next().value;Zi.delete(o),Lg-=o.length}Zi.set(t,s),Lg+=t.length}return s}var BM=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];function it(e){throw new v("INVALID_WORKFLOW",e)}function ai(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&it(`${t} 必须是 JSON 对象`),e}function lc(e,t,r){for(let n of Object.keys(e))t.includes(n)||it(`${r} 包含不支持的字段:${n}`)}function _t(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&it(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Mg(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&it(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>_t(i,t));return new Set(n).size!==n.length&&it(`${t} 不能包含重复值`),n}function Fg(e,t){return Mg(typeof e=="string"?[e]:e,t)}function uc(e,t){let r=ai(e,t);return lc(r,["id","version"],t),{id:_t(r.id,`${t}.id`),version:_t(r.version,`${t}.version`)}}function UE(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))UE(t);Object.freeze(e)}return e}function zE(e,t){try{let r=typeof e=="boolean"?e:ai(e,t);typeof r!="boolean"&&r.$async===!0&&it(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),od(r)}catch(r){it(`${t} 不是受支持的 JSON Schema:${r.message}`)}}function VM(e){let t=ai(e,"step"),r=_t(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(r)||it(`不支持的步骤类型:${r}`);let n=r==="ask_user"?["proposalFrom","choices"]:r==="child_workflow"?["workflow"]:r==="await_evidence"?["kind"]:[];lc(t,[...BM,...n],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&it("step.retry 必须是 manual、idempotent 或 reconcile");let s={...t.ref===void 0?{}:{ref:_t(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:uc(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:Mg(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:Mg(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&zE(t.outputSchema,"outputSchema"),r==="ask_user"?{...s,type:r,proposalFrom:Fg(t.proposalFrom,"step.proposalFrom"),choices:Fg(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...s,type:r,workflow:uc(t.workflow,"step.workflow")}:r==="await_evidence"?(s.validator||it("await_evidence 必须声明验证器"),{...s,type:r,kind:_t(t.kind,"step.kind"),validator:s.validator}):{...s,type:r,ref:_t(t.ref,"step.ref")}}var VE=new WeakSet;function Wr(e){if(VE.has(e))return e;let t=ai(Je(e),"workflow");lc(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=_t(t.id,"workflow.id"),n=_t(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&it("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&it("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&zE(t.stateSchema,"stateSchema");let i=ai(t.steps,"workflow.steps");Object.keys(i).length===0&&it("workflow.steps 必须至少包含一个步骤");let s=Object.fromEntries(Object.entries(i).map(([h,g])=>(_t(h,"step id"),[h,VM(g)])));function o(h,g){Object.hasOwn(s,h)||it(`${g} 引用了不存在的步骤:${h}`)}let c=Fg(t.entry,"workflow.entry");for(let h of c)o(h,"workflow.entry");let l=t.commands===void 0?{}:ai(t.commands,"workflow.commands"),f={};for(let[h,g]of Object.entries(l)){_t(h,"workflow command name");let w=typeof g=="string"?{stepId:_t(g,`workflow.commands.${h}`)}:ai(g,`workflow.commands.${h}`);lc(w,["stepId","validator"],`workflow.commands.${h}`);let k=_t(w.stepId,`workflow.commands.${h}.stepId`);o(k,`workflow.commands.${h}`);let b=s[k];(b.join||!["invoke_skill","call_tool","handoff"].includes(b.type))&&it(`workflow.commands.${h} 必须指向不带 join 的执行步骤`),Object.defineProperty(f,h,{value:{stepId:k,...w.validator===void 0?{}:{validator:uc(w.validator,`workflow.commands.${h}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let a=t.transitions===void 0?[]:t.transitions;Array.isArray(a)||it("workflow.transitions 必须是数组");let d=new Set,p=a.map(h=>{let g=ai(h,"transition");lc(g,["from","to","on"],"transition");let w=_t(g.from,"transition.from"),k=_t(g.to,"transition.to"),b=_t(g.on===void 0?"succeeded":g.on,"transition.on");o(w,"transition.from"),o(k,"transition.to");let R=JSON.stringify([w,k,b]);return d.has(R)&&it(`重复的状态转移:${w} -> ${k} (${b})`),d.add(R),{from:w,to:k,on:b}});for(let[h,g]of Object.entries(s)){if(g.join){let w=new Set(p.filter(k=>k.to===h).map(k=>k.from));for(let k of g.join)o(k,`${h}.join`),w.has(k)||it(`${h}.join 依赖缺少对应的进入边:${k}`);w.size!==g.join.length&&it(`${h}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let w of g.proposalFrom)o(w,`${h}.proposalFrom`)}let u=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof u!="number"||!Number.isSafeInteger(u)||u<1)&&it("workflow.maxTransitions 必须是正安全整数");let m=UE({id:r,version:n,entry:c,steps:s,...t.commands===void 0?{}:{commands:f},transitions:p,maxTransitions:u,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:uc(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:uc(t.transitionHandler,"workflow.transitionHandler")}});return VE.add(m),m}function dc(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!0,enumerable:!0,writable:!0})}function ad(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value]))}function UM(e){let t={};for(let r of e)for(let[n,i]of Object.entries(r.results))(!Object.hasOwn(t,n)||i.sequence>t[n].sequence)&&dc(t,n,i);return t}function Sn(e,t){if(e.status==="cancelled"||e.status==="failed")return;for(;e.ready.length>0;){let s=e.ready.shift(),o=t.steps[s.to],c=s.results;if(o.join?.length){if(s.from===null||!o.join.includes(s.from))throw new v("INVALID_JOIN","join 必须由其声明的父节点触发");Object.hasOwn(e.joins,s.to)||dc(e.joins,s.to,Object.fromEntries(o.join.map(p=>[p,[]])));let d=e.joins[s.to];if(d[s.from].push(s),o.join.some(p=>d[p].length===0))continue;c=UM(o.join.map(p=>d[p].shift()))}if(e.sequence>=t.maxTransitions){e.ready.unshift(s),e.status="failed",e.reason="TRANSITION_LIMIT: 工作流已达到允许的步骤激活次数";return}let l=++e.sequence,f=`${e.runId}:${l}`,a={input:o.input===void 0?e.input:o.input,outputs:ad(c),...s.activation===void 0?{}:{activation:s.activation}};if(o.type==="ask_user"){let d=Object.fromEntries(o.proposalFrom.map(u=>{if(!Object.hasOwn(c,u))throw new v("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${u}`);return[u,c[u].value]})),p={input:a.input,outputs:d,...s.activation===void 0?{}:{activation:s.activation}};e.waits.push({id:f,stepId:s.to,sequence:l,status:"pending",proposal:p,proposalHash:j(p),choices:[...o.choices],results:c})}else if(o.type==="await_evidence")e.evidenceWaits??=[],e.evidenceWaits.push({id:f,stepId:s.to,sequence:l,kind:o.kind,status:"pending",results:c});else{let d=o.type==="child_workflow"?`${o.workflow.id}@${o.workflow.version}`:o.ref,p=MR({id:f,runId:e.runId,stepId:s.to,type:o.type,ref:d,input:a,retry:o.retry,requiredCapabilities:o.requiredCapabilities});e.actions.push(p),dc(e.actionContexts,f,{sequence:l,results:c}),o.type==="child_workflow"&&e.children.push({actionId:f,runId:`child-${j(f)}`,workflow:o.workflow})}}let r=e.actions.some(s=>["pending","running","unknown"].includes(s.status)),n=e.waits.some(s=>s.status==="pending")||(e.evidenceWaits?.some(s=>s.status==="pending")??!1),i=Object.values(e.joins).some(s=>Object.values(s).some(o=>o.length>0));e.status=r?"running":n||i?"waiting":"completed"}function oo(e,t,r,n,i,s,o,c){let l={sequence:n,value:s},f={...i};dc(f,r,l),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&dc(e.outputs,r,l);let a=t.transitions.filter(u=>u.from===r),d=a.filter(u=>u.on===o),p=c??d.map(u=>u.to);if(p.length===0&&o==="failed"){e.status="failed",e.reason=`ACTION_FAILED: ${r}`;return}if(p.length===0&&c===void 0&&a.length>0)throw new v("TRANSITION_UNAVAILABLE",`步骤 ${r} 未声明 ${o} 的后续转换`);for(let u of p){let m=typeof u=="string"?u:u.stepId;if(!d.some(h=>h.to===m))throw new v("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:r,to:m,results:f,...typeof u=="string"?{}:{activation:u.input}})}}function KE(e){return Oe({runId:e.runId,revision:e.revision,status:e.status,sequence:e.sequence,workflow:e.workflow,input:e.input,...e.state===void 0?{}:{state:e.state},...e.reason===void 0?{}:{reason:e.reason},actions:e.actions.filter(t=>["pending","running","unknown"].includes(t.status)||t.status==="cancelled"&&t.claim&&!t.cancellation&&!t.executionStop),waits:e.waits.filter(t=>t.status==="pending"),evidenceWaits:(e.evidenceWaits??[]).filter(t=>t.status==="pending"),outputs:e.outputs,history:{actions:e.actions.length,waits:e.waits.length,evidenceWaits:e.evidenceWaits?.length??0}})}function Ue(e){return JSON.stringify([e.id,e.version])}function sr(e){if(e===void 0)return;if(!e||typeof e!="object"||Ug.isProxy(e))throw new v("INVALID_JSON","context 必须是普通对象");let t={},r;for(let i of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!s.enumerable||!("value"in s))throw new v("INVALID_JSON","context 必须使用普通数据属性");i==="signal"?r=s.value:s.value!==void 0&&Object.defineProperty(t,i,{value:s.value,enumerable:!0})}let n=Je(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new v("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function zg(e,t=new Set){if(e===null||typeof e!="object")return e;if(Ug.isProxy(e))throw new v("INVALID_JSON","请求不能包含代理对象");if(t.size>64)throw new v("INVALID_JSON","请求数据嵌套超过 64 层");if(t.has(e))throw new v("INVALID_JSON","请求包含循环引用");let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw new v("INVALID_JSON","请求必须使用普通数据对象");t.add(e);let n=Array.isArray(e)?[]:{};for(let i of Reflect.ownKeys(e)){if(Array.isArray(e)&&i==="length")continue;let s=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!s.enumerable||!("value"in s))throw new v("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(n,i,{enumerable:!0,writable:!0,configurable:!0,value:zg(s.value,t)})}return t.delete(e),n}function Bg(e){if(e===null||typeof e!="object")return e;if(Ug.isProxy(e))throw new v("INVALID_JSON","请求不能包含代理对象");let t={};for(let r of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,r);if(typeof r!="string"||!n.enumerable||!("value"in n))throw new v("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(t,r,{enumerable:!0,writable:!0,configurable:!0,value:r==="context"?sr(n.value):zg(n.value)})}return t}function es(e){let t=zg(e),r=Je(t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t);if(!r||typeof r.accepted!="boolean"||r.reason!==void 0&&typeof r.reason!="string"||"allowCompleted"in r&&typeof r.allowCompleted!="boolean"||"allowFailed"in r&&typeof r.allowFailed!="boolean")throw new v("INVALID_VALIDATION","验证器必须返回布尔 accepted 和有效原因");return r}function Vg(e,t){let r=e.supports(Oe(t));if(typeof r!="boolean")throw new v("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function tn(e){if(e?.signal?.aborted)throw new v("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function ts(e,t){if(e===t)return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>Object.hasOwn(t,n)&&ts(e[n],t[n]))}function GE(e){return{...e,definitionHashes:{...e.definitionHashes},actions:[...e.actions],...e.commands?{commands:[...e.commands]}:{},actionContexts:{...e.actionContexts},waits:e.waits.map(t=>({...t})),...e.evidenceWaits?{evidenceWaits:e.evidenceWaits.map(t=>({...t}))}:{},ready:[...e.ready],joins:Object.fromEntries(Object.entries(e.joins).map(([t,r])=>[t,Object.fromEntries(Object.entries(r).map(([n,i])=>[n,[...i]]))])),outputs:{...e.outputs},children:[...e.children],lineage:[...e.lineage]}}var JE=new WeakMap;function ao(e){let t=new Map,r=new Map;for(let y of e.workflows){let S=Wr(y),_=Ue(S);if(t.has(_))throw new v("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(_,S);let A=JE.get(S);A===void 0&&(A=j(S),JE.set(S,A)),r.set(S,A)}let n=new Map;for(let y of e.validators??[]){let S=Ue(y);if(n.has(S))throw new v("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(S,y)}let i=new Map;for(let y of e.stateValidators??[]){let S=Ue(y);if(i.has(S))throw new v("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(S,y)}let s=new Map;function o(y){let S=s.get(y);return S||(S=od(y),s.set(y,S)),S}let c=new Map,l=new Map;for(let y of e.transitionHandlers??[]){let S=Ue(y);if(l.has(S))throw new v("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");l.set(S,y)}let f=new Map;for(let y of e.evidenceValidators??[]){let S=Ue(y);if(f.has(S))throw new v("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");f.set(S,y)}let a=new Map;for(let y of e.commandValidators??[]){let S=Ue(y);if(a.has(S))throw new v("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");a.set(S,y)}for(let y of e.executors??[]){if(c.has(y.id))throw new v("DUPLICATE_EXECUTOR","不能重复注册同一执行器");c.set(y.id,y)}function d(y){let S=t.get(Ue(y));if(!S)throw new v("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(y.hash!==void 0&&y.hash!==r.get(S))throw new v("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return S}function p(y){if(y.transitionHandler&&!l.has(Ue(y.transitionHandler)))throw new v("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function u(y){if(y.stateValidator&&!i.has(Ue(y.stateValidator)))throw new v("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function m(y){for(let S of Object.values(y.steps))if(S.type==="await_evidence"&&!f.has(Ue(S.validator)))throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function h(y){for(let S of Object.values(y.commands??{}))if(S.validator&&!a.has(Ue(S.validator)))throw new v("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(y,S,_){if(y.stateSchema!==void 0){let A=o(y.stateSchema);if(!A.validate(S))throw new v(_,A.errorsText())}if(y.stateValidator){let A=i.get(Ue(y.stateValidator));if(!A)throw new v("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let I=es(A.validate({state:Je(S)}));if(!I.accepted)throw new Error(I.reason??"业务状态未通过验证")}catch(I){throw new v(_,I instanceof Error?I.message:String(I))}}}function w(y,S,_,A){if(!S.transitionHandler)return;let I=l.get(Ue(S.transitionHandler));if(!I)throw new v("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let W=Je(I.apply({run:Oe(y),event:Oe(_)})),M=Je(W.state);g(S,M,"TRANSITION_STATE_INVALID");let B=new Set(S.transitions.filter(Q=>Q.from===_.stepId&&Q.on===A).map(Q=>Q.to));if(!Array.isArray(W.next))throw new v("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let q=[],V=new Set;for(let Q of W.next){let N;if(typeof Q=="string")N=Q;else if(Q!==null&&typeof Q=="object"&&!Array.isArray(Q)){let ue=Object.keys(Q);if(ue.length!==2||!ue.includes("stepId")||!ue.includes("input")||typeof Q.stepId!="string")throw new v("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");N={stepId:Q.stepId,input:Je(Q.input)}}else throw new v("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let oe=typeof N=="string"?N:N.stepId,Y=j(N);if(!B.has(oe)||V.has(Y))throw new v("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");V.add(Y),q.push(N)}return y.state=M,q}function k(y,S=j){if(t.size>0)for(let[_,A]of Object.entries(y.definitionHashes)){let[I,W]=JSON.parse(_),M=d({id:I,version:W,hash:A});if(p(M),u(M),m(M),h(M),I===y.workflow.id&&W===y.workflow.version){let B=new Map(y.actions.map(q=>[q.id,q]));for(let q of y.commands??[]){let V=B.get(q.actionId),Q=Object.hasOwn(M.commands??{},q.name),N=V&&!Q&&!Object.hasOwn(M.steps,V.stepId)&&["succeeded","failed","cancelled"].includes(V.status);if(!V||!N&&(!Q||M.commands?.[q.name].stepId!==V.stepId)||V.input===null||typeof V.input!="object"||!Object.hasOwn(V.input,"activation")||S(V.input.activation)!==q.inputHash)throw new v("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(M.stateSchema!==void 0&&M.initialState===void 0&&y.initialStateHash===void 0)throw new v("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(M,y.state,"RUN_STATE_INVALID");for(let q of y.ready){let V=()=>{throw new v("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(M.steps,q.to)||V(),q.from===null){(!M.entry.includes(q.to)||Object.keys(q.results).length>0||y.sequence!==0&&!(y.status==="failed"&&y.reason?.startsWith("TRANSITION_LIMIT:")))&&V();continue}let Q=q.results[q.from];Q||V();let N=y.actions.find(Bt=>Bt.stepId===q.from&&y.actionContexts[Bt.id].sequence===Q.sequence),oe=y.waits.find(Bt=>Bt.stepId===q.from&&Bt.sequence===Q.sequence),Y=y.evidenceWaits?.find(Bt=>Bt.stepId===q.from&&Bt.sequence===Q.sequence),ue=N?.outcome?N.outcome.status==="failed"?"failed":N.outcome.event??"succeeded":oe?.decision?.choice??(Y?.invalidation?"invalidated":Y?.receipt?"succeeded":void 0),Ke=N?y.actionContexts[N.id].results:oe?.results??Y?.results,Io=N?.outcome?N.outcome.output:oe?.decision?{choice:oe.decision.choice,proposal:oe.proposal}:Y?.invalidation?{ref:Y.invalidation.ref,contentHash:Y.invalidation.contentHash,reason:Y.invalidation.reason}:Y?.receipt?{ref:Y.receipt.ref,contentHash:Y.receipt.contentHash}:void 0;(!ue||!Ke||N&&!["succeeded","failed"].includes(N.status)||oe&&oe.status!=="resolved"||Y&&!["resolved","invalidated"].includes(Y.status)||Io===void 0||S(q.results)!==S({...Ke,[q.from]:{sequence:Q.sequence,value:Io}})||!M.transitions.some(Bt=>Bt.from===q.from&&Bt.to===q.to&&Bt.on===ue))&&V()}for(let q of y.evidenceWaits??[]){let V=M.steps[q.stepId];if(!(!V&&q.status!=="pending")&&(!V||V.type!=="await_evidence"||V.kind!==q.kind))throw new v("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function b(y){let S=await e.store.read(y);if(!S)throw new v("RUN_NOT_FOUND",`找不到工作流实例:${y}`);let _=XR(S,y);return k(_),Mi(_)}async function R(y,S,_){for(let A=0;A<32;A+=1){tn(y.context);let I=A===0&&_?_:await b(y.runId),W=d(I.workflow);if(y.expectedRevision!==void 0&&y.expectedRevision!==I.revision)throw new v("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let M=GE(I);if(await S(M,W),mr(M),ts(M,I))return I;if(M.revision=I.revision+1,bu(M,I),k(M),Mi(M),tn(y.context),await e.store.compareAndSwap(y.runId,I.revision,M))return M}throw new v("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function E(y,S){let _=y.actions.find(A=>A.id===S);if(!_)throw new v("ACTION_NOT_FOUND","Run 不包含此 Action");return _}function O(y){if(y.status==="cancelled")throw new v("RUN_CANCELLED","Run 已取消,不能继续推进")}function z(y,S={}){let _=Ue(y);if(Object.hasOwn(S,_))return S;S[_]=r.get(y);for(let A of Object.values(y.steps))A.type==="child_workflow"&&z(d(A.workflow),S);return S}async function D(y,S){if(tn(y.context),S.length>32)throw new v("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let _=d(y.workflow);p(_),u(_),m(_),h(_);let A=Object.hasOwn(y,"initialState");if(A&&_.initialState!==void 0)throw new v("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let I=A?Je(y.initialState):_.initialState;if(_.stateSchema!==void 0&&I===void 0)throw new v("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");I!==void 0&&g(_,I,"INITIAL_STATE_INVALID");let W=I===void 0?void 0:j(I),M=y.runId??Hg(),B=Je(y.input),q={id:_.id,version:_.version,hash:r.get(_)},V=await e.store.read(M);if(V){if(j(V.workflow)!==j(q)||j(V.input)!==j(B)||j(V.lineage)!==j(S)||(V.initialStateHash??(_.initialState===void 0?void 0:j(_.initialState)))!==W)throw new v("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return b(M)}let Q={protocolVersion:1,schemaVersion:1,runId:M,revision:1,workflow:q,definitionHashes:z(_),input:B,...I===void 0?{}:{state:Je(I),initialStateHash:W},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:_.entry.map(N=>({from:null,to:N,results:{}})),joins:{},outputs:{},children:[],lineage:S};return Sn(Q,_),Mi(Q),tn(y.context),bu(Q),k(Q),await e.store.compareAndSwap(M,null,Q)?Oe(Q):D({...y,runId:M},S)}async function G(y){return D(y,[])}async function J(y){let S=Je(y.input),_=j(S);if(!y.commandId.trim()||y.commandId.length>4096||!y.name.trim()||y.name.length>4096)throw new v("INVALID_COMMAND","命令标识和名称不能为空");for(let A=0;A<32;A+=1){tn(y.context);let I=await b(y.runId),W=I.commands?.find(Y=>Y.id===y.commandId);if(W){if(W.name!==y.name||W.inputHash!==_)throw new v("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return I}if(y.expectedRevision!==I.revision)throw new v("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let M=d(I.workflow),B=Object.hasOwn(M.commands??{},y.name)?M.commands?.[y.name]:void 0;if(!B)throw new v("COMMAND_NOT_FOUND","工作流未声明此命令");let q=B.stepId;if(I.status==="cancelled")throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(I.actions.some(Y=>["running","unknown"].includes(Y.status)))throw new v("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let V=!1,Q=!1;if(B.validator){let Y=a.get(Ue(B.validator));if(!Y)throw new v("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let ue;try{ue=es(await Y.validate({run:Oe(I),name:y.name,input:Oe(S),context:sr(y.context)}))}catch(Ke){throw new v("COMMAND_VALIDATION_ERROR",Ke instanceof Error?Ke.message:String(Ke))}if(V=ue.accepted&&ue.allowCompleted===!0,Q=ue.accepted&&ue.allowFailed===!0,I.status==="failed"&&!Q)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(I.status==="completed"&&!V)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!ue.accepted)throw new v("COMMAND_REJECTED",ue.reason??"命令未通过当前工作流状态验证")}if(I.status==="completed"&&!V)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(I.status==="failed"&&!Q)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");let N=Oe(I);I.status==="failed"&&(N.status="running",delete N.reason),N.actions=N.actions.map(Y=>Y.status==="pending"?Fm(Y,`命令 ${y.name} 已取代待执行 Action`):Y);for(let Y of N.waits)Y.status==="pending"&&(Y.status="cancelled");for(let Y of N.evidenceWaits??[])Y.status==="pending"&&(Y.status="cancelled");N.ready=[{from:null,to:q,results:{},activation:S}],N.joins={},Sn(N,M);let oe=N.actions.at(-1);if(!oe||oe.stepId!==q||oe.status!=="pending")throw new v("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(N.commands=[...N.commands??[],{id:y.commandId,name:y.name,inputHash:_,actionId:oe.id}],N.revision=I.revision+1,bu(N,I),k(N),Mi(N),tn(y.context),await e.store.compareAndSwap(y.runId,I.revision,N))return Oe(N)}throw new v("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function te(y){for(let S of y.children)await e.store.read(S.runId)&&await T({runId:S.runId,reason:y.reason??"父工作流已取消"})}function Z(y,S,_){let A=d(y.workflow),I=Object.hasOwn(A.steps,_.stepId)?A.steps[_.stepId]:void 0;if(!I||I.type!=="child_workflow"||Ue(I.workflow)!==Ue(S.workflow)||_.type!==I.type||_.ref!==`${I.workflow.id}@${I.workflow.version}`||_.attempt!==1||_.retry!==I.retry||!ts(_.requiredCapabilities,I.requiredCapabilities??[])||_.claim&&(_.claim.executorId!=="comet-child-workflow"||_.claim.sessionId!==void 0||![S.runId,`portable-${j(S.runId)}`].includes(_.claim.token)))throw new v("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let W=_.input;if(!W||typeof W!="object"||Array.isArray(W)||!ts(W,{input:I.input===void 0?y.input:I.input,outputs:ad(y.actionContexts[_.id].results),...Object.hasOwn(W,"activation")?{activation:W.activation}:{}}))throw new v("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let M=d({...S.workflow,hash:y.definitionHashes[Ue(S.workflow)]});if(Object.entries(z(M)).some(([B,q])=>y.definitionHashes[B]!==q))throw new v("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return M}function we(y,S,_,A,I){let W=A.initialState===void 0?void 0:j(A.initialState);if(I.runId!==S.runId||Ue(I.workflow)!==Ue(S.workflow)||I.workflow.hash!==y.definitionHashes[Ue(S.workflow)]||!ts(I.definitionHashes,z(A))||!ts(I.input,_.input)||!ts(I.lineage,[...y.lineage,y.runId])||(I.initialStateHash??W)!==W)throw new v("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function K(y){let S=await R(y,(_,A)=>Sn(_,A));if(S.status==="cancelled")return await te(S),S;if(S.status==="failed"||S.children.length===0)return S;for(let _ of S.children){let A=E(S,_.actionId);if(!["pending","running","unknown"].includes(A.status))continue;let I=Z(S,_,A);A.status==="pending"&&(S=await ne({runId:S.runId,actionId:A.id,attempt:A.attempt,inputHash:A.inputHash,executorId:"comet-child-workflow",claimToken:_.runId,capabilities:["child-workflow"],context:sr(y.context)},!0),A=E(S,_.actionId));let W=A.status==="unknown"?await b(_.runId):await D({runId:_.runId,workflow:_.workflow,input:A.input,context:sr(y.context)},[...S.lineage,S.runId]);we(S,_,A,I,W);let M=await b(S.runId);if(M.status==="cancelled")return await te(M),M;let B=await K({runId:_.runId,context:y.context});we(S,_,A,I,B),["completed","failed","cancelled"].includes(B.status)&&(S=await P({runId:S.runId,context:sr(y.context),outcome:{actionId:A.id,attempt:A.attempt,inputHash:A.inputHash,claimToken:A.claim.token,outcomeId:`${_.runId}:${B.revision}`,status:B.status==="completed"?"succeeded":"failed",output:ad(B.outputs)}},!0))}return b(S.runId)}async function ne(y,S=!1,_){let A=y.claimToken??(y.context?.requestId?j({runId:y.runId,actionId:y.actionId,attempt:y.attempt,executorId:y.executorId,requestId:y.context.requestId}):Hg());return R(y,async I=>{if(O(I),I.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let W=E(I,y.actionId);if(W.type==="child_workflow"&&!S)throw new v("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let M=HR(W,{executionOrigin:{workflow:{...I.workflow}},attempt:y.attempt,inputHash:y.inputHash,executorId:y.executorId,token:A,...y.sessionId===void 0?{}:{sessionId:y.sessionId}});if(!W.claim){let B=new Set(y.capabilities??[]);if(W.requiredCapabilities.some(V=>!B.has(V)))throw new v("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let q=c.get(y.executorId);if(q&&Vg(q,W)){if(W.requiredCapabilities.some(V=>!q.capabilities.includes(V)))throw new v("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await q.preflight?.(Oe(W),sr(y.context),q.includeRun===!1?void 0:Oe(I)),tn(y.context)}}I.actions[I.actions.indexOf(W)]=M},_)}async function ze(y){return ne(y)}async function P(y,S=!1,_){let A,I;try{A=yu(y.outcome)}catch(B){I=B}y={...y,outcome:A};let W,M=await R(y,async(B,q)=>{if(W=void 0,O(B),!A)throw I;let V=E(B,y.outcome.actionId);if(V.type==="child_workflow"&&!S)throw new v("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let Q=Mm(V,y.outcome);if(Q.duplicate)return;let N=Q.action.outcome,oe=B.actions.indexOf(V);try{if(e.validateOutcome){let ue=es(await e.validateOutcome({run:Oe(B),action:Oe(V),outcome:Oe(N),context:sr(y.context)}));ue.accepted||(W={code:"OUTCOME_REJECTED",reason:ue.reason??"应用结果契约拒绝此结果"})}let Y=q.steps[V.stepId];if(!W&&N.status==="succeeded"&&Y.outputSchema!==void 0){let ue=o(Y.outputSchema);ue.validate(N.output)||(W={code:"OUTPUT_INVALID",reason:ue.errorsText()})}if(!W&&Y.validator){let ue=n.get(Ue(Y.validator));if(!ue)throw new v("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let Ke=es(await ue.validate({run:Oe(B),action:Oe(V),outcome:Oe(N),context:sr(y.context)}));Ke.accepted||(W={code:"OUTCOME_REJECTED",reason:Ke.reason?.trim()?Ke.reason:"结果未满足业务验收条件"})}if(!W){let ue=GE(B);ue.actions[oe]=Q.action;let Ke=ue.actionContexts[V.id],Io=N.status==="failed"?"failed":N.event??"succeeded",Bt=w(ue,q,{kind:"action-outcome",stepId:V.stepId,outcome:N},Io);oo(ue,q,V.stepId,Ke.sequence,Ke.results,N.output,Io,Bt),Sn(ue,q),Object.assign(B,ue)}}catch(Y){W={code:"OUTCOME_PROCESSING_ERROR",reason:Y instanceof Error&&Y.message.trim()?Y.message:"结果处理失败,请检查验证器或工作流定义"}}W&&(B.actions[oe]={...V,receipts:Q.action.receipts,rejectedOutcomes:[...V.rejectedOutcomes??[],{outcome:Q.action.outcome,...W}]})},_);if(W)throw new v(W.code,W.reason);return M}async function F(y){return P(y)}async function re(y){if(y.reason!==void 0&&!Vm(y.reason))throw new v("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return R(y,(S,_)=>{O(S);let A=S.waits.find(W=>W.id===y.waitId);if(!A)throw new v("WAIT_NOT_FOUND","Run 不包含此等待项");if(A.decision){if(A.decision.id!==y.decisionId||A.decision.choice!==y.choice||A.decision.proposalHash!==y.proposalHash||A.decision.reason!==y.reason)throw new v("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(A.status!=="pending"||A.proposalHash!==y.proposalHash)throw new v("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!y.decisionId.trim()||!A.choices.includes(y.choice))throw new v("INVALID_DECISION","决定标识或选择不符合当前等待项");A.status="resolved",A.decision={id:y.decisionId,choice:y.choice,proposalHash:y.proposalHash,...y.reason===void 0?{}:{reason:y.reason}};let I=w(S,_,{kind:"wait-resolved",stepId:A.stepId,choice:y.choice,proposalHash:y.proposalHash,decisionId:y.decisionId},y.choice);oo(S,_,A.stepId,A.sequence,A.results,{choice:y.choice,proposal:A.proposal},y.choice,I),Sn(S,_)})}async function He(y){return R(y,async(S,_)=>{if(O(S),S.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止,不能提交证据");let A=S.evidenceWaits?.find(q=>q.id===y.evidenceId);if(!A)throw new v("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(A.status!=="pending")throw new v("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(A.kind!==y.kind)throw new v("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!y.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(y.ref)||y.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(y.contentHash)||!y.submissionId.trim())throw new v("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let I=_.steps[A.stepId];if(!I||I.type!=="await_evidence"||I.kind!==y.kind)throw new v("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let W=f.get(Ue(I.validator));if(!W)throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let M=es(await W.validate({run:Oe(S),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:sr(y.context)}));if(!M.accepted||M.actualHash!==y.contentHash)throw new v("EVIDENCE_REJECTED",M.reason??"证据未通过验证或内容已改变");A.status="resolved",A.receipt={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId};let B=w(S,_,{kind:"evidence-recorded",stepId:A.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId},"succeeded");oo(S,_,A.stepId,A.sequence,A.results,{ref:y.ref,contentHash:y.contentHash},"succeeded",B),Sn(S,_)})}async function C(y){return R(y,async(S,_)=>{if(O(S),S.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止,不能使证据失效");let A=S.evidenceWaits?.find(V=>V.id===y.evidenceId);if(!A)throw new v("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(A.status!=="pending")throw new v("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(A.kind!==y.kind)throw new v("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!y.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(y.ref)||y.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(y.contentHash)||!y.submissionId.trim())throw new v("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let I=_.steps[A.stepId];if(!I||I.type!=="await_evidence"||I.kind!==y.kind)throw new v("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!_.transitions.some(V=>V.from===A.stepId&&V.on==="invalidated"))throw new v("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let W=f.get(Ue(I.validator));if(!W)throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let M=es(await W.validate({run:Oe(S),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:sr(y.context)}));if(M.accepted&&M.actualHash===y.contentHash)throw new v("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let B=(M.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);A.status="invalidated",A.invalidation={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:B};let q=w(S,_,{kind:"evidence-invalidated",stepId:A.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:B},"invalidated");oo(S,_,A.stepId,A.sequence,A.results,{ref:y.ref,contentHash:y.contentHash,reason:B},"invalidated",q),Sn(S,_)})}async function $(y){return R(y,S=>{O(S);let _=S.waits.find(A=>A.id===y.waitId);if(!_||_.status!=="pending"||_.proposalHash!==y.proposalHash)throw new v("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");_.proposal=Je(y.proposal),_.proposalHash=j(_.proposal)})}async function T(y){let S=await R(y,_=>{if(_.status==="completed"){if(y.stoppedActions?.length)throw new v("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let A=_.status==="cancelled";if(A||(_.actions=_.actions.map(I=>Fm(I,y.reason))),y.stoppedActions!==void 0){if(!Array.isArray(y.stoppedActions))throw new v("INVALID_ACTION","stoppedActions 必须是停止确认数组");let I=new Set;for(let W of y.stoppedActions){if(!W||typeof W!="object"||I.has(W.actionId))throw new v("INVALID_ACTION","停止确认重复或无效");I.add(W.actionId);let M=E(_,W.actionId);_.actions[_.actions.indexOf(M)]=Hm(M,W)}}if(!A){for(let I of _.waits)I.status==="pending"&&(I.status="cancelled");for(let I of _.evidenceWaits??[])I.status==="pending"&&(I.status="cancelled");_.ready=[],_.status="cancelled",_.reason=y.reason}});return S.status==="cancelled"&&await te(S),S}async function L(y){return R(y,S=>{if(!Array.isArray(y.stoppedActions)||!y.stoppedActions.length)throw new v("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let _=new Set;for(let A of y.stoppedActions){if(!A||typeof A!="object"||_.has(A.actionId))throw new v("INVALID_ACTION","停止确认重复或无效");_.add(A.actionId);let I=E(S,A.actionId);S.actions[S.actions.indexOf(I)]=Bm(I,A)}})}async function H(y){return R(y,S=>{O(S);let _=E(S,y.actionId);if(_.attempt!==y.attempt)throw new v("STALE_ACTION","Action 执行尝试已经改变");S.actions[S.actions.indexOf(_)]=BR(_,y.reason)})}async function ie(y){return R(y,async(S,_)=>{O(S);let A=E(S,y.actionId);if(A.attempt!==y.attempt)throw new v("STALE_ACTION","Action 执行尝试已经改变");if(A.type==="child_workflow")throw new v("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(A.status==="succeeded"&&e.validateRecovery){if(y.expectedRevision===void 0)throw new v("REVISION_CONFLICT","恢复已提交结果必须绑定当前 Run 版本");if(y.reconciliation!==void 0)throw new v("OUTCOME_ALREADY_RECORDED","已提交结果不能声明未执行;请使用应用的语义恢复");if(typeof y.proposalHash!="string"||!y.proposalHash.trim())throw new v("INVALID_REQUEST","恢复已提交结果必须绑定当前应用决定");if(S.actions.some(q=>["running","unknown"].includes(q.status)))throw new v("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(S.status!=="completed"||S.ready.length>0||S.actions.some(q=>q.status==="pending")||S.waits.some(q=>q.status==="pending")||S.evidenceWaits?.some(q=>q.status==="pending")||Object.values(S.joins).some(q=>Object.values(q).some(V=>V.length>0))||!A.outcome||A.outcome.status!=="succeeded")throw new v("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let I=es(await e.validateRecovery({run:Oe(S),action:Oe(A),outcome:Oe(A.outcome),context:sr(y.context),proposalHash:y.proposalHash}));if(!I.accepted)throw new v("ACTION_TERMINAL",I.reason??"应用拒绝恢复此结果");let W=A.outcome.event??"succeeded",M=w(S,_,{kind:"action-outcome",stepId:A.stepId,outcome:A.outcome},W);if(M?.length===0||M===void 0&&!_.transitions.some(q=>q.from===A.stepId&&q.on===W))throw new v("ACTION_TERMINAL","应用未声明可恢复的后续工作");let B=S.actionContexts[A.id];oo(S,_,A.stepId,B.sequence,B.results,A.outcome.output,W,M),Sn(S,_);return}if(A.status==="failed"){let I=S.actionContexts[A.id].sequence,W=B=>Object.hasOwn(B,A.stepId)&&B[A.stepId].sequence===I;if(Object.values(S.actionContexts).some(B=>W(B.results))||S.waits.some(B=>W(B.results))||S.evidenceWaits?.some(B=>W(B.results))||S.ready.some(B=>W(B.results))||Object.values(S.joins).some(B=>Object.values(B).some(q=>q.some(V=>W(V.results)))))throw new v("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}S.actions[S.actions.indexOf(A)]=VR(A,y.reconciliation),S.status="running",delete S.reason})}async function le(y,S){let _=c.get(y.executorId);if(!_)throw new v("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let A=S??await b(y.runId),I=E(A,y.actionId);if(I.status!=="pending")throw new v("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!Vg(_,I))throw new v("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");tn(y.context);let W=await ne({...y,attempt:I.attempt,inputHash:I.inputHash,claimToken:Hg(),capabilities:_.capabilities},!1,A),M=E(W,y.actionId),B;try{tn(y.context),B=await _.execute(Oe(M),sr(y.context),_.includeRun===!1?void 0:Oe(W))}catch(V){let Q=await b(y.runId),N=E(Q,M.id);throw Q.status!=="cancelled"&&N.status==="running"&&N.attempt===M.attempt&&await H({runId:y.runId,actionId:M.id,attempt:M.attempt,reason:V instanceof Error?V.message:String(V)}),new v("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let q=`${M.id}:${M.attempt}:executor-result`;try{return await P({runId:y.runId,context:sr(y.context),outcome:{...B,actionId:M.id,attempt:M.attempt,inputHash:M.inputHash,claimToken:M.claim.token,outcomeId:q}},!1,W)}catch(V){let Q=await b(y.runId),N=E(Q,M.id);if(N.receipts.some(oe=>oe.outcomeId===q)){if(N.rejectedOutcomes?.some(oe=>oe.outcome.outcomeId===q))throw V;if(N.outcome?.outcomeId===q)return Q}throw Q.status!=="cancelled"&&N.status==="running"&&N.attempt===M.attempt&&await H({runId:y.runId,actionId:M.id,attempt:M.attempt,reason:V instanceof Error?V.message.slice(0,4096):"执行结果无法提交"}),new v("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function Be(y){let S=y.maxActions??100;if(!Number.isSafeInteger(S)||S<1)throw new v("INVALID_REQUEST","maxActions 必须是正安全整数");let _=c.get(y.executorId);if(!_)throw new v("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let A=0,I=await b(y.runId),W=B=>({reason:B,run:I,actionsExecuted:A}),M=B=>{if(I.status==="completed"||I.status==="failed"||I.status==="cancelled")return I.status;if(I.actions.some(q=>q.status==="unknown"&&(!B||q.type!=="child_workflow")))return"execution-unknown";if(I.actions.some(q=>q.status==="running"&&(!B||q.type!=="child_workflow")))return"action-in-flight";if(I.waits.some(q=>q.status==="pending"))return"approval-required";if(I.evidenceWaits?.some(q=>q.status==="pending"))return"evidence-required"};for(;;){tn(y.context);let B=M(!0);if(B)return W(B);(I.ready.length||I.children.length)&&(I=await K({runId:y.runId,context:y.context}));let q=M(!1);if(q)return W(q);let V=I.actions.find(Q=>Q.status==="pending");if(!V)return W("idle");if(A>=S)return W("action-limit");if(!Vg(_,V)||V.requiredCapabilities.some(Q=>!_.capabilities.includes(Q)))return W("executor-required");A++;try{I=await le({...y,actionId:V.id},I)}catch(Q){if(!(Q instanceof v)||Q.code!=="EXECUTION_UNKNOWN"||(I=await b(y.runId),!I.actions.some(N=>N.status==="unknown")))throw Q;return W("execution-unknown")}}}async function Qe(y){let S=await Vs(e.store,y);return k(S.run,St),S}async function rr(y){return zm(await Qe(y.runId),y)}function Ce(y){return async(...S)=>{let _=S.map(A=>Bg(A));return Oe(await y(..._))}}return{start:Ce(G),dispatchCommand:Ce(J),inspect:Ce(b),inspectProjection:Qe,query:Ce(rr),inspectCurrent:async y=>await rr({runId:y,view:"current"}),executeCurrent:async y=>KE(await le(Bg(y))),runUntilBlockedCurrent:async y=>{let S=await Be(Bg(y));return{...S,run:KE(S.run)}},next:Ce(K),claim:Ce(ze),recordOutcome:Ce(F),resolveWait:Ce(re),recordEvidence:Ce(He),invalidateEvidence:Ce(C),reviseWait:Ce($),cancel:Ce(T),acknowledgeStopped:Ce(L),markUnknown:Ce(H),retry:Ce(ie),execute:Ce(y=>le(y)),runUntilBlocked:Ce(Be)}}To();Ri();import{createHash as oA,randomUUID as a9}from"node:crypto";import{types as QM}from"node:util";import{promises as kr}from"node:fs";import st from"node:path";import{randomUUID as JM}from"node:crypto";import{promises as ci}from"node:fs";import fc from"node:path";import{performance as ZE}from"node:perf_hooks";import{createRequire as zM}from"node:module";var KM=zM(import.meta.url??__filename),cd;function co(e,t){if(!cd){let r=process.emitWarning;process.emitWarning=((n,...i)=>{String(n instanceof Error?n.message:n).startsWith("SQLite is an experimental feature and might change at any time")||Reflect.apply(r,process,[n,...i])});try{cd=KM("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new cd(e):new cd(e,t)}import{AsyncLocalStorage as GM}from"node:async_hooks";var YE=new GM,Kg=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}};function XE(e){return Math.max(0,Math.min(e,(YE.getStore()?.deadline??1/0)-performance.now()))}function QE(){let e=YE.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new Kg}async function eA(e){let t,r;try{let n=await ci.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock metadata must be a regular file: "+e);r=[n.dev,n.ino,n.size,n.mtimeMs].join(":"),t=await ci.readFile(e,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{let n=JSON.parse(t),i=n.nonce??n.id,s=typeof n.createdAt=="number"?n.createdAt:Date.parse(n.createdAt);if(typeof i=="string"&&i&&Number.isFinite(s))return{owner:{nonce:i,createdAt:s,...n.protocolVersion===2?{protocolVersion:2}:{},...typeof n.operation=="string"?{operation:n.operation}:{}},token:i,legacy:n.protocolVersion!==2}}catch{}return{owner:null,token:r,legacy:!0}}async function YM(e){let t=e+".sqlite";try{let n=await ci.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock database must be a regular file: "+t)}catch(n){if(n.code!=="ENOENT")throw n}let r;try{r=co(fc.toNamespacedPath(t))}catch(n){throw new Error("Unable to open Runtime lock database "+t,{cause:n})}try{return r.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),r}catch(n){if(r.close(),/database is (?:locked|busy)/iu.test(String(n)))return null;throw new Error("Unable to acquire Runtime lock transaction "+t,{cause:n})}}function tA(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function XM(e,t={}){e=fc.resolve(e),await ci.mkdir(fc.dirname(e),{recursive:!0});let r=await ci.lstat(fc.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+fc.dirname(e));let n=ZE.now()+XE(t.timeoutMs??3e4),i;for(;QE(),i=await YM(e),!i;){if(ZE.now()>=n)throw new Error("Timed out waiting for file lock: "+e);await new Promise(c=>setTimeout(c,t.retryMs??20))}let s={protocolVersion:2,nonce:JM(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let c=await eA(e);if(c?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
|
|
153
|
+
Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));c&&await ci.unlink(e),await ci.writeFile(e,JSON.stringify(s),{mode:384,flag:"wx"})}catch(c){throw tA(i),c}let o=!1;return{owner:s,async release(){if(o)return!0;o=!0;let c=!0;try{let l=await eA(e);l?.token===s.nonce?l.owner?.createdAt===s.createdAt&&l.owner.operation===s.operation?await ci.unlink(e):(c=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
|
|
154
|
+
`)):l&&(c=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
|
|
155
|
+
`))}finally{tA(i)}return c}}}async function rA(e,t,r={}){let n=await XM(e,r),i;try{i=await t()}catch(s){try{await n.release()}catch(o){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(o)+`
|
|
156
|
+
`)}throw s}return await n.release(),i}jt();ye();nr();var nA=new WeakMap;function iA(e){return ld(e).encoded}function ld(e){let t=new WeakMap,r=new Map,n=a=>{if(typeof a=="string"){let m=r.get(a);return m===void 0&&(m=JSON.stringify(a).length,r.set(a,m)),m}if(a===null||typeof a!="object")return JSON.stringify(a).length;let d=nA.get(a)??t.get(a);if(d!==void 0)return d;let p=Object.entries(a),u=2+Math.max(0,p.length-1)+p.reduce((m,[h,g])=>m+(Array.isArray(a)?0:n(h)+1)+n(g),0);return t.set(a,u),pr(a)&&nA.set(a,u),u},i=n(e),s=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return s();let o=[],c=(a,d)=>{if(!a||typeof a!="object")return;let p=a;if(!(p.protocolVersion!==1||!Array.isArray(p.actions)||!p.actionContexts)){for(let[u,m]of p.actions.entries())m.input&&typeof m.input=="object"&&Object.hasOwn(m.input,"outputs")&&o.push({path:[...d,"actions",String(u),"input","outputs"],group:"outputs"});for(let[u,m]of Object.entries(p.actionContexts))m?.results&&o.push({path:[...d,"actionContexts",u,"results"],group:"results"});p.outputs&&o.push({path:[...d,"outputs"],group:"results"});for(let u of["ready","waits","evidenceWaits"])for(let[m,h]of(p[u]??[]).entries())h.results&&o.push({path:[...d,u,String(m),"results"],group:"results"})}};if(c(e,[]),c(e.run,["run"]),!o.length)return s();let l=DR(e,o,pr),f=JSON.stringify(l);return f.length<i*.9?{encoded:l,json:f}:s()}function rs(e){if(typeof e!="string"||e.trim().length===0)throw new v("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function ZM(e){return rs(e),oA("sha256").update(JSON.stringify(e)).digest("hex")}function ud(e){if(!Number.isSafeInteger(e)||e<1)throw new v("STORE_INVALID_REVISION","revision 必须是正安全整数")}function eF(e,t,r,n=!0){if(rs(e),QM.isProxy(r))throw new v("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&ud(t),mr(r);let i=n?structuredClone(r):r;if(!i||typeof i!="object"||Array.isArray(i)||i.runId!==e)throw new v("STORE_INVALID_RUN_ID","next.runId 必须与目标 runId 一致");if(ud(i.revision),i.revision!==(t??0)+1)throw new v("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}var sA="comet.runtime-store-checkpoint.v1";function tF(e,t,r){let n=Je(r);if(rs(e),!n||n.runId!==e)throw new v("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(ud(n.revision),t!==null&&t!==1||n.revision<=(t??0))throw new v("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(n)}function aA(e,t,r){let n=Je(e);n.revision=t;for(let i of r){let s=n;for(let o of i.slice(0,-1))s=s[o];s[i.at(-1)]=t}return n}function rF(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||yn(e)===yn(aA(r,1,n)))}function Mr(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new v("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(C=>{if(C!=="run.revision")throw new v("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function r(C){for(let $ of t){let T=C;for(let L of $){if(!T||typeof T!="object"||Array.isArray(T)||!Object.hasOwn(T,L))throw new v("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");T=T[L]}if(T!==C.revision)throw new v("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let n=st.resolve(e.rootDir),i=st.parse(n).root,s=st.relative(i,n).replaceAll("\\","/");if(!s)throw new v("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let o={label:"RuntimeStore root",expected:"directory"},c=ZM,l="checkpoint.json",f="comet.runtime-store-format.v2",a=".runtime-store-v2",d=C=>`${a}/${c(C)}`,p=C=>`.runtime-store-history/${c(C)}`,u="comet.runtime-store-format.v3",m="comet.runtime-store-snapshot.v2",h=".write.lock",g=/^[0-9]{16}\.json$/u;function w(){return{record:null,compacted:!1,legacyRevision:null,formatPresent:!1}}async function k(C,$){let T=await ae(n,C?`${C}/${$}`:$,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let L=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(T.bytes));return mr(L),L}catch{throw new v("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function b(C,$,T){if(!C||typeof C!="object"||Array.isArray(C)||C.runId!==$||C.revision!==T||!Number.isSafeInteger(T)||T<1)throw new v("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");r(C)}async function R(C,$=!1,T=c(C),L=!0){if(rs(C),!(await U(i,s,o)).exists)return w();let H=await U(n,T,{label:"RuntimeStore run",expected:"directory"});if(!H.exists)return w();let ie=await kr.lstat(H.target),le=await kr.readdir(H.target,{withFileTypes:!0}),Be=await kr.lstat(H.target);if(await U(i,`${s}/${T}`,o),!ie.isDirectory()||ie.isSymbolicLink()||!Be.isDirectory()||Be.isSymbolicLink()||!ar({dev:ie.dev,ino:ie.ino,birthtime:ie.birthtimeMs},{dev:Be.dev,ino:Be.ino,birthtime:Be.birthtimeMs}))throw new v("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let Qe=new Set,rr=[],Ce=0;for(let N of le){if((N.name===`${h}.contenders`||N.name==="legacy"&&T===d(C))&&N.isDirectory()&&!N.isSymbolicLink())continue;if(!N.isFile()||N.isSymbolicLink())throw new v("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);if(/^\..+\.tmp$/u.test(N.name)||N.name===h||[h+".sqlite",h+".sqlite-journal",h+".sqlite-wal",h+".sqlite-shm"].includes(N.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(N.name)||(Qe.add(N.name),N.name===l))continue;if(!g.test(N.name))throw new v("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);let oe=Number(N.name.slice(0,-5));if(!Number.isSafeInteger(oe)||oe<1)throw new v("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);rr.push(N.name),Ce=Math.max(Ce,oe)}let y=!1;if([d(C),p(C)].includes(T)&&rr.length>0)throw new v("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(Qe.has(l)){if(![d(C),p(C)].includes(T))throw new v("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let N=await k(T,l),oe=N?.record,Y=N?.legacyRevision;if(!N||![m,"comet.runtime-store-snapshot.v3"].includes(String(N.schema))||!oe||Object.keys(N).some(Ke=>!["schema","record","hash","legacyRevision",...N.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(Ke))||Y!==null&&(!Number.isSafeInteger(Y)||Y<1||Y>oe.revision)||N.hash!==j({record:oe,legacyRevision:Y,...N.schema==="comet.runtime-store-snapshot.v3"?{pool:N.pool}:{}}))throw new v("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let ue;try{ue=N.schema==="comet.runtime-store-snapshot.v3"?gu(oe,N.pool,L):oe}catch(Ke){throw new v("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${Ke instanceof Error?Ke.message:String(Ke)}`)}return b(ue,C,ue.revision),{record:ue,compacted:!0,legacyRevision:Y,formatPresent:y}}if(!Ce)return w();let S=new Map,_=N=>`${String(N).padStart(16,"0")}.json`,A=N=>Qe.has(_(N));async function I(N){if(S.has(N))return S.get(N);let oe=await k(T,_(N));return(N<=2||N===Ce)&&S.set(N,oe),oe}async function W(N,oe=0,Y=Ce){if(b(N,C,Y),$)for(let ue of rr){let Ke=Number(ue.slice(0,-5));Ke!==oe&&b(await I(Ke),C,Ke)}return{record:N,compacted:!1,legacyRevision:N.revision,formatPresent:!1}}let M=await I(Ce);if(Ce===rr.length&&(M?.schema!==sA||M?.runId!==void 0))return W(M);if(!A(1))throw new v("STORE_MISSING_REVISION","版本历史缺少 revision 1");let B=null;for(let N of[1,2]){if(!A(N))break;let oe=await I(N);if(oe?.schema!==sA||"runId"in oe)continue;let Y=oe.record;if(Y&&r(Y),!Y||Y.runId!==C||!Number.isSafeInteger(Y.revision)||Y.revision<N||oe.hash!==j(Y)||Object.keys(oe).some(ue=>!["schema","record","hash"].includes(ue))||N===2&&yn(await I(1))!==yn(aA(Y,1,t)))throw new v("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");B={slot:N,record:Y};break}let q=B?.record.revision??0,V=B?.slot??0,Q=Ce===V?q:Ce;if(Q<q||rr.length!==Q-q+V||rr.some(N=>{let oe=Number(N.slice(0,-5));return oe>V&&oe<=q})){let N=q+1;for(;A(N);)N+=1;throw new v("STORE_MISSING_REVISION",`版本历史缺少 revision ${N}`)}return W(B&&Ce===B.slot?B.record:M,V,B&&Ce===B.slot?B.record.revision:Ce)}async function E(C){let $=await U(n,c(C),{label:"RuntimeStore format",expected:"any"}),T=await U(n,`${d(C)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if($.kind==="directory"&&T.exists&&($=await U(n,c(C),{label:"RuntimeStore format",expected:"any"})),$.kind==="directory"&&T.exists)throw new v("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let L=null;if($.kind==="file"){let H=await k("",c(C));if(!H||H.runId!==C||(H.schema===f?!["pending","ready"].includes(H.state)||Object.keys(H).some(ie=>!["schema","runId","state","writerProtocol"].includes(ie)):H.schema!==u||!["closing","closed","reopening"].includes(H.state)||!Number.isSafeInteger(H.revision)||H.revision<1||typeof H.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(H.recordHash)||Object.keys(H).some(ie=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(ie))))throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(H.writerProtocol!==void 0&&H.writerProtocol!=="application-holder-v1")throw new v("STORE_WRITER_FENCED","存储协议版本不受支持");L=H}return{original:$,staged:T,marker:L}}function O(C){return Oa(C)?St(C,{cachePrefixes:!1}):j(C)}async function z(C,$){let T=await R(C,!1,d(C),!1),L=await R(C,!1,p(C),!1);if(!T.record&&!L.record||$.state==="closed"&&(T.record||!L.record))throw new v("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(T.record&&L.record){let ie=await kr.lstat(st.join(n,d(C),l)),le=await kr.lstat(st.join(n,p(C),l)),Be={dev:ie.dev,ino:ie.ino,birthtime:ie.birthtimeMs},Qe={dev:le.dev,ino:le.ino,birthtime:le.birthtimeMs};if(!Mc(Be,Qe)||!ar(Be,Qe))throw new v("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let H=L.record??T.record;if(H.revision!==$.revision||O(H)!==$.recordHash||T.record&&T.record!==H&&O(T.record)!==$.recordHash)throw new v("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:H,active:!!T.record,history:!!L.record}}async function D(C){if(rs(C),!(await U(i,s,o)).exists)return"missing";let $=await E(C),T=await U(n,`${d(C)}/${l}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),L=await U(n,`${p(C)}/${l}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if($.marker?.schema===u){if(!T.exists&&!L.exists||$.marker.state==="closed"&&(T.exists||!L.exists))throw new v("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return $.marker.state}if(L.exists)throw new v("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return $.marker||T.exists||$.original.kind==="directory"||$.staged.exists?"active":"missing"}async function G(C,$,T){await Te(st.join(n,c(C)),JSON.stringify({schema:u,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:C,state:$,revision:T.revision,recordHash:O(T)})+`
|
|
157
|
+
`,{containedRoot:n,requireAtomicPublication:!0})}async function J(C){let $=(await E(C)).marker;if(!$||!["closing","reopening"].includes($.state))return;let T=$.state==="closing",L=(await z(C,$)).record,H=await z(C,$),ie=T?d(C):p(C),le=T?p(C):d(C);await gt(n,le,{label:"RuntimeStore 历史目标"});let Be=st.join(n,ie,l),Qe=st.join(n,le,l),rr=T?H.active:H.history;(T?H.history:H.active)||(await U(n,`${ie}/${l}`,{label:"RuntimeStore 历史源",expected:"file"}),await U(n,le,{label:"RuntimeStore 历史目标",expected:"directory"}),await kr.link(Be,Qe),await z(C,$)),await ne(st.dirname(Qe)),await ne(st.dirname(st.dirname(Qe))),await ne(n),rr&&(await z(C,$),await zr(Be,{containedRoot:n,beforeRemove:async()=>{await z(C,$)}}),await ne(st.dirname(Be))),T?await G(C,"closed",L):await K(C,"ready",!1);let y=await Z(C,!1);if(!y||y.revision!==L.revision||O(y)!==O(L))throw new v("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function te(C,$,T){return rs(C),ud($),ze(C,async()=>{await J(C);let L=(await E(C)).marker,H;if(L?.schema===u){if(T&&L.state==="reopening")throw new v("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!T&&L.state==="closing")throw new v("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(H=(await z(C,L)).record,H.revision!==$)return!1;if(T&&L.state==="closed")return!0}else{if(H=(await re(C,!1)).record,!H||H.revision!==$)return!1;if(!T)return!0}return await G(C,T?"closing":"reopening",H),await J(C),!0})}async function Z(C,$=!0){if(rs(C),!(await U(i,s,o)).exists)return null;let T=await E(C);if(T.marker?.schema===u){let{record:ie}=await z(C,T.marker);return $?Jt(ie):ie}if((await R(C,!1,p(C),!1)).record)throw new v("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let H=await R(C,!1,d(C),$);if(H.record){if(!T.marker&&!(await E(C)).marker)throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return H.record}if(T.original.kind==="directory"){let ie=(await R(C)).record;if(!ie&&(await E(C)).original.kind!=="directory")throw new v("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return ie}if(T.marker?.state==="ready")throw new v("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(T.staged.exists){let ie;try{ie=(await R(C,!1,`${d(C)}/legacy`)).record}catch(le){throw(await E(C)).marker?.state==="ready"?new v("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):le}if(!ie){let le=await E(C);if(!le.staged.exists||le.marker?.state==="ready")throw new v("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return ie}return null}async function we(C,$=!0){for(let T=0;;T+=1)try{return await Z(C,$)}catch(L){let H=L instanceof mt&&L.reason==="changed",ie=["ENOENT","ENOTDIR"].includes(L.code??""),le=L instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(L.message);if(!H&&!ie&&!le||T>=15)throw L}}async function K(C,$,T){await Te(st.join(n,c(C)),JSON.stringify({schema:f,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:C,state:$})+`
|
|
158
|
+
`,{containedRoot:n,exclusive:T,requireAtomicPublication:!0})}async function ne(C){let $;try{$=await kr.open(C,"r"),await $.sync()}catch(T){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(T.code??""))throw T}finally{await $?.close()}}async function ze(C,$){if(await gt(i,s,o),(await U(n,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new v("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await gt(n,d(C),{label:"RuntimeStore run"}),await ne(st.join(n,a)),await ne(n);try{return e.singleWriter?await $():await rA(st.join(n,d(C),h),$)}catch(L){throw["ENOTSUP","EOPNOTSUPP"].includes(L.code??"")?new v("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):L}}async function P(C,$,T,L=ld($)){let H=st.join(n,d(C)),ie=T.legacyRevision,{encoded:le,json:Be}=L,Qe=le.pool?{record:le.record,legacyRevision:ie,pool:le.pool}:{record:$,legacyRevision:ie},rr=le.pool?"comet.runtime-store-snapshot.v3":m,Ce=`{"schema":${JSON.stringify(rr)},${Be.slice(1,-1)},"legacyRevision":${JSON.stringify(ie)},"hash":${JSON.stringify(j(Qe))}}
|
|
159
|
+
`;await Te(st.join(H,l),Ce,{containedRoot:n,exclusive:!T.compacted,requireAtomicPublication:!0}),T.formatPresent||await K(C,"ready",!1)}async function F(C,$){if($===null)return;let T=`${d(C)}/legacy`,L=await U(n,T,{label:"RuntimeStore legacy",expected:"directory"});if(L.exists)try{for(let H of await kr.readdir(L.target,{withFileTypes:!0}))H.isFile()&&!H.isSymbolicLink()&&g.test(H.name)&&Number(H.name.slice(0,-5))<=$&&await zr(st.join(L.target,H.name),{containedRoot:n});await U(n,T,{label:"RuntimeStore legacy",expected:"directory"}),await kr.rmdir(L.target).catch(H=>{if(H.code!=="ENOTEMPTY"&&H.code!=="EEXIST")throw H})}catch(H){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${H instanceof Error?H.message:String(H)}
|
|
160
|
+
`)}}async function re(C,$=!0){let T=(await E(C)).marker;if(T?.writerProtocol&&T.writerProtocol!==e.writerProtocol)throw new v("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await J(C);let L=await E(C);if(L.marker?.schema===u)throw new v("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await R(C,!1,p(C),!1)).record)throw new v("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let ie=await R(C,!1,d(C),$);if(ie.record&&!L.marker)throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(L.original.kind==="directory"){await R(C,!0);let Be=await kr.lstat(L.original.target);await U(i,`${s}/${c(C)}`,o),await U(n,d(C),o),await kr.rename(L.original.target,L.staged.target);let Qe=await kr.lstat(L.staged.target);if(!Qe.isDirectory()||Qe.isSymbolicLink()||!ar({dev:Be.dev,ino:Be.ino,birthtime:Be.birthtimeMs},{dev:Qe.dev,ino:Qe.ino,birthtime:Qe.birthtimeMs}))throw new v("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await ne(st.join(n,d(C))),await ne(n),L=await E(C)}if(!L.marker){try{await K(C,"pending",!0)}catch(Be){throw["EEXIST","EISDIR","ENOTDIR"].includes(Be.code??"")?new v("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):Be}L=await E(C)}let le=ie;if(!le.record&&L.marker?.state==="ready")throw new v("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!le.record&&L.staged.exists?(le=await R(C,!0,`${d(C)}/legacy`),le.record&&(await P(C,le.record,le),le={...le,compacted:!0,formatPresent:!0})):le.record&&L.marker?.state==="pending"&&await K(C,"ready",!1),le.record&&(le.formatPresent=!0,await F(C,le.legacyRevision)),le}return{queryScope:`file:${oA("sha256").update(n).digest("hex")}`,read:we,readProjection:C=>we(C,!1),readPartitionMetadata:D,settleRun:C=>Pn(async()=>await D(C)==="missing"?"missing":ze(C,async()=>{await J(C);let $=(await E(C)).marker;return $&&e.writerProtocol&&$.writerProtocol!==e.writerProtocol&&await Te(st.join(n,c(C)),JSON.stringify({...$,writerProtocol:e.writerProtocol})+`
|
|
161
|
+
`,{containedRoot:n,requireAtomicPublication:!0}),D(C)})),closeRun:(C,$)=>Pn(()=>te(C,$,!0)),reopenRun:(C,$)=>Pn(()=>te(C,$,!1)),async readDisposition(C){if(!await we(C,!1))return"missing";let T=(await E(C)).marker;return T?.schema===u?T.state:"active"},async restoreCheckpoint(C,$,T){let L=JSON.parse(tF(C,$,T));return r(L),ze(C,async()=>{let H=await re(C);return rF(H.record,$,L,t)?(await P(C,L,H),!0):!1})},compareAndSwap:async(C,$,T)=>He(C,$,T)(),prepareCompareAndSwap:He};function He(C,$,T){eF(C,$,T,!1),r(T);let{json:L}=ld(T),H=JSON.parse(L);return()=>ze(C,async()=>{let ie=await re(C,!1);return(ie.record?.revision??null)!==$?!1:(await P(C,H.record,ie,{encoded:H,json:L}),!0)})}}ye();import{isDeepStrictEqual as cA}from"node:util";var It="run_checkpoint",Gg="comet.workflow-run-checkpoint.v1",nF=/^portable-[a-f0-9]{64}$/u;function dd(e){return nF.test(e)?e:`portable-${j(e)}`}function fd(e){let t=iA(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:j(t)}:e}function pc(e,t){return cA(e,t)||cA(e,fd(t))}function lA(e){return{...e,revision:1,actions:e.actions.map(t=>{let r=new Set((t.rejectedOutcomes??[]).map(i=>i.outcome.outcomeId)),n={...t,receipts:t.receipts.filter(i=>!r.has(i.outcomeId)).map(i=>({...i}))};if(delete n.rejectedOutcomes,t.claim){let i=dd(t.claim.token);if(n.claim={...t.claim,token:i},t.executionStop&&(n.executionStop={...t.executionStop,claimToken:i}),t.cancellation&&(n.cancellation={...t.cancellation,claimToken:i}),t.outcome){n.outcome={...t.outcome,claimToken:i};let s=n.receipts.find(o=>o.outcomeId===t.outcome.outcomeId);s&&(s.hash=j(n.outcome))}}return t.status==="running"&&(n.status="unknown",n.reason="Portable recovery requires reconciliation of external execution"),n})}}var uA={hash:St,visitResults:mu,validateOrigins:hu};function iF(e){let t=Na(lA(e),e.runId,uA),r=St(t);return{schema:Gg,hash:r,run:t,sourceRevision:e.revision,sourceHash:j({hash:r,sourceRevision:e.revision})}}function lo(e){let t=Bs(lA(e),e.runId),r=j(t);return{schema:Gg,hash:r,run:t,sourceRevision:e.revision,sourceHash:j({hash:r,sourceRevision:e.revision})}}function dA(e,t,r={},n=!1){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Portable Run checkpoint for ${t} is invalid`);mr(e);let i=e;if(![Gg,"comet.workflow-run-checkpoint.v2"].includes(String(i.schema))||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash)||Object.keys(i).some(c=>!["schema","hash","run","sourceRevision","sourceHash",...i.schema==="comet.workflow-run-checkpoint.v2"?["pool","storageHash"]:[]].includes(c))||i.schema==="comet.workflow-run-checkpoint.v2"&&j({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let s=i.schema==="comet.workflow-run-checkpoint.v2"?gu(i.run,i.pool,!n):i.run;if((n?St:j)(s)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=n?Na(s,t,uA):Bs(s,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==j({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(r.preserveSourceRevision)return{...o,revision:i.sourceRevision}}return o}function rn(e,t,r={}){return dA(e,t,r)}function pd(e,t,r={}){return dA(e,t,r,!0)}function ns(e,t){if(e===void 0)return!1;let r=pd(e,t.runId,{preserveSourceRevision:!0});if(!r)return!1;let n=e,i=iF(t);return n.hash===i.hash&&n.sourceRevision===i.sourceRevision&&n.sourceHash===i.sourceHash&&r.revision===t.revision}function is(e){let t=structuredClone(e);for(let r of t.actions)r.claim&&!r.executionOrigin&&(r.executionOrigin={workflow:{...e.workflow}});return t}function Jg(e,t){if(!t.claim)throw new Error("执行绑定需要原领取记录");return{workflow:{...t.executionOrigin?.workflow??e.workflow},runId:e.runId,actionId:t.id,attempt:t.attempt,inputHash:t.inputHash,claimToken:dd(t.claim.token)}}var fA=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],uF={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}};function dF(e){return e.toISOString().slice(0,10)}function he(e,t,r,n){let i=e[r];e[r]=n,i!==n&&t.push({field:r,from:i,to:n})}function Pt(e,t,r={}){let n=uF[t];if(e.phase!==n.from)throw new Error(`Cannot apply ${t}: phase is '${e.phase}', expected '${n.from}'`);let i={...e},s=[],o=e.checkEpoch??0;if(!Number.isSafeInteger(o)||o<0||o===Number.MAX_SAFE_INTEGER)throw new Error("Invalid Classic check epoch");he(i,s,"checkEpoch",o+1);let c=r.now??new Date;if(t==="open-complete")he(i,s,"phase",i.workflow==="full"?"design":"build");else if(t==="design-complete")he(i,s,"phase","build");else if(t==="build-complete"){let l=i.verifyResult==="fail";he(i,s,"phase","verify"),he(i,s,"verifyResult","pending"),he(i,s,"branchStatus","pending"),l||he(i,s,"verificationReport",null)}else if(t==="verify-pass")he(i,s,"verifyResult","pass"),he(i,s,"verifyFailures",0),he(i,s,"phase","archive"),he(i,s,"verifiedAt",dF(c)),he(i,s,"archiveConfirmation","pending"),he(i,s,"branchStatus","pending");else if(t==="verify-fail")he(i,s,"verifyResult","fail"),he(i,s,"verifyFailures",i.verifyFailures+1),he(i,s,"phase","build"),he(i,s,"branchStatus","pending");else if(t==="preset-escalate"){if(i.workflow!=="hotfix"&&i.workflow!=="tweak")throw new Error(`Cannot apply ${t}: workflow must be hotfix or tweak, got '${i.workflow}'`);he(i,s,"workflow","full"),he(i,s,"classicProfile","full"),he(i,s,"phase","design"),he(i,s,"designDoc",null),he(i,s,"buildPause",null),he(i,s,"buildMode",null),he(i,s,"subagentDispatch",null),he(i,s,"tddMode",null),he(i,s,"reviewMode",null),he(i,s,"isolation",null),he(i,s,"boundBranch",null),he(i,s,"verifyMode",null),he(i,s,"directOverride",null)}else if(t==="archive-confirm"){if(i.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(i.archived)throw new Error(`Cannot apply ${t}: already archived`);he(i,s,"archiveConfirmation","confirmed")}else if(t==="archive-reopen"){if(i.archived)throw new Error(`Cannot apply ${t}: already archived`);he(i,s,"verifyResult","pending"),he(i,s,"verifyFailures",0),he(i,s,"phase","verify"),he(i,s,"verifiedAt",null),he(i,s,"archiveConfirmation",null),he(i,s,"branchStatus","pending")}else{if(i.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(i.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${t}: archiveConfirmation must be confirmed`);he(i,s,"archived",!0)}return{classic:i,effects:s,definition:n}}function pA(e){let t=e.state,r=[...e.actions].reverse().find(o=>o.stepId===t.workflow+".verify.run"),n=[...e.actions].reverse().find(o=>o.stepId===t.workflow+".verify.check"),i=e.evidenceWaits?.slice().reverse().find(o=>o.stepId===t.workflow+".verify.check.evidence");if(!r||!n||n.executionOrigin?.workflow.version!=="1"||n.status!=="succeeded"||n.outcome?.status!=="succeeded"||i?.status!=="resolved"||i.results[n.stepId]?.sequence!==e.actionContexts[n.id]?.sequence||e.actionContexts[n.id]?.results[r.stepId]?.sequence!==e.actionContexts[r.id]?.sequence)return null;let s=n.outcome.output;return s.scope!=="verify"||s.exitCode!==0||s.tier!=="full"||!Array.isArray(s.argv)||!s.argv.length||typeof s.receiptRef!="string"||typeof s.contentHash!="string"||i.receipt?.ref!==s.receiptRef||i.receipt.contentHash!==s.contentHash?null:{action:n,output:s}}function Yg(e,t,r){let n=Wr(t),i=j(n);if(e.workflow.version===n.version&&e.workflow.hash===i)return e;if(e.workflow.version===n.version)throw new Error("Classic 当前 Run 的 definition hash 不匹配;不能作为旧业务数据重新绑定。");if(!["1","2"].includes(e.workflow.version)||e.workflow.id!==n.id)throw new Error("Classic Run 不属于可升级的内置协议");let s=is(e),o=d=>Object.hasOwn(n.steps,d),c=new Set;for(let d of s.actions)!o(d.stepId)&&["pending","running","unknown"].includes(d.status)&&(c.add(d.stepId),d.status="cancelled",d.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let d of[...s.waits,...s.evidenceWaits??[]])!o(d.stepId)&&d.status==="pending"&&(c.add(d.stepId),d.status="cancelled");let l=s.ready;s.ready=l.filter(d=>o(d.to)&&(d.from===null||o(d.from)));for(let d of l)(!o(d.to)||d.from!==null&&!o(d.from))&&c.add(d.to);if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let d=e.reason.slice(15);o(d)||c.add(d)}let f=s.state;if(e.workflow.version==="1"&&f.phase==="verify"&&s.evidenceWaits?.some(d=>d.status==="pending"&&d.stepId.endsWith(".verify.report.evidence")))for(let d of s.evidenceWaits)d.status==="pending"&&d.stepId.endsWith(".verify.report.evidence")&&(d.status="cancelled",c.add(d.stepId));let a=s.actions.some(d=>["pending","running","unknown"].includes(d.status))||s.waits.some(d=>d.status==="pending")||s.evidenceWaits?.some(d=>d.status==="pending");if(c.size&&!a&&!s.ready.length&&!["completed","cancelled"].includes(e.status)){let d=[...s.actions].reverse().find(m=>m.stepId===f.workflow+".build.execute"&&m.status==="succeeded");if(!d)throw new Error("旧 Classic Run 缺少已接受的 Build 来源,原记录保持不变。");let p=f.phase==="build"&&r?r.apply({run:s,event:{kind:"action-outcome",stepId:d.stepId,outcome:d.outcome}}):void 0;p?s.state=p.state:f.phase==="build"&&(s.state=Pt(f,"build-complete").classic);let u=s.actionContexts[d.id];for(let m of p?.next??[f.workflow+".verify.run"])s.ready.push({from:d.stepId,to:typeof m=="string"?m:m.stepId,...typeof m=="string"?{}:{activation:m.input},results:{...u.results,[d.stepId]:{sequence:u.sequence,value:d.outcome.output}}});s.status="running",delete s.reason}s.workflow={id:n.id,version:n.version,hash:i};for(let d of Object.keys(s.definitionHashes))JSON.parse(d)[0]===n.id&&delete s.definitionHashes[d];return s.definitionHashes[JSON.stringify([n.id,n.version])]=i,s}jt();ye();var fF="@rpamis/comet",a3=`https://registry.npmjs.org/${fF}/latest`;ga();function ew(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var as=ew();function bA(e){as=e}var ss={exec:()=>null};function uo(e){let t=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=t[n];return i||(i=e(n),t[n]=i),i}}function ge(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(Ot.caret,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,t)};return n}var pF=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Ot={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:uo(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:uo(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:uo(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:uo(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:uo(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:uo(e=>new RegExp(`^ {0,${e}}>`))},mF=/^(?:[ \t]*(?:\n|$))+/,hF=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,gF=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,gc=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,wF=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,tw=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,RA=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,SA=ge(RA).replace(/bull/g,tw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),yF=ge(RA).replace(/bull/g,tw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),rw=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,vF=/^[^\n]+/,nw=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,kF=ge(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",nw).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),bF=ge(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,tw).getRegex(),yd="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",iw=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,RF=ge("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",iw).replace("tag",yd).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),CA=e=>ge(rw).replace("hr",gc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",yd).getRegex(),SF=CA(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),CF=CA(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),EF=ge(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",CF).getRegex(),sw={blockquote:EF,code:hF,def:kF,fences:gF,heading:wF,hr:gc,html:RF,lheading:SA,list:bF,newline:mF,paragraph:SF,table:ss,text:vF},mA=ge("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",gc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",yd).getRegex(),AF={...sw,lheading:yF,table:mA,paragraph:ge(rw).replace("hr",gc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",mA).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",yd).getRegex()},xF={...sw,html:ge(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",iw).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ss,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ge(rw).replace("hr",gc).replace("heading",` *#{1,6} *[^
|
|
162
|
+
]`).replace("lheading",SA).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_F=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,IF=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,EA=/^( {2,}|\\)\n(?!\s*$)/,PF=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Cn=/[\p{P}\p{S}]/u,fo=/[\s\p{P}\p{S}]/u,wc=/[^\s\p{P}\p{S}]/u,OF=ge(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,fo).getRegex(),TF=/[\p{Pi}\p{Ps}"']/u,AA=/(?!~)[\p{P}\p{S}]/u,NF=/(?!~)[\s\p{P}\p{S}]/u,$F=/(?:[^\s\p{P}\p{S}]|~)/u,jF=ge(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",pF?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),xA=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,DF=ge(xA,"u").replace(/punct/g,Cn).getRegex(),qF=ge(xA,"u").replace(/punct/g,AA).getRegex(),LF=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,WF=ge(LF,"u").replace(/openQuote/g,TF).replace(/punct/g,Cn).getRegex(),_A="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",MF=ge(_A,"gu").replace(/notPunctSpace/g,wc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),FF=ge(_A,"gu").replace(/notPunctSpace/g,$F).replace(/punctSpace/g,NF).replace(/punct/g,AA).getRegex(),HF="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",BF=ge(HF,"gu").replace(/notPunctSpace/g,wc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),VF=ge("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,wc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),UF="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",zF=ge(UF,"gu").replace(/notPunctSpace/g,wc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),KF=ge(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Cn).getRegex(),GF="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",JF=ge(GF,"gu").replace(/notPunctSpace/g,wc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),YF=ge(/\\(punct)/,"gu").replace(/punct/g,Cn).getRegex(),XF=ge(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),QF=ge(iw).replace("(?:-->|$)","-->").getRegex(),ZF=ge("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",QF).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),hd=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,eH=ge(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",hd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),IA=ge(/^!?\[(label)\]\[(ref)\]/).replace("label",hd).replace("ref",nw).getRegex(),PA=ge(/^!?\[(ref)\](?:\[\])?/).replace("ref",nw).getRegex(),tH=ge("reflink|nolink(?!\\()","g").replace("reflink",IA).replace("nolink",PA).getRegex(),hA=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ow={_backpedal:ss,anyPunctuation:YF,autolink:XF,blockSkip:jF,br:EA,code:IF,del:ss,delLDelim:ss,delRDelim:ss,emStrongLDelim:DF,emStrongRDelimAst:MF,emStrongRDelimUnd:VF,escape:_F,link:eH,nolink:PA,punctuation:OF,reflink:IA,reflinkSearch:tH,tag:ZF,text:PF,url:ss},rH={...ow,emStrongLDelim:WF,emStrongRDelimAst:BF,emStrongRDelimUnd:zF,link:ge(/^!?\[(label)\]\((.*?)\)/).replace("label",hd).getRegex(),reflink:ge(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",hd).getRegex()},Xg={...ow,emStrongRDelimAst:FF,emStrongLDelim:qF,delLDelim:KF,delRDelim:JF,url:ge(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",hA).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:ge(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",hA).getRegex()},nH={...Xg,br:ge(EA).replace("{2,}","*").getRegex(),text:ge(Xg.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},md={normal:sw,gfm:AF,pedantic:xF},mc={normal:ow,gfm:Xg,breaks:nH,pedantic:rH},iH={"&":"&","<":"<",">":">",'"':""","'":"'"},gA=e=>iH[e];function nn(e,t){if(t){if(Ot.escapeTest.test(e))return e.replace(Ot.escapeReplace,gA)}else if(Ot.escapeTestNoEncode.test(e))return e.replace(Ot.escapeReplaceNoEncode,gA);return e}function wA(e){try{e=encodeURI(e).replace(Ot.percentDecode,"%")}catch{return null}return e}function yA(e,t){let r=e.replace(Ot.findPipe,(s,o,c)=>{let l=!1,f=o;for(;--f>=0&&c[f]==="\\";)l=!l;return l?"|":" |"}),n=r.split(Ot.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(Ot.slashPipe,"|");return n}function li(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let s=e.charAt(n-i-1);if(s===t&&!r)i++;else if(s!==t&&r)i++;else break}return e.slice(0,n-i)}function vA(e){let t=e.split(`
|
|
163
|
+
`),r=t.length-1;for(;r>=0&&Ot.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
164
|
+
`)}function sH(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function oH(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let s=4-r%4;n+=" ".repeat(s),r+=s}else n+=i,r++;return n}function kA(e,t,r,n,i){let s=t.href,o=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";n.state.inLink=!0;let f=n.state.linkEmitted,a=n.state.inRawBlock;n.state.linkEmitted=!1;let d=n.inlineTokens(c),p=n.state.linkEmitted;if(n.state.linkEmitted=f,n.state.inLink=!1,!l){if(p){n.state.inRawBlock=a;return}n.state.linkEmitted=!0}return{type:l?"image":"link",raw:r,href:s,title:o,text:c,tokens:d}}function aH(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
|
|
165
|
+
`).map(s=>{let o=s.match(r.other.beginningSpace);if(o===null)return s;let[c]=o;return c.length>=i.length?s.slice(i.length):s}).join(`
|
|
166
|
+
`)}var gd=class{options;rules;lexer;constructor(e){this.options=e||as}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:vA(t[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=aH(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=li(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:li(t[0],`
|
|
167
|
+
`),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:li(t[0],`
|
|
168
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=li(t[0],`
|
|
169
|
+
`).split(`
|
|
170
|
+
`),n="",i="",s=[];for(;r.length>0;){let o=!1,c=[],l;for(l=0;l<r.length;l++)if(this.rules.other.blockquoteStart.test(r[l]))c.push(r[l]),o=!0;else if(!o)c.push(r[l]);else break;r=r.slice(l);let f=c.join(`
|
|
171
|
+
`),a=f.replace(this.rules.other.blockquoteSetextReplace,`
|
|
172
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
173
|
+
${f}`:f,i=i?`${i}
|
|
174
|
+
${a}`:a;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(a,s,!0),this.lexer.state.top=d,r.length===0)break;let p=s.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let u=p,m=r.join(`
|
|
175
|
+
`),h=u.raw+`
|
|
176
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(h);s[s.length-1]=g,n=`${n}
|
|
177
|
+
${m}`,i=i.substring(0,i.length-u.text.length)+g.text;break}else if(p?.type==="list"){let u=p,m=u.raw+`
|
|
178
|
+
`+r.join(`
|
|
179
|
+
`),h=this.list(m);s[s.length-1]=h,n=n.substring(0,n.length-p.raw.length)+h.raw,i=i.substring(0,i.length-u.raw.length)+h.raw,r=m.substring(s.at(-1).raw.length).split(`
|
|
180
|
+
`);continue}}return{type:"blockquote",raw:n,tokens:s,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let s=this.rules.other.listItemRegex(r),o=!1;for(;e;){let l=!1,f="",a="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let d=oH(t[2].split(`
|
|
181
|
+
`,1)[0],t[1].length),p=e.split(`
|
|
182
|
+
`,1)[0],u=!d.trim(),m=0;if(this.options.pedantic?(m=2,a=d.trimStart()):u?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,a=d.slice(m),m+=t[1].length),u&&this.rules.other.blankLine.test(p)&&(f+=p+`
|
|
183
|
+
`,e=e.substring(p.length+1),l=!0),!l){let h=this.rules.other.nextBulletRegex(m),g=this.rules.other.hrRegex(m),w=this.rules.other.fencesBeginRegex(m),k=this.rules.other.headingBeginRegex(m),b=this.rules.other.htmlBeginRegex(m),R=this.rules.other.blockquoteBeginRegex(m);for(;e;){let E=e.split(`
|
|
184
|
+
`,1)[0],O;if(p=E,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),O=p):O=p.replace(this.rules.other.tabCharGlobal," "),w.test(p)||k.test(p)||b.test(p)||R.test(p)||h.test(p)||g.test(p))break;if(O.search(this.rules.other.nonSpaceChar)>=m||!p.trim())a+=`
|
|
185
|
+
`+O.slice(m);else{if(u||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||k.test(d)||g.test(d))break;a+=`
|
|
186
|
+
`+p}u=!p.trim(),f+=E+`
|
|
187
|
+
`,e=e.substring(E.length+1),d=O.slice(m)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(o=!0)),i.items.push({type:"list_item",raw:f,task:!!this.options.gfm&&this.rules.other.listIsTask.test(a),loose:!1,text:a,tokens:[]}),i.raw+=f}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!i.loose){let f=l.tokens.filter(d=>d.type==="space"),a=f.length>0&&f.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=a}for(let l of i.items){let f=l.tokens[0];if(l.task&&(f?.type==="text"||f?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),f.raw=f.raw.replace(this.rules.other.listReplaceTask,""),f.text=f.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let a=this.rules.other.listTaskCheckbox.exec(l.raw);if(a){let d={type:"checkbox",raw:a[0]+" ",checked:a[0]!=="[ ]"};l.checked=d.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1)}if(i.loose)for(let l of i.items){l.loose=!0;for(let f of l.tokens)f.type==="text"&&(f.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=vA(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:li(t[0],`
|
|
188
|
+
`),href:n,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=yA(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
189
|
+
`):[],s={type:"table",raw:li(t[0],`
|
|
190
|
+
`),header:[],align:[],rows:[]};if(r.length===n.length){for(let o of n)this.rules.other.tableAlignRight.test(o)?s.align.push("right"):this.rules.other.tableAlignCenter.test(o)?s.align.push("center"):this.rules.other.tableAlignLeft.test(o)?s.align.push("left"):s.align.push(null);for(let o=0;o<r.length;o++)s.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:s.align[o]});for(let o of i)s.rows.push(yA(o,s.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:s.align[l]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:li(t[0],`
|
|
191
|
+
`),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
|
|
192
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let s=li(r.slice(0,-1),"\\");if((r.length-s.length)%2===0)return}else{let s=sH(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(n);s&&(n=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),kA(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[n.toLowerCase()];if(!i){let s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return kA(r,i,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,s,o,c=i,l=0,f=n[0][0],a=r===f,d=f==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(n=d.exec(t))!==null;){if(s=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!s)continue;if(o=[...s].length,n[3]||n[4]){c+=o;continue}else if(n[5]||n[6]){if(i%3&&!((i+o)%3)){l+=o;continue}if(a)break}if(c-=o,c>0)continue;o=Math.min(o,o+c+l);let p=[...n[0]][0].length,u=e.slice(0,i+n.index+p+o);if(Math.min(i,o)%2){let h=u.slice(1,-1);return{type:"em",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}let m=u.slice(2,-2);return{type:"strong",raw:u,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,s,o,c=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+i);(n=l.exec(t))!==null;){if(s=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!s||(o=[...s].length,o!==i))continue;if(n[3]||n[4]){c+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c);let f=[...n[0]][0].length,a=e.slice(0,i+n.index+f+o),d=a.slice(i,-i);return{type:"del",raw:a,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},br=class Qg{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||as,this.options.tokenizer=this.options.tokenizer||new gd,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:Ot,block:md.normal,inline:mc.normal};this.options.pedantic?(r.block=md.pedantic,r.inline=mc.pedantic):this.options.gfm&&(r.block=md.gfm,this.options.breaks?r.inline=mc.breaks:r.inline=mc.gfm),this.tokenizer.rules=r}static get rules(){return{block:md,inline:mc}}static lex(t,r){return new Qg(r).lex(t)}static lexInline(t,r){return new Qg(r).inlineTokens(t)}lex(t){t=t.replace(Ot.carriageReturn,`
|
|
193
|
+
`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Ot.tabCharGlobal," ").replace(Ot.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let s;if(this.options.extensions?.block?.some(c=>(s=c.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.space(t)){t=t.substring(s.raw.length);let c=r.at(-1);s.raw.length===1&&c!==void 0?c.raw+=`
|
|
194
|
+
`:r.push(s);continue}if(s=this.tokenizer.code(t)){t=t.substring(s.raw.length);let c=r.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
195
|
+
`)?"":`
|
|
196
|
+
`)+s.raw,c.text+=`
|
|
197
|
+
`+s.text,this.inlineQueue.at(-1).src=c.text):r.push(s);continue}if(s=this.tokenizer.fences(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.heading(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.hr(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.blockquote(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.list(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.html(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.def(t)){t=t.substring(s.raw.length);let c=r.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
198
|
+
`)?"":`
|
|
199
|
+
`)+s.raw,c.text+=`
|
|
200
|
+
`+s.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},r.push(s));continue}if(s=this.tokenizer.table(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.lheading(t)){t=t.substring(s.raw.length),r.push(s);continue}let o=t;if(this.options.extensions?.startBlock){let c=1/0,l=t.slice(1),f;this.options.extensions.startBlock.forEach(a=>{f=a.call({lexer:this},l),typeof f=="number"&&f>=0&&(c=Math.min(c,f))}),c<1/0&&c>=0&&(o=t.substring(0,c+1))}if(this.state.top&&(s=this.tokenizer.paragraph(o))){let c=r.at(-1);n&&c?.type==="paragraph"?(c.raw+=(c.raw.endsWith(`
|
|
201
|
+
`)?"":`
|
|
202
|
+
`)+s.raw,c.text+=`
|
|
203
|
+
`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):r.push(s),n=o.length!==t.length,t=t.substring(s.raw.length);continue}if(s=this.tokenizer.text(t)){t=t.substring(s.raw.length);let c=r.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
204
|
+
`)?"":`
|
|
205
|
+
`)+s.raw,c.text+=`
|
|
206
|
+
`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],s=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(s+1,-1)))&&!(s>1&&this.linkInText(i.slice(1,s-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let c=this.tokenizer.rules.inline.reflinkSearch,l=f=>{let a=f.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,f.slice(a+1,-1)))return f;if(a>1&&f.charAt(0)!=="!"){let d=f.slice(1,a-1);if(this.linkInText(d))return"["+d.replace(c,l)+"]["+"a".repeat(f.length-a-2)+"]"}return"["+"a".repeat(f.length-2)+"]"};n=n.replace(c,l)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,c=>"+".repeat(c.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(c,l,f)=>{let a=f?f.length:0;return c.slice(0,a)+"["+"a".repeat(c.length-a-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,s="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(s=""),i=!1;let c;if(this.options.extensions?.inline?.some(f=>(c=f.call({lexer:this},t,r))?(t=t.substring(c.raw.length),r.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let f=r.at(-1);c.type==="text"&&f?.type==="text"?(f.raw+=c.raw,f.text+=c.text):r.push(c);continue}if(c=this.tokenizer.emStrong(t,n,s)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.del(t,n,s)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),r.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),r.push(c);continue}let l=t;if(this.options.extensions?.startInline){let f=1/0,a=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},a),typeof d=="number"&&d>=0&&(f=Math.min(f,d))}),f<1/0&&f>=0&&(l=t.substring(0,f+1))}if(c=this.tokenizer.inlineText(l)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(s=c.raw.slice(-1)),i=!0;let f=r.at(-1);f?.type==="text"?(f.raw+=c.raw,f.text+=c.text):r.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},wd=class{options;parser;constructor(e){this.options=e||as}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(Ot.notSpaceStart)?.[0],i=e.replace(Ot.endingNewline,"")+`
|
|
207
|
+
`;return n?'<pre><code class="language-'+nn(n)+'">'+(r?i:nn(i,!0))+`</code></pre>
|
|
208
|
+
`:"<pre><code>"+(r?i:nn(i,!0))+`</code></pre>
|
|
209
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
210
|
+
${this.parser.parse(e)}</blockquote>
|
|
211
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
212
|
+
`}hr(e){return`<hr>
|
|
213
|
+
`}list(e){let t=e.ordered,r=e.start,n="";for(let o=0;o<e.items.length;o++){let c=e.items[o];n+=this.listitem(c)}let i=t?"ol":"ul",s=t&&r!==1?' start="'+r+'"':"";return"<"+i+s+`>
|
|
214
|
+
`+n+"</"+i+`>
|
|
215
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
216
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
217
|
+
`}table(e){let t="",r="";for(let i=0;i<e.header.length;i++)r+=this.tablecell(e.header[i]);t+=this.tablerow({text:r});let n="";for(let i=0;i<e.rows.length;i++){let s=e.rows[i];r="";for(let o=0;o<s.length;o++)r+=this.tablecell(s[o]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
|
|
218
|
+
<thead>
|
|
219
|
+
`+t+`</thead>
|
|
220
|
+
`+n+`</table>
|
|
221
|
+
`}tablerow({text:e}){return`<tr>
|
|
222
|
+
${e}</tr>
|
|
223
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
224
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${nn(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),i=wA(e);if(i===null)return n;e=i;let s='<a href="'+e+'"';return t&&(s+=' title="'+nn(t)+'"'),s+=">"+n+"</a>",s}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=wA(e);if(i===null)return nn(r);e=i;let s=`<img src="${e}" alt="${nn(r)}"`;return t&&(s+=` title="${nn(t)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:nn(e.text)}},aw=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Fr=class Zg{options;renderer;textRenderer;constructor(t){this.options=t||as,this.options.renderer=this.options.renderer||new wd,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new aw}static parse(t,r){return new Zg(r).parse(t)}static parseInline(t,r){return new Zg(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let n=0;n<t.length;n++){let i=t[n];if(this.options.extensions?.renderers?.[i.type]){let o=i,c=this.options.extensions.renderers[o.type].call({parser:this},o);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=c||"";continue}}let s=i;switch(s.type){case"space":{r+=this.renderer.space(s);break}case"hr":{r+=this.renderer.hr(s);break}case"heading":{r+=this.renderer.heading(s);break}case"code":{r+=this.renderer.code(s);break}case"table":{r+=this.renderer.table(s);break}case"blockquote":{r+=this.renderer.blockquote(s);break}case"list":{r+=this.renderer.list(s);break}case"checkbox":{r+=this.renderer.checkbox(s);break}case"html":{r+=this.renderer.html(s);break}case"def":{r+=this.renderer.def(s);break}case"paragraph":{r+=this.renderer.paragraph(s);break}case"text":{r+=this.renderer.text(s);break}default:{let o='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(s.type)){n+=c||"";continue}}let o=s;switch(o.type){case"escape":{n+=r.text(o);break}case"html":{n+=r.html(o);break}case"link":{n+=r.link(o);break}case"image":{n+=r.image(o);break}case"checkbox":{n+=r.checkbox(o);break}case"strong":{n+=r.strong(o);break}case"em":{n+=r.em(o);break}case"codespan":{n+=r.codespan(o);break}case"br":{n+=r.br(o);break}case"del":{n+=r.del(o);break}case"text":{n+=r.text(o);break}default:{let c='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return n}},hc=class{options;block;constructor(e){this.options=e||as}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?br.lex:br.lexInline}provideParser(e=this.block){return e?Fr.parse:Fr.parseInline}},cH=class{defaults=ew();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fr;Renderer=wd;TextRenderer=aw;Lexer=br;Tokenizer=gd;Hooks=hc;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let i=n;for(let s of i.header)r=r.concat(this.walkTokens(s.tokens,t));for(let s of i.rows)for(let o of s)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let i=n;r=r.concat(this.walkTokens(i.items,t));break}default:{let i=n;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(s=>{let o=i[s].flat(1/0);r=r.concat(this.walkTokens(o,t))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...o){let c=i.renderer.apply(this,o);return c===!1&&(c=s.apply(this,o)),c}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),n.extensions=t),r.renderer){let i=this.defaults.renderer||new wd(this.defaults);for(let s in r.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,c=r.renderer[o],l=i[o];i[o]=(...f)=>{let a=c.apply(i,f);return a===!1&&(a=l.apply(i,f)),a||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new gd(this.defaults);for(let s in r.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,c=r.tokenizer[o],l=i[o];i[o]=(...f)=>{let a=c.apply(i,f);return a===!1&&(a=l.apply(i,f)),a}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new hc;for(let s in r.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,c=r.hooks[o],l=i[o];hc.passThroughHooks.has(s)?i[o]=f=>{if(this.defaults.async&&hc.passThroughHooksRespectAsync.has(s))return(async()=>{let d=await c.call(i,f);return l.call(i,d)})();let a=c.call(i,f);return l.call(i,a)}:i[o]=(...f)=>{if(this.defaults.async)return(async()=>{let d=await c.apply(i,f);return d===!1&&(d=await l.apply(i,f)),d})();let a=c.apply(i,f);return a===!1&&(a=l.apply(i,f)),a}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,s=r.walkTokens;n.walkTokens=function(o){let c=[];return c.push(s.call(this,o)),i&&(c=c.concat(i.call(this,o))),c}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return br.lex(e,t??this.defaults)}parser(e,t){return Fr.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},s=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer(e):e?br.lex:br.lexInline)(o,i),l=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let f=await(i.hooks?await i.hooks.provideParser(e):e?Fr.parse:Fr.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(f):f})().catch(s);try{i.hooks&&(t=i.hooks.preprocess(t));let o=(i.hooks?i.hooks.provideLexer(e):e?br.lex:br.lexInline)(t,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?Fr.parse:Fr.parseInline)(o,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(o){return s(o)}}}onError(e,t){return r=>{if(r.message+=`
|
|
225
|
+
Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+nn(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},os=new cH;function qe(e,t){return os.parse(e,t)}qe.options=qe.setOptions=function(e){return os.setOptions(e),qe.defaults=os.defaults,bA(qe.defaults),qe};qe.getDefaults=ew;qe.defaults=as;function lH(...e){return os.use(...e),qe.defaults=os.defaults,bA(qe.defaults),qe}qe.use=lH;qe.walkTokens=function(e,t){return os.walkTokens(e,t)};qe.parseInline=os.parseInline;qe.Parser=Fr;qe.parser=Fr.parse;qe.Renderer=wd;qe.TextRenderer=aw;qe.Lexer=br;qe.lexer=br.lex;qe.Tokenizer=gd;qe.Hooks=hc;qe.parse=qe;var l3=qe.options,u3=qe.setOptions,uH=qe.walkTokens,d3=qe.parseInline;var f3=Fr.parse,p3=br.lex;ye();jt();ye();ye();ye();ye();function kd(e){return e.ref==="classic-archive"&&(e.status==="running"||e.status==="unknown"||e.status==="cancelled"&&!!e.claim&&!e.outcome)}function ui(e){return e.status==="cancelled"&&e.children.length===0&&e.actions.every(t=>!["pending","running","unknown"].includes(t.status)&&!kd(t))&&e.waits.every(t=>t.status!=="pending")&&(e.evidenceWaits??[]).every(t=>t.status!=="pending")&&e.ready.length===0}function bd(e,t){let r=e.state;return(t==="hotfix"||t==="tweak")&&e.workflow.id===`comet-classic-${t}`&&r?.workflow==="full"&&r.classicProfile==="full"&&e.waits.some(n=>n.stepId===`${t}.build.escalation-confirm`&&n.status==="resolved"&&n.decision?.choice==="upgrade"&&n.decision.proposalHash===n.proposalHash)}import _o from"node:path";ye();var pV=bt(Dt(),1);ye();import{AsyncLocalStorage as gH}from"async_hooks";import{promises as TA}from"fs";import yc from"path";var po=new gH;function wH(e,t){let r=yc.relative(e,t);return r===""||!yc.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${yc.sep}`)}async function yH(e){let t=yc.resolve(e.invocationCwd??process.cwd()),r=yc.resolve(e.projectRoot??await ut(t)),[n,i]=await Promise.all([TA.realpath(t),TA.realpath(r)]);if(!wH(i,n))throw new Error(`Classic command invocation cwd is outside the discovered project: ${t}`);return{invocationCwd:t,projectRoot:r,observations:new Map}}async function vH(e,t){let r=po.getStore();if(r)return t(r);let n=await yH(e);return po.run(n,()=>t(n))}function NA(){let e=po.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}async function $A(e,t){let r=po.getStore();if(!r?.observations)return t();let n=r.observations.get(e);if(n)return n;let i=t();r.observations.set(e,i);try{return await i}catch(s){throw r.observations.delete(e),s}}async function vc(e){let t=po.getStore();if(!t)return e();t.observations?.clear();try{return await po.run({...t,observations:null},e)}finally{t.observations?.clear()}}function jA(e){return(t,r)=>vH(r,()=>e(t,r))}ye();import{promises as Rd}from"fs";import Hr from"path";async function mo(e,t){let r=[],n=new Set;async function i(s,o){let c=await hn(e,s,{label:"Classic capability directory",expected:"directory"});if(!c.exists)return;let l=await Rd.realpath(c.target);if(n.has(l))throw new Error(`Classic capability directory cycle: ${s}`);if(n.add(l),o){let a=`${s}/spec.md`;(await hn(e,a,{label:"Classic capability spec",expected:"file"})).exists&&r.push(a)}let f=(await Rd.readdir(c.target,{withFileTypes:!0})).sort((a,d)=>a.name.localeCompare(d.name));for(let a of f)if(a.isDirectory()||a.isSymbolicLink()){if(a.name==="spec.md")continue;await i(`${s}/${a.name}`,!0)}n.delete(l)}return await i(t.replaceAll("\\","/"),!1),r}function ho(e){return e?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e)?e.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${e}'
|
|
226
|
+
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function sn(e){let t=ho(e);if(t)throw new Error(t)}async function En(e,t){sn(t);let r=[],n=async i=>(await U(e,Hr.relative(e,i),{label:"Classic change directory",expected:"directory"}),fe(i));for(let i of["openspec/changes","docs/openspec/changes"]){r.push(await n(Hr.join(e,i,t)));let s=Hr.join(e,i,"archive"),o=await Sd(e,s,t);for(let c of o??[])c===t?await n(Hr.join(s,c)):cw(c,t)&&r.push(await n(Hr.join(s,c)))}return r}function kH(e,t){return{label:be(e,t),directory:t}}async function kc(e,t,r){let n=kH(e,t);if(!(await hn(e,t,{label:r,expected:"directory"})).exists)return{change:n,exists:!1,stateExists:!1};let s=await hn(e,await fe(t),{label:`${r} state`,expected:"file"});return{change:n,exists:!0,stateExists:s.exists}}var bH=/^\d{4}-\d{2}-\d{2}-/u;function cw(e,t){return e.slice(11)===t&&bH.test(e)}async function Sd(e,t,r){sn(r);let n=()=>U(e,Hr.relative(e,t),{label:"Classic Archive directory",expected:"directory"}),i=await n();if(!i.exists)return null;let s=async()=>{let l=await Rd.lstat(i.target,{bigint:!0});if(!l.isDirectory()||l.isSymbolicLink())throw new Error("Classic Archive directory must be a real directory");return[l.dev,l.ino,l.mode,l.size,l.mtimeNs,l.ctimeNs].join(":")},o=await s(),c=await $A(`classic-archive:${JSON.stringify([i.target,r,o])}`,async()=>{let l=await Rd.readdir(i.target);if(await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return l.filter(f=>f===r||cw(f,r))});if(!(await n()).exists||await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return c}async function DA(e,t,r,n={}){if(!n.skipExactCompatibility){let o=await kc(e,Hr.join(t,r),`Classic archived change ${r}`);if(o.exists)return o.change}let i=await Sd(e,t,r),s=[];for(let o of i??[]){if(o===r)continue;let c=await kc(e,Hr.join(t,o),`Classic archived change ${o}`);c.exists&&c.stateExists&&s.push(c.change)}return s.sort((o,c)=>c.directory.localeCompare(o.directory))[0]??null}async function An(e,t=process.cwd()){sn(e);let r=await wt(t),n=await kc(r.projectRoot,Hr.join(r.changesDir,e),`Classic active change ${e}`);return{...n.change,exists:n.exists,stateExists:n.stateExists}}async function lw(e,t=process.cwd(),r={}){sn(e);let n=await wt(t);if(r.preferredArchiveName!==void 0){let i=r.preferredArchiveName;if(i!==e&&!cw(i,e))throw new Error(`Classic preferred archive name '${i}' does not belong to change '${e}'`);let s=await kc(n.projectRoot,Hr.join(n.archiveDir,i),`Classic preferred archived change ${i}`);return s.exists&&s.stateExists?s.change:null}return DA(n.projectRoot,n.archiveDir,e,r)}async function Cd(e,t=process.cwd()){sn(e);let r=await wt(t),n=await kc(r.projectRoot,Hr.join(r.changesDir,e),`Classic active change ${e}`);if(n.exists)return n.change;let i=await DA(r.projectRoot,r.archiveDir,e);return i||n.change}Ri();var $w=bt(Dt(),1);import{execFileSync as vi}from"node:child_process";import Er from"node:path";import{isDeepStrictEqual as Nw}from"node:util";import{execFileSync as BA}from"node:child_process";var RH=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_PREFIX","GIT_IMPLICIT_WORK_TREE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"]);function qA(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>{let r=t.toUpperCase();return!RH.has(r)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(r)}))}function LA(e){return{...qA(e.environment),...e.authentication?{}:{GIT_CONFIG_GLOBAL:process.platform==="win32"?"NUL":"/dev/null",GIT_CONFIG_NOSYSTEM:"1"},GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",SSH_ASKPASS_REQUIRE:"never",GIT_NO_REPLACE_OBJECTS:"1",GH_PROMPT_DISABLED:"1"}}import{spawn as w5,execFileSync as _H}from"node:child_process";import dw from"node:path";import{existsSync as uw,readFileSync as SH}from"node:fs";import Rr from"node:path";var CH=/[&|<>()^%"!\r\n]/u,d5=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function WA(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function EH(e){let t=(WA(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function AH(e,t,r){let i=Rr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(WA(t,"PATH")??"").split(Rr.delimiter).map(c=>c.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Rr.win32.extname(e)?[e]:EH(t).map(c=>`${e}${c}`);return i.flatMap(c=>o.map(l=>c?Rr.join(c,l):Rr.resolve(r,l)))}function go(e,t,r){return AH(e,t,r).find(n=>uw(n))??e}function xH(e){let t=e.replaceAll(`\r
|
|
227
|
+
`,`
|
|
228
|
+
`).trim(),r=/^@"([^"%\r\n]+)" "%~dp0([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(r&&Rr.win32.isAbsolute(r[1])&&Rr.win32.basename(r[1]).toLowerCase()==="node.exe")return{target:r[2],nodeCommand:r[1]};let n=/^@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT \/b\n:start\nSETLOCAL\nCALL :find_dp0\n\nIF EXIST "%dp0%\\node\.exe" \(\n {2}SET "_prog=%dp0%\\node\.exe"\n\) ELSE \(\n {2}SET "_prog=node"\n {2}SET PATHEXT=%PATHEXT:;\.JS;=;%\n\)\n\nendLocal & goto #_undefined_# 2>NUL \|\| title %COMSPEC% & "%_prog%" {2}"%dp0%\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(n)return{target:n[1]};let i=/^@SETLOCAL\n(?:@IF NOT DEFINED NODE_PATH \(\n {2}@SET "NODE_PATH=([^"\r\n]+)"\n\) ELSE \(\n {2}@SET "NODE_PATH=\1;%NODE_PATH%"\n\)\n)?@IF EXIST "%~dp0\\node\.exe" \(\n {2}"%~dp0\\node\.exe" {2}"%~dp0\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*\n\) ELSE \(\n {2}@SET PATHEXT=%PATHEXT:;\.JS;=;%\n {2}node {2}"%~dp0\\\2" %\*\n\)$/u.exec(t);return i?{target:i[2],...i[1]?{nodePath:i[1]}:{}}:null}function MA(e,t,r,n=process.execPath){let i=xH(SH(e,"utf8"));if(!i)return null;let s=i.target.replace(/^[/\\]+/u,"");if(Rr.win32.parse(s).root)return null;let o=Rr.resolve(Rr.dirname(e),s);if(!uw(o))throw new Error("Node CLI entry is missing: "+o);let c=Rr.join(Rr.dirname(e),"node.exe"),l={...r},f=Object.keys(l).find(d=>d.toUpperCase()==="NODE_PATH"),a=f?l[f]:void 0;return i.nodePath&&(f&&delete l[f],l.NODE_PATH=i.nodePath+(a?";"+a:"")),{command:i.nodeCommand??(uw(c)?c:n),args:[o,...t],...i.nodePath?{env:l}:{}}}function FA(e){if(e.some(t=>CH.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var IH=6e4,PH=8*1024*1024;var di=class extends Error{constructor(r,n,i,s){super(`${r} ${n.join(" ")} failed${i?`: ${i}`:""}`,s);this.command=r;this.args=n;this.stderr=i;this.name="ExternalCommandError",this.timedOut=s?.timedOut===!0}command;args;stderr;timedOut};function OH(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function HA(e,t,r={}){let n=r.timeoutMs??IH,i=r.maxBufferBytes??PH;if(!Number.isSafeInteger(n)||n<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(i)||i<1)throw new Error("External command max buffer must be a positive integer");let s=dw.resolve(r.cwd??process.cwd()),o=r.env??process.env,c=process.platform==="win32"?go(e,o,s):e,l=dw.win32.extname(c).toLowerCase(),f=l===".bat"||l===".cmd";process.platform==="win32"&&f&&FA(t);try{let a=()=>_H(c,[...t],{cwd:s,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:n,killSignal:"SIGKILL",maxBuffer:i,windowsHide:!0,shell:process.platform==="win32"&&f});return/^(?:git|git\.exe)$/iu.test(dw.win32.basename(e))?Jr(a):a()}catch(a){let d=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new di(e,t,d,{cause:a,timedOut:OH(a)})}}var NH=3e4,$H=8*1024*1024;function VA(e,t){if(t.some(o=>!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(o)))throw new Error("Git commit paths require complete commit IDs");if(!t.length)return new Map;let r;try{r=Jr(()=>BA("git",["diff-tree","--stdin","--always","--no-renames","--name-status","-r","-z"],{cwd:e,input:t.join(`
|
|
229
|
+
`)+`
|
|
230
|
+
`,encoding:"utf8",timeout:NH,maxBuffer:$H,windowsHide:!0}))}catch(o){if(!["ENOBUFS","ETIMEDOUT"].includes(o.code??""))throw o;return new Map(t.map(c=>[c,Jr(()=>BA("git",["diff-tree","--no-commit-id","--no-renames","--name-only","-r","-z",c],{cwd:e,encoding:"utf8",windowsHide:!0})).split("\0").filter(Boolean)]))}let n=r.split("\0"),i=new Map,s=0;for(let o of t){if(n[s++]!==o)throw new Error(`Git commit path response does not match ${o}`);let c=[];for(;/^[ACDMTUXB]$/u.test(n[s]??"");){s+=1;let l=n[s++];if(!l)throw new Error("Git commit path response is incomplete");c.push(l)}i.set(o,c)}if(n.slice(s).some(Boolean))throw new Error("Git commit path response has unexpected records");return i}qt();ye();function Sr(e,t,r){if(!e)return null;let n=e.replaceAll("\\","/");return n.startsWith(`${t}/`)?`${r}/${n.slice(t.length+1)}`:n}var XA=bt(Dt(),1);import on from"node:path";import{spawnSync as DH}from"child_process";import{accessSync as UA,constants as fw,statSync as zA,existsSync as P5,readFileSync as O5}from"node:fs";import wo from"node:path";function pw(e,t,r){if((r.platform??process.platform)!=="win32")return{command:e,args:[...t]};let n=go(e,r.env??process.env,r.cwd),i=wo.extname(n).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[wo.resolve(r.cwd,n),...t]};if(i===".cmd"){let s=MA(n,t,r.env??process.env);if(s)return s}if([".cmd",".bat",".ps1"].includes(i))throw new Error(`Unsupported Node CLI shim: ${n}. Use a standard npm/pnpm .cmd launcher or the Node CLI .js/.mjs/.cjs entry; no shell fallback is allowed.`);return{command:n,args:[...t]}}function KA(e,t,r){let n=pw(e,t,r),i=r.platform??process.platform,s=n.env??r.env??process.env,o=n.command;if(!(i==="win32"?[go(o,s,r.cwd)]:o.includes("/")?[wo.resolve(r.cwd,o)]:(s.PATH??"/usr/bin:/bin").split(wo.delimiter).map(f=>wo.resolve(r.cwd,f,o))).some(f=>{try{let a=wo.resolve(r.cwd,f);return zA(a).isFile()?(UA(a,i==="win32"?fw.F_OK:fw.X_OK),!0):!1}catch{return!1}}))throw new Error(`Executable not found or not executable: ${e}`);if(n.command!==e&&n.args.length>t.length){let f=n.args[0];if(!zA(f).isFile())throw new Error(`Node CLI entry is not a file: ${f}`);UA(f,fw.R_OK)}}var GA=bt(Dt(),1);ye();import jH from"path";async function JA(e,t){let r=t??await wt(e),n=jH.join(r.openSpecRoot,"config.yaml"),i=be(r.projectRoot,n),s;try{s=(await ae(r.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(f){throw f.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${i} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:f}):new Error(`Classic OpenSpec root is unhealthy: ${f instanceof Error?f.message:String(f)}`,{cause:f})}let o=(0,GA.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${i} is invalid YAML (${o.errors[0].message})`);let c=o.toJS();if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`Classic OpenSpec root is unhealthy: ${i} must contain a mapping`);let l=c.schema;if(typeof l!="string"||l.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${i} must declare a non-empty schema`);return{layout:r,configPath:i,schema:l}}async function YA(e,t=process.cwd()){let r=e[0]==="--"?e.slice(1):[...e];if(r.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- <openspec-args...>"};let n=await ut(t),i=await Ni(n);await JA(n,i);let s=process.env.COMET_OPENSPEC||"openspec",o;try{KA(s,r,{cwd:i.openSpecBase}),o=pw(s,r,{cwd:i.openSpecBase})}catch(l){return{exitCode:l.code==="ENOENT"?127:70,executionStarted:!1,stderr:l instanceof Error?l.message:String(l)}}let c=DH(o.command,o.args,{cwd:i.openSpecBase,encoding:"utf8",shell:!1,windowsHide:!0,timeout:12e4,...o.env?{env:o.env}:{}});if(c.error){let l=c.error.code;return{exitCode:l==="ENOENT"?127:70,...c.pid===0&&["ENOENT","EACCES","ENOTDIR","ENOEXEC"].includes(l??"")?{executionStarted:!1}:{},stdout:c.stdout||void 0,stderr:c.stderr||(l==="ENOENT"?`OpenSpec CLI not found: ${s}`:c.error.message)}}return{exitCode:c.status??1,executionCompleted:c.status!==null&&c.signal===null,stdout:c.stdout||void 0,stderr:c.stderr||void 0}}var qH=".comet/archive-requirements.json";async function QA(e,t){let r=on.join(t,qH),n=["proposal.md","design.md","tasks.md"];if(await Wt(e,r,{label:"Classic archive requirements",expected:"file"})){let s=JSON.parse(await Pe(e,r,{label:"Classic archive requirements"}));if(s?.schema!=="comet.classic.archive-requirements.v1")throw new Error("Unsupported Classic archive requirements");n=s.files}if(!Array.isArray(n)||!n.includes("proposal.md")||!n.includes("tasks.md")||n.some(s=>typeof s!="string"||!(["proposal.md","design.md","tasks.md"].includes(s)||/^specs\/(?:[^/\\:]+\/)+spec\.md$/u.test(s))||s.split("/").some(o=>o==="."||o==="..")))throw new Error("Invalid Classic archive required files");let i=[];for(let s of n)await Yn(e,on.join(t,s),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${s}`);return i}function LH(e){if(!e||typeof e!="object")throw new Error("Unsupported OpenSpec status: expected an object");let t=e;if(!Array.isArray(t.artifacts)||!Array.isArray(t.applyRequires))throw new Error("OpenSpec must expose artifacts and applyRequires; upgrade to a supported version");let r=new Map;for(let c of t.artifacts){if(!c||typeof c!="object"||typeof c.id!="string"||typeof c.outputPath!="string"||!["done","skipped","ready","blocked"].includes(c.status)||!Array.isArray(c.requires)||c.requires.some(l=>typeof l!="string"))throw new Error("OpenSpec must expose dependency edges for every artifact; upgrade to a supported version");if(r.has(c.id))throw new Error(`Duplicate OpenSpec artifact: ${c.id}`);r.set(c.id,c)}let n=[],i=new Set,s=new Set,o=c=>{if(typeof c!="string"||!r.has(c))throw new Error(`Missing OpenSpec dependency: ${String(c)}`);if(s.has(c))throw new Error(`Cyclic OpenSpec dependency: ${c}`);if(i.has(c))return;s.add(c);let l=r.get(c);for(let f of l.requires)o(f);s.delete(c),i.add(c),n.push(l)};for(let c of[...t.applyRequires,"proposal","tasks"])o(c);return n}async function Ed(e,t,r){let n=on.join(t,".openspec.yaml");if(!await Wt(e,n,{label:"OpenSpec change metadata",expected:"file"})){if(r!==void 0)throw new Error("OpenSpec change metadata is missing; cannot validate its status");return{source:"legacy",required:["proposal","design","tasks"],skipped:[],designRequired:!0,files:["proposal.md","design.md","tasks.md"].map(d=>on.join(t,d)),problems:[]}}let i=(0,XA.parseDocument)(await Pe(e,n,{label:"OpenSpec change metadata"}));if(i.errors.length)throw new Error(`Invalid OpenSpec metadata: ${i.errors[0].message}`);let s=await mo(e,on.join(t,"specs")),o=r===void 0?await YA(["status","--change",on.basename(t),"--json"],e):void 0;if(o&&o.exitCode!==0)throw new Error(`Cannot inspect OpenSpec artifact requirements: ${o.stderr??o.exitCode}`);let c;try{c=o?JSON.parse(o.stdout??""):r}catch{throw new Error("Unsupported OpenSpec status: expected JSON")}if(!c||typeof c.changeRoot!="string"||on.resolve(c.changeRoot)!==on.resolve(t))throw new Error("OpenSpec status resolves outside the selected Classic change");let l=LH(c),f=s,a={source:"openspec",required:l.map(d=>d.id),skipped:[],designRequired:l.some(d=>d.id==="design"),files:[],problems:[]};for(let d of l){if(!["proposal","specs","design","tasks"].includes(d.id))throw new Error(`Unsupported Classic artifact: ${d.id}; use a schema with supported artifact roles`);if(d.id!=="specs"&&d.outputPath!==`${d.id}.md`)throw new Error(`Unsupported Classic artifact output: ${d.outputPath}`);if(d.status==="skipped"){if(d.id!=="specs"||i.get("skip_specs")!==!0||f.length)throw new Error("OpenSpec skipped specs require explicit skip_specs: true and no conflicting spec files");a.skipped.push(d.id);continue}let p=d.outputPath.replaceAll("\\","/");if(on.posix.isAbsolute(p)||/^[A-Za-z]:/u.test(p)||p.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${p}`);let u;if(d.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(p))u=f;else{if(["?","*","[","]","{","}"].some(m=>p.includes(m)))throw new Error(`Unsupported OpenSpec artifact pattern: ${p}`);u=[on.join(t,p)]}(d.status!=="done"||!u.length)&&a.problems.push(`Required OpenSpec artifact is not complete: ${d.id}`);for(let m of u)await Yn(e,m,`OpenSpec required artifact ${d.id}`)||a.problems.push(`Required OpenSpec file is missing or empty: ${m}`),a.files.push(m)}return a}function cs(e){if(e.workflow!=="full")return{missingFields:[],invalidFields:[]};let t=[],r=[];return e.buildMode||t.push("build_mode"),e.tddMode||t.push("tdd_mode"),e.reviewMode||t.push("review_mode"),e.buildMode==="subagent-driven-development"&&e.subagentDispatch!=="confirmed"&&t.push("subagent_dispatch"),e.buildMode!=="subagent-driven-development"&&e.subagentDispatch==="confirmed"&&r.push({field:"subagent_dispatch",reason:"subagent_dispatch=confirmed 仅适用于 build_mode=subagent-driven-development"}),e.buildMode!=="direct"&&e.directOverride===!0&&r.push({field:"direct_override",reason:"direct_override=true 仅适用于 build_mode=direct"}),e.buildMode==="autonomous"&&e.reviewMode==="off"&&r.push({field:"review_mode",reason:"autonomous full build requires review_mode=standard or thorough"}),e.buildMode==="direct"&&e.directOverride!==!0&&r.push({field:"direct_override",reason:"full workflow direct execution requires direct_override=true"}),{missingFields:t,invalidFields:r}}function ZA(e){let t=cs(e);return t.missingFields.length===0&&t.invalidFields.length===0}import{randomUUID as $B}from"node:crypto";function yo(e){return e==="zh-CN"?"zh-CN":"en"}function mw(e,t,r){return e==="zh-CN"?r:t}function ex(e,t){let n={open:{en:"Source code edits are paused while the request is still being clarified.",zh:"需求仍在澄清中,暂时不修改源代码。"},design:{en:"Source code edits are paused until the design is agreed and recorded.",zh:"方案确定并记录之前,暂不修改源代码。"},build:{en:"A required design or plan record is missing, so source edits stay paused.",zh:"缺少必需的设计或计划记录,源代码修改暂被搁置。"},verify:{en:"Implementation edits are paused during verification; only verification output is accepted.",zh:"验证期间暂停修改实现,仅接受验证产出。"},archive:{en:"Source code edits are paused while the change is being archived.",zh:"归档期间暂不修改源代码。"}}[e]??{en:"This write is paused by the current workflow stage.",zh:"当前工作流阶段暂不允许这次写入。"};return{summary:mw(t,"This write was blocked on purpose, not by an error.","这次写入是被有意拦下的,不是发生了错误。"),user_message:mw(t,n.en,n.zh)}}function tx(e){let{name:t,locale:r}=e;return{summary:mw(r,`Handoff context for ${t} was written and recorded; the Build phase can resume from it.`,`需求 ${t} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}Am();import Ad from"path";var ls={trajectory:Number.MAX_SAFE_INTEGER,artifacts:Number.MAX_SAFE_INTEGER,context:Number.MAX_SAFE_INTEGER,pendingAction:Number.MAX_SAFE_INTEGER,checkpoint:Number.MAX_SAFE_INTEGER};function fi(e,t){if(Ad.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let r=Ad.resolve(e),n=Ad.resolve(r,t);if(n!==r&&!n.startsWith(r+Ad.sep))throw new Error("Run path must stay inside the change directory")}async function rx(e,t,r,n={}){fi(e,t),await fR(e,t,`${JSON.stringify(r)}
|
|
231
|
+
`,ls.trajectory,"Run trajectory",n)}async function nx(e,t,r={}){fi(e,t);let n=await $i(e,t,ls.trajectory,"Run trajectory",r);return n===null?[]:n.split(/\r?\n/).map((i,s)=>({line:i,number:s+1})).filter(({line:i})=>i.length>0).map(({line:i,number:s})=>{try{return JSON.parse(i)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function ix(e,t,r={}){fi(e,t);let n=await $i(e,t,ls.artifacts,"Run artifacts",r);return n===null?{}:JSON.parse(n)}async function sx(e,t,r,n={}){fi(e,t),await ji(e,t,JSON.stringify(r,null,2)+`
|
|
232
|
+
`,ls.artifacts,"Run artifacts",n)}async function ox(e,t,r,n={}){fi(e,t),await ji(e,t,r,ls.context,"Run context",n)}async function ax(e,t,r={}){fi(e,t);let n=await $i(e,t,ls.pendingAction,"Run pending action",r);return n===null?null:JSON.parse(n)}async function cx(e,t,r={}){fi(e,t),await iu(e,t,"Run pending action",r)}async function lx(e,t,r,n={}){fi(e,t),await ji(e,t,JSON.stringify(r,null,2)+`
|
|
233
|
+
`,ls.checkpoint,"Run checkpoint",n)}import pi from"node:path";async function hw(e,t){let r=pi.resolve(e,t),n=pi.relative(pi.resolve(e),r);if(pi.isAbsolute(t)||pi.isAbsolute(n)||n===".."||n.startsWith(`..${pi.sep}`))throw new Error("Run path must stay inside the change directory");let i=await ut(e),s=await Ra(i,r,{readOnly:!0}),o=s?.root??e,c=s?.target??r,l=o===pi.parse(c).root?pt(i):o;return{root:l,ref:pi.relative(l,c).replaceAll("\\","/"),inspectionRoot:o,target:c}}async function vo(...e){return e[0]=await Ee(e[0]),rx(...e)}async function xd(...e){let t=await hw(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,nx(...e)}async function ux(...e){let t=await hw(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,ix(...e)}async function _d(...e){return e[0]=await Ee(e[0]),sx(...e)}async function Id(...e){return e[0]=await Ee(e[0]),ox(...e)}async function dx(...e){let t=await hw(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,ax(...e)}async function fx(...e){return e[0]=await Ee(e[0]),cx(...e)}async function px(...e){return e[0]=await Ee(e[0]),lx(...e)}import{promises as Lx}from"fs";import or from"path";import{fileURLToPath as Wx}from"url";ye();import hi from"path";ye();qt();import bc from"path";function MH(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function mx(e,t,r,n){let i=rt(r,"Classic handoff artifact pointer");if((await U(e,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await wt(e),c=`${be(e,o.changesDir)}/`,f=(o.artifactLayout==="docs"?[c,"openspec/changes/"]:[c]).find(k=>i.startsWith(k));if(!f)return null;let a=i.slice(f.length).split("/");if(a.length<4||a[1]!==".comet"||a.slice(2).some(k=>k.length===0))return null;let d=a[0];sn(d);let p=a.slice(2),u=bc.resolve(t);if(bc.dirname(u)!==bc.resolve(o.archiveDir))return null;let m=bc.basename(u),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(m);if(m!==d&&h?.[1]!==d)return null;await U(e,be(e,u),{label:"Classic archived change directory",expected:"directory"});let g=bc.join(u,".comet",...p),w=be(e,g);try{return await ae(e,w,n,{label:"Historical Classic archived handoff artifact"}),w}catch(k){if(MH(k))return null;throw k}}import us from"node:path";async function Pd(e,t,r,n={}){if(r.workflow!=="full"||r.buildMode!=="autonomous")return[];let i=[];if(n.requirePlan!==!1){let s=cs(r);s.missingFields.includes("tdd_mode")&&i.push("tdd_mode must be selected for autonomous full build"),s.missingFields.includes("review_mode")&&i.push("review_mode must be selected for autonomous full build"),s.invalidFields.some(({field:o})=>o==="review_mode")&&i.push("review_mode must be standard or thorough for autonomous full build"),r.isolation||i.push("isolation must be selected for autonomous full build")}return(!r.designDoc||!await Yn(e,r.designDoc,"Classic autonomous design"))&&i.push("design_doc must reference a nonempty technical design for autonomous full build"),n.requirePlan!==!1&&(await mi(e,r.plan,{requireNonempty:!0})).status!=="ready"&&i.push("plan must reference a nonempty implementation plan in the configured plans directory"),i}async function mi(e,t,r={}){if(!t||t==="null")return{status:"missing",recordedPath:null};let n=await wt(e),i=us.resolve(e,t),s=us.relative(n.superpowersPlansDir,i);return us.isAbsolute(t)||!s||s.startsWith(`..${us.sep}`)||us.isAbsolute(s)||s.includes(us.sep)||us.extname(s).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await Wt(e,t,{label:`Classic build plan ${t}`,expected:"file"})&&(!r.requireNonempty||(await Pe(e,t,{label:`Classic build plan ${t}`})).trim().length>0)?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}var FH=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,HH=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function ds(e){let t=[],r=new Set,n=null;for(let[i,s]of e.split(/\r?\n/u).entries()){let o=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(s);if(o){n?o[1][0]===n.marker&&o[1].length>=n.length&&!o[2].trim()&&(n=null):n={marker:o[1][0],length:o[1].length};continue}if(n)continue;let c=FH.exec(s);if(!c)continue;let l=HH.exec(c[4]),f=l?.[1]??null;if(c[4].includes("<!-- comet-task:")&&(!l||c[4].slice(0,l.index).includes("<!-- comet-task:")))throw new Error(`Malformed Classic task ID at line ${i+1}`);if(f&&r.has(f))throw new Error(`Duplicate Classic task ID: ${f}`);f&&r.add(f);let a=c[4].slice(0,l?.index).trim();if(!a)throw new Error(`Empty Classic task at line ${i+1}`);t.push({id:f,text:a,completed:c[2].toLowerCase()==="x",line:i+1})}return t}function Od(e,t){return hi.relative(e,t).split(hi.sep).join("/")}async function Rc(e,t,r,n,i){if(!r)return{code:t,satisfied:!1};let s=r.replaceAll("\\","/");if(i)return{code:t,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${i instanceof Error?i.message:String(i)}`};try{if(n){let c=n.artifactLayout==="legacy"?"docs":"legacy",l=be(e,ha(e,c).openSpecRoot);if((s===l||s.startsWith(`${l}/`))&&(await U(e,s,{label:`${t} artifact`,expected:"file"})).exists)return{code:t,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await om(e,s,{label:`${t} artifact`});return{code:t,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:t,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function BH(e,t,r,n){try{n??=await wt(e)}catch(s){return{code:"design.handoff",satisfied:!1,...r?{source:r.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let i=await Rc(e,"design.handoff",r,n);if(!r||i.satisfied||i.detail)return i;try{let s=await mx(e,t,r,Number.MAX_SAFE_INTEGER);return s?{...i,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:i}catch(s){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function gw(e,t,r){return Rc(e,t,Od(e,r))}async function VH(e,t){let r=hi.join(t,"specs"),n;try{n=await mo(e,r)}catch(i){return i.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${i instanceof Error?i.message:String(i)}`}}return{code:"openspec.delta-spec",satisfied:n.length>0,source:n[0]?Od(e,n[0]):void 0,detail:`${n.length} delta spec${n.length===1?"":"s"}`}}async function UH(e,t){let r,n=Od(e,t);try{r=(await ae(e,n,Number.MAX_SAFE_INTEGER,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:n,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let i;try{i=ds(r)}catch(o){return{code:"build.tasks-complete",satisfied:!1,source:n,detail:`malformed tasks.md: ${o instanceof Error?o.message:String(o)}`}}let s=i.filter(o=>o.completed).length;return{code:"build.tasks-complete",satisfied:i.length>0&&s===i.length,source:n,detail:`${s} of ${i.length} tasks complete`}}function ko(e,t){return e.some(r=>r.code===t&&r.satisfied)}async function bo(e,t){let r=await ut(e),n=t.classic,i=hi.join(e,"proposal.md"),s=hi.join(e,"design.md"),o=hi.join(e,"tasks.md"),c=t.run?hi.resolve(e,t.run.checkpointRef):hi.join(e,".comet","checkpoint.json"),l,f;try{l=await wt(r)}catch(d){f=d}let a=await Promise.all([gw(r,"openspec.proposal",i),gw(r,"openspec.design",s),gw(r,"openspec.tasks",o),VH(r,e),Rc(r,"design.document",n?.designDoc??null,l,f),(async()=>{let d=await Rc(r,"build.plan",n?.plan??null,l,f);if(!d.satisfied)return d;try{let p=await mi(r,n?.plan??null,{requireNonempty:n?.buildMode==="autonomous"});return p.status==="ready"?d:{code:d.code,source:d.source,satisfied:!1,detail:`Implementation plan is ${p.status}`}}catch(p){return{code:d.code,source:d.source,satisfied:!1,detail:p instanceof Error?p.message:String(p)}}})(),UH(r,o),Rc(r,"verification.report",n?.verificationReport??null,l,f),BH(r,e,n?.handoffContext??null,l),(async()=>{try{return{code:"run.checkpoint",source:Od(r,c),satisfied:await Yn(r,c,"Classic Run checkpoint")}}catch(d){return{code:"run.checkpoint",satisfied:!1,detail:d instanceof Error?d.message:String(d)}}})()]);return a.push({code:"archive.confirmed",satisfied:n?.archiveConfirmation==="confirmed"}),a}import{createHash as kB,randomUUID as bB}from"crypto";import{promises as bw}from"fs";import xn from"path";function zH(e){return e.classicProfile??e.workflow}function KH(e){return e.isolation!==null&&ZA(e)}function GH(e){return(e.buildMode==="direct"||e.buildMode==="autonomous")&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function JH(e,t,r){if(e!=="full"&&t.verifyResult==="fail")return`${e}.build.execute`;if(e==="full"){if(ko(r,"build.plan")&&t.buildPause==="plan-ready")return"full.build.plan-ready";if(!KH(t))return"full.build.configure";if(!ko(r,"build.plan"))return"full.build.plan";if(t.verifyResult==="fail")return"full.build.fix"}else if(!GH(t))throw new Error(`${e} build configuration is incomplete`);return ko(r,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function YH(e,t,r){return t.verifyResult!=="pass"||!ko(r,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function XH(e,t){if(t.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return t.archiveConfirmation==="confirmed"?`${e}.archive.execute`:`${e}.archive.confirm`}function Td(e,t){let r=zH(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(r!=="full"&&e.phase==="design")throw new Error(`${r} workflow cannot enter design`);switch(e.phase){case"open":return`${r}.open`;case"design":return ko(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return JH(r,e,t);case"verify":return YH(r,e,t);case"archive":return XH(r,e)}}function hx(e,t,r){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:r,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}import{createHash as Ix,randomUUID as hB}from"crypto";import{promises as ft}from"fs";import ot from"path";var yx=bt(Dt(),1);import{promises as ww}from"fs";import Cr from"path";var QH=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],ZH=["deterministic","adaptive"],eB=["function","mcp","script","agent"],tB=["none","read","write","external"],rB=["progress","step","completion"],nB=["artifact_exists","state_equals"];function fs(e,t,r){return new Error(`${e}: ${t} ${r}`)}function tr(e,t,r="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw fs(t,r,"must be an object")}function gi(e,t,r){if(!Array.isArray(e))throw fs(t,r,"must be an array")}function Ht(e,t,r){if(typeof e!="string")throw fs(t,r,"must be a string")}function Br(e,t,r,n){t in e&&Ht(e[t],r,`${n}.${t}`)}function vx(e,t,r,n){if(t in e&&typeof e[t]!="boolean")throw fs(r,`${n}.${t}`,"must be a boolean")}function wi(e,t,r,n){if(typeof e!="string"||!t.includes(e))throw fs(r,n,`must be one of ${t.join(", ")}`)}function Nd(e,t,r){gi(e,t,r),e.forEach((n,i)=>{Ht(n,t,`${r}[${i}]`)})}function gx(e,t,r){tr(e,t,r),Ht(e.name,t,`${r}.name`),Ht(e.description,t,`${r}.description`),vx(e,"required",t,r)}function iB(e,t,r){tr(e,t,r),Ht(e.id,t,`${r}.id`),Br(e,"source",t,r),Br(e,"version",t,r)}function sB(e,t,r){tr(e,t,r),Ht(e.id,t,`${r}.id`),Ht(e.role,t,`${r}.role`),Br(e,"instructions",t,r)}function oB(e,t,r){tr(e,t,r),Ht(e.id,t,`${r}.id`),wi(e.kind,eB,t,`${r}.kind`),Ht(e.source,t,`${r}.source`),wi(e.sideEffect,tB,t,`${r}.sideEffect`),vx(e,"requiresConfirmation",t,r)}function aB(e,t,r){tr(e,t,r),wi(e.type,QH,t,`${r}.type`),Br(e,"ref",t,r),Br(e,"prompt",t,r),Br(e,"question",t,r),"options"in e&&Nd(e.options,t,`${r}.options`)}function cB(e,t,r){tr(e,t,r),Ht(e.id,t,`${r}.id`),aB(e.action,t,`${r}.action`),Br(e,"next",t,r),"completionEvals"in e&&Nd(e.completionEvals,t,`${r}.completionEvals`)}function lB(e,t){let r="goal";tr(e,t,r),Ht(e.statement,t,`${r}.statement`),gi(e.inputs,t,`${r}.inputs`),e.inputs.forEach((n,i)=>{gx(n,t,`${r}.inputs[${i}]`)}),gi(e.outputs,t,`${r}.outputs`),e.outputs.forEach((n,i)=>{gx(n,t,`${r}.outputs[${i}]`)}),Nd(e.success,t,`${r}.success`)}function uB(e,t){let r="orchestration";tr(e,t,r),wi(e.mode,ZH,t,`${r}.mode`),Br(e,"entry",t,r),"steps"in e&&(gi(e.steps,t,`${r}.steps`),e.steps.forEach((n,i)=>{cB(n,t,`${r}.steps[${i}]`)}))}function kx(e,t){return tr(e,t),wi(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),wi(e.kind,["Skill"],t,"kind"),tr(e.metadata,t,"metadata"),Ht(e.metadata.name,t,"metadata.name"),Ht(e.metadata.version,t,"metadata.version"),Ht(e.metadata.description,t,"metadata.description"),lB(e.goal,t),uB(e.orchestration,t),gi(e.skills,t,"skills"),e.skills.forEach((r,n)=>{iB(r,t,`skills[${n}]`)}),gi(e.agents,t,"agents"),e.agents.forEach((r,n)=>{sB(r,t,`agents[${n}]`)}),gi(e.tools,t,"tools"),e.tools.forEach((r,n)=>{oB(r,t,`tools[${n}]`)}),e}function bx(e,t){tr(e,t);for(let r of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])r in e&&Nd(e[r],t,r);for(let r of["maxIterations","maxRetriesPerAction"])if(r in e&&(typeof e[r]!="number"||!Number.isFinite(e[r])))throw fs(t,r,"must be a finite number");return e}function dB(e,t){return tr(e,t),"runtime"in e&&Rx(e.runtime,t,"runtime"),e}function Rx(e,t,r){return gi(e,t,r),e.forEach((n,i)=>{let s=`${r}[${i}]`;tr(n,t,s),Ht(n.id,t,`${s}.id`),wi(n.scope,rB,t,`${s}.scope`),wi(n.type,nB,t,`${s}.type`),Br(n,"artifact",t,s),Br(n,"field",t,s),Br(n,"equals",t,s)}),e}async function yw(e){let t=await ww.readFile(e,"utf8");try{return(0,yx.parse)(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw fs(e,"document",n)}}async function fB(e){try{return await yw(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wx(e){try{return await ww.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pB(e){let t=Cr.join(e,"checks.yaml"),r=Cr.join(e,"evals.yaml"),[n,i]=await Promise.all([wx(t),wx(r)]);if(i)throw new Error(`${r}: evals.yaml is no longer supported; use checks.yaml`);return n?{document:dB(await yw(t),t)}:{document:null}}async function Sx(e){let t=Cr.resolve(e.root),r=Cr.resolve(e.controlRoot);e.requireSkillMarkdown&&await ww.access(Cr.join(t,"SKILL.md"));let n=Cr.join(r,"skill.yaml"),i=Cr.join(r,"guardrails.yaml"),s=kx(await yw(n),n),o=await fB(i),c=o===null?null:bx(o,i),l=await pB(r),f={allowedSkills:s.skills.map(a=>a.id),allowedAgents:s.agents.map(a=>a.id),allowedTools:s.tools.map(a=>a.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(a=>a.requiresConfirmation).map(a=>a.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...f,...c},evals:l.document?.runtime??[]}}async function Cx(e){let t=Cr.resolve(e);return Sx({root:t,controlRoot:Cr.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Ex(e){let t=Cr.resolve(e);return Sx({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function Ax(e,t,r=Cr.join(t,"package.json")){tr(e,r);let n=e.packageKind==="runtime"?"runtime":void 0,i=kx(e.definition,r),s=bx(e.guardrails,r),o=Rx(e.evals,r,"evals"),c={allowedSkills:i.skills.map(l=>l.id),allowedAgents:i.agents.map(l=>l.id),allowedTools:i.tools.map(l=>l.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:i.tools.filter(l=>l.requiresConfirmation).map(l=>l.id)};return{root:Cr.resolve(t),packageKind:n,definition:i,guardrails:{...c,...s},evals:o}}import xx from"path";function mB(e,t,r,n){e.type==="invoke_skill"&&!t.definition.skills.some(i=>i.id===e.ref)&&r.push(`step ${n} references undeclared skill: ${e.ref??"(missing)"}`),e.type==="call_tool"&&!t.definition.tools.some(i=>i.id===e.ref)&&r.push(`step ${n} references undeclared tool: ${e.ref??"(missing)"}`),e.type==="handoff"&&!t.definition.agents.some(i=>i.id===e.ref)&&r.push(`step ${n} references undeclared agent: ${e.ref??"(missing)"}`),e.type==="ask_user"&&!e.question&&r.push(`step ${n} ask_user action requires question`)}function _x(e){let t=[],{definition:r,guardrails:n,evals:i}=e;r.apiVersion!=="comet/v1alpha1"&&t.push("unsupported apiVersion"),r.kind!=="Skill"&&t.push("kind must be Skill"),r.metadata.name||t.push("metadata.name is required"),r.goal.statement||t.push("goal.statement is required"),n.maxIterations<1&&t.push("maxIterations must be at least 1"),n.maxRetriesPerAction<0&&t.push("maxRetriesPerAction must not be negative");let s=r.orchestration.steps??[];if(r.orchestration.mode==="adaptive")(r.orchestration.entry||s.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let c of s)o.has(c.id)&&t.push(`duplicate step id: ${c.id}`),o.add(c.id),mB(c.action,e,t,c.id);(!r.orchestration.entry||!o.has(r.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${r.orchestration.entry??"(missing)"}`);for(let c of s){c.next&&!o.has(c.next)&&t.push(`step ${c.id} has unknown next step: ${c.next}`);for(let l of c.completionEvals??[])i.some(f=>f.id===l)||t.push(`step ${c.id} references unknown eval: ${l}`)}}for(let o of r.tools){if(o.kind!=="script")continue;let c=xx.posix.normalize(o.source.replaceAll("\\","/"));(xx.isAbsolute(o.source)||c===".."||c.startsWith("../"))&&t.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of n.allowedSkills)r.skills.some(c=>c.id===o)||t.push(`guardrails allow undeclared skill: ${o}`);for(let o of n.allowedAgents)r.agents.some(c=>c.id===o)||t.push(`guardrails allow undeclared agent: ${o}`);for(let o of n.allowedTools)r.tools.some(c=>c.id===o)||t.push(`guardrails allow undeclared tool: ${o}`);return t}function $d(e){return Array.isArray(e)?e.map($d):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,$d(r)])):e}function gB(e){return $d({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function wB(e){return ot.posix.normalize(e.replaceAll("\\","/"))}function Ro(e,t,r){let n=ot.relative(e,t);if(!(n===""||!ot.isAbsolute(n)&&!n.startsWith(`..${ot.sep}`)))throw new Error(`${r} resolves outside the Skill package`)}async function Px(e,t,r){let n=wB(t);if(ot.posix.isAbsolute(n)||n===".."||n.startsWith("../"))throw new Error(`${r} resolves outside the Skill package`);let i=ot.resolve(e,...n.split("/"));Ro(e,i,r);let s;try{s=await ft.realpath(i)}catch(o){throw o.code==="ENOENT"?new Error(`${r} does not exist: ${t}`,{cause:o}):o}if(Ro(e,s,r),!(await ft.stat(s)).isFile())throw new Error(`${r} is not a file: ${t}`);return{path:n,content:await ft.readFile(s)}}async function yB(e){let t=await ft.realpath(e.root),r=e.packageKind==="runtime"?[]:[await Px(t,"SKILL.md","SKILL.md")];for(let n of e.definition.tools)n.kind==="script"&&r.push(await Px(t,n.source,`Script tool ${n.id}`));return r.sort((n,i)=>n.path.localeCompare(i.path))}function vB(e,t){let r=t.map(n=>({path:n.path,sha256:Ix("sha256").update(n.content).digest("hex")}));return Ix("sha256").update(JSON.stringify($d({package:e,files:r}))).digest("hex")}function Nx(e){return JSON.stringify(e,null,2)+`
|
|
234
|
+
`}async function $x(e){let t=gB(e),r=await yB(e);return{document:t,files:r,hash:vB(t,r)}}async function jd(e){return(await $x(e)).hash}async function Ox(e){try{return await ft.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Tx(e,t){try{if((await ft.readFile(ot.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await ft.readFile(ot.join(e,"package.json"),"utf8")!==Nx(t.document))throw new Error("package mismatch");for(let i of t.files)if(!(await ft.readFile(ot.join(e,...i.path.split("/")))).equals(i.content))throw new Error(`file mismatch: ${i.path}`)}catch(r){throw new Error(`Existing Skill snapshot is invalid: ${t.hash}`,{cause:r})}}async function vw(e,t){let r=await $x(e),n=ot.resolve(t,".comet","skill-snapshots"),i=ot.join(n,r.hash);if(await ft.mkdir(n,{recursive:!0}),await Ox(i))return await Tx(i,r),{hash:r.hash,snapshotDir:i};let s=ot.join(n,`.tmp-${hB()}`);Ro(n,s,"Temporary snapshot"),Ro(n,i,"Published snapshot");try{await ft.mkdir(s);for(let o of r.files){let c=ot.join(s,...o.path.split("/"));Ro(s,c,`Snapshot file ${o.path}`),await ft.mkdir(ot.dirname(c),{recursive:!0}),await ft.writeFile(c,o.content)}await ft.writeFile(ot.join(s,"package.json"),Nx(r.document)),await ft.writeFile(ot.join(s,"sha256"),r.hash+`
|
|
235
|
+
`),await ft.rename(s,i)}catch(o){if(await Ox(i)){try{await Tx(i,r)}finally{await ft.rm(s,{recursive:!0,force:!0})}return{hash:r.hash,snapshotDir:i}}throw await ft.rm(s,{recursive:!0,force:!0}),o}return{hash:r.hash,snapshotDir:i}}async function kw(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let r=ot.resolve(e,".comet","skill-snapshots"),n=ot.join(r,t);Ro(r,n,"Skill snapshot");try{let i=(await ft.readFile(ot.join(n,"sha256"),"utf8")).trim();if(i!==t)throw new Error(`stored hash is ${i||"(empty)"}`);let s=ot.join(n,"package.json"),o=JSON.parse(await ft.readFile(s,"utf8")),c=Ax(o,n,s),l=_x(c);if(l.length>0)throw new Error(l.map(a=>` - ${a}`).join(`
|
|
236
|
+
`));let f=await jd(c);if(f!==t)throw new Error(`calculated hash is ${f}`);return c}catch(i){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:i})}}async function jx(e){try{return await bw.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Dx(e){return kB("sha256").update(e).digest("hex")}function RB(e){return Dx(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)))))}function SB(e){return e.replaceAll(".","_").replaceAll("-","_")}async function CB(e,t){let r=await ut(e),n=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[SB(o.code),o.source])),i=xn.join(e,"subagent-progress.md");await jx(i)&&(n.subagent_progress=xn.relative(r,i).split(xn.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(n.handoff_context=s.source),n}function EB(e,t,r){return[{sequence:1,timestamp:r,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:r,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:Li,profile:t,source:"pre-migration"}}]}async function AB(e){await Promise.all(e.map(t=>bw.rm(t,{recursive:!0,force:!0})))}async function qx(e,t){return Nr(e,()=>xB(e,t))}async function xB(e,t){let r=await ut(e),n=await Pe(r,await fe(e),{label:"Classic migration state"});if(ir(n))throw new Error("Classic managed Run is owned by the SDK and cannot be migrated to compat");let i=await dr(e);if(!i.classic)throw new Error("Classic migration requires a legacy state projection");let s=i.classic,o=s.classicProfile??s.workflow;if(i.run){if(s.classicMigration!==Li)throw new Error("Classic Run exists without a supported classic_migration marker");if(i.run.skill!==t.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${t.skillPackage.definition.metadata.name}, got ${i.run.skill}`);if(await jd(t.skillPackage)!==i.run.skillHash)return await kw(await Ee(e),i.run.skillHash),{classic:s,run:i.run,evidence:await bo(e,i),migrated:!1,snapshotDir:xn.join(await Ee(e),".comet","skill-snapshots",i.run.skillHash)};let m=await vw(t.skillPackage,await Ee(e));return{classic:s,run:i.run,evidence:await bo(e,i),migrated:!1,snapshotDir:m.snapshotDir}}let c=await bo(e,i),l=Td(s,c);if(!t.skillPackage.definition.orchestration.steps?.some(u=>u.id===l))throw new Error(`Classic Skill package does not define resolved step: ${l}`);let f=await jd(t.skillPackage),a=xn.join(await Ee(e),".comet","skill-snapshots",f),d=await jx(a),p=[];try{let u=await vw(t.skillPackage,await Ee(e)),m=hx(t.skillPackage,t.runId?.()??bB(),u.hash);m.currentStep=l,l==="completed"&&(m.status="completed");let h={...s,classicProfile:o,classicMigration:Li},g=await CB(e,c),w=await ut(e),k=c.find(O=>O.code==="design.handoff"&&O.satisfied),b=null;k?.source&&(b=await Pe(w,k.resolvedSource??k.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await Id(e,m.contextRef,b),p.push(xn.resolve(await Ee(e),m.contextRef))),await _d(e,m.artifactsRef,g),p.push(xn.resolve(await Ee(e),m.artifactsRef));let R=(t.now?.()??new Date).toISOString(),E={runId:m.runId,stateVersion:1,trajectoryOffset:2,contextHash:b===null?null:Dx(b),artifactsHash:RB(g),createdAt:R};await px(e,m.checkpointRef,E),p.push(xn.resolve(await Ee(e),m.checkpointRef)),p.push(xn.resolve(await Ee(e),m.trajectoryRef));for(let O of EB(m,o,R))await vo(e,m.trajectoryRef,O);return await qs(e,{classic:h,run:m,unknownKeys:i.unknownKeys}),{classic:h,run:m,evidence:c,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await AB(p),d||await bw.rm(a,{recursive:!0,force:!0}),u}}async function _B(e){try{return(await Lx.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dd(e){try{return(await Lx.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function IB(e){return await _B(e)?await Dd(or.join(e,"skill.yaml"))?!0:await Dd(or.join(e,"SKILL.md"))&&await Dd(or.join(e,"comet","skill.yaml")):!1}function PB(e){return{root:e,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.configure"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function OB(){let e=or.dirname(Wx(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,or.resolve(e,"..","runtime","classic"),or.resolve(e,"..","..","comet","runtime","classic"),or.resolve(e,"..","..","assets","skills","comet","runtime","classic"),or.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,or.resolve(e,"..","..","comet-classic"),or.resolve(e,"..","..","assets","skills","comet-classic"),or.resolve("assets","skills","comet-classic")].filter(r=>!!r);for(let r of t)if(await IB(r))return r;return null}async function TB(e){return await Dd(or.join(e,"skill.yaml"))?Ex(e):Cx(e)}async function Mx(e){let t=await OB();return qx(e,{skillPackage:t?await TB(t):PB(or.dirname(Wx(import.meta.url)))})}async function Fx(e,t,r,n){return Nr(e,()=>NB(e,t,r,n))}async function NB(e,t,r,n){let i=await dr(e);if(!i.classic||!i.run)throw new Error("Classic transition requires synchronized Classic and Run projections");if(i.run.runId!==r.runId||i.run.iteration!==r.iteration||(t.checkEpoch??0)<(i.classic.checkEpoch??0))throw new Error("Classic transition became stale; reload the current state");let s=await bo(e,{classic:t,run:r,unknownKeys:i.unknownKeys}),o=Td(t,s),c={...r,currentStep:o,iteration:r.iteration+1,status:o==="completed"?"completed":"running"};await qs(e,{classic:t,run:c,unknownKeys:i.unknownKeys});let l=await xd(e,c.trajectoryRef);return await vo(e,c.trajectoryRef,{sequence:l.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:c.runId,data:{kind:"classic",fromStep:r.currentStep,toStep:o,...n}}),c}function jB(e,t,r,n){return["# Comet Design Handoff","","- Change: "+e,"- Phase: design","- Mode: "+t,"","Generated-by: comet handoff","","Read source files for current requirements and task completion.","",...n.flatMap(i=>["## "+i.reference,"","- Source: "+i.reference,"",i.content,""])].join(`
|
|
237
|
+
`)}async function Hx(e){let{projectRoot:t,changeDir:r,change:n}=e,i=be(t,r);if(e.run&&(e.run.input.change!==n||e.run.input.changeDir!==i))throw new Error("Classic Design context belongs to a different Run");let s=i+"/proposal.md";if(!(await Pe(t,s,{label:"Classic Design source"})).trim())throw new Error("Classic Design source is empty");return{handoffContext:s,handoffHash:e.run?.actions.at(-1)?.inputHash??null}}async function Bx(e){let t=be(e.projectRoot,e.changeDir),r=e.contextCompression==="beta"?"spec-context":"design-context";return[t+"/proposal.md",t+"/.comet/handoff/"+r+".json"].includes(e.handoffContext)?(await Hx(e)).handoffContext===t+"/proposal.md":!1}async function DB(e){let{projectRoot:t,changeDir:r,change:n}=e,i=[],s=[...["proposal.md","design.md","tasks.md"].map(c=>r+"/"+c),...await mo(t,r+"/specs")];for(let c of s)await Wt(t,c,{label:"Classic handoff source",expected:"file"})&&i.push({reference:be(t,c),content:await Pe(t,c,{label:"Classic handoff source"})});await fu(t,r+"/.comet/handoff","Classic handoff view directory");let o=r+"/.comet/handoff/design-context.md";return await Wi(t,o,jB(n,"full","",i),{label:"Classic handoff view"}),be(t,o)}var DX=jA(async e=>{let[t,r,n,i]=e;if(r==="--hash-only")return{exitCode:64,stderr:`handoff --hash-only 已移除。由 Agent 读取实际文档并判断上下文是否需要更新。
|
|
238
|
+
`};if(r!=="design"||n!=="--write"||e.length!==3&&!(e.length===4&&i==="--full"))return{exitCode:64,stderr:`Usage: comet handoff <change-name> design --write [--full]
|
|
239
|
+
`};let s=ho(t);if(s)return{exitCode:1,stderr:s};let o=NA(),c=await Ni(o),l=await An(t,c.projectRoot);return!l.exists||!l.stateExists?{exitCode:1,stderr:"Classic change directory or state is missing"}:Nr(l.directory,async()=>{let f=await dr(l.directory);if(!f.classic||!["design","build"].includes(f.classic.phase))throw new Error("Design handoff requires phase: design or build");let a=await Ed(o,l.directory);if(a.problems.length)throw new Error(a.problems.join(`
|
|
240
|
+
`));let d=await Mx(l.directory),p=await dx(l.directory,d.run.pendingRef);if(d.run.pending&&p?.type!=="handoff")throw new Error("Another Classic action is pending");if(p&&d.run.pending!==p.id)throw new Error("Classic handoff pending identity does not match the original Run");let u=await Hx({projectRoot:o,changeDir:l.directory,change:t,contextCompression:d.classic.contextCompression}),m=u.handoffContext.replace(/\.json$/u,".md"),h=await Pe(o,m,{label:"Classic handoff"}),g=i==="--full"?await DB({projectRoot:o,changeDir:l.directory,change:t}):null;await Id(l.directory,d.run.contextRef,h),await _d(l.directory,d.run.artifactsRef,{...await ux(l.directory,d.run.artifactsRef),handoff_context:u.handoffContext,handoff_markdown:m});let w={...d.classic,...u},k={...d.run,pending:null};if(k.currentStep==="full.design.handoff"&&(k=await Fx(l.directory,w,k,{actionId:p?.id??$B(),kind:"classic-handoff"})),await qs(l.directory,{...f,classic:w,run:k}),p){let R=await xd(l.directory,k.trajectoryRef);R.some(E=>E.type==="recovery_reconciled"&&E.data?.actionId===p.id)||await vo(l.directory,k.trajectoryRef,{sequence:R.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:k.runId,data:{kind:"classic-handoff",actionId:p.id}}),await fx(l.directory,d.run.pendingRef)}let b=tx({name:t,locale:yo(w.language)});return{exitCode:0,envelope:b,stderr:b.summary+`
|
|
241
|
+
[HANDOFF] source `+u.handoffContext+(g?`
|
|
242
|
+
[HANDOFF] view `+g:"")+`
|
|
243
|
+
`}})});import qB from"node:path";async function Vx(e,t,r){if(r!=="en"&&r!=="zh-CN")return"Classic change language is not set";let n=t.replaceAll("\\","/");for(let i of["proposal.md","tasks.md","design.md"]){let s=qB.posix.join(n,i);if(i==="design.md"&&!await Wt(e,s,{label:"Classic Open design"}))continue;let o=await Pe(e,s,{label:`Classic Open ${i}`});if(!o.trim())return i+" is empty";if(i==="tasks.md"&&ds(o).length===0)return"tasks.md has no task"}return null}function Fe(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic delivery recovery evidence is missing");return e}function ps(e,t){let r=e.state.workflow,n=e.actions.slice().reverse().find(l=>l.stepId===`${r}.archive.execute`&&l.status==="succeeded"),i=e.actions.slice().reverse().find(l=>l.stepId===r+(e.workflow.version==="2"?".archive.preflight":".verify.check")&&l.status==="succeeded");if(!n?.outcome||!i?.outcome||t&&(t.archiveActionId!==n.id||t.checkActionId!==i.id))throw new Error("Classic delivery recovery requires its original Archive and Verify");let s=Fe(n.input).outputs,o=Fe(Fe(s)[`${r}.archive.preflight`]),c=Fe(n.outcome.output).archiveDirectory;if(typeof c!="string"||typeof o?.baseCommit!="string")throw new Error("Classic delivery recovery lacks its approved archive target");return{profile:r,archive:n,check:i,approved:{...o,baseCommit:o.baseCommit},archiveRef:c}}function Co(e){return Fe(Fe(e.input).activation).deliveryRepair}function So(e,t){let r=e.state;return r.archived&&r.phase==="archive"&&t.type==="call_tool"&&t.ref==="classic-check"&&t.stepId===`${r.workflow}.delivery.check`}function Rw(e,t){let r=ps(e,t),n=Fe(r.check.outcome.output),i=Array.isArray(n.deliveryPaths)?n.deliveryPaths:Object.keys(n.deliveryInputs??{}),s=new Set(t.excludedOutputPaths??Object.keys(t.excludedOutputs??{}));return i.filter(o=>!s.has(o))}function Sw(e){let t=e.state,r=e.actions.filter(i=>i.status==="pending"),n=e.waits.filter(i=>i.status==="pending");if(!t.archived||t.phase!=="archive"||!["running","waiting","failed"].includes(e.status)||e.actions.some(i=>["running","unknown"].includes(i.status))||e.evidenceWaits?.some(i=>i.status==="pending"))return!1;if(e.status==="failed"){let i=e.actions.at(-1);return r.length===0&&n.length===0&&i?.status==="failed"&&So(e,i)}return n.length?e.status==="waiting"&&r.length===0&&n.length===1&&n[0].stepId===`${t.workflow}.delivery.confirm`:e.status==="running"&&r.length===1&&!r[0].claim&&(r[0].stepId===`${t.workflow}.archive.deliver`||So(e,r[0]))}function Ux(e,t){if(e===void 0||t.state.archived!==!0)return!1;let r=j(e);return!!t.commands?.some(n=>{if(!["repair-delivery","continue-work"].includes(n.name))return!1;let i=t.actions.find(o=>o.id===n.actionId);if(!i||j(i.input)!==i.inputHash)return!1;let s=Fe(Fe(i.input).activation);if(n.name==="continue-work"){let o=t.actions.find(c=>c.id===s.interruptedActionId);return i.stepId==="classic.resume-work"&&typeof s.deliveryCheckpointHash=="string"&&j(s)===n.inputHash&&s.deliveryCheckpointHash===r&&!!(o?.status==="failed"&&_n(t,o))}return So(t,i)&&j(s)===n.inputHash&&Fe(s.deliveryRepair).checkpointHash===r})}function _n(e,t){let r=e.state;if(!r.archived||t.type!=="invoke_skill"||t.stepId!==`${r.workflow}.archive.deliver`)return null;let n=Fe(t.input).activation,i=n===void 0?{}:Fe(n),s=i.deliveryRepairCheckId;if(s===void 0&&i.interruptedActionId!==void 0){let p=e.actions.find(g=>g.id===i.interruptedActionId),u=e.actionContexts[t.id]?.sequence,m=e.actionContexts[t.id]?.results["classic.resume-work"],h=e.actions.find(g=>g.stepId==="classic.resume-work"&&e.actionContexts[g.id]?.sequence===m?.sequence);if(!p||p.status!=="failed"||p.type!==t.type||p.ref!==t.ref||p.stepId!==t.stepId||u===void 0||(e.actionContexts[p.id]?.sequence??1/0)>=u||h?.status!=="succeeded"||h.claim?.executorId!=="comet-classic-work-continuation"||j(h.outcome?.output)!==j({interruptedActionId:p.id,resumeStepId:p.stepId})||Fe(Fe(h.input).activation).interruptedActionId!==p.id||!e.commands?.some(g=>g.name==="continue-work"&&g.actionId===h.id&&g.inputHash===j(Fe(h.input).activation)))throw new Error("Classic delivery continuation is missing its original stopped Skill");return _n(e,p)}let o=ps(e),c=e.actionContexts[o.archive.id]?.results[`${r.workflow}.archive.confirm`]?.sequence,l=e.waits.find(p=>p.stepId===`${r.workflow}.archive.confirm`&&p.sequence===c&&p.status==="resolved"),f={outputs:{...Fe(Fe(o.archive.input).outputs),[o.archive.stepId]:o.archive.outcome.output},archiveActionId:o.archive.id,approvalWaitIds:l?[l.id]:[]};if(s===void 0){let p=Fe(Fe(t.input).outputs);if(e.actionContexts[t.id]?.results[o.archive.stepId]?.sequence!==e.actionContexts[o.archive.id]?.sequence||j(p[`${r.workflow}.archive.preflight`])!==j(o.approved)||j(p[o.archive.stepId])!==j(o.archive.outcome.output))throw new Error("Classic delivery is missing its original approved Archive context");return f}let a=e.actions.find(p=>p.id===s),d=e.waits.slice().reverse().find(p=>p.stepId===`${r.workflow}.delivery.confirm`&&p.results[`${r.workflow}.delivery.check`]?.sequence===(a&&e.actionContexts[a.id]?.sequence));if(!a||!So(e,a)||a.status!=="succeeded"||d?.status!=="resolved"||d.decision?.choice!=="approved"||j(Fe(Fe(d.proposal).outputs)[a.stepId])!==j(a.outcome.output))throw new Error("Classic delivery repair is missing its current check and explicit approval");return ps(e,Co(a)),{...f,outputs:{...f.outputs,[a.stepId]:a.outcome.output},repairCheckId:a.id,approvalWaitIds:[...f.approvalWaitIds,d.id]}}function Sc(e,t){let r=_n(e,t);if(r){let f=e.actions.find(a=>a.id===r.archiveActionId);if(!f)throw new Error("Classic delivery recovery is missing its original Archive");return Sc(e,f)}let n=t.input.outputs??{};if(n["full.build.plan"]!==void 0)return{outputs:n,recovered:!1};let i=e.actionContexts[t.id]?.sequence;if(i===void 0)return{outputs:n,recovered:!1};let s=[...e.commands??[]].reverse().find(f=>f.actionId===t.id||(e.actionContexts[f.actionId]?.sequence??1/0)<i);if(!s||!["reopen-verification","continue-build"].includes(s.name))return{outputs:n,recovered:!1};let o=e.actionContexts[s.actionId].sequence,c=[...e.actions].reverse().filter(f=>f.stepId==="full.build.execute"&&(e.actionContexts[f.id]?.sequence??1/0)<o),l=c[0];if(l?.status!=="succeeded"||l.outcome?.status!=="succeeded"||l.outcome.output.event!=="build-complete")return{outputs:n,recovered:!1};for(let f of c){let a=e.actionContexts[f.id].sequence;if(e.commands?.some(p=>["revise-design","revise-plan"].includes(p.name)&&e.actionContexts[p.actionId]?.sequence>a&&e.actionContexts[p.actionId].sequence<o))break;let d=f.input.outputs;if(!(d?.["full.build.plan"]===void 0||d["full.design.document"]===void 0))return{recovered:!0,outputs:{"full.design.document":d["full.design.document"],"full.build.plan":d["full.build.plan"]}}}return{outputs:n,recovered:!1}}import{promises as WB}from"node:fs";import ms from"node:path";qt();ye();qt();ye();import{promises as LB}from"node:fs";import qd from"node:path";async function zx(e,t,r,n){let i=t.input.changeDir;if(rt(i,"Classic active path"),rt(n,"Classic archive path"),r.status!=="succeeded"||r.outcome?.status!=="succeeded"||r.claim?.executorId!=="comet-classic-archive"||r.outcome.output?.archiveDirectory!==n)throw new Error("旧 Archive 缺少成功的原执行结果");let s=[],o=[];async function c(m){let h=await U(e,m,{label:"Classic legacy archive path",expected:"any"});if(h.exists)if(h.kind==="directory")for(let g of await LB.readdir(h.target)){if([".comet-state.lock",".comet-state-transaction.json"].includes(g)){let w=m+"/"+g+"/.comet-runtime-migration.json";(await U(e,w,{label:"Classic legacy migration marker",expected:"file"})).exists&&(o.push(w),s.push(i+"/"+w.slice(n.length+1)));continue}await c(m+"/"+g)}else s.push(m)}await c(n);let l=qd.relative(e,(await mn(e)).specsDir).replaceAll("\\","/");for(let m of[...s])m.startsWith(n+"/specs/")&&m.endsWith("/spec.md")&&s.push(l+"/"+m.slice((n+"/specs/").length));let f=Sc(t,r).outputs,a=f["full.design.document"]?.designDoc,d=f["full.build.plan"]?.plan;for(let m of[a,d])m&&s.push(Sr(m,i,n));let p=qd.relative(e,await fe(qd.join(e,n))).replaceAll("\\","/"),u=s.filter(m=>m.startsWith(n+"/")).map(m=>i+"/"+m.slice(n.length+1));return{paths:[...new Set([...s,...u])],sourcePaths:u,stateFiles:[p,i+"/"+qd.posix.basename(p)],optionalPaths:o}}var Kx=".comet/archive-manifest.json";function Cw(e,t){return j(Jg(e,t))}async function Gx(e){return Mr({singleWriter:!0,rootDir:ms.join(await jn(e),"archive-receipts/classic")})}async function MB(e){return Mr({singleWriter:!0,rootDir:ms.join(await jn(e),"archive-inputs/classic")})}async function Jx(e,t,r){if(r.status!=="failed"||r.outcome?.status!=="failed")throw new Error("原 Archive 尚未确认失败退出;先恢复原 Action 并核对实际归档进度");let n=t.input.changeDir;if(!(await U(e,n,{label:"Classic active change",expected:"directory"})).exists)throw new Error("原 change 目录已搬迁;恢复原 Archive 进度,不能重开执行");let s=await(await MB(e)).read(Cw(t,r));if(s?.snapshot.archivePaths){let o=await U(e,ms.posix.dirname(n)+"/archive",{label:"Classic Archive directory",expected:"directory"}),c=ms.posix.basename(n);if(o.exists&&(await WB.readdir(o.target)).some(l=>/^\d{4}-\d{2}-\d{2}-/u.test(l)&&l.slice(11)===c&&!s.snapshot.archivePaths.includes(l)))throw new Error("原 Archive 已创建归档目录;先恢复该事务,不能重开执行")}}async function FB(e,t,r,n){let i=await(await Gx(e)).read(Cw(t,r));if(!i||i.manifest.archiveRef!==n||i.manifest.execution.actionId!==r.id)throw new Error("原 Archive 执行收据缺失;核对原命令结果并恢复原记录,不能重复执行或用当前文件补造成功");return i}async function Yx(e,t,r,n,i){return await FB(e,t,r,n),Eo(e,t,r,n)}async function Eo(e,t,r,n,i=r.outcome?.artifacts){await U(e,n+"/"+Kx,{label:"Classic Archive manifest",expected:"file"});let s=await(await Gx(e)).read(Cw(t,r)),o=r.outcome?.output?.archiveManifest,c=s?.manifest??o;if(!c)return zx(e,t,r,n);if(!["comet.classic.archive-manifest.v1","comet.classic.archive-manifest.v2"].includes(c.schema)||c.activeRef!==t.input.changeDir||c.archiveRef!==n||c.execution?.actionId!==r.id||c.execution?.runId!==t.runId)throw new Error("归档交付记录不属于原 Run 和 Action");let l=c.paths??Object.keys(c.files??{}),f=c.sourcePaths??Object.keys(c.sources??{}),a=c.optionalPaths??Object.keys(c.optionalFiles??{});for(let p of[...l,...f,...a])rt(p,"Classic Archive path");let d=ms.relative(e,await fe(ms.join(e,n))).replaceAll("\\","/");return{paths:[...new Set([...l,n+"/"+Kx,...f.filter(p=>p.startsWith(c.activeRef+"/"))])],sourcePaths:f,stateFiles:[d,c.activeRef+"/"+ms.posix.basename(d)],optionalPaths:[...new Set([...a,...[".comet-state.lock",".comet-state-transaction.json"].map(p=>n+"/"+p+"/.comet-runtime-migration.json")])]}}function Ld(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yi(e,t){return St(e)===St(t)}function Xx(e){return{protocolVersion:e.protocolVersion,id:e.id,runId:e.runId,stepId:e.stepId,type:e.type,...e.ref===void 0?{}:{ref:e.ref},input:e.input,inputHash:e.inputHash,retry:e.retry,requiredCapabilities:e.requiredCapabilities}}function Ao(e,t,r={}){if(Ld(t.state).archived!==!0||Ux(e,t))return null;let n=(r.projection?pd:rn)(e,t.runId,{preserveSourceRevision:!0});if(!n)return null;let i=Ld(n.state),s=n.actions.at(-1),o=`${i.workflow}.archive.deliver`;if(i.archived!==!0||i.phase!=="archive"||!["full","tweak","hotfix"].includes(String(i.workflow))||n.status!=="running"||!s||s.stepId!==o||s.status!=="pending"||s.claim||s.outcome)return null;let c=()=>{throw new Error(`Classic SDK Run ${t.runId} does not match its archived delivery checkpoint; restore the original checkpoint and reconcile delivery on the same Run without changing its Archive or Verify history`)},l=n.outputs[o],f=n.actionContexts[s.id]?.sequence,a=l!==void 0&&l.sequence===f,d=l!==void 0&&!a&&n.actions.some(w=>w.id!==s.id&&w.stepId===o&&w.status==="failed"&&w.outcome?.status==="failed"&&n.actionContexts[w.id]?.sequence===l.sequence&&f!==void 0&&l.sequence<f&&yi(w.outcome.output,l.value));(i.branchStatus!=="pending"||s.type!=="invoke_skill"||typeof s.ref!="string"||!s.ref.trim()||s.retry!=="manual"||s.reconciliations.length!==s.attempt-1||s.reconciliations.some((w,k)=>w.attempt!==k+1)||s.receipts.length>=s.attempt||(s.rejectedOutcomes?.length??0)!==0||s.receipts.length!==0!==a||l!==void 0&&!a&&!d||s.reason!==void 0||n.reason!==void 0||!n.actions.some(w=>w.stepId===`${i.workflow}.archive.execute`&&w.ref==="classic-archive"&&w.status==="succeeded")||n.actions.slice(0,-1).some(w=>["pending","running","unknown"].includes(w.status))||n.ready.length!==0||n.waits.some(w=>w.status==="pending")||n.evidenceWaits?.some(w=>w.status==="pending")||Object.values(n.joins).some(w=>Object.values(w).some(k=>k.length!==0)))&&c();let p=t.actions.at(-1);if(!p)return c();yi(Xx(p),Xx(s))||c(),vu(p,St(p.input)),(!["pending","running","unknown","failed","succeeded"].includes(p.status)||p.cancellation||p.executionOrigin&&!yi(p.executionOrigin.workflow,t.workflow)||p.reconciliations.length!==p.attempt-1||p.reconciliations.some((w,k)=>w.attempt!==k+1)||p.attempt<s.attempt||!yi(p.receipts.slice(0,s.receipts.length),s.receipts)||!yi(p.reconciliations.slice(0,s.reconciliations.length),s.reconciliations)||p.receipts.length-(p.rejectedOutcomes?.length??0)>p.attempt||p.status==="pending"&&p.reason!==void 0)&&c();let u=p.status==="succeeded",m=p.status==="failed";(t.status!==(u?"completed":m?"failed":"running")||t.reason!==(m?`ACTION_FAILED: ${o}`:void 0)||Ld(t.state).branchStatus!==(u?"handled":i.branchStatus)||t.revision<n.revision+(p.attempt-s.attempt)*3+(p.status==="pending"?0:p.status==="running"?1:2))&&c(),!p.outcome&&p.receipts.length===s.receipts.length&&(Object.hasOwn(t.outputs,o)!==Object.hasOwn(n.outputs,o)||Object.hasOwn(n.outputs,o)&&!yi(t.outputs[o],n.outputs[o]))&&c(),p.outcome?yi(t.outputs[o],{sequence:n.actionContexts[s.id].sequence,value:p.outcome.output})||c():Object.hasOwn(t.outputs,o)&&!(d&&yi(t.outputs[o],l)&&p.receipts.length===(p.rejectedOutcomes?.length??0))&&(p.attempt===1||p.receipts.length===(p.rejectedOutcomes?.length??0)||t.outputs[o].sequence!==n.actionContexts[s.id].sequence)&&c();let h={...t.outputs};Object.hasOwn(n.outputs,o)?h[o]=n.outputs[o]:delete h[o];let g={...t,revision:n.revision,status:n.status,state:{...Ld(t.state),branchStatus:i.branchStatus},actions:[...t.actions.slice(0,-1),s],outputs:h};return delete g.reason,ns(e,g)||c(),n}import{execFileSync as BB}from"node:child_process";import e_ from"node:path";qt();pn();import HB from"node:path";async function Qx(e){let t=await fn(e,{allowPartialProject:!0,allowMissingNativeFields:!0});return t?.native?[HB.posix.join(t.native.artifact_root,"comet","changes")]:[]}function Zx(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function VB(e,t){return BB("git",t,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:Number.MAX_SAFE_INTEGER,stdio:["ignore","pipe","pipe"]})}async function UB(e){let t=await mn(e);return[".comet",t.openSpecRoot,t.superpowersRoot,...await Qx(e)].map(r=>e_.isAbsolute(r)?e_.relative(e,r).replaceAll("\\","/"):r)}async function t_(e,t){let r=t.state,n=[...t.actions].reverse().find(m=>m.stepId===r.workflow+".archive.deliver"),i=n?_n(t,n)?.repairCheckId:void 0,s=pA(t),o=i?t.actions.find(m=>m.id===i):[...t.actions].reverse().find(m=>m.stepId===r.workflow+".archive.preflight");if(o?.status!=="succeeded"||o.outcome?.status!=="succeeded")throw new Error("Classic 交付需要当前成功的 Verify 检查");let c=o.outcome.output,l=s?.output.deliveryInputs,f=c.deliveryPaths?[]:await UB(e),a=(c.deliveryPaths??Object.keys(c.deliveryInputs??l??{})).filter(m=>!Zx(m,f)),d=t.evidenceWaits?.slice().reverse().find(m=>m.stepId===r.workflow+".verify.report.evidence"&&m.status==="resolved")?.receipt,p=t.input.changeDir,u=t.outputs[r.workflow+".archive.execute"]?.value?.archiveDirectory;if(r.verificationReport&&!d)throw new Error("Classic 交付缺少已接受的验证报告");return d&&a.push(u?Sr(d.ref,p,u):d.ref),Ew(e,a)}async function Ew(e,t,r){let n=Array.isArray(t)?t:Object.keys(t);for(let s of n)rt(s,"Classic delivery path");let i=n.length?VB(e,["status","--porcelain","--untracked-files=all","--",...n]).trim():"";if(i)throw new Error("Classic 交付路径尚有未提交修改:"+i);return new Set(n)}import{createHash as zB}from"node:crypto";import{execFileSync as xw}from"node:child_process";function Aw(e,t,r){let n=xw("git",["remote","get-url",...r?["--push"]:[],t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim();if(!n)throw new Error("Classic delivery remote URL is empty");let i=null;try{i=new URL(n)}catch{}if(i&&(i.password||i.search||i.hash||["http:","https:"].includes(i.protocol)&&i.username))throw new Error("Classic delivery remote must not contain credentials");return n}function n_(e,t){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(t))throw new Error("Classic delivery remote must be a configured remote name");let r=Aw(e,t,!1),n=Aw(e,t,!0);if(r!==n)throw new Error("Classic delivery remote has different fetch and push URLs");return zB("sha256").update(r).digest("hex")}function i_(e,t,r){let n=`refs/heads/${r}`,i=xw("git",["-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",t,n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4}).trim(),s=/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(i);return s?.[2]===n?s[1]:null}function KB(e){let t=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(e);try{let r=new URL(t?`ssh://git@${t[1]}/${t[2]}`:e);if(!["https:","ssh:"].includes(r.protocol)||r.password||r.search||r.hash||r.port||r.protocol==="https:"&&r.username)return null;let n=r.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return n.length!==2||n.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${r.hostname}/${n.join("/")}`.toLowerCase()}catch{return null}}function r_(e,t){try{let r=new URL(e);if(r.protocol!=="https:"||r.username||r.password||r.port||r.search||r.hash)return null;let n=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(r.pathname);return n&&`${r.hostname}/${n[1]}/${n[2]}`.toLowerCase()===t?`https://${r.hostname}/${n[1]}/${n[2]}/pull/${n[3]}`:null}catch{return null}}function s_(e){let t=KB(Aw(e.projectRoot,e.remote,!1)),r=t&&r_(e.prUrl,t);if(!t||!r)return!1;let n=xw("gh",["pr","view",r,"--repo",t,"--json","url,headRefName,headRefOid,baseRefName,state"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,env:{...process.env,GH_PROMPT_DISABLED:"1",GIT_TERMINAL_PROMPT:"0"}}),i=JSON.parse(n);return typeof i.url=="string"&&r_(i.url,t)===r&&i.headRefName===e.targetBranch&&i.headRefOid===e.commit&&i.baseRefName===e.baseBranch&&(i.state==="OPEN"||i.state==="MERGED")}ye();import Cc from"node:path";async function _w(e,t,r){let n=await mn(e),i=await U(e,t,{label:"Classic Verify report",expected:"file"}),s=Cc.relative(n.superpowersReportsDir,i.target);if(!i.exists||!s||s.startsWith(`..${Cc.sep}`)||Cc.isAbsolute(s)||s.includes(Cc.sep)||Cc.extname(s).toLowerCase()!==".md")throw new Error("Classic Verify report is outside the configured reports directory");let o=i.relative.replaceAll("\\","/");if(!(await ae(e,o,Number.MAX_SAFE_INTEGER,{label:"Classic Verify report"})).bytes.toString("utf8").trim())throw new Error("Classic Verify report is empty");return{ref:o}}var Wd={type:"array",items:{type:"object",required:["name","result"],additionalProperties:!1,properties:{name:{type:"string",minLength:1},result:{enum:["passed","failed","not-run"]},note:{type:"string",minLength:1}}}},l_={id:"comet-classic-open-revalidate",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="classic-open-revalidate",async execute(e,t){if(!t?.projectRoot)throw new Error("Classic Open requires its project root");return{status:"succeeded",output:{contentHash:e.inputHash}}}},Iw={id:"comet-classic-open-revalidation",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=e.waits.find(o=>o.stepId==="full.open.confirm"&&o.status==="resolved"&&o.decision?.choice==="approved"),s=r.output;return i&&n?.projectRoot&&t.claim?.executorId===l_.id&&s?.contentHash===t.inputHash?{accepted:!0}:{accepted:!1,reason:"Classic Open has no approval for its current SDK request"}}},Pw={id:"comet-classic-design-handoff",version:"1",async validate({run:e,outcome:t,context:r}){if(t.status==="failed")return{accepted:!0};let n=e.input,i=e.state,s=t.output;if(!r?.projectRoot||typeof n.change!="string"||typeof n.changeDir!="string"||typeof s?.proposal!="string"||typeof s.handoffContext!="string")return{accepted:!1,reason:"Classic Design handoff lacks a source-bound context pack"};try{if(s.sourceEvidence||s.requirementsEvidence){let c=await Md(r.projectRoot,n.changeDir,{run:e}),l=c;if(s.sourceEvidence?.ref!==c.ref||s.requirementsEvidence?.ref!==l.ref)return{accepted:!1,reason:"Classic Design proposal sources changed before submission"}}return{accepted:await Bx({run:e,projectRoot:r.projectRoot,changeDir:Er.join(r.projectRoot,n.changeDir),change:n.change,contextCompression:i.contextCompression,handoffContext:s.handoffContext,handoffHash:typeof s.handoffHash=="string"?s.handoffHash:null}),reason:"Classic Design handoff no longer matches its OpenSpec sources"}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},Ow={id:"comet-classic-build-configuration",version:"1",validate({run:e,outcome:t}){if(t.status==="failed")return{accepted:!0};let r=e.state,n=t.output;if(!n||!r.isolation||n.isolation!==r.isolation||n.boundBranch!==r.boundBranch)return{accepted:!1,reason:"Classic Build workspace binding changed in the proposal"};let i={...r,...n},s=cs(i);return s.missingFields.length||s.invalidFields.length?{accepted:!1,reason:"Classic Build configuration is incomplete or invalid"}:{accepted:!0}}},GB={id:"comet-classic-archive-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=n?.projectRoot,s=t.input,o=r.output;if(!i||t.claim?.executorId!=="comet-classic-archive"||typeof s.input?.changeDir!="string"||typeof o?.archiveDirectory!="string")return{accepted:!1,reason:"Classic Archive result lacks its execution identity"};try{let c=await mn(i),[l,f]=await Promise.all([U(i,s.input.changeDir,{label:"Classic active change",expected:"directory"}),U(i,o.archiveDirectory,{label:"Classic archived change",expected:"directory"})]),a=Er.relative(c.archiveDir,f.target),d=Er.basename(f.target);if(l.exists||!f.exists||Er.dirname(l.target)!==c.changesDir||!a||a.startsWith(`..${Er.sep}`)||Er.isAbsolute(a)||a.includes(Er.sep)||!/^\d{4}-\d{2}-\d{2}-/u.test(d)||d.slice(11)!==Er.basename(l.target))return{accepted:!1,reason:"Classic Archive has not moved the approved change"};let p=await QA(i,f.target);if(p.length>0)return{accepted:!1,reason:p.join(`
|
|
244
|
+
`)};let u=e.actions.find(m=>m.id===t.id);return u?.status==="succeeded"&&u.outcome&&j(u)===j(t)&&j(u.outcome)===j(r)?await Eo(i,e,u,o.archiveDirectory):await Yx(i,e,t,o.archiveDirectory,r.artifacts),{accepted:!0}}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}};async function JB(e,t,r,n){let i=Er.relative(e,await fe(Er.join(e,t))).replaceAll("\\","/");if(r!==`M ${i}`)return!1;let s=vi("git",["show",`HEAD:${i}`],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),o=await Pe(e,Er.join(e,i),{label:"Classic state file"}),c=(0,$w.parseDocument)(s,{uniqueKeys:!0}),l=(0,$w.parseDocument)(o,{uniqueKeys:!0});if(c.errors.length>0||l.errors.length>0)return!1;let f=c.toJS(),a=l.toJS();return!rn(f[It],n.runId)||!rn(a[It],n.runId)||!pc(a[It],lo(n))&&!Ao(a[It],n)?!1:(delete f[It],delete a[It],Nw(f,a))}var YB={id:"comet-classic-delivery-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=n?.projectRoot,s=t.stepId.split(".")[0],o=t.input,c=_n(e,t)?.outputs??o.outputs,l=c?.[`${s}.archive.preflight`],f=c?.[`${s}.archive.execute`],a=r.output;if(!i||!["full","hotfix","tweak"].includes(s)||!l||!a||!["local","push","pr"].includes(String(l.deliveryAction))||a.action!==l.deliveryAction||a.targetBranch!==l.targetBranch||typeof l.baseCommit!="string"||!f||typeof f.archiveDirectory!="string"||typeof o.input?.changeDir!="string"||typeof a.commit!="string"||!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u.test(a.commit))return{accepted:!1,reason:"Classic delivery does not match its approval"};try{let d=fr(i);if(d!==l.targetBranch)return{accepted:!1,reason:`Classic 当前分支 ${d??"(detached HEAD)"} 与已批准目标 ${String(l.targetBranch)} 不一致`};if(l.deliveryAction!=="local"&&(typeof l.remote!="string"||a.remote!==l.remote||typeof l.remoteIdentity!="string"||n_(i,l.remote)!==l.remoteIdentity))return{accepted:!1,reason:"Classic delivery remote changed after approval"};let p=vi("git",["rev-parse","HEAD"],{cwd:i,encoding:"utf8"}).trim();if(p!==a.commit)return{accepted:!1,reason:`Classic 当前 HEAD ${p} 与交付提交 ${a.commit} 不一致`};if(!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u.test(l.baseCommit))return{accepted:!1,reason:"Classic 交付缺少有效的已批准基线 baseCommit"};let u=vi("git",["rev-list","--reverse","--parents",`${l.baseCommit}..${p}`,"--"],{cwd:i,encoding:"utf8"}).trim().split(`
|
|
245
|
+
`).filter(Boolean);if(!u.length)return{accepted:!1,reason:`Classic 已批准基线 ${l.baseCommit} 之后没有交付提交`};let m=l.baseCommit,h=new Set,g=VA(i,u.map($=>$.split(/\s+/u)[0]));for(let $ of u){let[T,...L]=$.split(/\s+/u);if(L.length!==1)return{accepted:!1,reason:`Classic 交付范围包含非线性提交 ${T}(父提交数 ${L.length});只接受从已批准基线 ${l.baseCommit} 连续产生的单父提交`};if(L[0]!==m)return{accepted:!1,reason:`Classic 交付提交 ${T} 的父提交 ${L[0]} 不等于 ${m};交付范围必须从已批准基线 ${l.baseCommit} 连续开始`};let H=g.get(T);for(let ie of H)h.add(ie);m=T}let w=vi("git",["ls-tree","-r","--name-only","HEAD","--",f.archiveDirectory],{cwd:i,encoding:"utf8"}).trim(),k=vi("git",["status","--porcelain","--untracked-files=all","--",f.archiveDirectory],{cwd:i,encoding:"utf8"}).trim(),b=o.input.changeDir.replaceAll("\\","/"),R=f.archiveDirectory.replaceAll("\\","/"),O=Sc(e,t).outputs,z=O["full.build.plan"],D=O["full.design.document"]?.designDoc??z?.designEvidence?.ref,G=z?.plan;if(s==="full"&&(typeof D!="string"||typeof G!="string"))return{accepted:!1,reason:"Classic Archive documents are missing"};let J=Er.posix.basename(R),te=typeof D=="string"?Sr(D,b,R):null,Z=typeof G=="string"?Sr(G,b,R):null,we=s==="full"?vi("git",["show",`HEAD:${te}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,K=s==="full"?vi("git",["show",`HEAD:${Z}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,ne=await t_(i,e),ze=e.actions.slice().reverse().find($=>$.stepId===`${s}.archive.execute`&&$.status==="succeeded");if(!ze)throw new Error("Classic delivery 缺少成功的 Archive Action");let P=await Eo(i,e,ze,R);for(let $ of P.optionalPaths){let T=$.startsWith(`${R}/`)?`${b}/${$.slice(R.length+1)}`:null;if(vi("git",["ls-tree","-z","HEAD","--",$],{cwd:i,encoding:"utf8"}))P.paths.push($,...T?[T]:[]);else if(T&&[...g.values()].some(H=>H.includes(T)))throw new Error(`Classic archive commit deletes an optional input without committing the archived copy: ${$}`)}let F=await Ew(i,P.paths),re=$=>ne.has($)||F.has($)||P.stateFiles.includes($),He=[...h].filter($=>!re($));if(He.length)return{accepted:!1,reason:`Classic 交付提交范围包含未批准的路径:${He.join(", ")}`};let C=k!==""&&await JB(i,R,k,e);return w?k&&!C?{accepted:!1,reason:`Classic 归档目录与交付 HEAD 不一致:${k}`}:[...h].some($=>$.startsWith(`${R}/`))?s==="full"&&(!te||!Z||!h.has(te)||!h.has(Z)||!we?.includes(`archived-with: ${J}`)||!we.includes("status: final")||!K?.includes(`archived-with: ${J}`))?{accepted:!1,reason:`Classic 交付范围缺少已归档的设计或计划,或归档标记不符:${te}, ${Z}`}:l.deliveryAction!=="local"&&i_(i,l.remote,l.targetBranch)!==a.commit?{accepted:!1,reason:"Classic remote branch does not contain the archive commit"}:l.deliveryAction==="pr"&&(typeof a.prUrl!="string"||typeof l.prBaseBranch!="string"||!s_({projectRoot:i,remote:l.remote,prUrl:a.prUrl,targetBranch:l.targetBranch,commit:a.commit,baseBranch:l.prBaseBranch}))?{accepted:!1,reason:"Classic PR does not match the approved delivery"}:{accepted:!0}:{accepted:!1,reason:`Classic 交付范围 ${l.baseCommit}..${p} 未包含归档目录:${R}`}:{accepted:!1,reason:`Classic 交付 HEAD 缺少归档目录:${R}`}}catch(d){return{accepted:!1,reason:d instanceof Error?d.message:String(d)}}}};async function Md(e,t,r={}){let n=await U(e,t,{label:"Classic change",expected:"directory"});if(!n.exists||r.run&&r.run.input.changeDir!==n.relative)throw new Error("Classic artifacts do not belong to the current change");let i=await Ed(e,n.target);if(i.problems.length)throw new Error(i.problems.join(`
|
|
246
|
+
`));return{ref:n.relative}}async function XB(e,t){let r=rt(t,"Classic Design document");if(!(await ae(e,r,Number.MAX_SAFE_INTEGER,{label:"Classic Design document"})).bytes.length)throw new Error("Classic Design document is empty");return{ref:r}}async function u_(e,t,r){if((await mi(e,t)).status!=="ready")throw new Error("Classic Build plan is not ready");let i=await U(e,t,{label:"Classic Build plan",expected:"file"}),s=await U(e,r,{label:"Classic change",expected:"directory"});if(!i.exists||!s.exists)throw new Error("Classic Build plan or change is missing");return{ref:i.relative}}var o_={id:"comet-classic-open-artifacts",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,s=e.input.changeDir,o=e.actions.slice().reverse().find(c=>c.stepId===i.workflow+".open");if(!n?.projectRoot||t!==s||o?.status!=="succeeded"||r!==o.inputHash)return{accepted:!1,actualHash:"",reason:"Classic Open evidence does not belong to its completed Action"};try{await Md(n.projectRoot,t,{run:e});let c=await Vx(n.projectRoot,t,i.language);if(c)throw new Error(c);return{accepted:!0,actualHash:o.inputHash}}catch(c){return{accepted:!1,actualHash:"",reason:String(c)}}}},QB={id:"comet-classic-design-document",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,s=e.actions.slice().reverse().find(o=>o.stepId==="full.design.document");if(!n?.projectRoot||i.designDoc!==t||s?.status!=="succeeded"||r!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic Design evidence does not belong to its completed Action"};try{return await XB(n.projectRoot,t),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},ZB={id:"comet-classic-build-plan",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,s=e.actions.slice().reverse().find(o=>o.stepId==="full.build.plan");if(!n?.projectRoot||i.plan!==t||s?.status!=="succeeded"||r!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic plan evidence does not belong to its completed Action"};try{return await u_(n.projectRoot,t,String(e.input.changeDir)),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},a_={id:"comet-classic-verification-report",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,s=e.actions.slice().reverse().find(o=>o.stepId===i.workflow+".verify.run");if(!n?.projectRoot||i.phase!=="verify"||i.verificationReport!==t||s?.status!=="succeeded"||r!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic report does not belong to its completed Verify Action"};try{return await _w(n.projectRoot,t,i.language),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},eV=["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],In={type:["string","null"]},c_={type:["boolean","null"]},Tw={id:"comet-classic-preset-scope",version:"1",async validate({run:e,outcome:t,context:r}){let n=t.output;if(t.status!=="succeeded"||n?.event!=="escalation-requested"||!n.requirementsEvidence)return{accepted:!0};if(!r?.projectRoot)return{accepted:!1,reason:"Classic preset scope requires its project root"};try{let i=await Md(r.projectRoot,e.input.changeDir,{presetRequirements:!0});return{accepted:n.requirementsEvidence.ref===i.ref,reason:"Classic preset scope changed before the proposal was recorded"}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};function d_(e){let t=e==="full"?null:d_("full"),r=`${e}.open`,n=`${e}.open.evidence`,i=e==="full"?"full.design.handoff":`${e}.build.execute`,s={id:`comet-classic-${e}-transition`,version:"2"},o={id:"comet-classic-open-artifacts",version:"1"};return{executors:e==="full"?[l_]:t.executors,validators:t?.validators??[...e==="full"?[Iw,Pw,Ow]:[],GB,YB,Tw],evidenceValidators:t?.evidenceValidators??(e==="full"?[o_,QB,ZB,a_]:[o_,a_]),workflow:{id:`comet-classic-${e}`,version:"2",entry:r,stateSchema:{type:"object",required:eV,additionalProperties:!1,properties:{workflow:{enum:e==="full"?["full"]:[e,"full"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},contextCompression:{enum:[null,"off","beta"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},reviewMode:{enum:[null,"off","standard","thorough"]},isolation:{enum:[null,"current","branch","worktree"]},boundBranch:In,verifyMode:{enum:[null,"light","full"]},autoTransition:c_,baseRef:In,designDoc:In,plan:In,verifyResult:{enum:["pending","pass","fail"]},verifyFailures:{type:"integer",minimum:0},checkEpoch:{type:"integer",minimum:0},verificationReport:In,branchStatus:{enum:[null,"pending","handled"]},createdAt:In,verifiedAt:In,archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},directOverride:c_,handoffContext:In,handoffHash:{anyOf:[{type:"null"},{type:"string",pattern:"^[a-f0-9]{64}$"}]},classicProfile:{enum:[null,"full","hotfix","tweak"]},classicMigration:{enum:[null,1]}}},transitionHandler:s,steps:{[r]:{type:"invoke_skill",ref:e==="full"?"comet-open":`comet-${e}`},[n]:{type:"await_evidence",kind:"classic-open-artifacts",validator:o},...e==="full"?{"full.open.confirm":{type:"ask_user",proposalFrom:[r,n],choices:["approved","rejected"]},"full.open.revalidate":{type:"call_tool",ref:"classic-open-revalidate",validator:{id:Iw.id,version:Iw.version},outputSchema:{type:"object",required:["contentHash"],properties:{contentHash:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}}}:{},[i]:{type:"invoke_skill",ref:e==="full"?"comet-design":"comet-build",...e==="full"?{validator:{id:Pw.id,version:Pw.version}}:{validator:{id:Tw.id,version:Tw.version}},...e==="full"?{outputSchema:{type:"object",required:["proposal"],properties:{proposal:{type:"string",minLength:1},handoffContext:{type:"string",minLength:1},handoffHash:{type:"string",pattern:"^[a-f0-9]{64}$"}}}}:{outputSchema:{type:"object",required:["event"],properties:{event:{enum:["build-complete","escalation-requested"]},proposal:{type:"string",minLength:1},requirementsEvidence:{type:"object",required:["ref","contentHash"],properties:{ref:{type:"string",minLength:1},contentHash:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1},checks:Wd,checksReason:{type:"string",minLength:1}},additionalProperties:!1}}},...e==="full"?{}:{[`${e}.build.escalation-confirm`]:{type:"ask_user",proposalFrom:i,choices:["continue","upgrade"]}},...e==="full"?{"full.design.confirm":{type:"ask_user",proposalFrom:"full.design.handoff",choices:["approved","rejected"]},"full.design.document":{type:"invoke_skill",ref:"comet-design",outputSchema:{type:"object",required:["designDoc"],properties:{designDoc:{type:"string",minLength:1}}}},"full.design.evidence":{type:"await_evidence",kind:"classic-design-document",validator:{id:"comet-classic-design-document",version:"1"}},"full.build.configure":{type:"invoke_skill",ref:"comet-build",validator:{id:Ow.id,version:Ow.version},outputSchema:{type:"object",required:["buildMode","tddMode","reviewMode","isolation"],properties:{buildMode:{enum:["subagent-driven-development","executing-plans","direct","autonomous"]},tddMode:{enum:["tdd","direct"]},reviewMode:{enum:["off","standard","thorough"]},isolation:{enum:["current","branch","worktree"]},boundBranch:In,subagentDispatch:{enum:["confirmed",null]},directOverride:{type:"boolean"}},additionalProperties:!1}},"full.build.confirm":{type:"ask_user",proposalFrom:"full.build.configure",choices:["approved","rejected"]},"full.build.plan":{type:"invoke_skill",ref:"comet-build",outputSchema:{type:"object",required:["plan"],properties:{plan:{type:"string",minLength:1},buildPause:{enum:["plan-ready"]}}}},"full.build.plan.evidence":{type:"await_evidence",kind:"classic-build-plan",validator:{id:"comet-classic-build-plan",version:"1"}},"full.build.execute":{type:"invoke_skill",ref:"comet-build",outputSchema:{type:"object",required:["event"],properties:{event:{enum:["build-complete"]},checks:Wd,checksReason:{type:"string",minLength:1}}}},"full.verify.run":{type:"invoke_skill",ref:"comet-verify",outputSchema:{type:"object",required:["event"],properties:{event:{enum:["verification-ready","verify-fail"]},verificationReport:{type:"string",minLength:1},reason:{type:"string",minLength:1},checks:Wd,checksReason:{type:"string",minLength:1}},additionalProperties:!1}},"full.verify.report.evidence":{type:"await_evidence",kind:"classic-verification-report",validator:{id:"comet-classic-verification-report",version:"1"}},"full.archive.prepare":{type:"invoke_skill",ref:"comet-archive",outputSchema:{type:"object",required:["targetBranch","summary"],properties:{targetBranch:{type:"string",minLength:1},remote:{type:"string",minLength:1},prBaseBranch:{type:"string",minLength:1},summary:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},"full.archive.confirm":{type:"ask_user",proposalFrom:"full.archive.prepare",choices:["local","push","pr","reverify","later"]},"full.archive.preflight":{type:"call_tool",ref:"classic-archive-preflight",outputSchema:{type:"object",required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],properties:{deliveryAction:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},verifiedBranch:{type:"string",minLength:1},baseCommit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},remoteIdentity:{type:"string",pattern:"^[0-9a-f]{64}$"},prBaseBranch:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},"full.archive.execute":{type:"call_tool",ref:"classic-archive",validator:{id:"comet-classic-archive-outcome",version:"1"},outputSchema:{type:"object",required:["archiveDirectory"],properties:{archiveDirectory:{type:"string",minLength:1}},additionalProperties:!1}},"full.archive.deliver":{type:"invoke_skill",ref:"comet-archive",validator:{id:"comet-classic-delivery-outcome",version:"1"},outputSchema:{type:"object",required:["action","targetBranch","commit"],properties:{action:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},commit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},prUrl:{type:"string",minLength:1}},additionalProperties:!1}},"full.build.plan-ready":{type:"ask_user",proposalFrom:"full.build.plan",choices:["continue"]}}:{[`${e}.verify.run`]:{type:"invoke_skill",ref:"comet-verify",outputSchema:{type:"object",required:["event"],properties:{event:{enum:["verification-ready","verify-fail"]},verificationReport:{type:"string",minLength:1},reason:{type:"string",minLength:1},checks:Wd,checksReason:{type:"string",minLength:1}},additionalProperties:!1}},[`${e}.verify.report.evidence`]:{type:"await_evidence",kind:"classic-verification-report",validator:{id:"comet-classic-verification-report",version:"1"}},[`${e}.archive.prepare`]:{type:"invoke_skill",ref:"comet-archive",outputSchema:{type:"object",required:["targetBranch","summary"],properties:{targetBranch:{type:"string",minLength:1},remote:{type:"string",minLength:1},prBaseBranch:{type:"string",minLength:1},summary:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},[`${e}.archive.confirm`]:{type:"ask_user",proposalFrom:`${e}.archive.prepare`,choices:["local","push","pr","reverify","later"]},[`${e}.archive.preflight`]:{type:"call_tool",ref:"classic-archive-preflight",outputSchema:{type:"object",required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],properties:{deliveryAction:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},verifiedBranch:{type:"string",minLength:1},baseCommit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},remoteIdentity:{type:"string",pattern:"^[0-9a-f]{64}$"},prBaseBranch:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},[`${e}.archive.execute`]:{type:"call_tool",ref:"classic-archive",validator:{id:"comet-classic-archive-outcome",version:"1"},outputSchema:{type:"object",required:["archiveDirectory"],properties:{archiveDirectory:{type:"string",minLength:1}},additionalProperties:!1}},[`${e}.archive.deliver`]:{type:"invoke_skill",ref:"comet-archive",validator:{id:"comet-classic-delivery-outcome",version:"1"},outputSchema:{type:"object",required:["action","targetBranch","commit"],properties:{action:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},commit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},prUrl:{type:"string",minLength:1}},additionalProperties:!1}}},...t?Object.fromEntries(Object.entries(t.workflow.steps).filter(([c])=>c.startsWith("full.")&&!c.startsWith("full.open"))):{}},transitions:[{from:r,to:n},{from:n,to:e==="full"?"full.open.confirm":i},...e==="full"?[{from:"full.open.confirm",to:"full.open.revalidate",on:"approved"},{from:"full.open.confirm",to:r,on:"rejected"},{from:"full.open.revalidate",to:i},{from:"full.open.revalidate",to:r}]:[{from:i,to:`${e}.build.escalation-confirm`},{from:`${e}.build.escalation-confirm`,to:i,on:"continue"},{from:`${e}.build.escalation-confirm`,to:"full.design.handoff",on:"upgrade"},{from:`${e}.verify.run`,to:`${e}.verify.report.evidence`},{from:`${e}.verify.run`,to:`${e}.build.execute`},{from:`${e}.archive.prepare`,to:`${e}.archive.confirm`},{from:`${e}.archive.confirm`,to:`${e}.archive.preflight`,on:"local"},{from:`${e}.archive.confirm`,to:`${e}.archive.preflight`,on:"push"},{from:`${e}.archive.confirm`,to:`${e}.archive.preflight`,on:"pr"},{from:`${e}.archive.confirm`,to:`${e}.verify.run`,on:"reverify"},{from:`${e}.archive.confirm`,to:`${e}.archive.confirm`,on:"later"},{from:`${e}.archive.preflight`,to:`${e}.archive.execute`},{from:`${e}.archive.execute`,to:`${e}.archive.deliver`}],...e==="full"?[{from:"full.design.handoff",to:"full.design.confirm"},{from:"full.design.confirm",to:"full.design.document",on:"approved"},{from:"full.design.confirm",to:"full.design.handoff",on:"rejected"},{from:"full.design.document",to:"full.design.evidence"},{from:"full.design.evidence",to:"full.build.configure"},{from:"full.build.configure",to:"full.build.confirm"},{from:"full.build.confirm",to:"full.build.plan",on:"approved"},{from:"full.build.confirm",to:"full.build.configure",on:"rejected"},{from:"full.build.plan",to:"full.build.plan.evidence"},{from:"full.build.plan.evidence",to:"full.build.execute"},{from:"full.build.plan.evidence",to:"full.build.plan-ready"},{from:"full.build.plan-ready",to:"full.build.plan.evidence",on:"continue"},{from:"full.verify.run",to:"full.verify.report.evidence"},{from:"full.verify.run",to:"full.build.plan"},{from:"full.archive.prepare",to:"full.archive.confirm"},{from:"full.archive.confirm",to:"full.archive.preflight",on:"local"},{from:"full.archive.confirm",to:"full.archive.preflight",on:"push"},{from:"full.archive.confirm",to:"full.archive.preflight",on:"pr"},{from:"full.archive.confirm",to:"full.verify.run",on:"reverify"},{from:"full.archive.confirm",to:"full.archive.confirm",on:"later"},{from:"full.archive.preflight",to:"full.archive.execute"},{from:"full.archive.execute",to:"full.archive.deliver"}]:[],...t?t.workflow.transitions?.filter(c=>c.from.startsWith("full.")&&!c.from.startsWith("full.open"))??[]:[],{from:`${e}.build.execute`,to:`${e}.verify.run`},{from:`${e}.verify.report.evidence`,to:`${e}.archive.prepare`}]},transitionHandler:{...s,apply({run:c,event:l}){if(l.kind==="action-outcome"&&l.outcome.status==="succeeded"&&(l.stepId.endsWith(".build.execute")||l.stepId.endsWith(".verify.run"))){let a=l.outcome.output;if(["build-complete","verification-ready"].includes(a.event??"")){let d=c.actions.find(p=>p.id===l.outcome.actionId);(d?.executionOrigin?.workflow.version!=="1"||d.status!=="succeeded"||c.outputs[l.stepId]?.sequence!==c.actionContexts[d.id]?.sequence||!Nw(c.outputs[l.stepId]?.value,d.outcome?.output)||!Nw(d.outcome,l.outcome))&&jw(a)}}if(l.kind==="action-outcome"&&l.outcome.status==="failed"&&c.actions.find(d=>d.id===l.outcome.actionId)?.type==="invoke_skill")return{state:c.state,next:[]};if(t&&l.stepId.startsWith("full."))return t.transitionHandler.apply({run:c,event:l});if(e!=="full"&&l.kind==="wait-resolved"&&l.stepId===`${e}.build.escalation-confirm`){if(l.choice==="continue")return{state:c.state,next:[i]};if(l.choice!=="upgrade")throw new Error("Classic preset escalation choice is invalid");let a=c.state;return{state:{...Pt(a,"preset-escalate").classic,isolation:a.isolation,boundBranch:a.boundBranch},next:["full.design.handoff"]}}if(e!=="full"&&l.kind==="action-outcome"&&l.stepId===i){let a=l.outcome.output;if(l.outcome.status==="succeeded"&&a.event==="escalation-requested"&&typeof a.proposal=="string"&&a.proposal.trim())return{state:c.state,next:[`${e}.build.escalation-confirm`]};if(l.outcome.status!=="succeeded"||a.event!=="build-complete")throw new Error("Classic preset Build result does not match its declared transition");return{state:Pt(c.state,"build-complete").classic,next:[`${e}.verify.run`]}}if(e!=="full"&&l.kind==="action-outcome"&&l.stepId===`${e}.verify.run`){let a=l.outcome.output;if(l.outcome.status==="succeeded"&&a.event==="verify-fail"){if(typeof a.reason!="string"||!a.reason.trim())throw new Error("Classic preset Verify failure requires a reason");return{state:Pt(c.state,"verify-fail").classic,next:[`${e}.build.execute`]}}if(l.outcome.status!=="succeeded"||a.event!=="verification-ready"||typeof a.verificationReport!="string")throw new Error("Classic preset Verify report did not complete");return{state:{...c.state,verificationReport:a.verificationReport},next:[`${e}.verify.report.evidence`]}}if(e!=="full"&&l.kind==="evidence-recorded"&&l.stepId===`${e}.verify.report.evidence`){if(l.ref!==c.state.verificationReport)throw new Error("Classic preset Verify report evidence does not match");return{state:Pt(c.state,"verify-pass").classic,next:[`${e}.archive.prepare`]}}if(e!=="full"&&l.kind==="action-outcome"&&l.stepId===`${e}.archive.prepare`){if(l.outcome.status!=="succeeded")throw new Error("Classic preset Archive preparation did not complete");return{state:c.state,next:[`${e}.archive.confirm`]}}if(l.kind==="action-outcome"&&l.stepId===r){if(l.outcome.status!=="succeeded"||l.outcome.output?.event!=="open-complete")throw new Error("Classic Open result does not match its declared transition");return{state:c.state,next:[n]}}if(e==="full"&&l.kind==="wait-resolved"&&l.stepId==="full.open.confirm")return{state:c.state,next:[l.choice==="approved"?"full.open.revalidate":r]};if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.open.revalidate"){if(l.outcome.status!=="succeeded")throw new Error("Classic Open revalidation did not complete");return{state:Pt(c.state,"open-complete").classic,next:[i]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId===i){if(l.outcome.status!=="succeeded")throw new Error("Classic Design handoff did not succeed");let a=l.outcome.output;return{state:{...c.state,...c.commands?.some(d=>d.name==="revise-design"&&d.actionId===l.outcome.actionId)?{phase:"design",verifyResult:"pending",verifiedAt:null,archiveConfirmation:null}:{},...a.handoffContext?{handoffContext:a.handoffContext,handoffHash:a.handoffHash??null}:{}},next:["full.design.confirm"]}}if(e==="full"&&l.kind==="wait-resolved"&&l.stepId==="full.design.confirm")return{state:c.state,next:[l.choice==="approved"?"full.design.document":"full.design.handoff"]};if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.design.document"){if(l.outcome.status!=="succeeded")throw new Error("Classic Design document work did not succeed");let a=l.outcome.output.designDoc;return{state:{...c.state,designDoc:a},next:["full.design.evidence"]}}if(e==="full"&&l.kind==="evidence-recorded"&&l.stepId==="full.design.evidence"){if(l.ref!==c.state.designDoc)throw new Error("Classic Design evidence does not match the selected document");return{state:Pt(c.state,"design-complete").classic,next:[c.commands?.some(d=>d.name==="revise-design"&&["build","verify","archive"].includes(c.actions.find(p=>p.id===d.actionId)?.input?.activation?.fromPhase??""))?"full.build.plan":"full.build.configure"]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.build.configure"){if(l.outcome.status!=="succeeded")throw new Error("Classic Build configuration did not succeed");return{state:c.state,next:["full.build.confirm"]}}if(e==="full"&&l.kind==="wait-resolved"&&l.stepId==="full.build.confirm"){if(l.choice==="rejected")return{state:c.state,next:["full.build.configure"]};let d=c.waits.find(g=>g.stepId==="full.build.confirm"&&g.decision?.id===l.decisionId&&g.proposalHash===l.proposalHash)?.proposal?.outputs?.["full.build.configure"],p=c.outputs["full.build.configure"]?.value;if(l.choice!=="approved"||d===void 0||p===void 0||j(d)!==j(p))throw new Error("Classic Build confirmation no longer matches the proposed choices");let u=d,m={...c.state,...u},h=cs(m);if(m.isolation===null||h.missingFields.length>0||h.invalidFields.length>0)throw new Error("Classic Build configuration is incomplete or invalid");return{state:m,next:["full.build.plan"]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.build.plan"){if(l.outcome.status!=="succeeded")throw new Error("Classic Build plan work did not succeed");let{plan:a,buildPause:d}=l.outcome.output;return{state:{...c.state,plan:a,buildPause:d??null},next:["full.build.plan.evidence"]}}if(e==="full"&&l.kind==="evidence-recorded"&&l.stepId==="full.build.plan.evidence"){if(l.ref!==c.state.plan)throw new Error("Classic Build plan evidence does not match the selected plan");return{state:c.state,next:[c.state.buildPause==="plan-ready"?"full.build.plan-ready":"full.build.execute"]}}if(e==="full"&&l.kind==="wait-resolved"&&l.stepId==="full.build.plan-ready"){if(l.choice!=="continue")throw new Error("Classic Build continuation requires explicit user choice");return{state:{...c.state,buildPause:null},next:["full.build.plan.evidence"]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.build.execute"){if(l.outcome.status!=="succeeded"||l.outcome.output?.event!=="build-complete")throw new Error("Classic Build work did not complete");return{state:Pt(c.state,"build-complete").classic,next:[`${e}.verify.run`]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.verify.run"){if(l.outcome.status!=="succeeded")throw new Error("Classic Verify assessment did not complete");let a=l.outcome.output;if(a.event==="verify-fail"){if(!a.reason?.trim())throw new Error("Classic Verify failure requires a reason");return{state:Pt(c.state,"verify-fail").classic,next:["full.build.plan"]}}if(a.event!=="verification-ready"||!a.verificationReport)throw new Error("Classic Verify report path is missing");return{state:{...c.state,verificationReport:a.verificationReport},next:["full.verify.report.evidence"]}}if(e==="full"&&l.kind==="evidence-recorded"&&l.stepId==="full.verify.report.evidence"){if(l.ref!==c.state.verificationReport)throw new Error("Classic Verify evidence does not match the selected report");return{state:Pt(c.state,"verify-pass").classic,next:[`${e}.archive.prepare`]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.archive.prepare"){if(l.outcome.status!=="succeeded")throw new Error("Classic Archive preparation did not complete");return{state:c.state,next:["full.archive.confirm"]}}if(l.kind==="wait-resolved"&&l.stepId===`${e}.archive.confirm`){if(l.choice==="reverify")return{state:Pt(c.state,"archive-reopen").classic,next:[`${e}.verify.run`]};if(l.choice==="later")return{state:c.state,next:[`${e}.archive.confirm`]};let d=c.waits.find(g=>g.stepId===`${e}.archive.confirm`&&g.decision?.id===l.decisionId&&g.proposalHash===l.proposalHash)?.proposal?.outputs?.[`${e}.archive.prepare`],p=c.outputs[`${e}.archive.prepare`]?.value;if(d===void 0||p===void 0||j(d)!==j(p))throw new Error("Classic Archive choice no longer matches its proposal");let u=d,m=c.state;if(!["local","push","pr"].includes(l.choice)||!m.boundBranch||u.targetBranch!==m.boundBranch||l.choice!=="local"&&!u.remote||l.choice==="pr"&&!u.prBaseBranch)throw new Error("Classic Archive target does not match the bound branch or delivery");return{state:Pt(m,"archive-confirm").classic,next:[`${e}.archive.preflight`]}}if(l.kind==="action-outcome"&&l.stepId===`${e}.archive.preflight`){if(l.outcome.status!=="succeeded")throw new Error("Classic Archive preflight did not pass");let a=c.waits.slice().reverse().find(u=>u.stepId===`${e}.archive.confirm`&&u.status==="resolved"&&["local","push","pr"].includes(u.decision?.choice??"")),d=a?.proposal?.outputs?.[`${e}.archive.prepare`],p=l.outcome.output;if(!a||!d||a.decision?.choice!==p.deliveryAction||d.targetBranch!==p.targetBranch||a.decision?.choice==="pr"&&d.prBaseBranch!==p.prBaseBranch||p.targetBranch!==p.verifiedBranch||p.targetBranch!==c.state.boundBranch)throw new Error("Classic Archive preflight no longer matches the approved target");return{state:c.state,next:[`${e}.archive.execute`]}}if(l.kind==="action-outcome"&&l.stepId===`${e}.archive.execute`){if(l.outcome.status!=="succeeded")return{state:c.state,next:[]};let a=Pt(c.state,"archived"),d=c.input.changeDir.replaceAll("\\","/"),p=l.outcome.output.archiveDirectory.replaceAll("\\","/");return{state:{...a.classic,designDoc:Sr(a.classic.designDoc,d,p),plan:Sr(a.classic.plan,d,p),verificationReport:Sr(a.classic.verificationReport,d,p),handoffContext:Sr(a.classic.handoffContext,d,p)},next:[`${e}.archive.deliver`]}}if(l.kind==="action-outcome"&&l.stepId===`${e}.archive.deliver`)return l.outcome.status!=="succeeded"?{state:c.state,next:[]}:{state:{...c.state,branchStatus:"handled"},next:[]};if(l.kind!=="evidence-recorded"||l.stepId!==n||l.evidenceKind!=="classic-open-artifacts")throw new Error("Classic Open evidence does not match its declared transition");return e==="full"?{state:c.state,next:["full.open.confirm"]}:{state:Pt(c.state,"open-complete").classic,next:[i]}}}}}function jw(e){if(!Array.isArray(e.checks)||!e.checks.length&&!e.checksReason?.trim()||e.checks.some(t=>!t.name?.trim()||!["passed","not-run"].includes(t.result)||t.result==="not-run"&&!t.note?.trim()))throw new Error("Classic completion requires actual check reports; explain checks not run and resolve failed checks before acceptance")}var Ec=d_;import{AsyncLocalStorage as cV}from"node:async_hooks";ga();import{AsyncLocalStorage as rV}from"node:async_hooks";import{createHash as nV,randomUUID as p_}from"node:crypto";import qw from"node:path";import{promises as Fd}from"node:fs";import Dw from"node:path";async function Hd(e,t){let r=df(e),n=Dw.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let o of["","workspaces",r.workspaceId,"observability"]){i=Dw.join(i,o);let c;try{c=await Fd.lstat(i)}catch(l){if(!t||l.code!=="ENOENT")throw l;await Fd.mkdir(i,{recursive:o===""}).catch(f=>{if(f.code!=="EEXIST")throw f}),c=await Fd.lstat(i)}if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let s=Dw.join(n,"performance.sqlite");for(let o of["","-wal","-shm"])try{let c=await Fd.lstat(s+o);if(!c.isFile()||c.isSymbolicLink()||c.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(c){if(c.code!=="ENOENT")throw c}return s}import{stripVTControlCharacters as tV}from"node:util";function f_(e,t=process.env){let r=tV(e).replace(/(Bearer\s+)[^\s"']+/giu,"$1[redacted]").replace(/((?:api[_-]?key|auth[_-]?token|access[_-]?token|_authToken|password|secret)\s*[=:]\s*["']?)[^\s"',}]+/giu,"$1[redacted]").replace(/(https?:\/\/[^\s/:]+:)[^\s@]+@/giu,"$1[redacted]@");for(let[n,i]of Object.entries(t))i&&i.length>=6&&/key|token|password|secret|credential/iu.test(n)&&(r=r.split(i).join("[redacted]"));return r}var iV=864e5,sV=1e4,Bd=new rV;function Lw(e){let t=Bd.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function Ac(e,t){return f_(e).slice(0,t)}async function Vd(e,t){if(!t.length)return;let r=Bd.getStore();if(r){let i=s=>process.platform==="win32"?qw.resolve(s).toLowerCase():qw.resolve(s);if(i(e)===i(await r.projectRoot())){r.spans.push(...t);return}}let n=co(await Hd(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
247
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
248
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
249
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
250
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
251
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
252
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
253
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
254
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
255
|
+
BEGIN IMMEDIATE;`);let i=n.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
256
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
257
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
258
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
259
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
260
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
261
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
262
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
263
|
+
WHERE excluded.revision >= trace_spans.revision OR (trace_spans.started_at IS NULL AND excluded.started_at IS NOT NULL)`),s=t.length>1e3?[...t.filter(o=>o.parentSpanId===null),...t.filter(o=>o.parentSpanId!==null).slice(-999)].slice(0,1e3):t;for(let o of s){if(!o.change||!o.runId||!o.traceId||!o.spanId||o.change.length>240||o.runId.length>240||o.traceId.length>512||o.spanId.length>512||(o.parentSpanId?.length??0)>512)continue;let c={...o,name:Ac(o.name,240),summary:o.summary?Ac(o.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(o.attributes??{}).slice(0,20).map(([a,d])=>[Ac(a,80),Array.isArray(d)?d.slice(0,30).map(p=>Ac(p,240)):typeof d=="string"?Ac(d,2e3):d]))};t.length>1e3&&o.parentSpanId===null&&(c.attributes.truncated=!0);let l=JSON.stringify(c);for(;Buffer.byteLength(l,"utf8")>4096;){let a=Object.keys(c.attributes).reverse().find(d=>d!=="truncated");if(a)delete c.attributes[a];else if(c.summary)c.summary=c.summary.slice(0,Math.floor(c.summary.length*.75));else break;l=JSON.stringify(c)}if(Buffer.byteLength(l,"utf8")>4096)continue;let f=nV("sha256").update(JSON.stringify([o.traceId,o.spanId])).digest("hex");i.run(f,o.traceId,o.workflow,o.change,o.runId,o.spanId,o.parentSpanId,o.kind,c.name,o.status,o.startedAt,o.endedAt,o.updatedAt,o.revision,l)}n.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*iV).toISOString()),n.prepare("DELETE FROM trace_spans WHERE id IN (SELECT id FROM trace_spans ORDER BY updated_at DESC, id DESC LIMIT -1 OFFSET ?)").run(sV),n.exec("COMMIT")}finally{n.close()}}async function m_(e,t){let r=Bd.getStore(),n=r?.binding.workflow===e.workflow?r:void 0;if(n)try{let p=(await Promise.all([e.projectRoot(),n.projectRoot()])).map(u=>{let m=qw.resolve(u);return process.platform==="win32"?m.toLowerCase():m});(p[0]!==p[1]||e.runId&&n.binding.runId&&e.runId!==n.binding.runId)&&(n=void 0)}catch{n=void 0}let i=new Date().toISOString(),s={traceId:n?.traceId??p_(),spanId:p_(),binding:n?.binding??{workflow:e.workflow,change:e.change,runId:e.runId},spans:n?.spans??[],startedAt:i,kind:e.kind,name:e.name,projectRoot:e.projectRoot,parent:n};if(s.binding.change&&s.binding.runId){let d=[];for(let p=s;p;p=p.parent)d.push({traceId:p.traceId,spanId:p.spanId,parentSpanId:p.parent?.spanId??null,workflow:s.binding.workflow,change:s.binding.change,runId:s.binding.runId,kind:p.kind,name:p.name,status:"running",startedAt:p.startedAt,endedAt:null,updatedAt:i,revision:0});try{await Vd(await e.projectRoot(),d)}catch{}}let o,c,l=!1;try{o=await Bd.run(s,t)}catch(d){l=!0,c=d}let f=new Date().toISOString(),a=l?"failed":"succeeded";try{!l&&e.status&&(a=e.status(o))}catch{a="unknown"}if(s.binding.change&&s.binding.runId&&s.spans.push({traceId:s.traceId,spanId:s.spanId,parentSpanId:n?.spanId??null,workflow:s.binding.workflow,change:s.binding.change,runId:s.binding.runId,kind:e.kind,name:e.name,startedAt:i,endedAt:f,updatedAt:f,revision:1,status:a}),!n&&s.spans.length)try{await Vd(await e.projectRoot(),s.spans)}catch{}if(l)throw c;return o}var oV=(e,t)=>`workflow:${e}:${t}`,h_=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},g_=e=>({runId:e.runId,revision:e.revision,status:e.status,actions:e.actions.map(t=>({id:t.id,attempt:t.attempt,status:t.status,reason:t.reason,...t.outcome?{outcome:{outcomeId:t.outcome.outcomeId,summary:t.outcome.summary}}:{}})),waits:e.waits.map(t=>({id:t.id,status:t.status})),evidenceWaits:e.evidenceWaits?.map(t=>({id:t.id,status:t.status}))}),w_=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function aV(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:s}=e,o=oV(t,n.runId),c=`run:${n.runId}`,l={workflow:t,change:n.runId,runId:n.runId,traceId:o,updatedAt:s,revision:n.revision},f=["completed","failed","cancelled"].includes(n.status),a=new Map(r?.actions.map(p=>[`${p.id}:${p.attempt}`,p])),d=[{...l,spanId:c,parentSpanId:null,kind:"workflow",name:n.workflow.id,status:n.status==="completed"?"succeeded":n.status,startedAt:i?s:null,endedAt:f&&(i||r!==null&&r.status!==n.status)?s:null,summary:n.reason,attributes:{workflowVersion:n.workflow.version,sequence:n.sequence,parentRunIds:n.lineage,childRunIds:n.children.map(p=>p.runId)}}];for(let p of n.actions){let u=a.get(`${p.id}:${p.attempt}`);if(u&&u.status===p.status&&u.outcome?.outcomeId===p.outcome?.outcomeId&&u.reason===p.reason&&u.outcome?.summary===p.outcome?.summary)continue;let m=["succeeded","failed","cancelled"].includes(p.status);d.push({...l,spanId:`action:${p.id}:${p.attempt}`,parentSpanId:c,kind:"action",name:p.stepId,status:p.status,attempt:p.attempt,startedAt:p.status==="running"&&(u?.status==="pending"||i)?s:null,endedAt:m&&(i||r!==null)?s:null,summary:p.outcome?.summary??p.reason,attributes:{phase:h_(p.stepId,t),actionId:p.id,actionType:p.type,ref:p.ref??null,executor:p.claim?.executorId??null,inputFields:w_(p.input),outputFields:p.outcome?w_(p.outcome.output):[],artifacts:(p.outcome?.artifacts??[]).map(h=>h.uri)}})}for(let p of["wait","evidence"]){let u=p==="wait"?n.waits:n.evidenceWaits??[],m=p==="wait"?r?.waits:r?.evidenceWaits,h=new Map(m?.map(g=>[g.id,g]));for(let g of u){let w=h.get(g.id);w?.status!==g.status&&d.push({...l,spanId:`${p}:${g.id}`,parentSpanId:c,kind:p,name:g.stepId,status:g.status==="pending"?"waiting":g.status==="resolved"?"succeeded":g.status==="cancelled"?"cancelled":"unknown",startedAt:!w&&(r!==null||i)&&g.status==="pending"?s:null,endedAt:g.status!=="pending"&&(i||r!==null)?s:null,attributes:{phase:h_(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return d}function y_(e,t,r){let n=null;return{...r,...r.restoreCheckpoint?{restoreCheckpoint:(i,s,o)=>r.restoreCheckpoint(i,s,o)}:{},async read(i){let s=await r.read(i);try{n=s?g_(s):null}catch{n=null}return s&&Lw({workflow:t,change:s.runId,runId:s.runId}),s},async compareAndSwap(i,s,o){let c=n?.runId===i&&n.revision===s?n:null,l=await r.compareAndSwap(i,s,o);if(l){Lw({workflow:t,change:i,runId:i});try{await Vd(e,aV({workflow:t,previous:c,next:o,initial:s===null,observedAt:new Date().toISOString()}))}catch{}try{n=g_(o)}catch{n=null}}return l}}}import{promises as lV}from"node:fs";var xc=bt(Dt(),1);import{createHash as uV}from"node:crypto";import hs from"node:path";import{isDeepStrictEqual as dV}from"node:util";var v_=new Set(["language","contextCompression","autoTransition","reviewMode"]);var k_=new cV;function fV(e){return["completed","cancelled","failed"].includes(e.status)||e.waits.some(t=>t.status==="pending")||e.actions.some(t=>["pending","running","unknown"].includes(t.status)&&(t.type==="invoke_skill"||t.status==="unknown"||t.type==="call_tool"&&!["classic-open-revalidate","classic-archive-preflight"].includes(t.ref??"")))}function Ar(e,t){return dV(e,t)}function b_(e,t){return Object.keys(e).filter(r=>!Ar(e[r],t[r]))}function Ww(e){return e.actions.some(kd)}function xo(e,t={},r=!1){let n=pt(e),i=!1,s=async(p=t.readOnly)=>{if(!p&&pt(e)!==n)throw new Error("Classic SDK workspace identity changed; reload the store in the current workspace");return!p&&!i&&(await Ur(e),i=!0),n},o=y_(e,"classic",t.store??Mr({singleWriter:!0,rootDir:hs.join(n,"sdk-runs","classic")})),c=p=>JSON.stringify([n,p]);function l(p,u){if(t.identity){let h=["runtime","dispatch","--application-file",hs.join(t.identity.packageRoot,"application.json"),"--project-root",e,"--request","<recovery-request.json>","--json"];throw new Error(`Classic SDK Run ${p} requires recovery: ${u}. Save the recovery request JSON to a file and replace <recovery-request.json> with its path. Run comet with the exact argument array below to restore the recorded state and advance only the Runtime, without executing host work.
|
|
264
|
+
Recovery argv: ${JSON.stringify(h)}
|
|
265
|
+
Recovery request: ${JSON.stringify({operation:"next",runId:p})}`)}let m=`Run comet state next ${p} --json`;throw new Error(`Classic SDK Run ${p} requires recovery: ${u}. ${m} in ${e} to restore or synchronize its recorded state.`)}async function f(p,u){let m=null;for(let J of await En(e,p)){let te;try{te=await Pe(e,J,{label:"Classic state file"})}catch(Z){if(Z.code==="ENOENT")continue;throw Z}if(ir(te)){if(m)throw new Error(`Classic change ${p} has multiple SDK state files`);m={file:J,source:te}}}if(!m)return null;let h=(0,xc.parseDocument)(m.source,{uniqueKeys:!0});if(h.errors.length>0)throw new Error(`Invalid Classic state file: ${h.errors[0].message}`);let g=h.toJS(),w=rn(g[It],p,{preserveSourceRevision:!0});if(!w)return null;if(j(g.application_checkpoint??null)!==j(t.identity??null))throw new Error("Classic portable checkpoint requires its original fixed Application package");let k=ur(g).classic,b=w.input,R=w.workflow.id.replace(/^comet-classic-/u,""),E=k?b_(w.state,k):[],O=typeof b?.changeDir=="string"?await fe(hs.join(e,...b.changeDir.split("/"))):null,z=O!==null&&m.file!==O;if(!k||E.some(J=>!v_.has(J))||b?.change!==p||b.changeDir!==`openspec/changes/${p}`&&b.changeDir!==`docs/openspec/changes/${p}`||z&&!k.archived&&!Ww(w)||!["full","hotfix","tweak"].includes(R)||w.workflow.id!==`comet-classic-${R}`||k.workflow!==R&&!bd(w,R)||!t.allowBranchRebind&&k.boundBranch!==null&&k.boundBranch!==fr(e))throw new Error(`Classic portable Run checkpoint for ${p} does not match its state`);let D=w.revision,G={...w,revision:D,...u?{state:k}:{}};if(u&&j(u)!==j({...G,revision:1}))throw new Error(`Classic SDK Run ${p} differs from the interrupted checkpoint import; preserve the local records and restore matching Run history before continuing`);if((D>1||u)&&!o.restoreCheckpoint)throw new Error(`Classic RuntimeStore cannot restore checkpoint revision ${D}; use a store with restoreCheckpoint support or restore the original Run history`);return await zl(e,{schema:da,workflow:"classic",change:p,format:"sdk",application:t.identity?.id??`classic-${R}`,runId:p}),D===1&&!u?await o.compareAndSwap(p,null,G):await o.restoreCheckpoint(p,u?1:null,G),o.read(p)}async function a(p){let u=p.input;if(u?.change!==p.runId||typeof u.changeDir!="string")throw new Error(`Classic SDK Run ${p.runId} has invalid change identity`);let m=u.changeDir.replaceAll("\\","/");if(m!==`openspec/changes/${p.runId}`&&m!==`docs/openspec/changes/${p.runId}`)throw new Error(`Classic SDK Run ${p.runId} has invalid change directory`);let h=hs.join(e,...m.split("/"));try{if((await lV.stat(h)).isDirectory())return fe(h)}catch(b){if(b.code!=="ENOENT")throw b}if(!p.state.archived&&!Ww(p))return null;let g=hs.join(hs.dirname(h),"archive"),w=await Sd(e,g,p.runId);if(w===null)return null;let k=w.filter(b=>b!==p.runId);if(k.length!==1)throw new Error(`Classic SDK Archive ${p.runId} is ambiguous`);return fe(hs.join(g,k[0]))}async function d(p,u){return await En(e,p),await s(),(async()=>{let h;if(r)try{h=(await Vs(o,p)).record}catch(K){if(K.code!=="RUN_NOT_FOUND")throw K;h=null}else h=await o.read(p);if(!h){t.readOnly&&l(p,"the recorded Run is missing or incomplete");let K=await vc(()=>f(p,h??void 0));if(h&&!K)throw new Error(`Classic SDK Run ${p} requires its matching portable checkpoint or original Run history before completing recovery`);h=K}if(!h)return null;let g=h,w=g.state,k=await a(g),b=g.revision===1&&g.actions.every(K=>K.status==="pending"&&!K.claim);if(!k)return t.readOnly&&!b&&l(p,"the change directory is missing"),g;let R;try{R=await Pe(e,k,{label:"Classic state file"})}catch(K){if(K.code!=="ENOENT")throw K;R=null}let E=R===null?new xc.Document:(0,xc.parseDocument)(R,{uniqueKeys:!0});if(E.errors.length>0)throw new Error(`Invalid Classic state file: ${E.errors[0].message}`);let O=E.toJS(),z=R===null?null:ur(O).classic,D=Ao(O?.[It],g,{projection:r});if(D)return(R===null||!ir(R)||!Ar(z,D.state)||t.identity&&!Ar(O.application_checkpoint,t.identity))&&l(p,"the immutable archived delivery checkpoint has changed"),g;if(z){let K=rn(O?.[It],p,{preserveSourceRevision:!0});if(g.revision===1&&K&&K.revision>g.revision){t.readOnly&&l(p,"the initial checkpoint import is incomplete");let P=await f(p,g);P||l(p,"the initial checkpoint import is incomplete"),g=P,w=g.state}let ne=K?.state??w,ze=b_(ne,z);if(ze.some(P=>!v_.has(P))){let P=g.input?.recoverySourceHash,F=g.revision===1&&typeof P=="string"&&R!==null&&uV("sha256").update(R).digest("hex")===P;if(!Ar(z,w)&&!F)throw new Error(`Classic state file ${k} changed a Runtime-owned field`)}else if(ze.some(P=>!Ar(w[P],z[P]))){if(!u)throw new Error(`Classic state file ${k} changed during an SDK transition`);for(let F of ze)if(!Ar(w[F],ne[F])&&!Ar(w[F],z[F]))throw new Error(`Classic state file ${k} conflicts with SDK field ${F}`);t.readOnly&&l(p,"state file settings have not been imported"),w={...w};for(let F of ze)w[F]=z[F];let P={...g,revision:g.revision+1,state:w};if(await vc(()=>En(e,p)),!await o.compareAndSwap(p,g.revision,P))throw new Error(`Classic SDK Run ${p} changed while importing state file settings`);g=P}}if(z&&w.boundBranch===null&&xa(w.isolation)&&!w.archived&&["running","waiting"].includes(g.status)&&!g.actions.some(K=>["running","unknown"].includes(K.status))){let K=gn({isolation:w.isolation,boundBranch:w.boundBranch,currentBranch:fr(e)});if(K.status==="needs-heal"){t.readOnly&&l(p,"the Git branch binding has not been recorded"),w={...w,boundBranch:K.branch};let ne={...g,revision:g.revision+1,state:w};if(await vc(()=>En(e,p)),!await o.compareAndSwap(p,g.revision,ne))throw new Error(`Classic SDK Run ${p} changed while binding its Git branch`);g=ne}}if(t.readOnly){let K=O?.[It],ne=K===void 0;return K!==void 0&&r?ne=ns(K,g):K!==void 0&&(ne=pc(K,lo(g))),(R===null||!ir(R)||!z||!Ar(z,w)||!ne||t.identity&&O.application_checkpoint!==void 0&&!Ar(O.application_checkpoint,t.identity))&&l(p,"the state projection or portable checkpoint is missing or stale"),g}let G=cu(w),J=O??{};for(let[K,ne]of Object.entries(G))Ar(J[K],ne)||(ne===void 0?E.delete(K):E.set(K,ne));let te=fd(lo(g));Ar(J[It],te)||E.set(It,te),t.identity&&!Ar(J.application_checkpoint,t.identity)&&E.set("application_checkpoint",t.identity);let Z=E.toString(),we=ir(Z)?Z:Tm+Z;return R!==we&&await Wi(e,k,we,{label:"Classic state file"}),ui(g)&&(t.identity||await nu(e,"classic",g.runId)),g})()}return{queryScope:o.queryScope,async read(p){if(!t.identity&&k_.getStore()?.has(c(p)))return await s(!0),o.read(p);if(!t.readOnly){await s(!0);try{let u=await xo(e,{...t,store:o,readOnly:!0}).read(p);if(u&&!ui(u))return u}catch{}}return d(p,!0)},async readProjection(p){await s(!0);let u=await xo(e,{...t,store:o,readOnly:!0},!0).read(p);return await s(!0),u},async compareAndSwap(p,u,m){return vc(async()=>{if(t.readOnly)throw new Error("Classic SDK read-only store cannot change a Run");if(m.status==="cancelled"&&u!==null){let g=await o.read(p);if(g&&Ww(g))throw new Error(`Classic Archive must finish or recover before cancelling this Run; preserve its original Action and use comet state check ${p} archive --recover --json to inspect the recovery path.`)}await En(e,p),u!==null&&await a(m),await s();let h=await o.compareAndSwap(p,u,m);if(h&&u!==null){let g=k_.getStore(),w=c(p);g&&!t.identity&&m.workflow.version==="2"&&!fV(m)?g.set(w,()=>d(p,!1)):(g?.delete(w),await d(p,!1))}return h})}}}import{isDeepStrictEqual as gV}from"node:util";var R_=bt(Dt(),1);import mV from"node:path";async function Ud(e,t,r,n="delivery",i){let s=ps(t,r),o=t.state,c=gn({isolation:o.isolation,boundBranch:o.boundBranch,currentBranch:fr(e),gitWorkTree:Xn(e)});if(!["ok","not-applicable"].includes(c.status))throw new Error("Classic delivery repair requires its approved branch");await Eo(e,t,s.archive,s.archiveRef);{if(!r.reports||r.command||r.excludedOutputPaths?.length)throw new Error("Classic v2 delivery repair requires platform reports and the approved paths");return{...s}}}async function S_(e,t,r){if(!Sw(t))throw new Error("Classic delivery repair requires the original archived Run with no unresolved execution");let n=ps(t);{if(!r)throw new Error("Classic v2 delivery repair requires --checks <checks-json-file>");jw(r);let i={checkpointHash:await hV(e,t),archiveActionId:n.archive.id,checkActionId:n.check.id,reports:r};return await Ud(e,t,i,"prepare"),i}}async function hV(e,t){let r=ps(t),n=await Pe(e,await fe(mV.join(e,r.archiveRef)),{label:"Classic archived delivery checkpoint",maxBytes:Number.MAX_SAFE_INTEGER}),i=(0,R_.parseDocument)(n,{uniqueKeys:!0});if(!ir(n)||i.errors.length)throw new Error("Classic archived checkpoint is invalid");let s=Fe(i.toJS()),o=s.run_checkpoint;if(j(ur(s).classic)!==j(t.state)||!ns(o,t)&&Ao(o,t,{projection:!0})===null)throw new Error("Classic archived checkpoint changed after the authoritative Run was read");return j(o)}function C_(e,t,r){let n=`${t}.delivery.check`,i=`${t}.delivery.confirm`,s={id:"comet-classic-delivery-repair-command",version:"1",async validate({run:l,name:f,input:a,context:d}){let p=Fe(a);if(!d?.projectRoot||f!=="repair-delivery"||p.expectedRevision!==l.revision||p.fromPhase!=="archive"||Object.keys(p).length!==3)return{accepted:!1,reason:"Classic delivery repair requires its current revision"};if(r){let h=l.workflow.hash===r.workflow.hash?structuredClone(r):is(r);if(h.workflow.hash=l.workflow.hash,h.definitionHashes[JSON.stringify([l.workflow.id,l.workflow.version])]=l.workflow.hash,j(h)!==j(l))return{accepted:!1,reason:"Classic delivery repair no longer matches its authoritative source Run"}}let u=await S_(d.projectRoot,r??l,p.deliveryRepair.reports),m=j(u)===j(p.deliveryRepair);return{accepted:m,allowFailed:m&&l.status==="failed",reason:"Classic delivery repair scope changed"}}},o={id:"comet-classic-delivery-repair-check",version:"1",async validate({run:l,action:f,outcome:a,context:d}){if(!d?.projectRoot||!So(l,f)||f.claim?.executorId!=="comet-classic-check")return{accepted:!1,reason:"Classic delivery repair check has the wrong execution owner"};{let p=Co(f);if(a.status!=="succeeded"||!gV(a.output,{...p.reports,deliveryPaths:Rw(l,p)}))return{accepted:!1,reason:"Classic delivery repair reports differ from the submitted reports"}}return a.status==="succeeded"&&await Ud(d.projectRoot,l,Co(f),"delivery"),{accepted:!0}}},c={id:"comet-classic-check",capabilities:[],supports:l=>l.type==="call_tool"&&l.ref==="classic-check"&&l.stepId===n,async preflight(l,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");await Ud(f.projectRoot,a,Co(l),"prepare")},async execute(l,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");{let d=Co(l);return{status:"succeeded",output:{...d.reports,deliveryPaths:Rw(a,d)}}}}};return{...e,workflow:{...e.workflow,steps:{...e.workflow.steps,[n]:{type:"call_tool",ref:"classic-check",validator:{id:o.id,version:o.version}},[i]:{type:"ask_user",proposalFrom:n,choices:["approved","later"]}},transitions:[...e.workflow.transitions??[],{from:n,to:i},{from:i,to:`${t}.archive.deliver`,on:"approved"},{from:i,to:i,on:"later"}],commands:{...e.workflow.commands,"repair-delivery":{stepId:n,validator:{id:s.id,version:s.version}}}},commandValidators:[...e.commandValidators,s],validators:[...e.validators,o],executors:[...e.executors,c],transitionHandler:{...e.transitionHandler,apply(l){if(l.event.kind==="action-outcome"&&l.event.stepId===n)return{state:l.run.state,next:l.event.outcome.status==="succeeded"?[i]:[]};if(l.event.kind==="wait-resolved"&&l.event.stepId===i){let f=l.run.actions.slice().reverse().find(a=>a.stepId===n&&a.status==="succeeded");return{state:l.run.state,next:l.event.choice==="approved"&&f?[{stepId:`${t}.archive.deliver`,input:{deliveryRepairCheckId:f.id}}]:[i]}}return e.transitionHandler.apply(l)}}}}function E_(e){let t=e.actions.at(-1);return e.status==="failed"&&t?.status==="failed"&&t.type==="invoke_skill"&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))&&!e.waits.some(r=>r.status==="pending")&&!e.evidenceWaits?.some(r=>r.status==="pending")?t:null}var _c={id:"comet-classic-work-continuation-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=r,s=E_(e),o=t==="continue-work"&&s!==null&&i?.expectedRevision===e.revision&&i.fromPhase===e.state.phase&&i.interruptedActionId===s.id&&Object.keys(i).filter(c=>c!=="deliveryCheckpointHash").length===3;return{accepted:o,allowFailed:o,reason:"Classic continuation requires the original settled failed Skill and current revision"}}},A_={id:"comet-classic-work-continuation",capabilities:[],supports:e=>e.ref==="classic-work-continuation",async execute(e,t,r){let n=e.input.activation?.interruptedActionId,i=r?.actions.find(s=>s.id===n);if(!i||i.status!=="failed"||i.type!=="invoke_skill")throw new Error("Classic original failed Skill is missing");return{status:"succeeded",output:{interruptedActionId:i.id,resumeStepId:i.stepId}}}},Mw={id:"comet-classic-work-continuation-outcome",version:"1",validate({run:e,action:t,outcome:r}){let n=t.input.activation?.interruptedActionId,i=e.actions.find(s=>s.id===n);return{accepted:t.claim?.executorId===A_.id&&r.status==="succeeded"&&i?.status==="failed"&&i.type==="invoke_skill"&&j(r.output)===j({interruptedActionId:i.id,resumeStepId:i.stepId}),reason:"Classic continuation does not match its original failed Skill"}}};function x_(e){let t=e.state,r=e.actions.at(-1);return t.phase==="build"&&e.status==="failed"&&!t.archived&&r?.status==="failed"&&r.stepId===`${t.workflow}.build.execute`&&!e.actions.some(n=>["running","unknown","pending"].includes(n.status))?r:null}var Fw={id:"comet-classic-build-continuation-command",version:"1",validate({run:e,name:t,input:r}){let n=r,i=e.state,s=t==="continue-build"&&(x_(e)!==null||Kd(e))&&n?.expectedRevision===e.revision&&n.fromPhase===i.phase&&Object.keys(n).length===2;return{accepted:s,allowFailed:s,reason:"Classic Build continuation requires the current stopped failed Builder"}}};function __(e){let t=e.state;return t.archived||t.phase!=="archive"||!["failed","running"].includes(e.status)||e.actions.some(r=>["running","unknown","pending"].includes(r.status))||e.waits.some(r=>r.status==="pending")||e.evidenceWaits?.some(r=>r.status==="pending")?null:e.actions.slice().reverse().find(r=>r.stepId===`${t.workflow}.archive.execute`&&r.status==="failed")??null}var Hw={id:"comet-classic-archive-repair-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=r,s=__(e);return t!=="repair-archive"||!s||!n?.projectRoot||i?.expectedRevision!==e.revision||i.fromPhase!=="archive"||Object.keys(i).length!==2?{accepted:!1,reason:"Classic Archive requires a stopped failed execution and the current revision"}:(await Jx(n.projectRoot,e,s),{accepted:!0,allowFailed:!0})}},Ic={id:"comet-classic-revision-command",version:"1",validate({run:e,name:t,input:r}){let n=e.state,i=t==="revise-design"?"design":t==="revise-plan"?"build":null,s=r,o=[...e.actions.filter(f=>f.status==="pending"),...e.waits.filter(f=>f.status==="pending"),...(e.evidenceWaits??[]).filter(f=>f.status==="pending")],c=t==="revise-design"?["full.design.handoff","full.design.confirm","full.design.document","full.design.evidence"]:["full.build.plan","full.build.plan.evidence","full.build.plan-ready","full.build.execute","full.build.check","full.build.check.evidence"],l=["verify","archive"].includes(n.phase)&&Kd(e);return{accepted:n.workflow==="full"&&(n.phase===i||t==="revise-design"&&n.phase==="build"||l)&&!n.archived&&s?.expectedRevision===e.revision&&Object.keys(s).length===2&&s.fromPhase===n.phase&&o.length===1&&(l||c.includes(o[0].stepId)||t==="revise-design"&&n.phase==="build"&&["full.build.plan","full.build.plan.evidence","full.build.plan-ready","full.build.execute","full.build.check","full.build.check.evidence"].includes(o[0].stepId)),reason:"Classic revision is stale or does not match the pending Design or Build work"}}};function Kd(e){let t=e.state;if(t.archived||!["verify","archive"].includes(t.phase)||!["running","waiting"].includes(e.status)||e.actions.some(n=>["running","unknown"].includes(n.status)||n.stepId.endsWith(".archive.execute")&&(!["pending","cancelled"].includes(n.status)||n.attempt!==1||!!n.claim||n.receipts.length>0)))return!1;let r=[...e.actions.filter(n=>n.status==="pending"),...e.waits.filter(n=>n.status==="pending"),...(e.evidenceWaits??[]).filter(n=>n.status==="pending")];return r.length===1&&["verify.run","verify.report.evidence","verify.check","verify.check.evidence","archive.prepare","archive.confirm","archive.preflight","archive.execute"].some(n=>r[0].stepId===`${t.workflow}.${n}`)}var zd={id:"comet-classic-verification-revision-command",version:"1",validate({run:e,name:t,input:r}){let n=r;return{accepted:t==="reopen-verification"&&Kd(e)&&n?.expectedRevision===e.revision&&Object.keys(n).length===2&&n.fromPhase===e.state.phase,reason:"Classic verification cannot reopen after Archive execution or while work has an unresolved outcome"}}};function wV(e,t=!0,r=!0,n=!0,i=!0,s){let o=Ec(e),c={..._c,async validate(f){if(!s)return _c.validate(f);let a=f.run.workflow.hash===s.workflow.hash?structuredClone(s):is(s);return a.workflow.hash=f.run.workflow.hash,a.definitionHashes[JSON.stringify([f.run.workflow.id,f.run.workflow.version])]=f.run.workflow.hash,j(a)!==j(f.run)?{accepted:!1,reason:"Classic continuation no longer matches its authoritative source Run"}:_c.validate({...f,run:s})}},l=r&&t==="full"&&e!=="full"?Ec("full").workflow:null;return{...o,workflow:{...o.workflow,steps:{...o.workflow.steps,...i?{"classic.resume-work":{type:"call_tool",ref:"classic-work-continuation",validator:{id:Mw.id,version:Mw.version}}}:{},...Object.fromEntries(Object.entries(l?.steps??{}).filter(([f])=>f.startsWith("full.open")))},transitions:[...o.workflow.transitions??[],...l?.transitions?.filter(f=>f.from.startsWith("full.open"))??[],{from:"full.design.evidence",to:"full.build.plan"},...i?Object.entries(o.workflow.steps).filter(([,f])=>f.type==="invoke_skill").map(([f])=>({from:"classic.resume-work",to:f})):[]],commands:{...i?{"continue-work":{stepId:"classic.resume-work",validator:{id:_c.id,version:_c.version}}}:{},...n?{"continue-build":{stepId:`${t==="full"?"full":e}.build.execute`,validator:{id:Fw.id,version:Fw.version}}}:{},...r?{"repair-archive":{stepId:`${t==="full"?"full":e}.open`,validator:{id:Hw.id,version:Hw.version}}}:{},...t?{"reopen-verification":{stepId:`${t==="full"?"full":e}.verify.run`,validator:{id:zd.id,version:zd.version}}}:{},"revise-design":{stepId:"full.design.handoff",validator:{id:Ic.id,version:Ic.version}},"revise-plan":{stepId:"full.build.plan",validator:{id:Ic.id,version:Ic.version}}}},commandValidators:[...i?[c]:[],...n?[Fw]:[],...r?[Hw]:[],Ic,...t?[{...zd,validate:f=>f.run.state.workflow!==(t==="full"?"full":e)?{accepted:!1,reason:"Classic verification command does not match the active workflow profile"}:zd.validate(f)}]:[]],executors:[...o.executors,...i?[A_]:[]],validators:[...o.validators,...i?[Mw]:[]],transitionHandler:{...o.transitionHandler,apply(f){if(f.event.kind==="action-outcome"&&f.event.stepId==="classic.resume-work"&&f.event.outcome.status==="succeeded"){let a=f.event.outcome.output,d=f.run.actions.find(u=>u.id===a.interruptedActionId),p=d?.stepId.endsWith(".archive.deliver")?d.input.activation?.deliveryRepairCheckId:void 0;return{state:f.run.state,next:[{stepId:a.resumeStepId,input:{interruptedActionId:a.interruptedActionId,...p?{deliveryRepairCheckId:p}:{},summary:"Continue preserved partial work; do not repeat completed side effects."}}]}}return o.transitionHandler.apply(f)}}}}function I_(e,t,r={}){let n={...Ec(e),commandValidators:[]};if(!t||t.workflow.hash===j(Wr(n.workflow)))return n;let i=t.state.workflow,s=wV(e,i==="full"&&e!=="full"?"full":!0);if(t.workflow.hash===j(Wr(s.workflow)))return s;let o=C_(s,i);if(t.workflow.hash===j(Wr(o.workflow)))return o;if(t.workflow.version!=="1")throw new Error("Classic 当前 Run 的 definition hash 不匹配,请保留原定义与业务记录。");return t.commands?.some(c=>c.name==="repair-delivery")?o:t.commands?.length||i!==e?s:n}async function Gd(e,t,r={}){await En(e,t);let n=(await Cd(t,e)).directory,i=r.owner??await Tr(e,"classic",t,{readOnly:r.readOnly});if(!i)throw new Error(`Classic change ${t} is not owned by an SDK Run`);if(!["classic-full","classic-hotfix","classic-tweak"].includes(i.application))throw new Error(`Classic change ${t} belongs to application ${i.application}; use comet runtime dispatch --application ${i.application} to continue its Run. Built-in commands cannot bypass composition checks.`);let s=i.application.slice(8),o=xo(e,r),c=await o.read(i.runId),l=I_(s,c);if(c){let b=Yg(c,l.workflow);b!==c&&(await ao({...l,workflows:[l.workflow],transitionHandlers:[l.transitionHandler],store:{read:async()=>b,compareAndSwap:async()=>!1}}).inspect(i.runId),c=b)}let f=!0,a=ao({store:{...o,async read(b){if(f&&b===i.runId)return f=!1,c;let R=await o.read(b);return R&&Yg(R,l.workflow)}},workflows:[l.workflow],transitionHandlers:[l.transitionHandler],evidenceValidators:l.evidenceValidators,validators:l.validators,executors:l.executors,commandValidators:l.commandValidators}),d=await a.inspect(i.runId),p=d.state,u=d.input&&typeof d.input=="object"&&!Array.isArray(d.input)&&typeof d.input.changeDir=="string"?_o.resolve(e,d.input.changeDir):null,m=u?_o.join(_o.dirname(u),"archive"):null,h=bd(d,s),g=h?"full":s,w=d.actions.some(b=>b.stepId===`${g}.archive.execute`&&(b.status==="running"||b.status==="unknown")),k=u!==null&&(n===u||(p?.archived===!0||w)&&_o.dirname(n)===m&&/^\d{4}-\d{2}-\d{2}-/u.test(_o.basename(n))&&_o.basename(n).slice(11)===t);if(d.workflow.id!==l.workflow.id||d.workflow.version!==l.workflow.version||!d.input||typeof d.input!="object"||Array.isArray(d.input)||d.input.change!==t||!k||!p||typeof p!="object"||Array.isArray(p)||p.workflow!==s&&!h)throw new Error(`Classic SDK Run ${t} does not match its change ownership`);return{run:d,state:p,runtime:a,profile:g,owner:i}}import{createHash as Qd,randomUUID as iee}from"node:crypto";var N_=bt(Dt(),1);import xr from"node:path";nr();ye();function gs(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic progress requires a JSON object");return e}function Vw(e,t){let r=Object.keys(e).filter(n=>!t.includes(n));if(r.length)throw new Error(`Unknown Classic progress field(s): ${r.join(", ")}; allowed fields: ${t.join(", ")}`)}function an(e,t){if(typeof e!="string"||!e.trim()||e.length>4096||[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127))throw new Error(`Invalid Classic progress ${t}`);return e}async function vV(e,t,r){let n=xr.join(t,".comet",r);if(await Wt(e,n,{label:"Classic progress",expected:"file"}))return JSON.parse(await Pe(e,n,{label:"Classic progress"}))}function kV(e,t){let r=Qd("sha256").update(t).digest("hex");return xr.join(pt(e),"classic-delivery",`${r}.json`)}async function bV(e,t){let r=kV(e,t);if(!await Wt(e,r,{label:"Classic delivery reauthorization",expected:"file"}))return null;let n=gs(JSON.parse(await Pe(e,r,{label:"Classic delivery reauthorization"})));if(Vw(n,["schemaVersion","changeIdentity","previousAuthorizationId","authorizationId","action","targetBranch","remote","authorizedRemoteUrl"]),n.schemaVersion!==1||n.changeIdentity!==t)throw new Error("Classic delivery reauthorization identity is invalid");let i=Uw({action:n.action,targetBranch:n.targetBranch,...n.remote===void 0?{}:{remote:n.remote}},!0);if(i.action==="archive-only")throw new Error("Classic archive-only delivery cannot be reauthorized");if(i.commit!==void 0||i.prUrl!==void 0)throw new Error("Classic delivery reauthorization cannot change sealed commit or PR evidence");return{schemaVersion:1,changeIdentity:t,previousAuthorizationId:an(n.previousAuthorizationId,"previousAuthorizationId"),authorizationId:an(n.authorizationId,"authorizationId"),...i,targetBranch:i.targetBranch,...n.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:an(n.authorizedRemoteUrl,"authorizedRemoteUrl")}}}function Uw(e,t=!1){let r=gs(e);if(Vw(r,["action","targetBranch","remote","commit","prUrl",...t?["schemaVersion","changeIdentity","authorizedRemoteUrl","authorizationId"]:[]]),!["local","push","pr","archive-only"].includes(r.action))throw new Error(`Invalid Classic delivery action '${String(r.action)}'; actions: local|push|pr|archive-only`);if(r.action==="archive-only"){if(r.targetBranch!==void 0||r.remote!==void 0||r.commit!==void 0||r.prUrl!==void 0)throw new Error("Classic archive-only delivery cannot claim a Git branch, remote, commit, or PR");return{action:"archive-only"}}let n=an(r.targetBranch,"targetBranch");if(n.startsWith("-")||/[~^:?*[\\\s]/u.test(n)||n.includes("..")||n.includes("@{"))throw new Error("Invalid Classic delivery targetBranch");let i={action:r.action,targetBranch:n};if(r.remote!==void 0){let s=an(r.remote,"remote");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(s))throw new Error("Classic delivery remote must be a name, not a URL");i.remote=s}if(r.commit!==void 0){let s=an(r.commit,"commit");if(!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u.test(s))throw new Error("Classic delivery commit must be a full object ID");i.commit=s.toLowerCase()}if(r.prUrl!==void 0){let s=an(r.prUrl,"prUrl"),o=new URL(s);if(o.protocol!=="https:"||o.username||o.password)throw new Error("Invalid Classic delivery prUrl");i.prUrl=s}return i}function $_(e){let t=(0,N_.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length)throw new Error("Invalid Classic delivery change state");return gs(t.toJS())}function RV(e,t,r){return typeof e.run_id=="string"&&e.run_id?`run:${e.run_id}`:j_(e,t,r)}function j_(e,t,r){let n=e.archived===!0||xr.basename(xr.dirname(t))==="archive"?xr.basename(t).replace(/^\d{4}-\d{2}-\d{2}-/u,""):xr.basename(t);if(typeof e.created_at!="string"||typeof e.base_ref!="string"&&e.base_ref!==null)throw new Error("Classic delivery requires stable change identity");return`legacy:${Qd("sha256").update(JSON.stringify([n,e.created_at,e.base_ref??xr.resolve(r)])).digest("hex")}`}function D_(e,t,r,n){let i=RV(t,r,n);if(e===i)return i;if(typeof e=="string"&&e.startsWith("legacy:")&&e===j_(t,r,n))return e;throw new Error("Classic delivery change identity mismatch")}var SV=je("classicCurrentState",async(e,t)=>CV(e,t));async function CV(e,t){return $_(await Pe(e,await fe(t),{label:"Classic delivery state"}))}async function EV(e,t){return SV(e,t)}var Xd=class extends Error{constructor(t,r){super(`Classic delivery git command timed out: ${[t,...r].join(" ")}`)}};function Bw(e,t,r,n){return HA(t,r,{cwd:e,timeoutMs:5e3,env:LA({authentication:n})}).trim()}function Oc(e,t,r,n=!1){try{return Bw(e,t,r,n)}catch{return null}}function AV(e,t,r,n=!1){try{return Bw(e,t,r,n)}catch(i){if(!(i instanceof di)||!i.timedOut)return null;try{return Bw(e,t,r,n)}catch(s){if(s instanceof di&&s.timedOut)throw new Xd(t,r);return null}}}function Pc(e,t){return Oc(e,"git",["-C",e,...t])}function Jd(e,t){return AV(e,"git",["-C",e,...t])}function P_(e,t,r=!1){return Oc(e,"git",["-C",e,"remote","get-url",...r?["--push"]:[],t],!0)}function xV(e,t){let r=xr.relative(e,t).replaceAll("\\","/");return[`:(literal)${r}`,...[".comet-state.lock",".comet-state-transaction.json",...[...Nm].map(n=>`.comet/${n}`)].map(n=>`:(exclude,literal)${r}/${n}`)]}function O_(e,t,r,n){let i=xr.relative(e,t).replaceAll("\\","/"),s=xV(e,t),o=Ns.map(l=>Jd(e,["show",`${r}:${i}/${l}`])).filter(l=>l!==null);if(o.length!==1)return!1;let c=o[0];try{let l=$_(c);return l.archived===!0&&D_(n,l,t,e)===n&&Jd(e,["merge-base","--is-ancestor",r,"HEAD"])!==null&&Jd(e,["diff","--quiet","--no-ext-diff","--no-textconv",r,"--",...s])!==null&&Jd(e,["ls-files","--others","--exclude-standard","--",...s])===""}catch(l){if(l instanceof Xd)throw l;return!1}}function _V(e){return Qd("sha256").update(e).digest("hex")+".json"}async function IV(e,t){let r=_V(t);return[{root:xr.dirname(pt(e)),file:xr.join(pt(e),"classic-delivery-receipts",r)}]}function PV(e,t){let r=gs(e);if(Vw(r,["schemaVersion","changeIdentity","authorizationId","invalidated","commit","prUrl","archiveFiles","archiveCompleted"]),r.schemaVersion!==1||r.changeIdentity!==t)throw new Error("Invalid Classic delivery receipt schema or identity");if(r.invalidated!==void 0&&typeof r.invalidated!="boolean")throw new Error("Invalid Classic delivery receipt invalidation");let n=Uw({action:"local",targetBranch:"main",...r.commit!==void 0?{commit:r.commit}:{},...r.prUrl!==void 0?{prUrl:r.prUrl}:{}});return{schemaVersion:1,changeIdentity:t,authorizationId:an(r.authorizationId,"authorizationId"),...r.invalidated===!0?{invalidated:!0}:{},...n.commit?{commit:n.commit}:{},...n.prUrl?{prUrl:n.prUrl}:{},...r.archiveCompleted===!0?{archiveCompleted:!0}:{},...r.archiveFiles===void 0?{}:{archiveFiles:TV(r.archiveFiles)}}}async function OV(e,t){let r=null;for(let n of await IV(e,t)){if(!await Wt(n.root,n.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=PV(JSON.parse(await Pe(n.root,n.file,{label:"Classic delivery receipt"})),t);if(r&&JSON.stringify(r)!==JSON.stringify(i))throw new Error("Conflicting Classic delivery receipts");r=i}return r}function TV(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic document archive receipt");let t=e;if(Object.keys(t).length===0||Object.keys(t).length>1e4||Object.entries(t).some(([r,n])=>r.startsWith("/")||r.includes("\\")||r.split("/").some(i=>!i||i==="."||i==="..")||typeof n!="string"||!/^[a-f0-9]{64}$/u.test(n)))throw new Error("Invalid Classic document archive receipt");return t}function NV(e){return e.authorizationId===void 0?`legacy:${Qd("sha256").update(JSON.stringify(e)).digest("hex")}`:an(e.authorizationId,"authorizationId")}function T_(e,t,r){return t===r||Pc(e,["merge-base","--is-ancestor",t,r])!==null}function $V(e){let t=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(e);try{let r=new URL(t?`ssh://git@${t[1]}/${t[2]}`:e);if(!["https:","ssh:"].includes(r.protocol)||r.password||r.search||r.hash||r.port||r.protocol==="https:"&&r.username)return null;let n=r.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return n.length!==2||n.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${r.hostname}/${n.join("/")}`.toLowerCase()}catch{return null}}function Yd(e,t){try{let r=new URL(e);if(r.protocol!=="https:"||r.username||r.password||r.port||r.search||r.hash)return null;let n=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(r.pathname);return n&&`${r.hostname}/${n[1]}/${n[2]}`.toLowerCase()===t?`https://${r.hostname}/${n[1]}/${n[2]}/pull/${n[3]}`:null}catch{return null}}async function Zd(e,t,r={}){let n=r.evidence!==!1,i=await vV(e,t,"delivery.json");if(i===void 0)return{delivery:null,verification:{status:"needsAuthorization"}};let s=gs(i);if(s.schemaVersion!==1)throw new Error("Unsupported Classic delivery schemaVersion");let o=Uw(s,!0),c=await EV(e,t),l=D_(s.changeIdentity,c,t,e),f=NV(s),a=await bV(e,l);if(a&&a.previousAuthorizationId!==f)throw new Error("Classic delivery reauthorization is stale for the sealed authorization");let d=a?{action:a.action,targetBranch:a.targetBranch,...a.remote===void 0?{}:{remote:a.remote}}:o,p=a?.authorizationId??f,u=await OV(e,l),m=u?.authorizationId===p?u:null;if(m?.invalidated)return{delivery:null,verification:{status:"needsAuthorization",invalidated:!0}};for(let K of["commit","prUrl"]){if(K==="commit"&&m?.[K]&&d[K]&&m[K]!==d[K])throw new Error("Classic delivery receipt conflicts with authorization evidence");m?.[K]&&(d[K]=m[K])}let h=s.authorizedRemoteUrl===void 0?void 0:an(s.authorizedRemoteUrl,"authorizedRemoteUrl"),g=a?.authorizedRemoteUrl??h,w={...d,schemaVersion:1,changeIdentity:l,authorizationId:p,...g?{authorizedRemoteUrl:g}:{}};if(d.action==="archive-only"){let K=c.archived===!0&&!!(m?.archiveCompleted||m?.archiveFiles);return{delivery:w,verification:{status:K?"complete":"needsVerification",archiveVerified:K}}}if(!n)return{delivery:w,verification:{status:m?.commit||m?.prUrl?"complete":"needsVerification",currentBranch:null,commitExists:!1,archiveCommitted:!1,observedCommit:null,observedPrUrl:null,remoteVerified:!1,prVerified:!1,remoteStatus:"notChecked",prStatus:"notChecked"}};let k=Pc(e,["symbolic-ref","--quiet","--short","HEAD"]),b=xr.relative(e,t).replaceAll("\\","/"),R=null;!d.commit&&c.archived===!0&&(R=Pc(e,["log","-20","--format=%H","HEAD","--",...Ns.map(ne=>`:(literal)${b}/${ne}`)])?.split(/\r?\n/u).find(ne=>/^[a-f0-9]{40,64}$/u.test(ne)&&O_(e,t,ne,l))??null);let E=d.commit??R,O=!!E&&Pc(e,["cat-file","-t",E])==="commit",z=c.archived===!0&&O&&O_(e,t,E,l),D=k===d.targetBranch&&(!c.bound_branch||a!==null||c.bound_branch===k)&&z,G=!1,J=!1,te=null,Z=r.verifyRemote&&d.action!=="local"?"unavailable":"notChecked",we="notChecked";if(r.verifyRemote&&D&&d.action!=="local"&&d.remote&&g&&P_(e,d.remote)===g&&P_(e,d.remote,!0)===g){let K=`refs/heads/${d.targetBranch}`,ne=Oc(e,"git",["-C",e,"-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",d.remote,K],!0),ze=ne?.split(/\r?\n/u)??[],P=ze.length===1?/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(ze[0]):null,F=P?.[2]===K?P[1]:null;G=!!E&&!!F&&T_(e,E,F),Z=G?"verified":ne===""?"missing":ne===null||!F||Pc(e,["cat-file","-t",F])!=="commit"?"unavailable":"missing";let re=$V(g),He=re&&d.prUrl?Yd(d.prUrl,re):null,C=G||ne==="",$=T=>T.headRefName===d.targetBranch&&typeof T.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(T.headRefOid)&&(G?T.headRefOid===F&&["OPEN","MERGED"].includes(T.state):ne===""&&T.state==="MERGED"&&!!E&&T_(e,E,T.headRefOid));if(C&&d.action==="pr"&&(we="unavailable"),C&&d.action==="pr"&&He&&re){let T=Oc(e,"gh",["pr","view",He,"--repo",re,"--json","url,headRefName,headRefOid,state"],!0);try{let L=T?gs(JSON.parse(T)):null;J=!!L&&typeof L.url=="string"&&Yd(L.url,re)===He&&$(L),we=J?"verified":L?"missing":"unavailable"}catch{J=!1,we="unavailable"}}else if(C&&d.action==="pr"&&!d.prUrl&&re){let T=Oc(e,"gh",["pr","list","--repo",re,"--head",d.targetBranch,"--state","all","--json","url,headRefName,headRefOid,state","--limit","100"],!0);try{let L=T===null?null:JSON.parse(T);if(!Array.isArray(L)||L.length>=100)throw new Error("Incomplete PR discovery");let H=L.map(gs).filter(ie=>typeof ie.url=="string"&&Yd(ie.url,re)&&$(ie));H.length===1?(te=Yd(H[0].url,re),J=!0,we="verified"):we=H.length===0?"missing":"unavailable"}catch{we="unavailable"}}}return{delivery:w,verification:{status:D&&(d.action==="local"||(d.action==="push"?G:J))?"complete":"needsVerification",currentBranch:k,commitExists:O,archiveCommitted:z,observedCommit:R,observedPrUrl:te,remoteVerified:G,prVerified:J,remoteStatus:Z,prStatus:we}}}var WV=bt(Dt(),1);import{AsyncLocalStorage as zw}from"node:async_hooks";var See=new zw,Cee=new zw,Eee=new zw;pn();Zl();ye();qt();jt();import{stripVTControlCharacters as jV}from"node:util";function Kw(e,t={}){return{code:"CLASSIC_COMMAND_FAILED",message:jV(e instanceof Error?e.message:String(e)),...t}}var MV=je("readCometCurrentSelection",e=>js(e)),FV=je("classicHookSdkRun",(e,t)=>Gd(e,t,{readOnly:!0}));async function HV(e,t){let{run:r,state:n}=await FV(e,t);if(r.status==="cancelled")throw new Error(`Cannot select current change '${t}': Run is cancelled`);if(n.archived||r.status==="completed")throw new Error(`Cannot select current change '${t}': change is archived`);let i=fr(e),s=gn({isolation:n.isolation,boundBranch:n.boundBranch,currentBranch:i,gitWorkTree:Xn(e)});if(s.status==="drift")throw new Error(Ws(t,s.boundBranch,i));if(s.status==="unbound-detached")throw new Error(Ms(t));if(s.status==="needs-heal")throw new Error(`Classic SDK change '${t}' has no bound branch in its Run`);return i}async function BV(e,t){sn(t);let r=await An(t,e);if(!r.stateExists)throw new Error(`Cannot select current change '${t}': active change state not found`);let n=await dr(r.directory,{migrate:!1});if(!n.classic)throw new Error(`Cannot select current change '${t}': Classic state is incomplete`);if(n.classic.archived)throw new Error(`Cannot select current change '${t}': change is archived`);return r.directory}async function q_(e){let t;try{t=await MV(e)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(t.status==="missing")return{status:"missing"};if(t.selection.workflow!=="classic")return{status:"stale",reason:`current change '${t.selection.change}' belongs to Native, not Classic`};let r=t.selection;try{if(await Tr(e,"classic",r.change,{readOnly:!0})){let s=await HV(e,r.change);return r.branch!==null&&s!==r.branch?{status:"stale",reason:`current change '${r.change}' was selected on branch '${r.branch}', current branch is '${s??"detached HEAD"}'`}:{status:"selected",selection:r}}}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let n;try{n=await BV(e,r.change)}catch(s){try{let o=await lw(r.change,e);if(!o)throw s;let c=await dr(o.directory,{migrate:!1}),l=await Zd(e,o.directory);if(!c.classic?.archived||["complete","local-verified"].includes(l.verification.status))throw s;n=o.directory}catch(o){return{status:"stale",reason:o instanceof Error?o.message:String(o)}}}let i=await _a(n,{heal:!1,cwd:e});return i.status==="drift"?{status:"stale",reason:Ws(r.change,i.boundBranch,i.currentBranch)}:i.status==="unbound-detached"?{status:"stale",reason:Ms(r.change)}:i.status==="ok"?{status:"selected",selection:r}:r.branch!==null&&i.currentBranch!==r.branch?{status:"stale",reason:`current change '${r.change}' was selected on branch '${r.branch}', current branch is '${i.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:r}}qt();Sm();pn();import VV from"os";import ef from"path";function UV(e={}){let t=e.cwd??process.cwd(),r=e.homeDir??VV.homedir(),n=[{file:ef.resolve(t,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:ef.resolve(r,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return n.filter((i,s)=>n.findIndex(o=>o.file===i.file)===s)}async function L_(e,t={}){for(let r of UV(t)){let n=ef.dirname(ef.dirname(r.file)),i=r.scope==="global"?(await Rm(n))?.classic:(await fn(n,{allowPartialProject:!0}))?.value.classic;if(!i||typeof i!="object"||Array.isArray(i))continue;let s=i[e];if(s!=null)return{value:String(s),source:r.source}}return null}async function Gw(e){let t=await L_("document_evidence",{cwd:e});if(!t)return"neutral";if(t.value==="neutral"||t.value==="strict")return t.value;throw new Error(`classic.document_evidence must be neutral or strict, got '${t.value}' (${t.source})`)}function zV(e,t){return[be(e,t.openSpecRoot),be(e,t.superpowersRoot)]}async function W_(e,t,r){return await Gw(e)==="strict"?!1:Fb(r,zV(e,t))}var KV=je("classicHookSdkRun",(e,t)=>Gd(e,t,{readOnly:!0})),GV=je("classicHookWritableLayout",e=>Ni(e));function at(e,t){return{exitCode:e,stderr:t+`
|
|
266
|
+
`}}function Tt(e){return at(0,`[COMET-HOOK] allowed: ${e}`)}async function JV(){if(process.env.FILE_PATH)return{intent:"write",toolName:null,targets:[process.env.FILE_PATH]};if(process.stdin.isTTY)return{intent:"unknown",toolName:null,targets:[]};let e=await sf();e.text===null&&(process.stderr.write(`[COMET-HOOK] stdin timeout: the host did not provide hook input within the expected window
|
|
267
|
+
`),process.exit(1));let t=$c(e.text);return iy(t)}function Tc(e){return e.replaceAll("\\","/").replace(/\/+/gu,"/")}function kt(e){let t=Tc(e);return process.platform==="win32"?t.toLowerCase():t}function YV(e){let t=e.indexOf("--project-root"),r=t>=0?e[t+1]:void 0;return Nt.resolve(r&&!r.startsWith("--")?r:process.cwd())}function M_(e,t){let r=Tc(Nt.relative(t,e));return r===""?"":r.startsWith("../")||r===".."||Nt.isAbsolute(r)?null:r}async function XV(e){let t=Nt.resolve(e),r=Nt.parse(t).root,n=[],i=t;for(;i&&i!==r;)try{let s=await tf.realpath(i);return Nt.join(s,...n.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;n.push(Nt.basename(i)),i=Nt.dirname(i)}try{let s=await tf.realpath(r);return Nt.join(s,...n.reverse())}catch{return null}}async function QV(e,t){let r=Nt.isAbsolute(e)?e:Nt.resolve(t,e),n=Tc(r),i=M_(r,t);if(i!==null)return i;try{let s=await XV(r),o=await tf.realpath(t);if(s){let c=M_(s,o);if(c!==null)return c;n=Tc(s)}}catch{if(!Nt.isAbsolute(e))return Tc(e).replace(/^\.\//u,"")}return n.replace(/^\.\//u,"")}async function Jw(e){try{let t=await dr(e,{migrate:!1}),r=Array.from(new Set(t.unknownKeys)).sort();if(r.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${r.join(", ")}`);if(!t.classic)throw new Error("Classic state projection is unavailable");return{changeDir:e,phase:t.classic.phase,classic:t.classic,archived:t.classic.archived}}catch(t){if(!(t instanceof Error)||!t.message.startsWith("Invalid Classic state:")&&t.message!=="Classic state projection is unavailable"||t.message.startsWith("Invalid Classic state: change_id"))throw t;let r=await _R(e);return r.phase?{changeDir:e,phase:r.phase,classic:null,archived:r.archived,invalidState:t instanceof Error&&t.message.includes("unknown field")}:null}}async function Yw(e,t,r){let{run:n,state:i}=await KV(e,t);return{runtimeFormat:"sdk",changeDir:r,phase:i.phase,classic:i,archived:i.archived,cancelled:ui(n),cancellationPending:n.status==="cancelled"&&!ui(n),executionUnresolved:n.actions.some(s=>s.status==="unknown")}}async function ZV(e){let t=(await wt(e)).changesDir,r=[];if(!(await hn(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return r;for(let i of(await tf.readdir(t,{withFileTypes:!0})).sort((s,o)=>s.name.localeCompare(o.name))){if(i.name==="archive"||ho(i.name))continue;let s=await An(i.name,e);if(!s.exists)continue;let o=await Tr(e,"classic",i.name,{readOnly:!0})?await Yw(e,i.name,s.directory):s.stateExists?await Jw(s.directory):null;!o||o.archived||o.cancelled||r.push(o)}return r}var Xw=je("classicActiveChanges",e=>ZV(e)),Qw=je("classicActiveChange",async(e,t)=>{let r=await An(t,e);if(await Tr(e,"classic",t,{readOnly:!0})){let i=await Yw(e,t,r.directory);return i.archived||i.cancelled?null:i}if(!r.exists||!r.stateExists)return null;let n=await Jw(r.directory);return!n||n.archived||n.cancelled?null:n}),V_=je("classicPlanReadiness",mi);function U_(e,t){return`${be(e,t.superpowersRoot)}/`}function z_(e,t){return kt(e).startsWith(kt(t))}function K_(e,t){return[{prefix:`${be(e,t.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${be(e,t.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${be(e,t.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function G_(e,t){let r=kt(e),n=t.find(s=>r.startsWith(kt(s.prefix)));if(!n)return null;let i=r.slice(kt(n.prefix).length);return!i||i.includes("/")||!i.endsWith(".md")?null:n}function J_(e,t){return e.classic?.[t.field]??null}function eU(e,t){return e.classic!==null&&e.phase===t.phase&&!J_(e,t)}async function F_(e,t,r){return eU(t,r)?!0:r.field!=="plan"||t.phase!=="build"?!1:(await V_(e,t.classic?.plan??null,{requireNonempty:t.classic?.buildMode==="autonomous"})).status==="broken"}function Y_(e){return e.phase==="design"||e.phase==="build"||e.phase==="verify"}function ki(e){return e.changeDir?Nt.basename(e.changeDir):null}var tU=new Set(["design","plan","verify","verification","verification-report","report"]);function H_(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function rU(e,t){return[t.classic?.designDoc,t.classic?.plan,t.classic?.verificationReport].some(n=>n&&kt(n)===kt(e))}function nU(e,t){let n=(e.split("/").at(-1)??e).replace(/\.[^.]+$/u,"");if(n===t)return!0;let i=[...tU].map(H_).join("|");return new RegExp(`(^|[-_.])${H_(t)}[-_.](${i})$`,"u").test(n)}async function iU(e,t,r){let n=r?[await Qw(t,r)].filter(c=>c!==null):await Xw(t),i=n.find(c=>rU(e,c));if(i)return{governing:i,match:"recorded"};let o=n.filter(Y_).filter(c=>{let l=ki(c);return l!==null&&nU(e,l)}).sort((c,l)=>(ki(l)?.length??0)-(ki(c)?.length??0))[0];return o?{governing:o,match:"named"}:null}async function B_(e,t,r){if(r)return await Qw(e,r)??{blockedResult:ws(t,`selected change '${r}' is no longer active`)};let n=await Xw(e);if(n.length===0)return null;let i=await q_(e);if(i.status==="stale")return{blockedResult:ws(t,i.reason)};if(i.status==="selected"){let s=n.find(o=>ki(o)===i.selection.change);return s||{blockedResult:ws(t,`selected change '${i.selection.change}' is no longer active`)}}if(n.length===1){let s=n[0];if(s.changeDir!==null){let o=await _a(s.changeDir,{heal:!1,cwd:e}),c=ki(s)??"unknown";if(o.status==="drift")return{blockedResult:ws(t,Ws(c,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:ws(t,Ms(c))}}return s}return{blockedResult:hU(t,n.map(s=>ki(s)).filter(Boolean))}}function sU(e){let r=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(e)?.[1]??e;return ho(r)?null:r}function X_(e,t,r){let n=`${be(t,r.changesDir)}/`;if(!kt(e).startsWith(kt(n)))return null;let i=e.slice(n.length).split("/").filter(Boolean),[s,o]=i;return s?kt(s)===kt("archive")?{kind:"archive",archiveName:o??null,changeName:o?sU(o):null}:{kind:"active",changeName:s}:null}function Q_(e,t,r){return t?.kind==="archive"?wU(e,t.archiveName,t.changeName,r):t?.kind==="active"&&r&&kt(t.changeName)!==kt(r)?gU(e,t.changeName,r):null}async function oU(e,t,r,n){let i=X_(e,t,r),s=Q_(e,i,n);if(s)return{blockedResult:s};if(i?.kind==="active"){let o=i.changeName,c=await An(o,t);if(await Tr(t,"classic",o,{readOnly:!0})){let l=await Yw(t,o,c.directory);return l.archived?{blockedResult:ws(e,`Classic SDK change '${o}' is already archived`)}:l}if(c.stateExists){let l=await Jw(c.directory);return l||{changeDir:c.directory,phase:"open",classic:null,archived:!1}}return{changeDir:c.directory,phase:"open",classic:null,archived:!1}}if(z_(e,U_(t,r))){let o=await iU(e,t,n);if(o?.match==="recorded")return{...o.governing,superpowersArtifact:"matched"};let c=G_(e,K_(t,r));if(o)return c?{...o.governing,superpowersArtifact:await F_(t,o.governing,c)?"matched":"unmatched",superpowersSlot:c}:{...o.governing,superpowersArtifact:"matched"};if(c){let f=await B_(t,e,n);return!f||"blockedResult"in f?f:{...f,superpowersArtifact:await F_(t,f,c)?"matched":"unmatched",superpowersSlot:c}}let l=n?await Qw(t,n):(await Xw(t))[0]??null;return l?{...l,superpowersArtifact:"unmatched"}:null}return B_(t,e,n)}function aU(e){return!e.includes("/")&&e.endsWith(".md")}function cU(e){return e.startsWith(".comet/")||e.includes("/.comet/")}function lU(e){return e===".superpowers"||e.startsWith(".superpowers/")}function uU(e,t,r){let n=kt(e);if(!n.startsWith(kt(r)))return null;let i=ma(Nt.posix.basename(n))||n.endsWith("/.openspec.yaml"),s=n.endsWith("/proposal.md")||n.endsWith("/design.md")||n.endsWith("/tasks.md"),o=n.includes("/.comet/"),c=n.includes("/specs/");return t==="open"&&(s||i||o||c)?`${e} (phase: open, openspec artifacts)`:t==="design"&&(s||i||o||c)?`${e} (phase: design, handoff/spec)`:t==="build"&&(n.endsWith("/tasks.md")||i||c)?`${e} (phase: build, spec/tasks)`:t==="verify"&&i?`${e} (phase: verify, state)`:t==="archive"&&i?`${e} (phase: archive, state)`:null}function dU(e,t,r,n){let i=t==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard",` NEXT: finish clarification and artifacts, then run comet guard ${r} open --apply`]:t==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard",` NEXT: finish the Design Doc, then run comet guard ${r} design --apply to enter build`]:t==="verify"?[" BLOCKED: implementation writes are not allowed during verify"," This phase allows verification reports and state updates only",` NEXT: run comet state transition ${r} verify-fail, then retry the implementation edit in Build`]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes",` NEXT: run comet archive ${r} to complete Archive; use the reported recovery action if Archive is blocked`];return Z_(e,t,t,n,i)}function Z_(e,t,r,n,i){let s=ex(r,n);return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t}`,` Target file: ${e}`,"",` ${s.summary}`,` RELAY TO USER: ${s.user_message}`,"",...i,""].join(`
|
|
268
|
+
`))}function fU(e,t,r){return Z_(e,"build (workflow: full), but design_doc is empty","build",r,[" BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded",` NEXT: create the Design Doc, run comet state complete-design ${t} --design-doc <repo-relative-ref>, then retry the original write`])}function pU(e,t,r,n,i){let s=ki(t)??"<change-name>",o=r.status==="missing",c=o?"classic-build-plan-missing":"classic-build-plan-broken",l=o?"plan is not recorded":"the recorded plan path does not resolve to a file",f=o?[]:[`RECORDED_PLAN: ${r.recordedPath}`],a=t.changeDir?be(n,t.changeDir):"<classic-change-dir>",d=be(n,i.superpowersPlansDir),p=t.classic?.buildMode==="autonomous",u=o?`comet state set ${s} plan <repository-relative-plan-path>`:`comet state set ${s} plan <new-repository-relative-plan-path>`,m=o?[p?"2. Plan the implementation autonomously from the confirmed design and task IDs.":"2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${s} design_doc" and read ${a}/tasks.md.`,`4. Create the implementation plan under ${d}/.`,"5. Record the plan path:",` ${u}`]:[p?`2. Restore the plan file at ${r.recordedPath}, or create a replacement autonomously under ${d}/.`:`2. Restore the plan file at ${r.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${d}/.`,"3. When creating a replacement, record its path:",` ${u}`];return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${c}`,`CHANGE: ${s}`,"WORKFLOW: full","PHASE: build",`TARGET: ${e}`,`STATE: ${l}`,...f,"",p?"BLOCKED: project source writes require a ready implementation plan.":"BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${d}/<plan-file>.md`,"- Comet state updates performed by the comet CLI",`- ${a} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${s} and resume Step 1.`,...m,`${o?"6":"4"}. Verify recovery:`,` comet state check ${s} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${e} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.",p?"Autonomous planning does not require an external Skill; all normal acceptance checks still apply.":"If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(`
|
|
269
|
+
`))}function mU(e,t){let r=t.superpowersSlot,n=r?J_(t,r):null,i=r?t.phase!==r.phase?[` BLOCKED: ${r.wireField} cannot be first-written in phase ${t.phase}`,` Expected phase: ${r.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:n?[` BLOCKED: ${r.wireField} is already recorded for this change`,` Recorded path: ${n}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t.phase}`,` Target file: ${e}`,"",...i,""].join(`
|
|
270
|
+
`))}function hU(e,t){return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${e}`,` Active changes: ${t.join(", ")}`,"",` NEXT: choose the intended change, run one of: ${t.map(r=>`comet state select ${r}`).join(" | ")}, then retry the source write`,""].join(`
|
|
271
|
+
`))}function ws(e,t){return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${e}`,` Reason: ${t}`,""," NEXT: run comet state current --json, follow its exact selection recovery action, then retry the source write",""].join(`
|
|
272
|
+
`))}function gU(e,t,r){return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` BLOCKED: target belongs to Classic change '${t}', but the current selection is '${r}'`,` Target file: ${e}`,"",` NEXT: write the matching artifact for '${r}', or run comet state select ${t} before modifying this target`,""].join(`
|
|
273
|
+
`))}function wU(e,t,r,n){let i=r?`archived Classic change '${r}'`:t?`Classic archive entry '${t}'`:"the Classic archive",s=n?`, but the current selection is '${n}'`:"";return at(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` BLOCKED: target belongs to ${i}${s}; archived artifacts are immutable`,` Target file: ${e}`,""," NEXT: modify the active change artifact instead; if follow-up work is required, create or select an active change and retry there",""].join(`
|
|
274
|
+
`))}async function yU(e,t,r,n=Gl,i){try{if((await n(e,[t])).projectTargets.length===0)return Tt(`${t} (outside guarded project)`)}catch(h){return at(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${t}.`,`REASON: ${h instanceof Error?h.message:String(h)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(`
|
|
275
|
+
`))}let s=await QV(t,e),o;try{o=await GV(e)}catch(h){return at(2,`[COMET-HOOK] blocked: ${h instanceof Error?h.message:String(h)}`)}let c=X_(s,e,o),l=Q_(s,c,r);if(l)return l;if(cU(s))return Tt(`${s} (whitelist: comet config)`);if(Mb(s,Nt.relative(e,o.changesDir))&&!s.replaceAll("\\","/").includes("/archive/"))return Tt(`${s} (change walkthrough)`);if(lU(s))return Tt(`${s} (whitelist: superpowers workspace)`);if(await W_(e,o,s))return Tt(`${s} (whitelist: neutral document)`);if(s==="CHANGELOG.md"||s==="README.md"||aU(s)&&!hm(s))return Tt(`${s} (whitelist: root markdown)`);let f=await pm(e,t,[Nt.join(e,".comet"),o.openSpecRoot,o.superpowersRoot]);if(f)return Tt(f);let a;try{a=await oU(s,e,o,r)}catch(h){return at(2,`[COMET-HOOK] blocked: ${h instanceof Error?h.message:String(h)}`)}if(!a)return Tt("no active comet change");if("blockedResult"in a)return a.blockedResult;if(a.cancellationPending)return at(2,"Classic Run still has an unresolved Archive or child Run. Reconcile its original business result before writing; platform tasks are cancelled and cleaned up by the Agent platform.");if(a.executionUnresolved)return at(2,"Classic execution is unresolved: reconcile the original claim and business result before writing. Cancel ordinary tasks through the Agent platform, then record business cancellation without a process-stop receipt.");if(a.archived)return Tt(`${s} (own change archived)`);let d=a.phase,p=ki(a)??r;if(!p)return ws(s,"active Classic change name cannot be resolved");if(a.classic?.buildMode==="autonomous"&&a.changeDir)try{let h=await _a(a.changeDir,{heal:!1,cwd:e});if(h.status==="drift")return at(2,Ws(p,h.boundBranch,h.currentBranch));if(h.status==="unbound-detached")return at(2,Ms(p))}catch(h){return at(2,h instanceof Error?h.message:String(h))}let u=G_(s,K_(e,o));if(d==="build"&&a.classic?.buildMode==="autonomous"&&u?.field==="plan"){let h=await Pd(e,p,a.classic,{requirePlan:!1});if(h.length)return at(2,h.join(`
|
|
276
|
+
`))}let m=uU(s,d,`${be(e,o.openSpecRoot)}/`);if(m)return Tt(m);if(z_(s,U_(e,o))){if(a.superpowersArtifact==="matched"&&Y_(a))return Tt(`${s} (phase: ${d}, superpowers)`);if(a.superpowersArtifact==="unmatched")return mU(s,a)}if(a.invalidState)return at(2,`[COMET-HOOK] blocked: active Classic state is invalid; run comet classic validate ${p}, repair only the reported fields, then run comet state next ${p} --json before retrying ${s}`);if(["verify","archive"].includes(d)&&await Gw(e)!=="strict")return Tt(`${s} (preserve the current Run and user edits; before advancing, the current Agent must assess the actual changes, formal decisions, and check applicability, then follow comet state next ${p} --json; uncovered changes cannot be accepted or archived)`);if(d==="build"&&a.classic?.workflow==="full"&&!a.classic.designDoc)return fU(s,p,yo(a.classic?.language));if(d==="build"&&a.classic?.workflow==="full"){let h=await V_(e,a.classic.plan,{requireNonempty:a.classic.buildMode==="autonomous"});if(h.status!=="ready")return pU(s,a,h,e,o)}if(d==="build"){if(a.classic?.buildMode==="autonomous"){let h=await Pd(e,p,a.classic);if(h.length)return at(2,h.join(`
|
|
277
|
+
`))}return Tt(`${s} (phase: ${d})`)}if(d==="verify"&&i?.writes)return Tt(s+" (保留当前阶段;由 Agent 判断修改影响,修复实现前通过 Runtime 返回 Build)");if(d==="design"&&a.changeDir&&kt(s)===kt(`${be(e,a.changeDir)}/brainstorm-summary.md`)){let h=`${be(e,a.changeDir)}/.comet/handoff/brainstorm-summary.md`,g=yo(a.classic?.language)==="zh-CN";return at(2,[`[COMET-HOOK] blocked: ${g?"设计讨论摘要应保存到检查点目录。":"Save the Design discussion summary in the checkpoint directory."}`,`Target file: ${s}`,`NEXT: ${g?`将候选摘要写入 ${h},保留 Design 阶段,等待当前方案的确认;保存摘要不需要进入 Build。`:`write the candidate summary to ${h}; keep the Design phase and await the current design decision. Saving a summary does not require entering Build.`}`].join(`
|
|
278
|
+
`))}return dU(s,d,p,yo(a.classic?.language))}var eI=async e=>{let t=YV(e),r=await JV();if(!r.targets.length)return Tt("no file path in tool input");let n;for(let i of r.targets){let s=await yU(t,i,void 0,void 0,r);if(s.exitCode!==0)return s;n=s}return r.targets.length===1&&n?n:Tt("all write targets passed the Classic guard")};var vU=new Set([...ba,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),tI=new Set(Gn.filter(e=>!vU.has(e))),Zw={workflow:["full","hotfix","tweak"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct","autonomous"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]};var kU=`
|
|
279
|
+
Options: --json (machine-readable output), --compact (requires --json), --help
|
|
280
|
+
精简视图用 outputView.references 的 JSON Pointer 定位重复字段;Request 模板保留完整;没有字节收益时返回原完整协议。去掉 --compact 获取完整协议。
|
|
281
|
+
JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
|
|
282
|
+
Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
|
|
283
|
+
`;function rI(e,t){let r=t.indexOf("--"),n=r<0?t:t.slice(0,r);if(!n.includes("--help")&&!n.includes("-h"))return;let i={check:["comet check run <change> <build|verify> -- <program> [args...]","comet check rerun <change> <build|verify>","These legacy commands return Agent platform guidance only; they do not execute or replay programs, create a claim, or record a passing result.","Run ordinary development and checks with the Agent platform tools. The platform owns timeout, cancellation and process cleanup.","Submit the actual results with --checks when completing SDK Build/Verify; use comet state record-check for Compat.","The Agent judges which checks apply. User choices, approvals, tasks and acceptance remain required.","Result: data.executed=false, data.nextAction and platform guidance; exitCode=0 means guidance was returned, not that a check passed."],state:["comet state <command> [args]","init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>] [--runtime <compat|sdk>]","state init defaults to sdk in Git roots and compat in non-Git roots for document-only archive; explicit sdk remains available but SDK Archive requires Git.","restore <change-name> --confirmed (recover a copied SDK Run; older states without a checkpoint restart at Open)","get <change-name> <field> [<field> ...]","set <change-name> <field> <value> [<field> <value> ...]","propose-design <change-name> --proposal <text> (SDK full workflow)","revise-design <change-name> --expected-revision <number> (SDK full workflow)","decide-design <change-name> --proposal-hash <sha256> --choice <approved|rejected> (SDK)","complete-design <change-name> --design-doc <repo-relative-ref> [--approval-hash <sha256>]","propose-build <change-name> --file <json> [--confirmed] (SDK full; --confirmed only for choices already explicitly approved)","decide-build <change-name> --proposal-hash <sha256> --choice <approved|rejected>","submit-plan <change-name> --plan <repo-relative-ref> [--pause]","revise-plan <change-name> --expected-revision <number> (SDK full workflow)","continue-build <change-name> --expected-revision <number> (SDK; resume a stopped failed Builder with preserved work)","continue-work <change-name> --expected-revision <number> (SDK; continue a settled failed Skill from preserved work)","continue-plan <change-name> --proposal-hash <sha256>","complete-build <change-name>","propose-escalation <change-name> --reason <text> (SDK hotfix/tweak)","decide-escalation <change-name> --proposal-hash <sha256> --choice <continue|upgrade> (SDK)","propose-archive <change-name> --summary <text> [--remote <name>] [--pr-base <branch>] [--delivery-path <file>]... (SDK)","decide-archive <change-name> --proposal-hash <sha256> --choice <local|push|pr|reverify|later> (SDK)","reopen-verification <change-name> --expected-revision <number> (SDK; before Archive execution)","repair-archive <change-name> --expected-revision <number> (SDK; stopped failure with unchanged Archive inputs)","repair-delivery <change-name> --expected-revision <number> [--checks <checks-json-file>] (SDK; repair delivery after Archive)","decide-delivery-repair <change-name> --proposal-hash <hash> --choice <approved|later>","complete-delivery <change-name> --commit <sha> [--pr-url <url>] (SDK)","transition <change-name> <event>","transition <change-name> verify-fail --reason <text> (SDK)","check <change-name> <phase> [--recover] [--details]","scale <change-name>","artifacts <change-name>","record-check <change-name> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","task-checkoff <file> <task-text>","tasks <change-name> [--assign-ids]","task-complete <change-name> <task-id> --expect <revision>","sync-plan <change-name>","checkpoint <change-name> [--file <json>]","delivery <change-name> [--file <json> | --verify]","select <change-name> [--details] | rebind <change-name> | next <change-name> [--details]","current | clear-selection","","Start with current or next <change-name> to inspect workflow guidance.","Advanced writes: init, set, transition, task-checkoff, select, rebind, clear-selection.","Use comet state <command> --help for details. --recover is for cold recovery, not normal progression.","A copied SDK change with a Run checkpoint in comet-state.yaml (or legacy .comet.yaml) resumes at its saved phase. If the checkpoint is absent, state restore requires confirmation and restarts at Open with fresh approvals and checks.","For SDK Design, propose-design records the exact proposal before asking the user; decide-design accepts only its current hash and may return a rejected proposal to Design. complete-design requires the approved hash and records the Design Doc in the same Run.","For SDK Build, propose-build reads build_mode, tdd_mode, review_mode and subagent_dispatch from a project-relative JSON file; optional direct_override is required for full direct execution. Workspace isolation remains the Open decision.","内置 Build 配置提案已拒绝时,修正 JSON 后用 propose-build --file 重提;保留原 claim 和拒绝记录,禁止 --confirmed,须使用新的 proposalHash 再执行 decide-build。未回传或非配置执行任务仍须核对原执行器。","decide-build resolves only the current proposal. Rejecting it returns to configuration; approving it stores the choices and advances to planning.","submit-plan validates the plan and its tasks.md authority before recording both the Action and evidence in the SDK Run. --pause requires an explicit continue-plan decision before execution.","continue-plan accepts only the current plan-ready proposal and rejects changes to the approved plan or tasks.","After source or plan changes, use the revision-bound revise-design or revise-plan command returned by recovery guidance; old approvals and accepted evidence cannot authorize changed content.","complete-build accepts finished full-workflow tasks and actual platform check reports through --checks before scheduling Verify.","For SDK hotfix/tweak, propose-escalation records why full Design is needed; decide-escalation applies only the current user choice. Upgrading continues the same Run and workspace through full Design.","For SDK Archive, propose-archive binds the current branch and verified change to a user decision; decide-archive accepts only its current proposal hash. A local, push, or PR choice is required before the Archive Guard can perform filesystem archiving.","Repeat --delivery-path for a complete explicit file list when this change includes pre-existing work. The original Archive proposal includes those paths for user approval. Without it, pre-existing dirty paths stay outside automatic delivery selection.","SDK 归档后,修复与归档可分成连续单父提交;从已批准 baseCommit 到交付 HEAD 的每个提交只能包含已验证实现和本次归档产物。complete-delivery 核对整个范围、最终内容和已批准的远端/PR;不执行 commit、push、建 PR 或改写历史。","For compat Design, complete-design registers the reference, refreshes handoff, and applies the guard; interrupted retries retain completed work.","Use data.artifactRefs for state references and task-authority markers; absolute paths are for file operations."],guard:["comet guard <change-name> <open|design|build|verify|archive> [--apply]","SDK-owned full Design: comet guard <change-name> design --design-doc <repo-relative-ref> [--apply --approval-hash <sha256>]","SDK Design preview reads the current proposal, handoff and document without advancing the Run; apply requires the matching user approval hash.","SDK-owned Build: comet guard <change-name> build [--apply --checks <checks-json-file> --session <builder-execution-ref>]","SDK Build preview is read-only; apply validates the actual platform reports and completed tasks before Verify. It does not infer or execute commands.","SDK-owned Verify: comet guard <change-name> verify --report <repo-relative-ref> [--apply --checks <checks-json-file>]","--session records the actual Builder session. Preserve any selected independent review and report the actual verification results.","SDK Verify preview checks the report and pending Run without advancing it; apply submits the report and actual platform checks before Archive. Failed or missing reports do not advance the Run.","SDK-owned Archive: comet guard <change-name> archive [--apply]","SDK Archive preview checks the approved delivery and current Verify evidence; apply runs preflight and OpenSpec Archive once. Commit, push, and PR delivery remain a separate pending SDK Action.","Compat Guard validates phase requirements; --apply advances the phase after all checks pass.","Compat Guard reads the latest Agent check report for this phase and Run; it never executes a detected build.","Preview does not advance the phase. Apply requires the current tasks, user approvals and accepted reports.","Repeated previews preserve the Run and reports. The Agent assesses whether changes require further checks.","Do not poll guard for status. Use comet state next <change-name> for guidance.","On failure follow the reported next action; do not blindly retry side-effecting checks.","","Examples:"," comet guard demo build --apply --json"," comet state next demo --json"],handoff:["comet handoff <change-name> design --write [--full]","References the original source files; --full explicitly generates one readable Markdown view without changing approvals."],archive:["comet archive <change-name> [--dry-run|--recover]","--recover reconciles one moved SDK Archive after the original executor has stopped; it never runs OpenSpec Archive again.","If interrupted specification synchronization has no original result receipt, review recoveryApproval.changes with the user, then use --recover --confirmed --proposal-hash <current-hash>. Changed outputs invalidate that decision; do not self-confirm."],validate:["comet classic validate <change-name>"],workspace:["comet classic workspace prepare <change-name> --isolation <current|branch|worktree> [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]","comet classic workspace resolve <change-name>"]},s={current:["comet state current","Reports the selected Classic change. Does not advance the phase."],next:["comet state next <change-name> [--details] [--continue]","Reports the next workflow action. --continue executes only recorded SDK commands and authorized internal steps, stopping for Agent work, user decisions, failures or unresolved executions.","SDK JSON includes recovery paths, configuration, compact task state and current Run handles. --details expands tasks, checkpoint content and full Run history."],select:["comet state select <change-name> [--details]","Writes the current change selection used by workflow routing.","SDK JSON includes recovery paths, configuration, compact task state and current Run handles. --details expands tasks, checkpoint content and full Run history."],rebind:["comet state rebind <change-name>","Updates the change branch binding to the current Git branch after validation."],"clear-selection":["comet state clear-selection","Clears the current change selection; does not delete change artifacts."],init:["comet state init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","Creates Classic workflow state. Follow the Open workflow for required user decisions."],scale:["comet state scale <change-name>","Reports a verification recommendation without changing verify_mode.","JSON: data.recommendation, data.selected and data.metrics. Scale is not a risk assessment.","Preserve an existing selection; record a new decision explicitly with state set when needed."],artifacts:["comet state artifacts <change-name>","Inspects the OpenSpec apply dependency closure, including dependencies of already-complete artifacts.","JSON: data.source, required, skipped, designRequired, files and problems. This does not execute implementation or verification.","Optional design is omitted only when the active schema excludes it from the required closure.","Skipped specs require explicit skip_specs: true, upstream support and no conflicting spec files.","Compat changes without .openspec.yaml retain the existing Classic artifact requirements."],"task-checkoff":["comet state task-checkoff <file> <task-text>","Checks that exactly one matching task is already checked. Does not write the task file or execute the task."],tasks:["comet state tasks <change-name> [--assign-ids]","Reads tasks.md as the task completion authority. Fenced examples are excluded.","--assign-ids persists IDs for legacy/new tasks in Open, Design or Build; existing IDs remain unchanged.","Assign IDs before generating the design handoff and plan. ID assignment changes task requirements.","JSON: data.authority, data.revision, data.needsIds, data.tasks and data.progress.","Each task has id, text, completed and line. Never use line/order as task identity.","Example: comet state tasks demo --assign-ids --json"],"task-complete":["comet state task-complete <change-name> <task-id> --expect <revision>","Records accepted task completion during Build; does not execute or independently verify work.","Use the revision returned by state tasks. Changed requirements reject the write; refresh and reassess the task.","Writes tasks.md under the state lock and synchronizes explicitly ID-mapped legacy plan checkboxes. Retries repair interrupted projection writes.","Reconcile code, checks and review evidence before recording completion; unchecked does not mean unimplemented.","Unmapped legacy items are preserved and reported as mapping-required; never match tasks by position or wording."],"sync-plan":["comet state sync-plan <change-name>","Synchronizes legacy plan checkboxes from tasks.md by explicit comet-task IDs; does not execute or accept work.","Rejects missing or unknown plan IDs. Reconcile extra requirements into tasks.md before mapping.","New plans should reference task IDs without a second completion checklist."],checkpoint:["comet state checkpoint <change-name> [--file <json>]","Reads a structured coordination checkpoint, or records an explicitly bounded work package during Build.","Input: taskIds, revision, stage, sessionId, evidence, unresolved, reviewRounds.","Include schemaVersion: 1. JSON state is .comet/coordination.json, separate from the Engine checkpoint.","Stages: implementing|task-review|checkoff|done|blocked. Evidence is a coordination record, not automatic acceptance.","Runtime checks task IDs and revision and renders subagent-progress.md. Do not maintain its projection manually."],delivery:["comet state delivery <change-name> [--file <json> | --verify]","Reads delivery authorization and observed progress, or records the user-authorized local|push|pr action.","Input: action, targetBranch, optional remote, commit and prUrl. Recording never performs remote writes.","First authorization requires Archive with passing verification before archival. Missing legacy authorization is never inferred.","Resume only authorized unfinished steps; supplied commit or PR text alone does not prove delivery.","compat 的 --verify 只做有界远端/PR 读取。SDK 的 --verify 使用当前 HEAD 转交 complete-delivery 校验并结束已批准的交付;已完成 Run 只核对历史回执和原提交对象,不将后续 HEAD、工作区或远端变化视为旧交付失败;普通读取不访问网络。","SDK 的 --file 仅接受与已批准 action、targetBranch、remote 一致的实际 commit 和可选 prUrl,不创建或覆盖授权。PR 首次交付使用 complete-delivery --commit <sha> --pr-url <url>,或 --file 提交完整记录。"],get:["comet state get <change-name> <field> [<field> ...]","Reads the requested fields from one state snapshot. JSON: data.change and data.fields (string values).","One field preserves the bare stdout value; multiple fields print field=value lines in request order.",`Fields: ${[...Gn,...ba].join(", ")}`,"Example: comet state get demo phase --json","Example: comet state get demo phase workflow build_mode tdd_mode review_mode --json"],set:["comet state set <change-name> <field> <value> [<field> <value> ...]","Advanced: validates all fields, then commits one atomic state update and reconciles Runtime state.","Invalid values or duplicate fields reject the whole update. Do not bypass workflow confirmations.","JSON: data.change and data.updated contain the committed field values.","Writable fields (enum values shown where applicable):",...[...tI].map(l=>` ${l}${Zw[l]?`: ${Zw[l].join("|")}`:l==="language"?": en|zh-CN":""}`),"Other Runtime-owned fields cannot be set manually. Artifact paths must stay within the project.","Example: comet state set demo verify_mode full","Example: comet state set demo build_mode executing-plans tdd_mode direct review_mode standard --json"],check:["comet state check <change-name> <open|design|build|verify|archive> [--recover] [--details]","Checks phase entry requirements; this is not a build/test execution command.","--recover is for cold recovery after context loss, not normal phase progression.","Recovery reads the original business state, reports and approvals; it does not replay commands or recover processes.","It preserves completed work. The Agent checks current implementation and acceptance, runs necessary checks with platform tools, and submits the actual results.","JSON entry data includes layout, configuration, configurationReadiness, nextAction, compact taskState, planMapping and checks.","--recover includes checkpoint references; --details expands tasks, checkpoint content and full SDK Run history.","Reconcile existing implementation and acceptance before dispatching work; unchecked tasks are not proof of missing implementation.","Read fresh state after changing configuration or advancing phases; do not reuse an earlier entry snapshot.","SDK entry, proposal, decision and completion results include nextAction from that Run revision, with Action, evidence or decision handles. User approval and fresh validation are still required for subsequent writes.","","Examples:"," comet state check demo build --json"," comet state check demo build --recover --json"],"revise-design":["comet state revise-design <change-name> --expected-revision <number>","Reopens SDK full Design from Design, Build, Verify, or Archive before side effects; retains implementation, configuration and decision history. Reconcile running or unknown work first.","Use the current Run revision from state next or state check --recover. A stale revision is rejected.","Then propose-design with the revised design and any agreed Spec Patch, obtain a new explicit user decision, and decide-design with the new proposal hash.","Revision does not approve the new design. Old approval hashes do not authorize changed requirements."],"reopen-verification":["comet state reopen-verification <change-name> --expected-revision <number>","保留当前修改和审计历史,取消未执行的归档或验收工作并重开 Verify;通过后必须重新批准 Archive。","仅支持尚未执行归档、活动目录仍存在且没有 running/unknown Action 的内置 SDK Run。旧 revision 不生效。"],"continue-build":["comet state continue-build <change-name> --expected-revision <number>","Resume a stopped failed Builder, or return Verify or pre-execution Archive to Build on the same SDK Run. Preserve partial work and task completion; invalidate verification and Archive authorization.","Changed full requirements still require revise-design; changed hotfix/tweak scope requires propose-escalation and a new scope decision. Never replay unknown executions."],"continue-work":["comet state continue-work <change-name> --expected-revision <number>","Create successor work for the original failed Skill on the same Run. Preserve completed stages, decisions, partial artifacts and the original failure receipt. Reject running, unknown, stale, or cancelled work."],"repair-archive":["comet state repair-archive <change-name> --expected-revision <number>","Verify that the failed Archive left its original inputs and specifications unchanged and created no archive directory, then reopen Open on the same Run. Correct the inputs and obtain fresh approval and verification. Unknown execution results must be reconciled first."],"repair-delivery":["comet state repair-delivery <change-name> --expected-revision <number> [--checks <checks-json-file>]","归档已完成、交付尚未完成时,在同一 SDK Run 补充检查输出声明并重新检查。保留原归档、业务批准和执行历史,不重放 OpenSpec。","v2:由 Agent 平台完成必要检查,通过 --checks 提交与 Build/Verify 相同格式的报告;保留原批准的路径范围,Runtime 不重跑命令。","旧 v1:在 .comet/check-policy.json 为原 Verify 命令声明 outputs,只排除原批准基线未追踪的生成物。移除这些生成物后沿原命令检查,保持原实现和归档。","随后沿 state next 的原检查请求推进,展示新的交付范围,并取得当前 proposalHash 的明确批准。旧批准不能直接完成本次修复后的交付。"],"decide-delivery-repair":["comet state decide-delivery-repair <change-name> --proposal-hash <hash> --choice <approved|later>","核对补声明的输出、原检查结果和保留的归档,再确认当前交付范围。approved 只恢复当前已核验范围的交付;later 保持等待,不提交或重做归档。"],"revise-plan":["comet state revise-plan <change-name> --expected-revision <number>","Reopens SDK full planning after accepted plan content changes, retaining completed implementation and prior evidence history.","Use the current Run revision from state next or state check --recover. A stale revision is rejected.","Then submit-plan with the revised plan and current task mapping. Use --pause when the user requested a planning pause; continue only with the new plan-ready proposal hash.","Revision does not accept the new plan or bypass task authority, design approval, or Runtime checks.","Changed requirements or task scope require revise-design and a fresh Design approval before resubmitting the plan."],restore:["comet state restore <change-name> --confirmed","Only for a copied SDK change whose state file survived but local Run history did not.","Confirm the original execution process stopped before using this command. A portable checkpoint restores the saved phase and decisions; an older state without one restarts at Open and requires fresh evidence and approvals.","Unknown external actions are not replayed. A branch binding mismatch or archived change is rejected."],"record-check":["comet state record-check <change> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","Records the actual Agent platform result for Compat; does not execute the command.","The latest report belongs to this Run and phase. A failed report cannot advance the phase or borrow an earlier success.","SDK Build/Verify accepts a checks JSON report through --checks; use the command returned by the current Run.","--cwd: relative to project root, defaults to .; must stay inside the project.","","Examples:",' comet state record-check demo verify --command "external test run" --exit-code 1'],transition:["comet state transition <change-name> <event>","SDK: comet state transition <change-name> verify-fail --reason <text>",`Events: ${fA.join(", ")}`,"Advanced: applies a state-machine event and writes workflow state. Required confirmations still apply.","This is not a substitute for the workflow Skill or phase guard. Use state next for the next action."]},o=n.find(l=>!l.startsWith("-")),c=e==="state"&&o&&s[o]||i[e];return c?`Usage: ${c.join(`
|
|
284
|
+
`)}
|
|
285
|
+
${kU}Command placeholders must be replaced with actual values.
|
|
286
|
+
`:void 0}function nI(e,t){let r=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)?h:{},n=r(e),i=r(n.entry),s=r(n.run??i.run??(typeof n.runId=="string"?n:void 0)),o=r(n.state??i.state??n),c=r(n.preparation??n.workspace??i.workspace),l=r(n.continuation??i.continuation??n.nextAction??i.nextAction),f=typeof c.projectRoot=="string"&&c.projectRoot!=="."?c.projectRoot:typeof l.cwd=="string"?l.cwd:typeof n.projectRoot=="string"?n.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,a=o.stateVersion??o.state_version,d=o.status??s.status,{current:p,...u}=l,m=p===void 0?l:{...u,currentRef:n.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof o.phase=="string"?o.phase:null,status:typeof d=="string"?d:null,stateVersion:typeof a=="number"?a:null,workspace:{cwd:f},continuation:Object.keys(l).length?{...m,cwd:f}:null,...Object.keys(s).length?{run:{id:typeof s.id=="string"?s.id:typeof s.runId=="string"?s.runId:null,revision:typeof s.revision=="number"?s.revision:null,status:typeof s.status=="string"?s.status:null}}:{}}}import{randomUUID as bU}from"node:crypto";import{performance as iI}from"node:perf_hooks";var RU=7*864e5,SU=1e4;async function CU(e,t){let r=co(await Hd(e,!0));try{r.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
287
|
+
CREATE TABLE IF NOT EXISTS samples (
|
|
288
|
+
id TEXT PRIMARY KEY, workflow TEXT NOT NULL, kind TEXT NOT NULL, command TEXT NOT NULL,
|
|
289
|
+
occurredAt TEXT NOT NULL, durationMs REAL NOT NULL, exitCode INTEGER NOT NULL,
|
|
290
|
+
gitCommands INTEGER NOT NULL, gitDurationMs REAL NOT NULL);
|
|
291
|
+
CREATE INDEX IF NOT EXISTS samples_time ON samples(occurredAt);
|
|
292
|
+
BEGIN IMMEDIATE;`),r.prepare("DELETE FROM samples WHERE occurredAt < ?").run(new Date(Date.now()-RU).toISOString()),r.prepare("INSERT INTO samples VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(bU(),t.workflow,t.kind,t.command,t.occurredAt,t.durationMs,t.exitCode,t.gitCommands,t.gitDurationMs),r.prepare("DELETE FROM samples WHERE id IN (SELECT id FROM samples ORDER BY occurredAt DESC, rowid DESC LIMIT -1 OFFSET ?)").run(SU),r.exec("COMMIT")}finally{r.close()}}async function sI(e,t){let r=iI.now(),n,i,s=!1,o=1,c=!0,{metrics:l}=await m_({projectRoot:e.projectRoot,workflow:e.workflow,kind:e.kind??"command",name:e.traceName??e.command,status:()=>{try{o=n?e.exitCode?.(n)??n.exitCode??1:e.errorExitCode?.(i)??1}catch{return c=!1,"unknown"}return o===0?"succeeded":"failed"}},()=>Kb(async()=>{try{n=await t()}catch(a){s=!0,i=a}})),f=Math.max(0,iI.now()-r);try{if(!c)throw new Error("Runtime result classification unavailable");await CU(await e.projectRoot(),{workflow:e.workflow,kind:e.kind??"command",command:e.command,occurredAt:new Date().toISOString(),durationMs:f,exitCode:o,...l})}catch{}if(s)throw i;return n}function EU(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e,exitCode:t.exitCode,agent:nI(t.data),...t.data===void 0?{}:{data:t.data},...t.envelope===void 0?{}:{summary:t.envelope.summary,...t.envelope.next===void 0?{}:{next:t.envelope.next},...t.envelope.user_message===void 0?{}:{user_message:t.envelope.user_message}},...t.stdout===void 0?{}:{stdout:t.stdout},...t.stderr===void 0?{}:{stderr:t.stderr}})+`
|
|
293
|
+
`,...t.envelope===void 0?{}:{envelope:t.envelope}}}async function AU(e,t,r,n={}){let i=r.indexOf("--"),s=f=>i<0||f<i,o=r.some((f,a)=>s(a)&&f==="--json"),c=r.filter((f,a)=>!s(a)||f!=="--json"),l;try{let f=rI(e,c),a=()=>t(c,{json:o,invocationCwd:n.invocationCwd??process.cwd(),...n.projectRoot?{projectRoot:n.projectRoot}:{}});l=f?{exitCode:0,stdout:f}:e==="hook-guard"?await a():await zb(()=>sI({projectRoot:()=>n.projectRoot??ut(n.invocationCwd??process.cwd()),workflow:"classic",command:e,errorExitCode:d=>d instanceof Ti?1:70},a))}catch(f){l={exitCode:f instanceof Ti?1:70,stderr:f instanceof Error?f.message:String(f),data:{issues:[Kw(f)]}}}return o?EU(e,l):l}async function oI(e,t,r=process.argv.slice(2)){let n=await AU(e,t,r);return n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr+(n.stderr.endsWith(`
|
|
294
|
+
`)?"":`
|
|
295
|
+
`)),n.exitCode}process.exitCode=await oI("hook-guard",eI);
|