comet-dsh-plugin 0.0.0-stage → 0.5.3
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 +57 -4
- package/rules/comet-workflow-guard.md +63 -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 +294 -0
- package/skills/comet/scripts/comet-hook-router-guard.mjs +628 -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 +571 -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 +464 -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,294 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var sI=Object.create;var rf=Object.defineProperty;var oI=Object.getOwnPropertyDescriptor;var aI=Object.getOwnPropertyNames;var cI=Object.getPrototypeOf,lI=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}},uI=(e,t)=>{for(var r in t)rf(e,r,{get:t[r],enumerable:!0})},dI=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of aI(t))!lI.call(e,i)&&i!==r&&rf(e,i,{get:()=>t[i],enumerable:!(n=oI(t,i))||n.enumerable});return e};var vt=(e,t,r)=>(r=e!=null?sI(cI(e)):{},dI(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 ty from"node:path";import{fileURLToPath as fI}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 hI(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 gI(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!ty.isAbsolute(r.trim())))return r.trim()}}function wI(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 yI(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 vI(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function kI(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 bI(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return kI(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 Io(e){return[...new Set(e.flatMap(t=>{let r=t.trim();if(!r)return[];if(/^file:/iu.test(r))try{return[fI(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 ry)bi(e,t[r]);for(let r of ny)bi(e,t[r])}}function RI(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 ry)bi(r,i[s]);for(let s of ny)bi(r,i[s]);for(let s of iy){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 iy)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 sy(e,t){if(t?.trim()){let u=Io([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=Io(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=hI(r),i=bI(r),s=n&&jc(n)==="applypatch"&&ys(i)&&typeof i.command=="string"?{...i,patch:i.command}:i,o=RI(r,s),c=Io(o),l=Dc(s),f=gI(r),a=f?ty.resolve(f):void 0,d=f!==a?f:void 0,p=wI(r);if(yI(r)==="beforeagentstart"){let u=vI(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&&pI.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&&mI.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 pI,mI,af,ry,ny,iy,cf=Le(()=>{"use strict";nf();of();pI=new Set(["applypatch","create","createfile","deletefile","edit","editfile","multiedit","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),mI=new Set(["glob","grep","listfiles","read","readfile","search","view"]),af=["file_path","filePath","path","target_file","targetFile"],ry=["file_paths","filePaths","paths","files","targets"],ny=["operations","edits"],iy=["patch","diff","patchText","patch_text","changes"]});import{AsyncLocalStorage as SI}from"node:async_hooks";function Lc(){let e=lf.getStore();return e?.active?e:null}function oy(){Lc()?.entries.clear()}async function ay(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 cy(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=cy(`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=cy(`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 SI});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 Oo=Le(()=>{"use strict"});import{constants as Tn,promises as Vt}from"fs";import{createHash as OI}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 TI(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 TI(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 kt("not-regular-file",`${n} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new kt("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 kt("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 kt("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 k=t+1-u,{bytesRead:b}=await l.read(m,0,Math.min(m.length,k),null);if(b===0)break;if(u+=b,u>t)throw new kt("too-large",`${n} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,g,w]=await Promise.all([l.stat({bigint:i}),Vt.lstat(e,{bigint:i}),Vt.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||w!==o||!Nn(s,h)||!Nn(s,g))throw new kt("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:$n(h)}),{bytes:Buffer.concat(p,u),stat:h,realPath:w}}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 kt("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 kt("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 kt("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:a,identity:$n(l)}),await t.hooks?.afterOpen?.();let d=OI(t.algorithm??"sha256"),p=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:g}=await c.read(p,0,p.length,null);if(g===0)break;d.update(p.subarray(0,g))}await t.hooks?.beforeFinalCheck?.();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 kt("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:$n(u)}),{digest:d.digest("hex"),stat:u,realPath:h}}finally{await c.close()}}var kt,Ri=Le(()=>{"use strict";Oo();kt=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||!$I.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 $I,mf,my=Le(()=>{"use strict";$I=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),mf=[50,100,200]});import{randomUUID as hy}from"crypto";import{constants as jI,promises as Ve}from"fs";import Je 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,jI.COPYFILE_EXCL),{linked:!1}}function Ci(e,t){let r=Je.relative(e,t);return r===""||!Je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Je.sep}`)}function Bc(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function DI(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 bt(e){for(let t of e){let r=await Ve.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!DI(t,r)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function qI(e,t,r){let[n,i]=await Promise.all([Ve.lstat(e),Ve.realpath(e),bt(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=Je.resolve(e),i=Je.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=Je.relative(n,i).split(Je.sep).filter(Boolean),c=n;for(let l of o){await bt(s),c=Je.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 bt(s),s}async function kf(e,t){let r=Je.resolve(e),n=Je.resolve(t);if(!Ci(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await Vc(r)],s=Je.relative(r,n).split(Je.sep).filter(Boolean),o=r;for(let c of s){o=Je.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 bt(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 LI(e,t,r){let n=Je.dirname(e),i=await wy(r.containedRoot,n),s=Je.join(n,`.${Je.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 bt(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 qI(s,l,i),await r.beforeCommit?.(),await bt(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 bt(i),await Ve.rm(s,{force:!0})}catch{}throw f}}async function Te(e,t,r){await LI(e,t,r)}async function yy(e,t,r){let n=await kf(r.containedRoot,Je.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await wy(r.containedRoot,Je.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=Je.join(Je.dirname(t),`.${Je.basename(t)}.${hy()}.tmp`);try{await bt(n),await bt(i),await Hc(e,o),await r.beforeCommit?.(),await bt(n),await bt(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(Je.dirname(t)),await bt(n),await bt(i)}catch(c){try{await bt(i),await Ve.unlink(o)}catch{}throw c}}async function zr(e,t){let r=Je.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 bt(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 bt(n),await bf(r),!0}var $t=Le(()=>{"use strict";my();Oo()});var ke=x(mt=>{"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"),ln=Symbol.for("yaml.node.type"),WI=e=>!!e&&typeof e=="object"&&e[ln]===Rf,MI=e=>!!e&&typeof e=="object"&&e[ln]===vy,FI=e=>!!e&&typeof e=="object"&&e[ln]===Uc,HI=e=>!!e&&typeof e=="object"&&e[ln]===ky,by=e=>!!e&&typeof e=="object"&&e[ln]===Sf,BI=e=>!!e&&typeof e=="object"&&e[ln]===zc;function Ry(e){if(e&&typeof e=="object")switch(e[ln]){case Uc:case zc:return!0}return!1}function VI(e){if(e&&typeof e=="object")switch(e[ln]){case Rf:case Uc:case Sf:case zc:return!0}return!1}var UI=e=>(by(e)||Ry(e))&&!!e.anchor;mt.ALIAS=Rf;mt.DOC=vy;mt.MAP=Uc;mt.NODE_TYPE=ln;mt.PAIR=ky;mt.SCALAR=Sf;mt.SEQ=zc;mt.hasAnchor=UI;mt.isAlias=WI;mt.isCollection=Ry;mt.isDocument=MI;mt.isMap=FI;mt.isNode=VI;mt.isPair=HI;mt.isScalar=by;mt.isSeq=BI});var To=x(Cf=>{"use strict";var at=ke(),Ut=Symbol("break visit"),Sy=Symbol("skip children"),Kr=Symbol("remove node");function Kc(e,t){let r=Cy(t);at.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(at.isNode(i)||at.isPair(i))return Ay(e,n,i),ks(e,i,r,n);if(typeof i!="symbol"){if(at.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(at.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 Jc(e,t){let r=Cy(t);at.isDocument(e)?await bs(null,e.contents,r,Object.freeze([e]))===Kr&&(e.contents=null):await bs(null,e,r,Object.freeze([]))}Jc.BREAK=Ut;Jc.SKIP=Sy;Jc.REMOVE=Kr;async function bs(e,t,r,n){let i=await Ey(e,t,r,n);if(at.isNode(i)||at.isPair(i))return Ay(e,n,i),bs(e,i,r,n);if(typeof i!="symbol"){if(at.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(at.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(at.isMap(t))return r.Map?.(e,t,n);if(at.isSeq(t))return r.Seq?.(e,t,n);if(at.isPair(t))return r.Pair?.(e,t,n);if(at.isScalar(t))return r.Scalar?.(e,t,n);if(at.isAlias(t))return r.Alias?.(e,t,n)}function Ay(e,t,r){let n=t[t.length-1];if(at.isCollection(n))n.items[e]=r;else if(at.isPair(n))e==="key"?n.key=r:n.value=r;else if(at.isDocument(n))n.contents=r;else{let i=at.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Cf.visit=Kc;Cf.visitAsync=Jc});var Ef=x(_y=>{"use strict";var xy=ke(),zI=To(),KI={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},JI=e=>e.replace(/[!,[\]{}]/g,t=>KI[t]),No=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+JI(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={};zI.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
|
+
`)}};No.defaultYaml={explicit:!1,version:"1.2"};No.defaultTags={"!!":"tag:yaml.org,2002:"};_y.Directives=No});var Gc=x($o=>{"use strict";var Iy=ke(),GI=To();function YI(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 GI.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 XI(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}}$o.anchorIsValid=YI;$o.anchorNames=Py;$o.createNodeAnchors=XI;$o.findNewAnchor=Oy});var Af=x(Ty=>{"use strict";function jo(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=jo(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=jo(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=jo(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=jo(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}Ty.applyReviver=jo});var Dn=x($y=>{"use strict";var QI=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||!QI.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 ZI=Af(),jy=ke(),eP=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=eP.toJS(this,"",o);if(typeof i=="function")for(let{count:l,res:f}of o.anchors.values())i(f,l);return typeof s=="function"?ZI.applyReviver(s,{"":c},"",c):c}};Dy.NodeBase=xf});var Do=x(qy=>{"use strict";var tP=Gc(),rP=To(),Rs=ke(),nP=Yc(),iP=Dn(),_f=class extends nP.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=[],rP.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||(iP.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(tP.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 sP=ke(),oP=Yc(),aP=Dn(),cP=e=>!e||typeof e!="function"&&typeof e!="object",qn=class extends oP.NodeBase{constructor(t){super(sP.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:aP.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=cP});var qo=x(Wy=>{"use strict";var lP=Do(),Ei=ke(),Ly=tt(),uP="tag:yaml.org,2002:";function dP(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 fP(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 lP.Alias(l.anchor);l={anchor:null,node:null},c.set(e,l)}t?.startsWith("!!")&&(t=uP+t.slice(2));let f=dP(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=fP});var Zc=x(Qc=>{"use strict";var pP=qo(),Jr=ke(),mP=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 pP.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 mP.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=>Jr.isNode(n)||Jr.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(Jr.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(Jr.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&&Jr.isScalar(s)?s.value:s:Jr.isCollection(s)?s.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Jr.isPair(r))return!1;let n=r.value;return n==null||t&&Jr.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 Jr.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(Jr.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 Lo=x(el=>{"use strict";var hP=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Tf(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var gP=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?Tf(r,t):r.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+Tf(r,t):(e.endsWith(" ")?"":" ")+r;el.indentComment=Tf;el.lineComment=gP;el.stringifyComment=hP});var Hy=x(Wo=>{"use strict";var wP="flow",Nf="block",tl="quoted";function yP(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 S=e[h+1];S&&S!==" "&&S!==`
|
|
11
|
+
`&&S!==" "&&(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 S=h>w+1?h-2:g-1;if(a[S])return e;f.push(S),a[S]=!0,d=S+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 S=f[b],E=f[b+1]||e.length;S===0?k=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(r===tl&&a[S]&&(k+=`${e[S]}\\`),k+=`
|
|
13
|
+
${t}${e.slice(S+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}Wo.FOLD_BLOCK=Nf;Wo.FOLD_FLOW=wP;Wo.FOLD_QUOTED=tl;Wo.foldFlowLines=yP});var Fo=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 vP(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 Mo(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 Mo(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=Mo;else{let i=e.includes('"'),s=e.includes("'");i&&!s?n=$f:s&&!i?n=Mo:n=r?$f:Mo}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:!vP(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 S=(h?f?"2":"1":"")+d;if(e&&(S+=" "+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`>${S}
|
|
31
|
+
${f}${D}`}return r=r.replace(/\n+/g,`$&${f}`),`|${S}
|
|
32
|
+
${f}${k}${r}${u}`}function kP(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 bP(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 Mo(o.value,t);case _r.Scalar.QUOTE_SINGLE:return $f(o.value,t);case _r.Scalar.PLAIN:return kP(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=bP});var Ho=x(Df=>{"use strict";var RP=Gc(),Wn=ke(),SP=Lo(),CP=Fo();function EP(e,t){let r=Object.assign({blockQuote:!0,commentString:SP.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 AP(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 xP(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],s=(Wn.isScalar(e)||Wn.isCollection(e))&&e.anchor;s&&RP.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 _P(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=AP(t.doc.schema.tags,s));let o=xP(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)?CP.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=EP;Df.stringify=_P});var Ky=x(zy=>{"use strict";var un=ke(),Vy=tt(),Uy=Ho(),Bo=Lo();function IP({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=un.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(un.isCollection(e)||!un.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||un.isCollection(e)||(un.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+=Bo.lineComment(g,r.indent,f(p)):h&&i&&i(),g;m&&(p=null),u?(p&&(g+=Bo.lineComment(g,r.indent,f(p))),g=`? ${g}
|
|
38
|
+
${c}:`):(g=`${g}:`,p&&(g+=Bo.lineComment(g,r.indent,f(p))));let w,k,b;un.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&&un.isScalar(t)&&(r.indentAtStart=g.length+1),h=!1,!a&&l.length>=2&&!r.inFlow&&!u&&un.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let S=!1,E=Uy.stringify(t,r,()=>S=!0,()=>h=!0),O=" ";if(p||w||k){if(O=w?`
|
|
39
|
+
`:"",k){let z=f(k);O+=`
|
|
40
|
+
${Bo.indentComment(z,r.indent)}`}E===""&&!r.inFlow?O===`
|
|
41
|
+
`&&b&&(O=`
|
|
42
|
+
|
|
43
|
+
`):O+=`
|
|
44
|
+
${r.indent}`}else if(!u&&un.isCollection(t)){let z=E[0],D=E.indexOf(`
|
|
45
|
+
`),J=D!==-1,G=r.inFlow??t.flow??t.items.length===0;if(J||!G){let te=!1;if(J&&(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?S&&n&&n():b&&!S?g+=Bo.lineComment(g,r.indent,f(b)):h&&i&&i(),g}zy.stringifyPair=IP});var Lf=x(qf=>{"use strict";var Jy=Nc("process");function PP(e,...t){e==="debug"&&console.log(...t)}function OP(e,t){(e==="debug"||e==="warn")&&(typeof Jy.emitWarning=="function"?Jy.emitWarning(t):console.warn(t))}qf.debug=PP;qf.warn=OP});var ll=x(cl=>{"use strict";var al=ke(),Gy=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 Gy.Scalar(Symbol(sl)),{addToJSMap:Yy}),stringify:()=>sl},TP=(e,t)=>(ol.identify(t)||al.isScalar(t)&&(!t.type||t.type===Gy.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=TP;cl.merge=ol});var Ff=x(ev=>{"use strict";var NP=Lf(),Qy=ll(),$P=Ho(),Zy=ke(),Mf=Dn();function jP(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=DP(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 DP(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Zy.isNode(e)&&r?.doc){let n=$P.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)+'..."'),NP.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=jP});var Mn=x(Hf=>{"use strict";var tv=qo(),qP=Ky(),LP=Ff(),ul=ke();function WP(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 LP.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?qP.stringifyPair(this,t,r,n):JSON.stringify(this)}};Hf.Pair=dl;Hf.createPair=WP});var Bf=x(nv=>{"use strict";var Ai=ke(),rv=Ho(),fl=Lo();function MP(e,t,r){return(t.inFlow??e.flow?HP:FP)(e,t,r)}function FP({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 HP({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=MP});var Hn=x(Uf=>{"use strict";var BP=Bf(),VP=Ff(),UP=Zc(),Fn=ke(),ml=Mn(),zP=tt();function Vo(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 UP.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=Vo(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Fn.isScalar(i.value)&&zP.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=Vo(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=Vo(this.items,t)?.value;return(!r&&Fn.isScalar(i)?i.value:i)??void 0}has(t){return!!Vo(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)VP.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})),BP.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};Uf.YAMLMap=Vf;Uf.findPair=Vo});var Cs=x(sv=>{"use strict";var KP=ke(),iv=Hn(),JP={collection:"map",default:!0,nodeClass:iv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return KP.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>iv.YAMLMap.from(e,t,r)};sv.map=JP});var Bn=x(ov=>{"use strict";var GP=qo(),YP=Bf(),XP=Zc(),gl=ke(),QP=tt(),ZP=Dn(),zf=class extends XP.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)&&QP.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(ZP.toJS(s,String(i++),r));return n}toString(t,r,n){return t?YP.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(GP.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 eO=ke(),av=Bn(),tO={collection:"seq",default:!0,nodeClass:av.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return eO.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>av.YAMLSeq.from(e,t,r)};cv.seq=tO});var Uo=x(lv=>{"use strict";var rO=Fo(),nO={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),rO.stringifyString(e,t,r,n)}};lv.string=nO});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 iO=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 iO.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 sO({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=sO});var Gf=x(yl=>{"use strict";var oO=tt(),Jf=As(),aO={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:Jf.stringifyNumber},cO={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():Jf.stringifyNumber(e)}},lO={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 oO.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Jf.stringifyNumber};yl.float=lO;yl.floatExp=cO;yl.floatNaN=aO});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 uO={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")},dO={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},fO={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=dO;kl.intHex=fO;kl.intOct=uO});var vv=x(yv=>{"use strict";var pO=Cs(),mO=wl(),hO=Es(),gO=Uo(),wO=Kf(),Qf=Gf(),Zf=Xf(),yO=[pO.map,hO.seq,gO.string,mO.nullTag,wO.boolTag,Zf.intOct,Zf.int,Zf.intHex,Qf.floatNaN,Qf.floatExp,Qf.float];yv.schema=yO});var Rv=x(bv=>{"use strict";var vO=tt(),kO=Cs(),bO=Es();function kv(e){return typeof e=="bigint"||Number.isInteger(e)}var bl=({value:e})=>JSON.stringify(e),RO=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:bl},{identify:e=>e==null,createNode:()=>new vO.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}],SO={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},CO=[kO.map,bO.seq].concat(RO,SO);bv.schema=CO});var tp=x(Sv=>{"use strict";var zo=Nc("buffer"),ep=tt(),EO=Fo(),AO={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof zo.Buffer=="function")return zo.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 zo.Buffer=="function")c=o instanceof zo.Buffer?o.toString("base64"):zo.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 EO.stringifyString({comment:e,type:t,value:c},n,i,s)}};Sv.binary=AO});var Cl=x(Sl=>{"use strict";var Rl=ke(),rp=Mn(),xO=tt(),_O=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 xO.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 _O.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 IO={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Cv,createNode:Ev};Sl.createPairs=Ev;Sl.pairs=IO;Sl.resolvePairs=Cv});var sp=x(ip=>{"use strict";var Av=ke(),np=Dn(),Ko=Hn(),PO=Bn(),xv=Cl(),xi=class e extends PO.YAMLSeq{constructor(){super(),this.add=Ko.YAMLMap.prototype.add.bind(this),this.delete=Ko.YAMLMap.prototype.delete.bind(this),this.get=Ko.YAMLMap.prototype.get.bind(this),this.has=Ko.YAMLMap.prototype.has.bind(this),this.set=Ko.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 OO={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=OO});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 TO=tt(),ap=As(),NO={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},$O={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)}},jO={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 TO.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=jO;El.floatExp=$O;El.floatNaN=NO});var jv=x(Go=>{"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 DO={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")},qO={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")},LO={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},WO={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")};Go.int=LO;Go.intBin=DO;Go.intHex=WO;Go.intOct=qO});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 MO={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=MO});var fp=x(Pl=>{"use strict";var FO=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 FO.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 HO={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},BO={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=BO;Pl.intTime=HO;Pl.timestamp=qv});var Mv=x(Wv=>{"use strict";var VO=Cs(),UO=wl(),zO=Es(),KO=Uo(),JO=tp(),Lv=Tv(),pp=Nv(),Ol=jv(),GO=ll(),YO=sp(),XO=Cl(),QO=up(),mp=fp(),ZO=[VO.map,zO.seq,KO.string,UO.nullTag,Lv.trueTag,Lv.falseTag,Ol.intBin,Ol.intOct,Ol.int,Ol.intHex,pp.floatNaN,pp.floatExp,pp.float,JO.binary,GO.merge,YO.omap,XO.pairs,QO.set,mp.intTime,mp.floatTime,mp.timestamp];Wv.schema=ZO});var Yv=x(wp=>{"use strict";var Vv=Cs(),e0=wl(),Uv=Es(),t0=Uo(),r0=Kf(),hp=Gf(),gp=Xf(),n0=vv(),i0=Rv(),zv=tp(),Yo=ll(),Kv=sp(),Jv=Cl(),Fv=Mv(),Gv=up(),Tl=fp(),Hv=new Map([["core",n0.schema],["failsafe",[Vv.map,Uv.seq,t0.string]],["json",i0.schema],["yaml11",Fv.schema],["yaml-1.1",Fv.schema]]),Bv={binary:zv.binary,bool:r0.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:Yo.merge,null:e0.nullTag,omap:Kv.omap,pairs:Jv.pairs,seq:Uv.seq,set:Gv.set,timestamp:Tl.timestamp},s0={"tag:yaml.org,2002:binary":zv.binary,"tag:yaml.org,2002:merge":Yo.merge,"tag:yaml.org,2002:omap":Kv.omap,"tag:yaml.org,2002:pairs":Jv.pairs,"tag:yaml.org,2002:set":Gv.set,"tag:yaml.org,2002:timestamp":Tl.timestamp};function o0(e,t,r){let n=Hv.get(t);if(n&&!e)return r&&!n.includes(Yo.merge)?n.concat(Yo.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(Yo.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=s0;wp.getTags=o0});var kp=x(Xv=>{"use strict";var yp=ke(),a0=Cs(),c0=Es(),l0=Uo(),Nl=Yv(),u0=(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:a0.map}),Object.defineProperty(this,yp.SCALAR,{value:l0.string}),Object.defineProperty(this,yp.SEQ,{value:c0.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?u0: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 d0=ke(),bp=Ho(),Xo=Lo();function f0(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(Xo.indentComment(l,""))}let o=!1,c=null;if(e.contents){if(d0.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let a=s(e.contents.commentBefore);r.push(Xo.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+=Xo.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(Xo.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(Xo.indentComment(s(l),"")))}return r.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}Qv.stringifyDocument=f0});var Qo=x(ek=>{"use strict";var p0=Do(),xs=Zc(),cr=ke(),m0=Mn(),h0=Dn(),g0=kp(),w0=Zv(),Rp=Gc(),y0=Af(),v0=qo(),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 p0.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=v0.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 m0.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 g0.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=h0.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"?y0.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 w0.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 ta=x(ea=>{"use strict";var Zo=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Ep=class extends Zo{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Ap=class extends Zo{constructor(t,r,n){super("YAMLWarning",t,r,n)}},k0=(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
|
+
`}};ea.YAMLError=Zo;ea.YAMLParseError=Ep;ea.YAMLWarning=Ap;ea.prettifyError=k0});var ra=x(tk=>{"use strict";function b0(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,S=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 J=D.source.substring(1)||" ";d?d+=p+J:d=J,p="",f=!1;break}case"newline":f?d?d+=D.source:(!S||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`),S&&s(D,"UNEXPECTED_TOKEN",`Unexpected ${D.source} in ${t??"collection"}`),S=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:S,spaceBefore:l,comment:d,hasNewline:u,anchor:g,tag:w,newlineAfterProp:k,end:z,start:E??z}}tk.resolveProps=b0});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 R0=$l();function S0(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&R0.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}nk.flowIndentCheck=S0});var Ip=x(sk=>{"use strict";var ik=ke();function C0(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=C0});var dk=x(uk=>{"use strict";var ok=Mn(),E0=Hn(),ak=ra(),A0=$l(),ck=_p(),x0=Ip(),lk="All mapping items must start at the same column";function _0({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??E0.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||A0.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,x0.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 S=m?e(r,m,b,i):t(r,l,u,null,b,i);r.schema.compat&&ck.flowIndentCheck(n.indent,m,i),l=S.range[2];let E=new ok.Pair(k,S);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 S=new ok.Pair(k);r.options.keepSourceTokens&&(S.srcToken=a),c.items.push(S)}}return f&&f<l&&i(f,"IMPOSSIBLE","Map comment with trailing content"),c.range=[n.offset,l,f??l],c}uk.resolveBlockMap=_0});var pk=x(fk=>{"use strict";var I0=Bn(),P0=ra(),O0=_p();function T0({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??I0.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=P0.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&&O0.flowIndentCheck(n.indent,d,i),l=u.range[2],c.items.push(u)}return c.range=[n.offset,l,f??l],c}fk.resolveBlockSeq=T0});var Is=x(mk=>{"use strict";function N0(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=N0});var yk=x(wk=>{"use strict";var $0=ke(),j0=Mn(),hk=Hn(),D0=Bn(),q0=Is(),gk=ra(),L0=$l(),W0=Ip(),Pp="Block collections are not allowed within flow collections",Op=e=>e&&(e.type==="block-map"||e.type==="block-seq");function M0({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:D0.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:S,value:E}=w,O=gk.resolveProps(k,{flow:c,indicator:"explicit-key-ind",next:b??S?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!S&&!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&&L0.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];$0.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&&!S&&!O.found){let z=E?e(r,E,O,i):t(r,O.end,S,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 J=gk.resolveProps(S??[],{flow:c,indicator:"map-value-ind",next:E,offset:D.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(J.found){if(!o&&!O.found&&r.options.strict){if(S)for(let Z of S){if(Z===J.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<J.found.offset-1024&&i(J.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(J.start,"MISSING_CHAR",`Missing , or : between ${c} items`));let G=E?e(r,E,J,i):J.found?t(r,J.end,S,null,J,i):null;G?Op(E)&&i(G.range,"BLOCK_IN_FLOW",Pp):J.comment&&(D.comment?D.comment+=`
|
|
71
|
+
`+J.comment:D.comment=J.comment);let te=new j0.Pair(D,G);if(r.options.keepSourceTokens&&(te.srcToken=w),o){let Z=f;W0.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=(G??D).range;Z.range=[D.range[0],we[1],we[2]],f.items.push(Z)}d=G?G.range[2]:J.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=q0.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=M0});var kk=x(vk=>{"use strict";var F0=ke(),H0=tt(),B0=Hn(),V0=Bn(),U0=dk(),z0=pk(),K0=yk();function Tp(e,t,r,n,i,s){let o=r.type==="block-map"?U0.resolveBlockMap(e,t,r,n,s):r.type==="block-seq"?z0.resolveBlockSeq(e,t,r,n,s):K0.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 J0(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===B0.YAMLMap.tagName&&c==="map"||o===V0.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=F0.isNode(a)?a:new H0.Scalar(a);return d.range=f.range,d.tag=o,l?.format&&(d.format=l.format),d}vk.composeCollection=J0});var $p=x(bk=>{"use strict";var Np=tt();function G0(e,t,r){let n=t.offset,i=Y0(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?X0(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 S=`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",S),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 Y0({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 X0(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=G0});var Dp=x(Sk=>{"use strict";var jp=tt(),Q0=Is();function Z0(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=eT(s,f);break;case"single-quoted-scalar":c=jp.Scalar.QUOTE_SINGLE,l=tT(s,f);break;case"double-quoted-scalar":c=jp.Scalar.QUOTE_DOUBLE,l=rT(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=Q0.resolveEnd(o,a,t,r);return{value:l,type:c,comment:d.comment,range:[n,a,d.offset]}}function eT(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 tT(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 rT(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}=nT(e,n);r+=s,n=o}else if(i==="\\"){let s=e[++n],o=iT[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+=sT(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 nT(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 iT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function sT(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=Z0});var Ak=x(Ek=>{"use strict";var Ii=ke(),Ck=tt(),oT=$p(),aT=Dp();function cT(e,t,r,n){let{value:i,type:s,comment:o,range:c}=t.type==="block-scalar"?oT.resolveBlockScalar(e,t,n):aT.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=lT(e.schema,i,l,r,n):t.type==="scalar"?f=uT(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 lT(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 uT({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=cT});var _k=x(xk=>{"use strict";function dT(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=dT});var Ok=x(Lp=>{"use strict";var fT=Do(),pT=ke(),mT=kk(),Ik=Ak(),hT=Is(),gT=_k(),wT={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=yT(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=mT.composeCollection(wT,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&&(!pT.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:gT.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 yT({options:e},{offset:t,source:r,end:n},i){let s=new fT.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=hT.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 vT=Qo(),Tk=Ok(),kT=Is(),bT=ra();function RT(e,t,{offset:r,start:n,value:i,end:s},o){let c=Object.assign({_directives:t},e),l=new vT.Document(void 0,c),f={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},a=bT.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=kT.resolveEnd(s,d,!1,o);return p.comment&&(l.comment=p.comment),l.range=[r,d,p.offset],l}Nk.composeDoc=RT});var Mp=x(qk=>{"use strict";var ST=Nc("process"),CT=Ef(),ET=Qo(),na=ta(),jk=ke(),AT=$k(),xT=Is();function ia(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=ia(r);s?this.warnings.push(new na.YAMLWarning(o,n,i)):this.errors.push(new na.YAMLParseError(o,n,i))},this.directives=new CT.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(ST.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let s=ia(t);s[0]+=r,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=AT.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 na.YAMLParseError(ia(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 na.YAMLParseError(ia(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=xT.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 na.YAMLParseError(ia(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 ET.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 _T=$p(),IT=Dp(),PT=ta(),Lk=Fo();function OT(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 PT.YAMLParseError([c,c+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return IT.resolveFlowScalar(e,t,n);case"block-scalar":return _T.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function TT(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 NT(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">":$T(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 $T(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=TT;jl.resolveAsScalar=OT;jl.setScalarValue=NT});var Hk=x(Fk=>{"use strict";var jT=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=jT});var zk=x(Uk=>{"use strict";var Hp=Symbol("break visit"),DT=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=DT;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(),qT=Hk(),LT=zk(),Vp="\uFEFF",Up="",zp="",Kp="",WT=e=>!!e&&"items"in e,MT=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function FT(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 HT(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=qT.stringify;zt.visit=LT.visit;zt.BOM=Vp;zt.DOCUMENT=Up;zt.FLOW_END=zp;zt.SCALAR=Kp;zt.isCollection=WT;zt.isScalar=MT;zt.prettyToken=FT;zt.tokenType=HT});var Yp=x(Jk=>{"use strict";var sa=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"),BT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wl=new Set(",[]{}"),VT=new Set(` ,[]{}
|
|
121
|
+
\r `),Jp=e=>!e||VT.has(e),Gp=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]===sa.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 sa.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(Jp),"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 sa.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(Jp),"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 sa.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 sa.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(Jp),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(BT.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)}};Jk.Lexer=Gp});var Qp=x(Gk=>{"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}}}};Gk.LineCounter=Xp});var em=x(eb=>{"use strict";var UT=Nc("process"),Yk=Ll(),zT=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 zT.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,UT.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(aa=>{"use strict";var tb=Mp(),KT=Qo(),oa=ta(),JT=Lf(),GT=ke(),YT=Qp(),rb=em();function nb(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new YT.LineCounter||null,prettyErrors:t}}function XT(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(oa.prettifyError(e,r)),c.warnings.forEach(oa.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 oa.YAMLParseError(c.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(oa.prettifyError(e,r)),o.warnings.forEach(oa.prettifyError(e,r))),o}function QT(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=>JT.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 ZT(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 GT.isDocument(e)&&!n?e.toString(r):new KT.Document(e,n,r).toString(r)}aa.parse=QT;aa.parseAllDocuments=XT;aa.parseDocument=ib;aa.stringify=ZT});var jt=x(_e=>{"use strict";var eN=Mp(),tN=Qo(),rN=kp(),tm=ta(),nN=Do(),Un=ke(),iN=Mn(),sN=tt(),oN=Hn(),aN=Bn(),cN=Ll(),lN=Yp(),uN=Qp(),dN=em(),Hl=sb(),ob=To();_e.Composer=eN.Composer;_e.Document=tN.Document;_e.Schema=rN.Schema;_e.YAMLError=tm.YAMLError;_e.YAMLParseError=tm.YAMLParseError;_e.YAMLWarning=tm.YAMLWarning;_e.Alias=nN.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=iN.Pair;_e.Scalar=sN.Scalar;_e.YAMLMap=oN.YAMLMap;_e.YAMLSeq=aN.YAMLSeq;_e.CST=cN;_e.Lexer=lN.Lexer;_e.LineCounter=uN.LineCounter;_e.Parser=dN.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 pN(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 ca(e){let t=pN(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 mN(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=mN(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 hN(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:ca(n),toArtifactRoot:ca(i),stage:s,...o?{cleanup:o}:{}}}function gN(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??fN;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 wN(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=hN(r.pending_root_move),a=gN(r.finish);return{artifact_root:ca(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 yN(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 vN(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 kN(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 bN(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 RN(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)=>bN(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 SN(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 CN(e){let t=rm(e,"knowledge.remote"),r=SN(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 EN(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:RN(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:CN(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 AN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function xN(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 fn(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=AN(i.ambient_resume),o=vb(i.change_walkthrough),c=i.hook===void 0?void 0:vN(i.hook),l=kN(i.memory),f=EN(i.knowledge),a=i.native===void 0?void 0:wN(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=i.classic===void 0?void 0:yN(i.classic),p=xN(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:ca(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:pb,max_parallel_children:mb}}}var lr,dn,ab,cb,pb,mb,Bl,lb,hb,ub,fN,db,Dt=Le(()=>{"use strict";lr=vt(jt(),1),dn=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,fN=12e4,db=6e5});import{promises as Kt}from"fs";import Ie from"path";import{AsyncLocalStorage as _N}from"node:async_hooks";async function la(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),S=await Kt.lstat(k,{bigint:!0});if(!S.isDirectory()||S.isSymbolicLink()||l(S)!==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 S of Ie.relative(n,Ie.dirname(h)).split(Ie.sep).filter(Boolean))k=Ie.join(k,S),b.push(k);for(let S of b){let E=await s.get(S),O=await Kt.lstat(S,{bigint:!0});if(!O.isDirectory()||O.isSymbolicLink()||l(O)!==l(E.stat))throw new Error(`${t} directory changed while reading: ${Ie.relative(n,S)||"."}`)}}})},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(!PN(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 ON(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 ht(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?IN.getStore():void 0;if(i){let c=Ie.resolve(e),l=i.get(c);return l||(l=la(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 la(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 TN(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(im)&&(i.message=i.message.replaceAll(im,n.label)),i}}var IN,Rb,Sb,PN,ON,im,TN,ye=Le(()=>{"use strict";Ri();Dt();nr();IN=new _N;Rb=je("protectedChainLstat",e=>Kt.lstat(e)),Sb=je("protectedChainRealpath",e=>Kt.realpath(e)),PN=Vr("protectedChainInside",Os);ON=je("protectedInspectPath",(e,t,r)=>Eb(e,t,{label:"Protected project path",expected:r}));im="Cached protected project read",TN=je("protectedReadFile",(e,t,r)=>Ab(e,t,r,{label:im}))});import{promises as Ts}from"fs";import Jt from"path";function Kl(e,t){let r=Jt.relative(e,t);return r===""||r!==".."&&!r.startsWith(`..${Jt.sep}`)&&!Jt.isAbsolute(r)}function qb(e,t){return Jt.isAbsolute(t)?t:`${e}${Jt.sep}${t}`}async function um(e){let t=qb(process.cwd(),e),r=c=>c.split(process.platform==="win32"?/[\\/]+/u:/\/+/u),n=Jt.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=Jt.dirname(i);continue}let l=Jt.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 Jt.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(Jt.isAbsolute(a)){let d=Jt.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=Jt.resolve(e),n=Jt.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 Jl(e,t){let r=Jt.resolve(e),n=await Ts.realpath(r),i=[],s=[];for(let o of Io(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 FN}from"crypto";function HN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function pn(e,t={}){return(await Gl(e,t)).document}async function BN(e){try{return(await ae(e,da,dn,{label:da})).bytes}catch(t){if(HN(t))return null;throw t}}function VN(e){return e?{exists:!0,sha256:FN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Gl(e,t={}){let r=await BN(e);return{source:r?.toString("utf8")??null,document:r?fn(r.toString("utf8"),t):null,identity:VN(r)}}async function fm(e){return(await pn(e))?.config??null}var da,mn=Le(()=>{"use strict";Dt();ye();da=".comet/config.yaml"});import ct from"path";function zN(e,t){let r=ct.relative(e,t);return r===""||!ct.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ct.sep}`)}function KN(e,t){let r=ct.isAbsolute(t)?ct.resolve(t):ct.resolve(e,t),n=ct.relative(ct.resolve(e),r);return n===""||ct.isAbsolute(n)||n===".."||n.startsWith(`..${ct.sep}`)?null:n.replaceAll("\\","/")}function Wb(e){return process.platform==="win32"?e.toLowerCase():e}async function pm(e,t,r=[]){let n=ct.isAbsolute(t)?ct.resolve(t):ct.resolve(e,t),i=ct.resolve(e);if(!zN(i,n))return null;let s=KN(e,t);if(!s)return null;let c=(await UN(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 Jl(e,[t]),f=ct.isAbsolute(t)?t:`${i}${ct.sep}${t}`;if(l.projectTargets.length!==1)return null;let a=[ct.join(i,".git"),ct.join(i,".comet"),...r];for(let d of a)if(await Lb(ct.resolve(d),f))return null;return`${s} (configured Hook allow path: ${c})`}var UN,mm=Le(()=>{"use strict";nr();mn();dm();UN=je("hookWritePolicy",async e=>(await fm(e))?.hook??{allow_paths:[]})});var gK,vm=Le(()=>{"use strict";$t();mn();ye();gK=Number.MAX_SAFE_INTEGER});var Zl=Le(()=>{"use strict";$t();Dt();mn();ye();vm()});var eu=Le(()=>{"use strict"});var Zb=Le(()=>{"use strict"});var Rm=Le(()=>{"use strict";eu()});var eR=Le(()=>{"use strict";eu();Rm()});function v$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function k$(e){let t=(0,tR.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 nR(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 b$(e){let t=fn(JSON.stringify({...e,schema:"comet.project.v1"})).config;if(!t)throw new Error("Invalid global Comet config: workflow template is incomplete");return nR(t)}function R$(e){let t=fn(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 iR(e){let t=k$(e);if(Object.keys(t).length===0)return null;if(t.schema===void 0)return R$(e);if(t.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return b$(t)}async function Sm(e){try{let t=await ae(e,rR,dn,{label:"global Comet config"});return iR(t.bytes.toString("utf8"))}catch(t){if(v$(t))return null;throw t}}var tR,rR,Cm=Le(()=>{"use strict";tR=vt(jt(),1);$t();Dt();ye();rR=".comet/config.yaml"});var KK,sR=Le(()=>{"use strict";$t();ye();KK=Number.MAX_SAFE_INTEGER});import{promises as S$}from"node:fs";import C$ from"node:path";function ru(e){return C$.join(e,".comet","current-change.json")}function E$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function oR(e){return e===null||typeof e=="string"}function A$(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(!E$(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&&!oR(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(!oR(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,aR,{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",...A$(t)}}async function Em(e){await S$.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 Em(e),!0)}var tu,aR,x$,ha=Le(()=>{"use strict";nr();Ri();tu="comet.selection.v2",aR=Number.MAX_SAFE_INTEGER;x$=je("readCometCurrentSelection",e=>js(e))});var lR=Le(()=>{"use strict";eu();$t();Zb();eR();Dt();Cm();ye();mn();Zl();sR();mm();ha();vm();Rm()});import{TextDecoder as _$}from"util";function uR(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function I$(e,t){try{return new _$("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t} is not valid UTF-8`,{cause:r})}}async function Am(e,t,r,n,i={}){try{let s=await ae(e,t,r,{label:n,hooks:i.hooks});return{result:s,text:I$(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 Am(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 Am(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 Am(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(uR(o.result.stat),uR(l.result.stat))||o.text!==l.text)throw new Error(`${i} changed before commit`)}}})}async function dR(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 xm=Le(()=>{"use strict";lR();Oo()});var mR={};uI(mR,{RUN_STATE_FILE:()=>su,applyRunStateToDocument:()=>_m,readRunState:()=>ya,removeRunState:()=>va,runStateFromDocument:()=>Di,writeRunState:()=>qi});import P$ from"path";function wa(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 ga(e,t){let r=wa(e,t);if(P$.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 O$(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=wa(e,"run_id"),r=wa(e,"skill"),n=wa(e,"skill_version"),i=wa(e,"skill_hash"),s=ga(e,"pending_ref"),o=ga(e,"trajectory_ref"),c=ga(e,"context_ref"),l=ga(e,"artifacts_ref"),f=ga(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:fR(e,"current_step"),iteration:a,pending:fR(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:c,artifactsRef:l,checkpointRef:f,status:e.run_status,retries:O$(e)}}function _m(e,t){t?e.run_id=t.runId:delete e.run_id}function T$(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 N$(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 ya(e,t={}){let r=await $i(e,su,pR,"Run state",t);if(r===null)return null;let n=JSON.parse(r);return N$(n)}async function qi(e,t,r={}){await ji(e,su,JSON.stringify(T$(t),null,2),pR,"Run state",r)}async function va(e,t={}){await iu(e,su,"Run state",t)}var fR,su,pR,ou=Le(()=>{"use strict";xm();fR=(e,t)=>{let r=e[t];return r==null?null:String(r)};su=".comet/run-state.json",pR=Number.MAX_SAFE_INTEGER});var ja=x(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.regexpCode=Ee.getEsmExportName=Ee.getProperty=Ee.safeStringify=Ee.stringify=Ee.strConcat=Ee.addCodeArg=Ee.str=Ee._=Ee.nil=Ee._Code=Ee.Name=Ee.IDENTIFIER=Ee._CodeOrName=void 0;var Na=class{};Ee._CodeOrName=Na;Ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fi=class extends Na{constructor(t){if(super(),!Ee.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}}};Ee.Name=Fi;var gr=class extends Na{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),{})}};Ee._Code=gr;Ee.nil=new gr("");function ZR(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Gm(r,t[n]),r.push(e[++n]);return new gr(r)}Ee._=ZR;var Jm=new gr("+");function eS(e,...t){let r=[$a(e[0])],n=0;for(;n<t.length;)r.push(Jm),Gm(r,t[n]),r.push(Jm,$a(e[++n]));return Oj(r),new gr(r)}Ee.str=eS;function Gm(e,t){t instanceof gr?e.push(...t._items):t instanceof Fi?e.push(t):e.push($j(t))}Ee.addCodeArg=Gm;function Oj(e){let t=1;for(;t<e.length-1;){if(e[t]===Jm){let r=Tj(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Tj(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 Nj(e,t){return t.emptyStr()?e:e.emptyStr()?t:eS`${e}${t}`}Ee.strConcat=Nj;function $j(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:$a(Array.isArray(e)?e.join(","):e)}function jj(e){return new gr($a(e))}Ee.stringify=jj;function $a(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ee.safeStringify=$a;function Dj(e){return typeof e=="string"&&Ee.IDENTIFIER.test(e)?new gr(`.${e}`):ZR`[${e}]`}Ee.getProperty=Dj;function qj(e){if(typeof e=="string"&&Ee.IDENTIFIER.test(e))return new gr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Ee.getEsmExportName=qj;function Lj(e){return new gr(e.toString())}Ee.regexpCode=Lj});var Qm=x(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.ValueScope=Xt.ValueScopeName=Xt.Scope=Xt.varKinds=Xt.UsedValueState=void 0;var Yt=ja(),Ym=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 Wj=(0,Yt._)`\n`,Xm=class extends Cu{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Wj: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 Ym(f);l.set(f,Su.Completed)})}return s}};Xt.ValueScope=Xm});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=ja(),jr=Qm(),ei=ja();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=Qm();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}},Zm=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)}},eh=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}},th=class extends vn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},rh=class extends vn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},nh=class extends vn{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},ih=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:{}}},Da=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)||(Mj(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 Da{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},sh=class extends Da{},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(tS(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 oh=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)}},ah=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)}},qa=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)}};qa.kind="func";var La=class extends Da{render(t){return"return "+super.render(t)}};La.kind="return";var ch=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}},Wa=class extends kn{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Wa.kind="catch";var Ma=class extends kn{render(t){return"finally"+super.render(t)}};Ma.kind="finally";var lh=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 sh]}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 Zm(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 eh(t,de.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==ve.nil&&this._leafNode(new ih(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 oh(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 ah(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 th(t))}break(t){return this._leafNode(new rh(t))}return(t){let r=new La;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(La)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new ch;if(this._blockNode(i),this.code(t),r){let s=this.name("e");this._currNode=i.catch=new Wa(s),r(s)}return n&&(this._currNode=i.finally=new Ma,this.code(n)),this._endBlockNode(Wa,Ma)}throw(t){return this._leafNode(new nh(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 qa(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(qa)}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=lh;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 Mj(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function tS(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,ve._)`!${uh(e)}`}de.not=tS;var Fj=rS(de.operators.AND);function Hj(...e){return e.reduce(Fj)}de.and=Hj;var Bj=rS(de.operators.OR);function Vj(...e){return e.reduce(Bj)}de.or=Vj;function rS(e){return(t,r)=>t===ve.nil?r:r===ve.nil?t:(0,ve._)`${uh(t)} ${e} ${uh(r)}`}function uh(e){return e instanceof ve.Name?e:(0,ve._)`(${e})`}});var be=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(),Uj=ja();function zj(e){let t={};for(let r of e)t[r]=!0;return t}me.toHash=zj;function Kj(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(sS(e,t),!oS(t,e.self.RULES.all))}me.alwaysValidSchema=Kj;function sS(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]||lS(e,`unknown keyword: "${s}"`)}me.checkUnknownRules=sS;function oS(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}me.schemaHasRules=oS;function Jj(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=Jj;function Gj({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=Gj;function Yj(e){return aS(decodeURIComponent(e))}me.unescapeFragment=Yj;function Xj(e){return encodeURIComponent(fh(e))}me.escapeFragment=Xj;function fh(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=fh;function aS(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=aS;function Qj(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}me.eachItem=Qj;function nS({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:nS({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} || {}`),ph(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:cS}),items:nS({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 cS(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,De._)`{}`);return t!==void 0&&ph(e,r,t),r}me.evaluatedPropsToName=cS;function ph(e,t,r){Object.keys(r).forEach(n=>e.assign((0,De._)`${t}${(0,De.getProperty)(n)}`,!0))}me.setEvaluated=ph;var iS={};function Zj(e,t){return e.scopeValue("func",{ref:t,code:iS[t.code]||(iS[t.code]=new Uj._Code(t.code))})}me.useFunc=Zj;var dh;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(dh||(me.Type=dh={}));function eD(e,t,r){if(e instanceof De.Name){let n=t===dh.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():"/"+fh(e)}me.getErrorPath=eD;function lS(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=lS});var bn=x(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var St=pe(),tD={data:new St.Name("data"),valCxt:new St.Name("valCxt"),instancePath:new St.Name("instancePath"),parentData:new St.Name("parentData"),parentDataProperty:new St.Name("parentDataProperty"),rootData:new St.Name("rootData"),dynamicAnchors:new St.Name("dynamicAnchors"),vErrors:new St.Name("vErrors"),errors:new St.Name("errors"),this:new St.Name("this"),self:new St.Name("self"),scope:new St.Name("scope"),json:new St.Name("json"),jsonPos:new St.Name("jsonPos"),jsonLen:new St.Name("jsonLen"),jsonPart:new St.Name("jsonPart")};mh.default=tD});var Fa=x(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.extendErrors=Ct.resetErrorsCount=Ct.reportExtraError=Ct.reportError=Ct.keyword$DataError=Ct.keywordError=void 0;var Re=pe(),Pu=be(),Wt=bn();Ct.keywordError={message:({keyword:e})=>(0,Re.str)`must pass "${e}" keyword validation`};Ct.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Re.str)`"${e}" keyword must be ${t} ($data)`:(0,Re.str)`"${e}" keyword is invalid ($data)`};function rD(e,t=Ct.keywordError,r,n){let{it:i}=e,{gen:s,compositeRule:o,allErrors:c}=i,l=fS(e,t,r);n??(o||c)?uS(s,l):dS(i,(0,Re._)`[${l}]`)}Ct.reportError=rD;function nD(e,t=Ct.keywordError,r){let{it:n}=e,{gen:i,compositeRule:s,allErrors:o}=n,c=fS(e,t,r);uS(i,c),s||o||dS(n,Wt.default.vErrors)}Ct.reportExtraError=nD;function iD(e,t){e.assign(Wt.default.errors,t),e.if((0,Re._)`${Wt.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Re._)`${Wt.default.vErrors}.length`,t),()=>e.assign(Wt.default.vErrors,null)))}Ct.resetErrorsCount=iD;function sD({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,Wt.default.errors,c=>{e.const(o,(0,Re._)`${Wt.default.vErrors}[${c}]`),e.if((0,Re._)`${o}.instancePath === undefined`,()=>e.assign((0,Re._)`${o}.instancePath`,(0,Re.strConcat)(Wt.default.instancePath,s.errorPath))),e.assign((0,Re._)`${o}.schemaPath`,(0,Re.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,Re._)`${o}.schema`,r),e.assign((0,Re._)`${o}.data`,n))})}Ct.extendErrors=sD;function uS(e,t){let r=e.const("err",t);e.if((0,Re._)`${Wt.default.vErrors} === null`,()=>e.assign(Wt.default.vErrors,(0,Re._)`[${r}]`),(0,Re._)`${Wt.default.vErrors}.push(${r})`),e.code((0,Re._)`${Wt.default.errors}++`)}function dS(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,Re._)`new ${e.ValidationError}(${t})`):(r.assign((0,Re._)`${n}.errors`,t),r.return(!1))}var Ui={keyword:new Re.Name("keyword"),schemaPath:new Re.Name("schemaPath"),params:new Re.Name("params"),propertyName:new Re.Name("propertyName"),message:new Re.Name("message"),schema:new Re.Name("schema"),parentSchema:new Re.Name("parentSchema")};function fS(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Re._)`{}`:oD(e,t,r)}function oD(e,t,r={}){let{gen:n,it:i}=e,s=[aD(i,r),cD(e,r)];return lD(e,t,s),n.object(...s)}function aD({errorPath:e},{instancePath:t}){let r=t?(0,Re.str)`${e}${(0,Pu.getErrorPath)(t,Pu.Type.Str)}`:e;return[Wt.default.instancePath,(0,Re.strConcat)(Wt.default.instancePath,r)]}function cD({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,Re.str)`${t}/${e}`;return r&&(i=(0,Re.str)`${i}${(0,Pu.getErrorPath)(r,Pu.Type.Str)}`),[Ui.schemaPath,i]}function lD(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,Re._)`{}`]),l.messages&&n.push([Ui.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([Ui.schema,o],[Ui.parentSchema,(0,Re._)`${a}${d}`],[Wt.default.data,s]),f&&n.push([Ui.propertyName,f])}});var mS=x(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.boolOrEmptySchema=Ks.topBoolOrEmptySchema=void 0;var uD=Fa(),dD=pe(),fD=bn(),pD={message:"boolean schema is false"};function mD(e){let{gen:t,schema:r,validateName:n}=e;r===!1?pS(e,!1):typeof r=="object"&&r.$async===!0?t.return(fD.default.data):(t.assign((0,dD._)`${n}.errors`,null),t.return(!0))}Ks.topBoolOrEmptySchema=mD;function hD(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),pS(e)):r.var(t,!0)}Ks.boolOrEmptySchema=hD;function pS(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,uD.reportError)(i,pD,void 0,t)}});var hh=x(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.getRules=Js.isJSONType=void 0;var gD=["string","number","integer","boolean","null","object","array"],wD=new Set(gD);function yD(e){return typeof e=="string"&&wD.has(e)}Js.isJSONType=yD;function vD(){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:{}}}Js.getRules=vD});var gh=x(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.shouldUseRule=ti.shouldUseGroup=ti.schemaHasRulesForType=void 0;function kD({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&hS(e,n)}ti.schemaHasRulesForType=kD;function hS(e,t){return t.rules.some(r=>gS(e,r))}ti.shouldUseGroup=hS;function gS(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=gS});var Ha=x(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.reportTypeError=Et.checkDataTypes=Et.checkDataType=Et.coerceAndCheckDataType=Et.getJSONTypes=Et.getSchemaTypes=Et.DataType=void 0;var bD=hh(),RD=gh(),SD=Fa(),ce=pe(),wS=be(),Gs;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Gs||(Et.DataType=Gs={}));function CD(e){let t=yS(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}Et.getSchemaTypes=CD;function yS(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(bD.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Et.getJSONTypes=yS;function ED(e,t){let{gen:r,data:n,opts:i}=e,s=AD(t,i.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,RD.schemaHasRulesForType)(e,t[0]));if(o){let c=yh(t,n,i.strictNumbers,Gs.Wrong);r.if(c,()=>{s.length?xD(e,t,s):vh(e)})}return o}Et.coerceAndCheckDataType=ED;var vS=new Set(["string","number","integer","boolean","null"]);function AD(e,t){return t?e.filter(r=>vS.has(r)||t==="array"&&r==="array"):[]}function xD(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(yh(t,i,s.strictNumbers),()=>n.assign(c,i))),n.if((0,ce._)`${c} !== undefined`);for(let f of r)(vS.has(f)||f==="array"&&s.coerceTypes==="array")&&l(f);n.else(),vh(e),n.endIf(),n.if((0,ce._)`${c} !== undefined`,()=>{n.assign(i,c),_D(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 _D({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,ce._)`${t} !== undefined`,()=>e.assign((0,ce._)`${t}[${r}]`,n))}function wh(e,t,r,n=Gs.Correct){let i=n===Gs.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===Gs.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)}}Et.checkDataType=wh;function yh(e,t,r,n){if(e.length===1)return wh(e[0],t,r,n);let i,s=(0,wS.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,wh(o,t,r,n));return i}Et.checkDataTypes=yh;var ID={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,ce._)`{type: ${e}}`:(0,ce._)`{type: ${t}}`};function vh(e){let t=PD(e);(0,SD.reportError)(t,ID)}Et.reportTypeError=vh;function PD(e){let{gen:t,data:r,schema:n}=e,i=(0,wS.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var bS=x(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});Ou.assignDefaults=void 0;var Ys=pe(),OD=be();function TD(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)kS(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,s)=>kS(e,s,i.default))}Ou.assignDefaults=TD;function kS(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,OD.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(),kh=be(),ri=bn(),ND=be();function $D(e,t){let{gen:r,data:n,it:i}=e;r.if(Rh(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,We._)`${t}`},!0),e.error()})}$e.checkReportMissingProp=$D;function jD({gen:e,data:t,it:{opts:r}},n,i){return(0,We.or)(...n.map(s=>(0,We.and)(Rh(e,t,s,r.ownProperties),(0,We._)`${i} = ${s}`)))}$e.checkMissingProp=jD;function DD(e,t){e.setParams({missingProperty:t},!0),e.error()}$e.reportMissingProp=DD;function RS(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,We._)`Object.prototype.hasOwnProperty`})}$e.hasPropFunc=RS;function bh(e,t,r){return(0,We._)`${RS(e)}.call(${t}, ${r})`}$e.isOwnProperty=bh;function qD(e,t,r,n){let i=(0,We._)`${t}${(0,We.getProperty)(r)} !== undefined`;return n?(0,We._)`${i} && ${bh(e,t,r)}`:i}$e.propertyInData=qD;function Rh(e,t,r,n){let i=(0,We._)`${t}${(0,We.getProperty)(r)} === undefined`;return n?(0,We.or)(i,(0,We.not)(bh(e,t,r))):i}$e.noPropertyInData=Rh;function SS(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}$e.allSchemaProperties=SS;function LD(e,t){return SS(t).filter(r=>!(0,kh.alwaysValidSchema)(e,t[r]))}$e.schemaProperties=LD;function WD({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=WD;var MD=(0,We._)`new RegExp`;function FD({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"?MD:(0,ND.useFunc)(e,i)}(${r}, ${n})`})}$e.usePattern=FD;function HD(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:kh.Type.Num},s),t.if((0,We.not)(s),c)})}}$e.validateArray=HD;function BD(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,kh.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=BD});var AS=x(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.validateKeywordUsage=Zr.validSchemaType=Zr.funcKeywordCode=Zr.macroKeywordCode=void 0;var Mt=pe(),zi=bn(),VD=wr(),UD=Fa();function zD(e,t){let{gen:r,keyword:n,schema:i,parentSchema:s,it:o}=e,c=t.macro.call(o.self,i,s,o),l=ES(r,n,c);o.opts.validateSchema!==!1&&o.self.validateSchema(c,!0);let f=r.name("valid");e.subschema({schema:c,schemaPath:Mt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}Zr.macroKeywordCode=zD;function KD(e,t){var r;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:c,it:l}=e;GD(l,t);let f=!c&&t.compile?t.compile.call(l.self,s,o,l):t.validate,a=ES(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&&CS(e),g(()=>e.error());else{let w=t.async?u():m();t.modifying&&CS(e),g(()=>JD(e,w))}}function u(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Mt._)`await `),k=>n.assign(d,!1).if((0,Mt._)`${k} instanceof ${l.ValidationError}`,()=>n.assign(w,(0,Mt._)`${k}.errors`),()=>n.throw(k))),w}function m(){let w=(0,Mt._)`${a}.errors`;return n.assign(w,null),h(Mt.nil),w}function h(w=t.async?(0,Mt._)`await `:Mt.nil){let k=l.opts.passContext?zi.default.this:zi.default.self,b=!("compile"in t&&!c||t.schema===!1);n.assign(d,(0,Mt._)`${w}${(0,VD.callValidateCode)(e,a,k,b)}`,t.modifying)}function g(w){var k;n.if((0,Mt.not)((k=t.valid)!==null&&k!==void 0?k:d),w)}}Zr.funcKeywordCode=KD;function CS(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Mt._)`${n.parentData}[${n.parentDataProperty}]`))}function JD(e,t){let{gen:r}=e;r.if((0,Mt._)`Array.isArray(${t})`,()=>{r.assign(zi.default.vErrors,(0,Mt._)`${zi.default.vErrors} === null ? ${t} : ${zi.default.vErrors}.concat(${t})`).assign(zi.default.errors,(0,Mt._)`${zi.default.vErrors}.length`),(0,UD.extendErrors)(e)},()=>e.error())}function GD({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function ES(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,Mt.stringify)(r)})}function YD(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")}Zr.validSchemaType=YD;function XD({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)}}Zr.validateKeywordUsage=XD});var _S=x(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.extendSubschemaMode=ni.extendSubschemaData=ni.getSubschema=void 0;var en=pe(),xS=be();function QD(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,en._)`${e.schemaPath}${(0,en.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,en._)`${e.schemaPath}${(0,en.getProperty)(t)}${(0,en.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,xS.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=QD;function ZD(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,en._)`${t.data}${(0,en.getProperty)(r)}`,!0);l(p),e.errorPath=(0,en.str)`${f}${(0,xS.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,en._)`${r}`,e.dataPathArr=[...a,e.parentDataProperty]}if(i!==void 0){let f=i instanceof en.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=ZD;function e1(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=e1});var Sh=x((w4,IS)=>{"use strict";IS.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 OS=x((y4,PS)=>{"use strict";var ii=PS.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+"/"+t1(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 t1(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ba=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 r1=be(),n1=Sh(),i1=OS(),s1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o1(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ch(e):t?TS(e)<=t:!1}Qt.inlineRef=o1;var a1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ch(e){for(let t in e){if(a1.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ch)||typeof r=="object"&&Ch(r))return!0}return!1}function TS(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!s1.has(r)&&(typeof e[r]=="object"&&(0,r1.eachItem)(e[r],n=>t+=TS(n)),t===1/0))return 1/0}return t}function NS(e,t="",r){r!==!1&&(t=Xs(t));let n=e.parse(t);return $S(e,n)}Qt.getFullPath=NS;function $S(e,t){return e.serialize(t).split("#")[0]+"#"}Qt._getFullPath=$S;var c1=/#\/?$/;function Xs(e){return e?e.replace(c1,""):""}Qt.normalizeId=Xs;function l1(e,t,r){return r=Xs(r),e.resolve(t,r)}Qt.resolveUrl=l1;var u1=/^[a-z_][-a-z0-9._]*$/i;function d1(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Xs(e[r]||t),s={"":i},o=NS(n,i,!1),c={},l=new Set;return i1(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 S=this.opts.uriResolver.resolve;if(b=Xs(g?S(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(!u1.test(b))throw new Error(`invalid anchor "${b}"`);w.call(this,`#${b}`)}}}),c;function f(d,p,u){if(p!==void 0&&!n1(d,p))throw a(u)}function a(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Qt.getSchemaRefs=d1});var za=x(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.getData=si.KeywordCxt=si.validateFunctionCode=void 0;var WS=mS(),jS=Ha(),Ah=gh(),Nu=Ha(),f1=bS(),Ua=AS(),Eh=_S(),ee=pe(),se=bn(),p1=Ba(),Rn=be(),Va=Fa();function m1(e){if(HS(e)&&(BS(e),FS(e))){w1(e);return}MS(e,()=>(0,WS.topBoolOrEmptySchema)(e))}si.validateFunctionCode=m1;function MS({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"; ${DS(r,i)}`),g1(e,i),e.code(s)}):e.func(t,(0,ee._)`${se.default.data}, ${h1(i)}`,n.$async,()=>e.code(DS(r,i)).code(s))}function h1(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 g1(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 w1(e){let{schema:t,opts:r,gen:n}=e;MS(e,()=>{r.$comment&&t.$comment&&US(e),R1(e),n.let(se.default.vErrors,null),n.let(se.default.errors,0),r.unevaluated&&y1(e),VS(e),E1(e)})}function y1(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 DS(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 v1(e,t){if(HS(e)&&(BS(e),FS(e))){k1(e,t);return}(0,WS.boolOrEmptySchema)(e,t)}function FS({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 HS(e){return typeof e.schema!="boolean"}function k1(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&US(e),S1(e),C1(e);let s=n.const("_errs",se.default.errors);VS(e,s),n.var(t,(0,ee._)`${s} === ${se.default.errors}`)}function BS(e){(0,Rn.checkUnknownRules)(e),b1(e)}function VS(e,t){if(e.opts.jtd)return qS(e,[],!1,t);let r=(0,jS.getSchemaTypes)(e.schema),n=(0,jS.coerceAndCheckDataType)(e,r);qS(e,r,!n,t)}function b1(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 R1(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 S1(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,p1.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function C1(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function US({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 E1(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&&A1(e),t.return((0,ee._)`${se.default.errors} === 0`))}function A1({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 qS(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(()=>KS(e,"$ref",a.all.$ref.definition));return}l.jtd||x1(e,t),i.block(()=>{for(let p of a.rules)d(p);d(a.post)});function d(p){(0,Ah.shouldUseGroup)(s,p)&&(p.type?(i.if((0,Nu.checkDataType)(p.type,o,l.strictNumbers)),LS(e,p),t.length===1&&t[0]===p.type&&r&&(i.else(),(0,Nu.reportTypeError)(e)),i.endIf()):LS(e,p),c||i.if((0,ee._)`${se.default.errors} === ${n||0}`))}}function LS(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,f1.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,Ah.shouldUseRule)(n,s)&&KS(e,s.keyword,s.definition,t.type)})}function x1(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(_1(e,t),e.opts.allowUnionTypes||I1(e,t),P1(e,e.dataTypes))}function _1(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{zS(e.dataTypes,r)||xh(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),T1(e,t)}}function I1(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&xh(e,"use allowUnionTypes to allow union type keyword")}function P1(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Ah.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>O1(t,o))&&xh(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function O1(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function zS(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function T1(e,t){let r=[];for(let n of e.dataTypes)zS(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function xh(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,Ua.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,Ua.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?Va.reportExtraError:Va.reportError)(this,this.def.error,r)}$dataError(){(0,Va.reportError)(this,this.def.$dataError||Va.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Va.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,Eh.getSubschema)(this.it,t);(0,Eh.extendSubschemaData)(n,this.it,t),(0,Eh.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return v1(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 KS(e,t,r,n){let i=new $u(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,Ua.funcKeywordCode)(i,r):"macro"in r?(0,Ua.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,Ua.funcKeywordCode)(i,r)}var N1=/^\/(?:[^~]|~0|~1)*$/,$1=/^([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(!N1.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,s=se.default.rootData}else{let f=$1.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(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var _h=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ih.default=_h});var Ka=x(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var Ph=Ba(),Oh=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ph.resolveUrl)(t,r,n),this.missingSchema=(0,Ph.normalizeId)((0,Ph.getFullPath)(t,this.missingRef))}};Th.default=Oh});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(),j1=ju(),Ki=bn(),qr=Ba(),GS=be(),D1=za(),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 $h(e){let t=YS.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:j1.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,D1.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=$h;function q1(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=M1.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]=L1.call(this,s)}yr.resolveRef=q1;function L1(e){return(0,qr.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:$h.call(this,e)}function YS(e){for(let t of this._compilations)if(W1(t,e))return t}yr.getCompilingSchema=YS;function W1(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function M1(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 Nh.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:Nh.call(this,r,c)}if(typeof o?.schema=="object"){if(o.validate||$h.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 Nh.call(this,r,o)}}yr.resolveSchema=Du;var F1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Nh(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,GS.unescapeFragment)(c)];if(l===void 0)return;r=l;let f=typeof r=="object"&&r[this.opts.schemaId];!F1.has(c)&&f&&(t=(0,qr.resolveUrl)(this.opts.uriResolver,t,f))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,GS.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 XS=x((C4,H1)=>{H1.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 Mh=x((E4,sC)=>{"use strict";var B1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Dh=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),V1=RegExp.prototype.test.bind(/^\d*$/u),Ji=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),qh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ZS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Lh=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),U1=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 At(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 z1(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 K1=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),J1=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),G1=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Y1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function X1(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!G1(e[t])){if(e[t]==="%"&&t+2<e.length&&Ji(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function QS(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 Q1(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||!Dh(l))return;s+=2;continue}if(!K1(l))return;i[c]=parseInt(l,16).toString(16),s++}if(t===-1)return s!==8?void 0:QS(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 QS(o)}function jh(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&&J1(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(Z1(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),!X1(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,s)}let o=Q1(n);return o===void 0?{host:e,isIPV6:!1,error:!0}:{host:o+(i?"%"+i:""),escapedHost:o+(i?"%25"+i:""),isIPV6:!0}}function Z1(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function eC(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 eq(e){if(e===""||e[0]==="/")return eC(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 tq={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},rq=/[@/?#:]/g,nq=/[@/?#]/g;function tC(e,t){let r=t?nq:rq;return r.lastIndex=0,e.replace(r,n=>tq[n])}function rC(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(Ji(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));t&&qh(o)?r+=o:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function iq(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(Ji(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&qh(o)?t+=o:t+="%"+s,r+=2;continue}}if(ZS(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=iC(i)?n:Zt[i];else if(i<55296||i>57343)t+=At(i);else if(i<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=At(65536+(i-55296<<10)+(s-56320)),r++):t+=At(65533)}else t+=At(65533)}}return t}function sq(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(Ji(o)){r+="%"+o.toUpperCase(),i+=2;continue}}if(s==="/"&&(n=!1),ZS(s)&&(s!==":"||!n))r+=s;else{let o=e.charCodeAt(i);if(o<128)r+=Zt[o];else if(o<55296||o>57343)r+=At(o);else if(o<=56319&&i+1<e.length){let c=e.charCodeAt(i+1);c>=56320&&c<=57343?(r+=At(65536+(o-55296<<10)+(c-56320)),i++):r+=At(65533)}else r+=At(65533)}}return r}function Wh(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(Ji(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+=At(s);else if(s<=56319&&n+1<e.length){let o=e.charCodeAt(n+1);o>=56320&&o<=57343?(r+=At(65536+(s-55296<<10)+(o-56320)),n++):r+=At(65533)}else r+=At(65533)}}return r}function nC(e){return Wh(e,U1)}function oq(e){return Wh(e,Lh)}function aq(e){return Wh(e,Lh)}function iC(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 cq(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(Ji(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));qh(o)?t+=o:t+="%"+s,r+=2;continue}}if(Lh(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=iC(i)?n:Zt[i];else if(i<55296||i>57343)t+=At(i);else if(i<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=At(65536+(i-55296<<10)+(s-56320)),r++):t+=At(65533)}else t+=At(65533)}}return t}function lq(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(Ji(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function uq(e){let t=[];if(e.userinfo!==void 0&&(t.push(nC(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!Dh(r)){let n=jh(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=rC(r,!0),n=jh(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=tC(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!V1(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}sC.exports={nonSimpleDomain:Y1,recomposeAuthority:uq,reescapeHostDelimiters:tC,normalizePercentEncoding:rC,normalizePathEncoding:iq,serializePathEncoding:sq,normalizeQueryFragmentEncoding:cq,encodeUserinfo:nC,encodeQuery:oq,encodeFragment:aq,escapePreservingEscapes:lq,removeDotSegments:eC,removeDotSegmentsRelative:eq,isIPv4:Dh,isUUID:B1,normalizeIPv6:jh,stringArrayToHexStripped:z1}});var uC=x((A4,lC)=>{"use strict";var{isUUID:dq}=Mh(),fq=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,pq=["http","https","ws","wss","urn","urn:uuid"];function mq(e){return pq.indexOf(e)!==-1}function Fh(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 oC(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function aC(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 hq(e){return e.secure=Fh(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function gq(e){if((e.port===(Fh(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 wq(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(fq);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=Hh(i);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function yq(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=Hh(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 vq(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!dq(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function kq(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var cC={scheme:"http",domainHost:!0,parse:oC,serialize:aC},bq={scheme:"https",domainHost:cC.domainHost,parse:oC,serialize:aC},Lu={scheme:"ws",domainHost:!0,parse:hq,serialize:gq},Rq={scheme:"wss",domainHost:Lu.domainHost,parse:Lu.parse,serialize:Lu.serialize},Sq={scheme:"urn",parse:wq,serialize:yq,skipNormalize:!0},Cq={scheme:"urn:uuid",parse:vq,serialize:kq,skipNormalize:!0},Wu={http:cC,https:bq,ws:Lu,wss:Rq,urn:Sq,"urn:uuid":Cq};Object.setPrototypeOf(Wu,null);function Hh(e){return e&&(Wu[e]||Wu[e.toLowerCase()])||void 0}lC.exports={wsIsSecure:Fh,SCHEMES:Wu,isValidSchemeName:mq,getSchemeHandler:Hh}});var EC=x((x4,Vu)=>{"use strict";var{normalizeIPv6:hC,removeDotSegments:Ga,removeDotSegmentsRelative:gC,recomposeAuthority:Eq,normalizePercentEncoding:Bh,normalizePathEncoding:Aq,serializePathEncoding:dC,normalizeQueryFragmentEncoding:fC,encodeQuery:xq,encodeFragment:_q,reescapeHostDelimiters:Iq,isIPv4:wC,nonSimpleDomain:Pq}=Mh(),{SCHEMES:yC,getSchemeHandler:Vh}=uC(),vC=/^[A-Za-z][A-Za-z0-9+.-]*$/u,kC="URI scheme is malformed.",Mu="URI host is malformed.",Oq=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function pC(e){let t=String(e);if(!vC.test(t))throw new TypeError(kC);return t}function Tq(e,t){return typeof e=="string"?e=Fq(e,t):typeof e=="object"&&(e=Hu(Gi(e,t),t)),e}function Nq(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=bC(i,a,n,!0),w=Vh(r&&r.scheme||g.scheme),k=g.host,b=k!==void 0&&k!==""&&(wC(k)||hC(k).isIPV6);if(SC(g,r||{},w,b))throw new Error(Mu);RC(g,r||{},w,b);let S=k&&k.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(k);if(g.error&&!S)throw new Error(g.error);return n.skipEscape=!0,Gi(g,n)}function bC(e,t,r,n){let i={};if(n||(e=Hu(Gi(e,r),r),t=Hu(Gi(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=Ga(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=Ga(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=Ga(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]!=="/"?gC(i.path):Ga(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 $q(e,t,r){let n=mC(e,r),i=mC(t,r);return n!==void 0&&i!==void 0&&n===i}function Gi(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=pC(r.scheme));let s=Vh(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=Bh(r.path):r.path=dC(r.path,l)),n.reference!=="suffix"&&r.scheme&&(r.scheme=pC(r.scheme),i.push(r.scheme,":"));let f=Eq(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]!=="/"?gC(a):Ga(a)),c&&(a=dC(a,!0)),f===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",xq(r.query)),r.fragment!==void 0&&i.push("#",_q(r.fragment)),i.join("")}var jq=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Dq=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,qq=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function Lq(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 Wq(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 RC(e,t,r,n){if(SC(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&&Pq(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(!Mq(i))return e.error=e.error||Mu,!0;e.host=i.hostname}return!1}function SC(e,t,r,n){return!!(e.host&&n===!1&&!Bu(e.host)&&(t.domainHost||r&&r.domainHost)&&Oq.test(e.host))}function Mq(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(Dq);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let p=e.match(qq);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(jq);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&&(vC.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||kC,f=!0)),s=Wq(u),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=u[5]);let m=Lq(n,u);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(wC(n.host)===!1){let w=Bu(n.host),k=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,b=hC(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=Vh(r.scheme||n.scheme);if(l||(c=RC(n,r,h,a)),e.indexOf("%")!==-1&&n.host!==void 0&&!l){let g=a?n.host:Bh(n.host,!0);a||(g=Bh(g.toLowerCase())),n.host=a||r.scheme!=="null"?Iq(g,a):g}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=Aq(n.path)),n.query&&(n.query=fC(n.query)),n.fragment&&(n.fragment=fC(n.fragment))),h&&h.parse&&(h.parse(n,r),h===yC.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 Fq(e,t){return CC(e,t).normalized}function CC(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:Gi(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}}function mC(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Gi(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:c,malformedScheme:l}=CC(r,t);return i||s||o||c||l?void 0:n}var Uh={SCHEMES:yC,normalize:Tq,resolve:Nq,resolveComponent:bC,equal:$q,serialize:Gi,parse:Hu};Vu.exports=Uh;Vu.exports.default=Uh;Vu.exports.fastUri=Uh});var xC=x(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var AC=EC();AC.code='require("ajv/dist/runtime/uri").default';zh.default=AC});var jC=x(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.CodeGen=wt.Name=wt.nil=wt.stringify=wt.str=wt._=wt.KeywordCxt=void 0;var Hq=za();Object.defineProperty(wt,"KeywordCxt",{enumerable:!0,get:function(){return Hq.KeywordCxt}});var Zs=pe();Object.defineProperty(wt,"_",{enumerable:!0,get:function(){return Zs._}});Object.defineProperty(wt,"str",{enumerable:!0,get:function(){return Zs.str}});Object.defineProperty(wt,"stringify",{enumerable:!0,get:function(){return Zs.stringify}});Object.defineProperty(wt,"nil",{enumerable:!0,get:function(){return Zs.nil}});Object.defineProperty(wt,"Name",{enumerable:!0,get:function(){return Zs.Name}});Object.defineProperty(wt,"CodeGen",{enumerable:!0,get:function(){return Zs.CodeGen}});var Bq=ju(),TC=Ka(),Vq=hh(),Ya=qu(),Uq=pe(),Xa=Ba(),Uu=Ha(),Jh=be(),_C=XS(),zq=xC(),NC=(e,t)=>new RegExp(e,t);NC.code="new RegExp";var Kq=["removeAdditional","useDefaults","coerceTypes"],Jq=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Gq={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."},Yq={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},IC=200;function Xq(e){var t,r,n,i,s,o,c,l,f,a,d,p,u,m,h,g,w,k,b,S,E,O,z,D,J;let G=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:NC,K=(i=e.uriResolver)!==null&&i!==void 0?i:zq.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:G)!==null&&o!==void 0?o:!0,strictNumbers:(l=(c=e.strictNumbers)!==null&&c!==void 0?c:G)!==null&&l!==void 0?l:!0,strictTypes:(a=(f=e.strictTypes)!==null&&f!==void 0?f:G)!==null&&a!==void 0?a:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:G)!==null&&p!==void 0?p:"log",strictRequired:(m=(u=e.strictRequired)!==null&&u!==void 0?u:G)!==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:IC,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:IC,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:(S=e.schemaId)!==null&&S!==void 0?S:"$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:(J=e.int32range)!==null&&J!==void 0?J:!0,uriResolver:K}}var Qa=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,...Xq(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Uq.ValueScope({scope:{},prefixes:Jq,es5:r,lines:n}),this.logger=nL(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,Vq.getRules)(),PC.call(this,Gq,t,"NOT SUPPORTED"),PC.call(this,Yq,t,"DEPRECATED","warn"),this._metaOpts=tL.call(this),t.formats&&Zq.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&eL.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),Qq.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=_C;n==="id"&&(i={..._C},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 TC.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,Xa.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=OC.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Ya.SchemaEnv({schema:{},schemaId:n});if(r=Ya.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=OC.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,Xa.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(sL.call(this,n,r),!r)return(0,Jh.eachItem)(n,s=>Kh.call(this,s)),this;aL.call(this,r);let i={...r,type:(0,Uu.getJSONTypes)(r.type),schemaType:(0,Uu.getJSONTypes)(r.schemaType)};return(0,Jh.eachItem)(n,i.type.length===0?s=>Kh.call(this,s,i):s=>i.type.forEach(o=>Kh.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]=$C(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,Xa.normalizeId)(o||n);let f=Xa.getSchemaRefs.call(this,t,n);return l=new Ya.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):Ya.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{Ya.compileSchema.call(this,t)}finally{this.opts=r}}};Qa.ValidationError=Bq.default;Qa.MissingRefError=TC.default;wt.default=Qa;function PC(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 OC(e){return e=(0,Xa.normalizeId)(e),this.schemas[e]||this.refs[e]}function Qq(){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 Zq(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function eL(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 tL(){let e={...this.opts};for(let t of Kq)delete e[t];return e}var rL={log(){},warn(){},error(){}};function nL(e){if(e===!1)return rL;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 iL=/^[a-z_$][a-z0-9_$:-]*$/i;function sL(e,t){let{RULES:r}=this;if((0,Jh.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!iL.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 Kh(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?oL.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 oL(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 aL(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=$C(t)),e.validateSchema=this.compile(t,!0))}var cL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function $C(e){return{anyOf:[e,cL]}}});var DC=x(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var lL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Gh.default=lL});var MC=x(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.callRef=Yi.getValidate=void 0;var uL=Ka(),qC=wr(),er=pe(),eo=bn(),LC=qu(),zu=be(),dL={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=LC.resolveRef.call(l,f,i,r);if(a===void 0)throw new uL.default(n.opts.uriResolver,i,r);if(a instanceof LC.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=WC(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 WC(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=WC;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,qC.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,qC.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=dL});var FC=x(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var fL=DC(),pL=MC(),mL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fL.default,pL.default];Yh.default=mL});var HC=x(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var Ju=pe(),oi=Ju.operators,Gu={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}},hL={message:({keyword:e,schemaCode:t})=>(0,Ju.str)`must be ${Gu[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ju._)`{comparison: ${Gu[e].okStr}, limit: ${t}}`},gL={keyword:Object.keys(Gu),type:"number",schemaType:"number",$data:!0,error:hL,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Ju._)`${r} ${Gu[t].fail} ${n} || isNaN(${r})`)}};Xh.default=gL});var BC=x(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var Za=pe(),wL={message:({schemaCode:e})=>(0,Za.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Za._)`{multipleOf: ${e}}`},yL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wL,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),c=s?(0,Za._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,Za._)`${o} !== parseInt(${o})`;e.fail$data((0,Za._)`(${n} === 0 || (${o} = ${r}/${n}, ${c}))`)}};Qh.default=yL});var eg=x(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});function VC(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}Zh.default=VC;VC.code='require("ajv/dist/runtime/ucs2length").default'});var UC=x(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var Xi=pe(),vL=be(),kL=eg(),bL={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}}`},RL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bL,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,vL.useFunc)(e.gen,kL.default)}(${r})`;e.fail$data((0,Xi._)`${o} ${s} ${n}`)}};tg.default=RL});var zC=x(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var SL=wr(),CL=be(),to=pe(),EL={message:({schemaCode:e})=>(0,to.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,to._)`{pattern: ${e}}`},AL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:EL,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,CL.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,SL.usePattern)(e,i);e.fail$data((0,to._)`!${l}.test(${r})`)}}};rg.default=AL});var KC=x(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var ec=pe(),xL={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,ec.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,ec._)`{limit: ${e}}`},_L={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:xL,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?ec.operators.GT:ec.operators.LT;e.fail$data((0,ec._)`Object.keys(${r}).length ${i} ${n}`)}};ng.default=_L});var JC=x(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var tc=wr(),rc=pe(),IL=be(),PL={message:({params:{missingProperty:e}})=>(0,rc.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,rc._)`{missingProperty: ${e}}`},OL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:PL,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,IL.checkStrictMode)(o,w,o.opts.strictRequired)}}function f(){if(l||s)e.block$data(rc.nil,d);else for(let u of r)(0,tc.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,tc.checkMissingProp)(e,r,u)),(0,tc.reportMissingProp)(e,u),t.else()}function d(){t.forOf("prop",n,u=>{e.setParams({missingProperty:u}),t.if((0,tc.noPropertyInData)(t,i,u,c.ownProperties),()=>e.error())})}function p(u,m){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(m,(0,tc.propertyInData)(t,i,u,c.ownProperties)),t.if((0,rc.not)(m),()=>{e.error(),t.break()})},rc.nil)}}};ig.default=OL});var GC=x(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var nc=pe(),TL={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,nc.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,nc._)`{limit: ${e}}`},NL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:TL,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?nc.operators.GT:nc.operators.LT;e.fail$data((0,nc._)`${r}.length ${i} ${n}`)}};sg.default=NL});var Yu=x(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});var YC=Sh();YC.code='require("ajv/dist/runtime/equal").default';og.default=YC});var XC=x(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var ag=Ha(),yt=pe(),$L=be(),jL=Yu(),DL={message:({params:{i:e,j:t}})=>(0,yt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,yt._)`{i: ${e}, j: ${t}}`},qL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:DL,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,ag.getSchemaTypes)(s.items):[];e.block$data(l,a,(0,yt._)`${o} === false`),e.ok(l);function a(){let m=t.let("i",(0,yt._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(l,!0),t.if((0,yt._)`${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,ag.checkDataTypes)(f,g,c.opts.strictNumbers,ag.DataType.Wrong),k=t.const("indices",(0,yt._)`{}`);t.for((0,yt._)`;${m}--;`,()=>{t.let(g,(0,yt._)`${r}[${m}]`),t.if(w,(0,yt._)`continue`),f.length>1&&t.if((0,yt._)`typeof ${g} == "string"`,(0,yt._)`${g} += "_"`),t.if((0,yt._)`typeof ${k}[${g}] == "number"`,()=>{t.assign(h,(0,yt._)`${k}[${g}]`),e.error(),t.assign(l,!1).break()}).code((0,yt._)`${k}[${g}] = ${m}`)})}function u(m,h){let g=(0,$L.useFunc)(t,jL.default),w=t.name("outer");t.label(w).for((0,yt._)`;${m}--;`,()=>t.for((0,yt._)`${h} = ${m}; ${h}--;`,()=>t.if((0,yt._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(l,!1).break(w)})))}}};cg.default=qL});var QC=x(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var lg=pe(),LL=be(),WL=Yu(),ML={message:"must be equal to constant",params:({schemaCode:e})=>(0,lg._)`{allowedValue: ${e}}`},FL={keyword:"const",$data:!0,error:ML,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,lg._)`!${(0,LL.useFunc)(t,WL.default)}(${r}, ${i})`):e.fail((0,lg._)`${s} !== ${r}`)}};ug.default=FL});var ZC=x(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var ic=pe(),HL=be(),BL=Yu(),VL={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,ic._)`{allowedValues: ${e}}`},UL={keyword:"enum",schemaType:"array",$data:!0,error:VL,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,HL.useFunc)(t,BL.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,ic.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,ic._)`${f()}(${r}, ${u})`,()=>t.assign(a,!0).break()))}function p(u,m){let h=i[m];return typeof h=="object"&&h!==null?(0,ic._)`${f()}(${r}, ${u}[${m}])`:(0,ic._)`${r} === ${h}`}}};dg.default=UL});var eE=x(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var zL=HC(),KL=BC(),JL=UC(),GL=zC(),YL=KC(),XL=JC(),QL=GC(),ZL=XC(),eW=QC(),tW=ZC(),rW=[zL.default,KL.default,JL.default,GL.default,YL.default,XL.default,QL.default,ZL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eW.default,tW.default];fg.default=rW});var mg=x(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.validateAdditionalItems=void 0;var Qi=pe(),pg=be(),nW={message:({params:{len:e}})=>(0,Qi.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Qi._)`{limit: ${e}}`},iW={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:nW,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,pg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}tE(e,n)}};function tE(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,pg.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:pg.Type.Num},f),o.allErrors||r.if((0,Qi.not)(f),()=>r.break())})}}sc.validateAdditionalItems=tE;sc.default=iW});var hg=x(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.validateTuple=void 0;var rE=pe(),Xu=be(),sW=wr(),oW={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return nE(e,"additionalItems",t);r.items=!0,!(0,Xu.alwaysValidSchema)(r,t)&&e.ok((0,sW.validateArray)(e))}};function nE(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,rE._)`${s}.length`);r.forEach((d,p)=>{(0,Xu.alwaysValidSchema)(c,d)||(n.if((0,rE._)`${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)}}}oc.validateTuple=nE;oc.default=oW});var iE=x(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var aW=hg(),cW={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,aW.validateTuple)(e,"items")};gg.default=cW});var oE=x(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var sE=pe(),lW=be(),uW=wr(),dW=mg(),fW={message:({params:{len:e}})=>(0,sE.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,sE._)`{limit: ${e}}`},pW={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:fW,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,lW.alwaysValidSchema)(n,t)&&(i?(0,dW.validateAdditionalItems)(e,i):e.ok((0,uW.validateArray)(e)))}};wg.default=pW});var aE=x(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var vr=pe(),Qu=be(),mW={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}}`},hW={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:mW,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)))}}};yg.default=hW});var uE=x(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.validateSchemaDeps=tn.validatePropertyDeps=tn.error=void 0;var vg=pe(),gW=be(),ac=wr();tn.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,vg.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,vg._)`{property: ${e},
|
|
147
|
+
missingProperty: ${n},
|
|
148
|
+
depsCount: ${t},
|
|
149
|
+
deps: ${r}}`};var wW={keyword:"dependencies",type:"object",schemaType:"object",error:tn.error,code(e){let[t,r]=yW(e);cE(e,t),lE(e,r)}};function yW({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 cE(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,ac.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,ac.checkReportMissingProp)(e,f)}):(r.if((0,vg._)`${l} && (${(0,ac.checkMissingProp)(e,c,s)})`),(0,ac.reportMissingProp)(e,s),r.else())}}tn.validatePropertyDeps=cE;function lE(e,t=e.schema){let{gen:r,data:n,keyword:i,it:s}=e,o=r.name("valid");for(let c in t)(0,gW.alwaysValidSchema)(s,t[c])||(r.if((0,ac.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))}tn.validateSchemaDeps=lE;tn.default=wW});var fE=x(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var dE=pe(),vW=be(),kW={message:"property name must be valid",params:({params:e})=>(0,dE._)`{propertyName: ${e.propertyName}}`},bW={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kW,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,vW.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,dE.not)(s),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(s)}};kg.default=bW});var Rg=x(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var Zu=wr(),Lr=pe(),RW=bn(),ed=be(),SW={message:"must NOT have additional properties",params:({params:e})=>(0,Lr._)`{additionalProperty: ${e.additionalProperty}}`},CW={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:SW,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} === ${RW.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)}}};bg.default=CW});var hE=x(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var EW=za(),pE=wr(),Sg=be(),mE=Rg(),AW={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&&mE.default.code(new EW.KeywordCxt(s,mE.default,"additionalProperties"));let o=(0,pE.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Sg.mergeEvaluated.props(t,(0,Sg.toHash)(o),s.props));let c=o.filter(d=>!(0,Sg.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,pE.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)}}};Cg.default=AW});var vE=x(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var gE=wr(),td=pe(),wE=be(),yE=be(),xW={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,gE.allSchemaProperties)(r),l=c.filter(h=>(0,wE.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,yE.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,wE.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,g=>{t.if((0,td._)`${(0,gE.usePattern)(e,h)}.test(${g})`,()=>{let w=l.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:yE.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())})})}}};Eg.default=xW});var kE=x(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var _W=be(),IW={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,_W.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"}};Ag.default=IW});var bE=x(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var PW=wr(),OW={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:PW.validateUnion,error:{message:"must match a schema in anyOf"}};xg.default=OW});var RE=x(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var rd=pe(),TW=be(),NW={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,rd._)`{passingSchemas: ${e.passing}}`},$W={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:NW,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,TW.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)})})}}};_g.default=$W});var SE=x(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var jW=be(),DW={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,jW.alwaysValidSchema)(n,s))return;let c=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(c)})}};Ig.default=DW});var AE=x(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var nd=pe(),EE=be(),qW={message:({params:e})=>(0,nd.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,nd._)`{failingKeyword: ${e.ifClause}}`},LW={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qW,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,EE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=CE(n,"then"),s=CE(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 CE(e,t){let r=e.schema[t];return r!==void 0&&!(0,EE.alwaysValidSchema)(e,r)}Pg.default=LW});var xE=x(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var WW=be(),MW={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,WW.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Og.default=MW});var _E=x(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var FW=mg(),HW=iE(),BW=hg(),VW=oE(),UW=aE(),zW=uE(),KW=fE(),JW=Rg(),GW=hE(),YW=vE(),XW=kE(),QW=bE(),ZW=RE(),eM=SE(),tM=AE(),rM=xE();function nM(e=!1){let t=[XW.default,QW.default,ZW.default,eM.default,tM.default,rM.default,KW.default,JW.default,zW.default,GW.default,YW.default];return e?t.push(HW.default,VW.default):t.push(FW.default,BW.default),t.push(UW.default),t}Tg.default=nM});var IE=x(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var Ze=pe(),iM={message:({schemaCode:e})=>(0,Ze.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Ze._)`{format: ${e}}`},sM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iM,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 S=a.$async?(0,Ze._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,Ze._)`${w}(${n})`,E=(0,Ze._)`(typeof ${w} == "function" ? ${S} : ${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(S());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 S(){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})`}}}};Ng.default=sM});var PE=x($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var oM=IE(),aM=[oM.default];$g.default=aM});var OE=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 NE=x(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var cM=FC(),lM=eE(),uM=_E(),dM=PE(),TE=OE(),fM=[cM.default,lM.default,(0,uM.default)(),dM.default,TE.metadataVocabulary,TE.contentVocabulary];jg.default=fM});var jE=x(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});id.DiscrError=void 0;var $E;(function(e){e.Tag="tag",e.Mapping="mapping"})($E||(id.DiscrError=$E={}))});var qE=x(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var no=pe(),Dg=jE(),DE=qu(),pM=Ka(),mM=be(),hM={message:({params:{discrError:e,tagName:t}})=>e===Dg.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}}`},gM={keyword:"discriminator",type:"object",schemaType:"object",error:hM,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:Dg.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:Dg.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 S=0;S<o.length;S++){let E=o[S];if(E?.$ref&&!(0,mM.schemaHasRulesButRef)(E,s.self.RULES)){let z=E.$ref;if(E=DE.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,z),E instanceof DE.SchemaEnv&&(E=E.schema),E===void 0)throw new pM.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,S)}if(!g)throw new Error(`discriminator: "${c}" must be required`);return m;function w({required:S}){return Array.isArray(S)&&S.includes(c)}function k(S,E){if(S.const)b(S.const,E);else if(S.enum)for(let O of S.enum)b(O,E);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function b(S,E){if(typeof S!="string"||S in m)throw new Error(`discriminator: "${c}" values must be unique strings`);m[S]=E}}}};qg.default=gM});var LE=x((h6,wM)=>{wM.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 ME=x((Me,Lg)=>{"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 yM=jC(),vM=NE(),kM=qE(),WE=LE(),bM=["/properties"],sd="http://json-schema.org/draft-07/schema",io=class extends yM.default{_addVocabularies(){super._addVocabularies(),vM.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(kM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(WE,bM):WE;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;Lg.exports=Me=io;Lg.exports.Ajv=io;Object.defineProperty(Me,"__esModule",{value:!0});Me.default=io;var RM=za();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return RM.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 SM=ju();Object.defineProperty(Me,"ValidationError",{enumerable:!0,get:function(){return SM.default}});var CM=Ka();Object.defineProperty(Me,"MissingRefError",{enumerable:!0,get:function(){return CM.default}})});nf();cf();nr();of();import{promises as tf}from"fs";import Tt from"path";import{promises as fy}from"node:fs";import NI from"node:path";nr();import{createHash as CI}from"node:crypto";import{lstatSync as Po,readFileSync as EI,realpathSync as ly}from"node:fs";import AI from"node:os";import Nt from"node:path";function uf(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function Wc(e){return process.platform==="win32"?ly.native(e):ly(e)}var xI=Vr("workspaceIdentity",II);function _I(e){return xI(e)}function II(e){let t=Wc(Nt.resolve(e)),r=Po(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=uf(r),i=(l,f)=>({projectRoot:t,workspaceId:CI("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,l,f])).digest("hex")}),s=Nt.join(t,".git"),o,c;try{let l=Po(s);if(l.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${s}`);if(l.isDirectory())o=Wc(s),c=uf(Po(o,{bigint:!0}));else if(l.isFile()){let f=/^gitdir: (.+)\r?\n?$/u.exec(EI(s,"utf8"));if(!f)throw new Error(`工作区 .git 文件格式无效:${s}`);o=Wc(Nt.resolve(t,f[1].trim()));let a=Po(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{Po(s)}catch(f){if(f.code==="ENOENT")return i(s,null);throw f}throw l}return i(o,c)}function uy(e){let t=Nt.dirname(e);if(t===e)return e;try{return Nt.join(Wc(t),Nt.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return Nt.join(uy(t),Nt.basename(e))}}var PI=Vr("workspaceRuntimeParent",uy);function df(e){let t=_I(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!Nt.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=PI(r??Nt.join(AI.homedir(),".comet")),i=Nt.relative(t.projectRoot,n);if(i===""||!Nt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Nt.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let s=Nt.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:s,runtimeRoot:Nt.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=NI.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();$t();Ri();ye();import{promises as NN}from"node:fs";import{AsyncLocalStorage as $N}from"node:async_hooks";import Pr from"node:path";var ua="comet.change-owner.v1",_b=["native","classic-full","classic-hotfix","classic-tweak"],jN=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===ua&&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 la(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 DN(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 ht(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 qN(e,t,r){let n;try{n=await lm(e,t,r)}catch(s){if(s instanceof kt&&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 $N,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)??jN(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?ay(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 qN(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 LN(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 NN.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 Hz=je("changeOwnerPartitions",LN);async function WN(e,t,r){return oy(),Oi.run(null,()=>Pn(async()=>{let n=await Ur(e);return Or(t.workflow,t.change),r(n)}))}async function MN(e,t,r={}){let n=Or(t.workflow,t.change),i=cm(t,t.workflow,t.change);return WN(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 ht(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 DN(s,i),i})}function zl(e,t,r={}){return MN(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 JN=new Set([".md",".markdown"]);function gm(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 GN=new Set([".md",".markdown",".rst",".txt"]),YN=new Set(["docs","doc","documentation",".github"]),XN=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function Yl(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function QN(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 Mb(e,t=[]){let r=Yl(e);if(hm(r)||!r||r.endsWith("/")||QN(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?JN.has(o)||XN.some(c=>c.test(i)):YN.has(n[0])&&GN.has(o)}nr();import{promises as ZN}from"node:fs";import wm from"node:path";var Fb="comet-state.yaml",Xl=".comet.yaml",Ns=[Fb,Xl],fa=class extends Error{};function pa(e){return Ns.some(t=>t===e)}async function e$(e,t={}){let r=[],n=[];for(let i of Ns)try{let s=await ZN.lstat(wm.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 fa(`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: ${wm.join(e,n[0])}`);return wm.join(e,r[0]??t.defaultFileName??Fb)}var t$=je("classicStateFile",(e,t)=>e$(e,t));async function fe(e,t={}){return t$(e,t)}import{AsyncLocalStorage as Vb}from"node:async_hooks";import{performance as Hb}from"node:perf_hooks";var r$=0,n$=0,ym=new Vb,Bb=new Vb;async function Ub(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(Bb.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 Bb.run(r,e)}finally{clearInterval(i)}}function i$(e=0){r$+=1,n$+=e;for(let t of ym.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}async function zb(e){let t={gitCommands:0,gitDurationMs:0};return{result:await ym.run([...ym.getStore()??[],t],e),metrics:t}}function Gr(e){let t=Hb.now();try{return e()}finally{i$(Hb.now()-t)}}var qm=vt(jt(),1);nr();import{execFileSync as Dm}from"child_process";import{promises as dj}from"fs";import fj from"path";nr();import{randomUUID as ej}from"node:crypto";ye();import{promises as Xb}from"fs";import Ye from"path";import u$ from"os";import{promises as s$}from"fs";async function Ql(e){try{return await s$.access(e),!0}catch(t){if(o$(t))return!1;throw t}}function o$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}Dt();mn();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"}},Gb=".comet/config.yaml";function bm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ma(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 Qb(e){let t=await pn(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 Yr(e,t){return ma(e,t??await Qb(e))}async function d$(e){try{return await Xb.lstat(e),!0}catch(t){if(bm(t))return!1;throw t}}async function f$(e,t){let r=await Yr(e,t),n=r.artifactLayout==="legacy"?"docs":"legacy",i=ma(e,n).openSpecRoot,[s,o]=await Promise.all([U(r.projectRoot,Ae(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),d$(i)]),c=s.exists;return{paths:r,configuredRootExists:c,alternateRoot:i,alternateRootExists:o,dualRoots:c&&o}}async function p$(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=Ae(e.projectRoot,r);await U(e.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function gt(e,t){let r=await f$(e,t);if(await p$(r.paths),!r.configuredRootExists){let n=Ae(r.paths.projectRoot,r.paths.openSpecRoot),i=Ae(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 gt(e,t);if(!await Ql(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${Ae(n.projectRoot,n.openSpecRoot)}`);return n}async function lt(e){let t=Ye.resolve(e),r=null;try{(await Xb.lstat(t)).isDirectory()||(t=Ye.dirname(t))}catch(s){if(!bm(s))throw s}let n=t,i=Ye.resolve(u$.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,Gb,dn,{label:Gb});c=f.toString("utf8")}catch(f){if(!bm(f))throw f}if(c!==null)try{let f=fn(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 Ae(e,t){return Ye.relative(Ye.resolve(e),t).replaceAll("\\","/")}ou();var Om=["full","hotfix","tweak"],Li=1,Tm=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u,Nm=`# comet-execution: managed-run
|
|
152
|
+
`;function ir(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}var gR=["open","design","build","verify","archive"],$$=["en","zh-CN"],j$=["off","beta"],D$=["subagent-driven-development","executing-plans","direct","autonomous"],q$=["plan-ready"],L$=["confirmed"],W$=["tdd","direct"],M$=["off","standard","thorough"],F$=["current","branch","worktree"],H$=["light","full"],B$=["pending","pass","fail"],V$=["pending","handled"],U$=["pending","confirmed"],Jn=["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"],ka=["change_id","run_id","run_checkpoint","application_checkpoint"],wR=new Set([...Jn,...ka]),z$=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Im(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 qt(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 Pm(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 hR(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 K$(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 J$(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 G$(e){if(!Jn.some(r=>Im(e,r)))return null;for(let r of z$)if(!Im(e,r))return null;return{workflow:qt(e,"workflow",Om,!1),language:qt(e,"language",$$),phase:qt(e,"phase",gR,!1),contextCompression:qt(e,"context_compression",j$),buildMode:qt(e,"build_mode",D$),buildPause:qt(e,"build_pause",q$),subagentDispatch:qt(e,"subagent_dispatch",L$),tddMode:qt(e,"tdd_mode",W$),reviewMode:qt(e,"review_mode",M$),isolation:qt(e,"isolation",F$),boundBranch:Ds(e,"bound_branch"),verifyMode:qt(e,"verify_mode",H$),autoTransition:Pm(e,"auto_transition"),baseRef:Ds(e,"base_ref"),designDoc:au(e,"design_doc"),plan:au(e,"plan"),verifyResult:qt(e,"verify_result",B$,!1),verifyFailures:hR(e,"verify_failures"),...Im(e,"check_epoch")?{checkEpoch:hR(e,"check_epoch")}:{},verificationReport:au(e,"verification_report"),branchStatus:qt(e,"branch_status",V$),createdAt:Ds(e,"created_at"),verifiedAt:Ds(e,"verified_at"),archiveConfirmation:qt(e,"archive_confirmation",U$),archived:Pm(e,"archived",!1),directOverride:Pm(e,"direct_override"),handoffContext:au(e,"handoff_context"),handoffHash:K$(e,"handoff_hash"),classicProfile:qt(e,"classic_profile",Om),classicMigration:J$(e)}}function ur(e,t){if(e.change_id!==void 0&&(typeof e.change_id!="string"||!Tm.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:G$(e),run:r,unknownKeys:Object.keys(e).filter(n=>!wR.has(n))}}function yR(e){let t=e.workflow,r=e.phase,n=e.archived,i=e.design_doc;return{workflow:typeof t=="string"&&Om.includes(t)?t:null,phase:typeof r=="string"&&gR.includes(r)?r:null,archived:n===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(e).filter(s=>!wR.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 vR=vt(jt(),1);$t();ye();import{createHash as Y$,randomUUID as X$}from"node:crypto";import xe from"node:path";var $m=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=Y$("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 kR(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,vR.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"||!Tm.test(o)))throw new Error("Invalid Classic change_id: expected an immutable UUID");return{source:i,document:s,id:o}}async function Q$(e,t){let r=await fe(t),n=xe.relative(e,r).replaceAll("\\","/"),i=()=>kR(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}`):X$();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 jm(e,t,r={}){let n=t??await lt(e),i;try{i=await kR(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 Ce(e,t){return Z$(e,t)}async function Z$(e,t){let r=t??await lt(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 Q$(r,e),o=xe.join(i,"classic-changes",s);return await ht(i,xe.relative(i,o),{label:"Classic local Run directory"}),o}async function ba(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||!$m.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 jm(f,e,{includeMissing:!0}):await Ce(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 Ca=vt(jt(),1);$t();ye();import Xr from"path";import{AsyncLocalStorage as tj}from"node:async_hooks";ou();var bR=new tj,Ra=".comet-state-transaction.json";async function Nr(e,t){let r=await Ce(e);return bR.getStore()===r?t():bR.run(r,async()=>(await SR(e),t()))}async function Sa(e,t){let r=t===Ra?await Ce(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 rj(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 SR(e){let t=await Sa(e,Ra);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"||!pa(i)||Xr.basename(n)!==i)throw new Error("Classic state transaction belongs to a different state filename; preserve files for recovery");let s=await Sa(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=rj(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 Ce(e),o):await va(await Ce(e));let c=await Ce(e);await zr(Xr.join(c,Ra),{containedRoot:c})}function CR(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 Gn(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 RR(e,t,r){e.get(t)!==r&&e.set(t,r)}function ER(e,t){if(t.classic)for(let[r,n]of Object.entries(cu(t.classic)))r==="auto_transition"&&n===null&&!e.has(r)||RR(e,r,n);else for(let r of Jn)e.delete(r);_m(e.toJS(),t.run),t.run?RR(e,"run_id",t.run.runId):e.delete("run_id")}function nj(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 AR(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(Xr.dirname(e),Xr.basename(e),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(n){if(n.code!=="ENOENT")throw n;return new Ca.Document({})}let r=(0,Ca.parseDocument)(t);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return Gn(r),r}var ij=je("classicStateProjection",e=>sj(e));async function dr(e,t={}){return t.migrate===!1?ij(e):Nr(e,()=>oj(e,t))}async function sj(e){let t=await jm(e);if(t===null)return ur({});if((await U(t,Ra,{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));AR(r);let n=Gn(r),i=await ya(t);return!i&&n.run_id&&n.skill&&(i=Di(n)),CR(n,i),ur(n,i)}async function oj(e,t){let r=t.migrate!==!1,n=await fe(e),i=await uu(n),s=Gn(i),o=AR(i);o&&(s=Gn(i));let c=await ya(await Ce(e));if(CR(s,c),!c&&s.run_id&&s.skill){let{runStateFromDocument:l}=await Promise.resolve().then(()=>(ou(),mR));c=l(s),c&&r&&(await qi(await Ce(e),c),nj(i),o=!0)}return o&&r&&await Te(n,i.toString(),{containedRoot:e}),ur(Gn(i),c)}async function xR(e){let t=await uu(await fe(e));return yR(Gn(t))}async function qs(e,t,r={}){let n=await fe(e,{defaultFileName:Xl});if(await Sa(e,Xr.basename(n))===null){let i=new Ca.Document({change_id:ej()});ER(i,{...t,unknownKeys:t.unknownKeys??[]}),ur(Gn(i),t.run??null);let s=await lt(e),o=await Ur(s),c=await ht(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,()=>aj(e,t,r))}async function aj(e,t,r){let n=await fe(e),i=await Sa(e,Xr.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",Xr.basename(await Ce(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");ER(s,{...t,unknownKeys:t.unknownKeys??[]}),ur(Gn(s),t.run??null);let c=await Sa(e,Xr.basename(n)),l=s.toString();if(c===l){await r.beforeCommit?.(),t.run?await qi(await Ce(e),t.run):await va(await Ce(e));return}let f=await Ce(e),a=Xr.join(f,Ra);await Te(a,JSON.stringify({schema:"comet.classic.state-transaction.v1",stateFile:Xr.basename(n),beforeYaml:c,afterYaml:l,beforeRun:await ya(await Ce(e)),afterRun:t.run}),{containedRoot:f});try{t.run?await qi(await Ce(e),t.run):await va(await Ce(e)),await Te(n,l,{containedRoot:e,beforeCommit:r.beforeCommit})}catch(d){throw await SR(e).catch(()=>{}),d}await zr(a,{containedRoot:f}).catch(()=>{})}import Ls from"path";import{AsyncLocalStorage as cj}from"node:async_hooks";$t();Dt();ye();var Ea=Number.MAX_SAFE_INTEGER,lj=new cj;async function uj(e,t){let r=lj.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,Ea),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 ba(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 Lt(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 Lt(e,t,{label:r,expected:"file"})?(await _R(e,t,{label:r,hooks:n})).byteLength>0:!1}async function Pe(e,t,r){return(await _R(e,t,r)).toString("utf8")}async function _R(e,t,r){let n=await du(e,t,r.label);if(!r.hooks){let i=await uj(n.root,n.relative);if(i){if(i.bytes.length>(r.maxBytes??Ea))throw new Error(`${r.label} exceeds the read limit`);return i.bytes}}return(await ae(n.root,n.relative,r.maxBytes??Ea,{label:r.label,hooks:r.hooks})).bytes}async function fu(e,t,r){let n=await du(e,t,r,!0);return ht(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})}$t();ye();function fr(e){let t={cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0};try{let r=Gr(()=>Dm("git",["rev-parse","--abbrev-ref","HEAD"],t).trim());if(r&&r!=="HEAD")return r}catch{}try{return Gr(()=>Dm("git",["symbolic-ref","--quiet","--short","HEAD"],t).trim())||null}catch{return null}}var pj=Vr("liveGitBranch",e=>fr(e));function Xn(e){try{return Gr(()=>Dm("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 mj=Vr("isGitWorkTree",e=>Xn(e)),hj=["current","branch","worktree"];function Aa(e){return hj.includes(e)}function gn(e){return Aa(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 xa(e,t){return t.heal?Nr(e,()=>IR(e,t)):IR(e,t)}async function IR(e,t){let r=await fe(e),n=(0,qm.parseDocument)(await dj.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=Aa(s),l=pj(t.cwd),f=c&&o===null&&l===null?mj(t.cwd):!0,a=gn({isolation:s,boundBranch:o,currentBranch:l,gitWorkTree:f});return a.status==="needs-heal"&&t.heal?(await gj(e,a.branch),{status:"healed",branch:a.branch,bindingRequired:c,currentBranch:l}):{...a,bindingRequired:c,currentBranch:l}}async function gj(e,t){return Nr(e,()=>wj(e,t))}async function wj(e,t){let r=await fe(e),n=(await ae(e,fj.basename(r),Ea,{label:"Classic branch binding"})).bytes.toString("utf8"),i=(0,qm.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 yj(e){return e??"detached HEAD"}function Ws(e,t,r){return`change '${e}' is bound to branch '${t}', but current branch is '${yj(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.`}ha();nr();import{randomUUID as Pj}from"node:crypto";import{types as vj}from"node:util";import{createHash as kj}from"node:crypto";var PR=new WeakMap,OR=new WeakMap;function TR(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=OR.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&OR.set(e,n),n}function bj(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=TR(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),S=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,S),S};for(let w of t){let k=s,b=e;for(let J of w.path.slice(0,-1)){b=b[J];let G=i(b);Object.defineProperty(k,J,{value:G,enumerable:!0,writable:!0,configurable:!0}),k=G}let S=w.path.at(-1),E=k[S];if(!E||typeof E!="object"||Array.isArray(E))continue;if(r?.(E)){let J=PR.get(E);if(!J){let G=E,te=u.get(w.group),Z=Object.entries(G),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(G,ze)):[],ne=te&&we.length+K.length<Z.length;J={...ne?{base:te.node}:{},entries:ne?we:Z,removed:ne?K:[]},PR.set(E,J)}u.set(w.group,{source:E,node:J}),l.push({path:w.path,map:g(J)}),Object.defineProperty(k,S,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let O=new Map;for(let[J,G]of Object.entries(E)){let te=G&&typeof G=="object"?d.get(G):void 0;if(te===void 0){let Z=TR(G,r);te=f.get(Z),te===void 0&&(te=o.length,o.push(G),f.set(Z,te)),G&&typeof G=="object"&&d.set(G,te)}O.set(J,te)}let z=JSON.stringify([...O]),D=a.get(z);if(D===void 0){let J=p.get(w.group),G=[...O].filter(([we,K])=>J?.entries.get(we)!==K),te=J?[...J.entries.keys()].filter(we=>!O.has(we)):[],Z=J&&G.length+te.length<O.size;D=c.length,c.push({...Z?{base:J.id}:{},entries:Z?G:[...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,S,{value:{},enumerable:!0,writable:!0,configurable:!0})}return l.length?{record:s,pool:{version:1,values:o,maps:c,bindings:l}}:{record:s}}function Rj(){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 $R(e){let{nodes:t,set:r}=Rj(),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 jR(e,t,r){let n=bj(e,t,r);return{record:n.record,...n.pool?{pool:$R(n.pool)}:{}}}var wn=new WeakMap,_a=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 Sj(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 DR(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])}),DR($R(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 Cj(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||vj.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=DR(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:Sj({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 S=d.get(b);if(S!==void 0)return S;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,S)=>Math.max(b,1+p(S)),0);return a.set(m,k),k};p(i)>64&&Xe("JSON 逻辑数据嵌套超过 64 层"),Ia(n),Ia(i);let u=m=>{if(!(!m||typeof m!="object"||wn.has(m)||_a.has(m))){_a.set(m,s);for(let h of Object.values(m))u(h)}};return u(i),{value:i,stats:s,materialize:(m=[])=>Gt(m.reduce((h,g)=>h?.[g],i)),hash:()=>Rt(i)}}function Ia(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 Gt(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,Gt(i)]))}return Array.isArray(e)?e.map(Gt):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Gt(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 Ej(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 NR=new WeakMap;function Rt(e,t={}){let r=kj("sha256"),n=e&&typeof e=="object"?_a.get(e):void 0,i=f=>{if(!f||typeof f!="object")return;let a=wn.get(f)?.stats??_a.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?NR.get(n):void 0;n&&!s&&t.cachePrefixes!==!1&&(s={root:{hash:r.copy(),next:new Map},size:0},NR.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("{"),Ej(f).forEach((a,d)=>{d&&c(","),c(JSON.stringify(a)+":"),l(f[a])}),c("}")};return l(e),r.digest("hex")}function Pa(e){return _a.get(e)??wn.get(e)?.stats}function gu(e,t,r=!0){let n=Cj(e,t);return r?n.materialize():n.value}var qR=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(qR,r)?qR[r]:"manual-review"}code;recovery};import{createHash as Aj}from"node:crypto";import{types as xj}from"node:util";var Lm=new WeakMap,LR=new WeakMap;function pr(e){return Lm.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(xj.isProxy(c))throw new v("INVALID_JSON","仅接受无执行行为的 JSON 数据");let f=Lm.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),Lm.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 S=o(b.value,l+1);d=Math.max(d,1+p(b.value)),(t||r)&&w.push(S)}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),S=String(k),E=String(Number(b))===b&&Number.isInteger(Number(b))&&Number(b)>=0&&Number(b)<4294967295,O=String(Number(S))===S&&Number.isInteger(Number(S))&&Number(S)>=0&&Number(S)<4294967295;return E||O?E&&O?Number(b)-Number(S):E?-1:1:b<S?-1:b>S?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 Ge(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?LR.get(e):void 0;if(r!==void 0)return r;let n=Aj("sha256").update(yn(e)).digest("hex");return t&&LR.set(e,n),n}function Mi(e){return wu(e,!1,!1,!0),e}function ut(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new v("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function Qr(e){return pr(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Wm(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new v("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Mm(e){return["succeeded","failed","cancelled"].includes(e.status)}function WR(e){return MR(e,e.input)}function MR(e,t,r){for(let o of["id","runId","stepId","type"])ut(e[o],o);e.ref!==void 0&&ut(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)ut(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 FR(e,t){Wm(e,t.attempt,t.inputHash),ut(t.executorId,"executorId"),ut(t.token,"token"),t.sessionId!==void 0&&ut(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 Qr(e);throw new v("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new v("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...Qr(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Fm(e,t){if(t=yu(t),ut(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new v("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&ut(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:Qr(e),duplicate:!0}}if(Wm(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new v("STALE_ACTION","结果不属于当前 Action");if(Mm(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(ut(s.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(s.sha256))throw new v("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...Qr(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function HR(e,t){if(ut(t,"reason"),!["running","unknown"].includes(e.status))throw new v("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...Qr(e),status:"unknown",reason:t}}function BR(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=Qr(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:Ge(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 Hm(e,t){return ut(t,"reason"),Mm(e)?Qr(e):{...Qr(e),status:"cancelled",reason:t}}function VR(e,t){$r(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])ut(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new v("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Wm(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new v("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function Bm(e,t){if(VR(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{...Qr(e),cancellation:structuredClone(t)}}function Vm(e,t){if(VR(e,t),!Mm(e))throw new v("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&j(e.executionStop)!==j(t))throw new v("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Qr(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=Ge(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=MR(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&&ut(r.reason,"reason"),r.claim!==void 0&&($r(r.claim,["executorId","sessionId","token"]),ut(r.claim.executorId,"executorId"),ut(r.claim.token,"token"),r.claim.sessionId!==void 0&&ut(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"]),ut(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),ut(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&&Bm({...r,input:null},r.cancellation),r.executionStop!==void 0&&Vm({...r,input:null},r.executionStop);let i=new Set;for(let o of r.receipts){if($r(o,["outcomeId","hash"]),ut(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","终态结果与已接受摘要不一致");Fm({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new v("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}function Um(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}var JR=new WeakSet,GR=new WeakSet,zm=new WeakSet,UR=["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 zR(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 Oa(e,t,r){let n=nt(e,t);if(!r&&pr(n)&&GR.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 KR(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:Oa(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 _j(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:Oa(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&&!Um(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 Ij(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:Oa(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(Ge(e),"WorkflowRun");return Ru(r,t)}function YR(e,t){if(e&&typeof e=="object"&&zm.has(e)&&pr(e)){let r=e;return t!==void 0&&r.runId!==t&&X("WorkflowRun.runId 与存储键不一致"),r}return mr(e),XR(Ru(nt(structuredClone(e),"WorkflowRun"),t))}function Ta(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&&zm.has(t)&&pr(t)?t:void 0),XR(e)}function XR(e){Mi(e),zm.add(e);for(let r of e.actions)JR.add(r);let t=r=>GR.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,UR,"WorkflowRun");for(let P of UR.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=zR(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=>_j(P,i,o,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&X("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(P=>Ij(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 S=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))&&!((S.get(P)??1/0)<=re)){S.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=Oa(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=>KR(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=KR(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]})),J=Oa(e.outputs,"WorkflowRun.outputs",n);E(J),Array.isArray(e.children)||X("WorkflowRun.children 必须是数组");let G=e.children.map(P=>{let F=nt(P,"WorkflowRun.children item");hr(F,["actionId","runId","workflow"],"WorkflowRun.children item");let re=zR(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(G.map(P=>P.actionId)).size!==G.length||d.filter(P=>P.type==="child_workflow").length!==G.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:J,children:G,lineage:a,...e.reason===void 0?{}:{reason:e.reason}}}var QR=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}`);Pa(r)||(mr(r),r=structuredClone(r),Ia(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=Ta(n,t,{hash:Rt,visitResults:mu,validateOrigins:hu})}catch(c){throw c instanceof v?c:new v("INVALID_RUN",c instanceof Error?c.message:String(c))}Ia(i);let s=Pa(r);s&&(s.validationActions=i.actions.length,s.validationMaterializedEntries=s.materializedEntries);let o=e.queryScope??QR.get(e);return o||(o=Pj(),QR.set(e,o)),Object.freeze({record:r,run:i,scope:o,stats:s,materialize:(c=[])=>Gt(c.reduce((l,f)=>l?.[f],i)),hash:()=>Rt(i)})}var Zn=e=>{throw new v("INVALID_REQUEST",e)};function Km(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 Gt({...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 Gt({...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 Gt({...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"),Gt({...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 超出历史范围"),{...Gt(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 Bg}from"node:crypto";import{types as zg}from"node:util";var Mg=vt(ME(),1);var et=vt(eg(),1),EM=(()=>{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})(),AM=(()=>{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})(),xM=(()=>{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})(),_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:["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})(),IM=(()=>{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})(),PM=(()=>{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})(),OM=(()=>{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})(),TM=(()=>{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})(),NM=(()=>{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})(),$M=(()=>{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})(),jM=(()=>{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})(),DM=(()=>{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})(),qM=(()=>{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})(),LM=(()=>{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})(),WM=(()=>{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})(),FE=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"}',EM],['{"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"}',AM],['{"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"}',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":["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"}',_M],['{"additionalProperties":false,"properties":{"archiveDirectory":{"minLength":1,"type":"string"}},"required":["archiveDirectory"],"type":"object"}',IM],['{"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"}',PM],['{"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"}',OM],['{"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"}',TM],['{"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"}',NM],['{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"}},"required":["contentHash"],"type":"object"}',$M],['{"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"}',jM],['{"properties":{"buildPause":{"enum":["plan-ready"]},"plan":{"minLength":1,"type":"string"}},"required":["plan"],"type":"object"}',DM],['{"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"}',qM],['{"properties":{"designDoc":{"minLength":1,"type":"string"}},"required":["designDoc"],"type":"object"}',LM],['{"properties":{"handoffContext":{"minLength":1,"type":"string"},"handoffHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"proposal":{"minLength":1,"type":"string"}},"required":["proposal"],"type":"object"}',WM]]);var MM=128,HE=1024*1024,Zi=new Map,Wg=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=FE.get(t)??new Mg.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),s={validate:i,errorsText:()=>Mg.Ajv.prototype.errorsText(i.errors)};if(t.length<=HE){for(;Zi.size>=MM||Wg+t.length>HE;){let o=Zi.keys().next().value;Zi.delete(o),Wg-=o.length}Zi.set(t,s),Wg+=t.length}return s}var FM=["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 cc(e,t,r){for(let n of Object.keys(e))t.includes(n)||it(`${r} 包含不支持的字段:${n}`)}function xt(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&it(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Fg(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&it(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>xt(i,t));return new Set(n).size!==n.length&&it(`${t} 不能包含重复值`),n}function Hg(e,t){return Fg(typeof e=="string"?[e]:e,t)}function lc(e,t){let r=ai(e,t);return cc(r,["id","version"],t),{id:xt(r.id,`${t}.id`),version:xt(r.version,`${t}.version`)}}function VE(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))VE(t);Object.freeze(e)}return e}function UE(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 HM(e){let t=ai(e,"step"),r=xt(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"]:[];cc(t,[...FM,...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:xt(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:lc(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:Fg(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:Fg(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&UE(t.outputSchema,"outputSchema"),r==="ask_user"?{...s,type:r,proposalFrom:Hg(t.proposalFrom,"step.proposalFrom"),choices:Hg(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...s,type:r,workflow:lc(t.workflow,"step.workflow")}:r==="await_evidence"?(s.validator||it("await_evidence 必须声明验证器"),{...s,type:r,kind:xt(t.kind,"step.kind"),validator:s.validator}):{...s,type:r,ref:xt(t.ref,"step.ref")}}var BE=new WeakSet;function Wr(e){if(BE.has(e))return e;let t=ai(Ge(e),"workflow");cc(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=xt(t.id,"workflow.id"),n=xt(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&&UE(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])=>(xt(h,"step id"),[h,HM(g)])));function o(h,g){Object.hasOwn(s,h)||it(`${g} 引用了不存在的步骤:${h}`)}let c=Hg(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)){xt(h,"workflow command name");let w=typeof g=="string"?{stepId:xt(g,`workflow.commands.${h}`)}:ai(g,`workflow.commands.${h}`);cc(w,["stepId","validator"],`workflow.commands.${h}`);let k=xt(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:lc(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");cc(g,["from","to","on"],"transition");let w=xt(g.from,"transition.from"),k=xt(g.to,"transition.to"),b=xt(g.on===void 0?"succeeded":g.on,"transition.on");o(w,"transition.from"),o(k,"transition.to");let S=JSON.stringify([w,k,b]);return d.has(S)&&it(`重复的状态转移:${w} -> ${k} (${b})`),d.add(S),{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=VE({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:lc(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:lc(t.transitionHandler,"workflow.transitionHandler")}});return BE.add(m),m}function uc(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 BM(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)&&uc(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)||uc(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=BM(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=WR({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),uc(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};uc(f,r,l),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&uc(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 zE(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"||zg.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=Ge(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new v("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function Kg(e,t=new Set){if(e===null||typeof e!="object")return e;if(zg.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:Kg(s.value,t)})}return t.delete(e),n}function Vg(e){if(e===null||typeof e!="object")return e;if(zg.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):Kg(n.value)})}return t}function es(e){let t=Kg(e),r=Ge(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 Ug(e,t){let r=e.supports(Oe(t));if(typeof r!="boolean")throw new v("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function rn(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 KE(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 R=Wr(y),_=Ue(R);if(t.has(_))throw new v("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(_,R);let A=JE.get(R);A===void 0&&(A=j(R),JE.set(R,A)),r.set(R,A)}let n=new Map;for(let y of e.validators??[]){let R=Ue(y);if(n.has(R))throw new v("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(R,y)}let i=new Map;for(let y of e.stateValidators??[]){let R=Ue(y);if(i.has(R))throw new v("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(R,y)}let s=new Map;function o(y){let R=s.get(y);return R||(R=od(y),s.set(y,R)),R}let c=new Map,l=new Map;for(let y of e.transitionHandlers??[]){let R=Ue(y);if(l.has(R))throw new v("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");l.set(R,y)}let f=new Map;for(let y of e.evidenceValidators??[]){let R=Ue(y);if(f.has(R))throw new v("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");f.set(R,y)}let a=new Map;for(let y of e.commandValidators??[]){let R=Ue(y);if(a.has(R))throw new v("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");a.set(R,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 R=t.get(Ue(y));if(!R)throw new v("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(y.hash!==void 0&&y.hash!==r.get(R))throw new v("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return R}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 R of Object.values(y.steps))if(R.type==="await_evidence"&&!f.has(Ue(R.validator)))throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function h(y){for(let R of Object.values(y.commands??{}))if(R.validator&&!a.has(Ue(R.validator)))throw new v("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(y,R,_){if(y.stateSchema!==void 0){let A=o(y.stateSchema);if(!A.validate(R))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:Ge(R)}));if(!I.accepted)throw new Error(I.reason??"业务状态未通过验证")}catch(I){throw new v(_,I instanceof Error?I.message:String(I))}}}function w(y,R,_,A){if(!R.transitionHandler)return;let I=l.get(Ue(R.transitionHandler));if(!I)throw new v("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let W=Ge(I.apply({run:Oe(y),event:Oe(_)})),M=Ge(W.state);g(R,M,"TRANSITION_STATE_INVALID");let B=new Set(R.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:Ge(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,R=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")||R(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,_o=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)||_o===void 0||R(q.results)!==R({...Ke,[q.from]:{sequence:Q.sequence,value:_o}})||!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 R=await e.store.read(y);if(!R)throw new v("RUN_NOT_FOUND",`找不到工作流实例:${y}`);let _=YR(R,y);return k(_),Mi(_)}async function S(y,R,_){for(let A=0;A<32;A+=1){rn(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=KE(I);if(await R(M,W),mr(M),ts(M,I))return I;if(M.revision=I.revision+1,bu(M,I),k(M),Mi(M),rn(y.context),await e.store.compareAndSwap(y.runId,I.revision,M))return M}throw new v("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function E(y,R){let _=y.actions.find(A=>A.id===R);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,R={}){let _=Ue(y);if(Object.hasOwn(R,_))return R;R[_]=r.get(y);for(let A of Object.values(y.steps))A.type==="child_workflow"&&z(d(A.workflow),R);return R}async function D(y,R){if(rn(y.context),R.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?Ge(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??Bg(),B=Ge(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(R)||(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:Ge(I),initialStateHash:W},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:_.entry.map(N=>({from:null,to:N,results:{}})),joins:{},outputs:{},children:[],lineage:R};return Sn(Q,_),Mi(Q),rn(y.context),bu(Q),k(Q),await e.store.compareAndSwap(M,null,Q)?Oe(Q):D({...y,runId:M},R)}async function J(y){return D(y,[])}async function G(y){let R=Ge(y.input),_=j(R);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){rn(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(R),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"?Hm(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:R}],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),rn(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 R of y.children)await e.store.read(R.runId)&&await T({runId:R.runId,reason:y.reason??"父工作流已取消"})}function Z(y,R,_){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(R.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||![R.runId,`portable-${j(R.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({...R.workflow,hash:y.definitionHashes[Ue(R.workflow)]});if(Object.entries(z(M)).some(([B,q])=>y.definitionHashes[B]!==q))throw new v("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return M}function we(y,R,_,A,I){let W=A.initialState===void 0?void 0:j(A.initialState);if(I.runId!==R.runId||Ue(I.workflow)!==Ue(R.workflow)||I.workflow.hash!==y.definitionHashes[Ue(R.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 R=await S(y,(_,A)=>Sn(_,A));if(R.status==="cancelled")return await te(R),R;if(R.status==="failed"||R.children.length===0)return R;for(let _ of R.children){let A=E(R,_.actionId);if(!["pending","running","unknown"].includes(A.status))continue;let I=Z(R,_,A);A.status==="pending"&&(R=await ne({runId:R.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(R,_.actionId));let W=A.status==="unknown"?await b(_.runId):await D({runId:_.runId,workflow:_.workflow,input:A.input,context:sr(y.context)},[...R.lineage,R.runId]);we(R,_,A,I,W);let M=await b(R.runId);if(M.status==="cancelled")return await te(M),M;let B=await K({runId:_.runId,context:y.context});we(R,_,A,I,B),["completed","failed","cancelled"].includes(B.status)&&(R=await P({runId:R.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(R.runId)}async function ne(y,R=!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}):Bg());return S(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"&&!R)throw new v("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let M=FR(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&&Ug(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)),rn(y.context)}}I.actions[I.actions.indexOf(W)]=M},_)}async function ze(y){return ne(y)}async function P(y,R=!1,_){let A,I;try{A=yu(y.outcome)}catch(B){I=B}y={...y,outcome:A};let W,M=await S(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"&&!R)throw new v("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let Q=Fm(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=KE(B);ue.actions[oe]=Q.action;let Ke=ue.actionContexts[V.id],_o=N.status==="failed"?"failed":N.event??"succeeded",Bt=w(ue,q,{kind:"action-outcome",stepId:V.stepId,outcome:N},_o);oo(ue,q,V.stepId,Ke.sequence,Ke.results,N.output,_o,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&&!Um(y.reason))throw new v("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return S(y,(R,_)=>{O(R);let A=R.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(R,_,{kind:"wait-resolved",stepId:A.stepId,choice:y.choice,proposalHash:y.proposalHash,decisionId:y.decisionId},y.choice);oo(R,_,A.stepId,A.sequence,A.results,{choice:y.choice,proposal:A.proposal},y.choice,I),Sn(R,_)})}async function He(y){return S(y,async(R,_)=>{if(O(R),R.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止,不能提交证据");let A=R.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(R),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(R,_,{kind:"evidence-recorded",stepId:A.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId},"succeeded");oo(R,_,A.stepId,A.sequence,A.results,{ref:y.ref,contentHash:y.contentHash},"succeeded",B),Sn(R,_)})}async function C(y){return S(y,async(R,_)=>{if(O(R),R.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止,不能使证据失效");let A=R.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(R),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(R,_,{kind:"evidence-invalidated",stepId:A.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:B},"invalidated");oo(R,_,A.stepId,A.sequence,A.results,{ref:y.ref,contentHash:y.contentHash,reason:B},"invalidated",q),Sn(R,_)})}async function $(y){return S(y,R=>{O(R);let _=R.waits.find(A=>A.id===y.waitId);if(!_||_.status!=="pending"||_.proposalHash!==y.proposalHash)throw new v("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");_.proposal=Ge(y.proposal),_.proposalHash=j(_.proposal)})}async function T(y){let R=await S(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=>Hm(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)]=Bm(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 R.status==="cancelled"&&await te(R),R}async function L(y){return S(y,R=>{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(R,A.actionId);R.actions[R.actions.indexOf(I)]=Vm(I,A)}})}async function H(y){return S(y,R=>{O(R);let _=E(R,y.actionId);if(_.attempt!==y.attempt)throw new v("STALE_ACTION","Action 执行尝试已经改变");R.actions[R.actions.indexOf(_)]=HR(_,y.reason)})}async function ie(y){return S(y,async(R,_)=>{O(R);let A=E(R,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(R.actions.some(q=>["running","unknown"].includes(q.status)))throw new v("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(R.status!=="completed"||R.ready.length>0||R.actions.some(q=>q.status==="pending")||R.waits.some(q=>q.status==="pending")||R.evidenceWaits?.some(q=>q.status==="pending")||Object.values(R.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(R),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(R,_,{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=R.actionContexts[A.id];oo(R,_,A.stepId,B.sequence,B.results,A.outcome.output,W,M),Sn(R,_);return}if(A.status==="failed"){let I=R.actionContexts[A.id].sequence,W=B=>Object.hasOwn(B,A.stepId)&&B[A.stepId].sequence===I;if(Object.values(R.actionContexts).some(B=>W(B.results))||R.waits.some(B=>W(B.results))||R.evidenceWaits?.some(B=>W(B.results))||R.ready.some(B=>W(B.results))||Object.values(R.joins).some(B=>Object.values(B).some(q=>q.some(V=>W(V.results)))))throw new v("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}R.actions[R.actions.indexOf(A)]=BR(A,y.reconciliation),R.status="running",delete R.reason})}async function le(y,R){let _=c.get(y.executorId);if(!_)throw new v("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let A=R??await b(y.runId),I=E(A,y.actionId);if(I.status!=="pending")throw new v("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!Ug(_,I))throw new v("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");rn(y.context);let W=await ne({...y,attempt:I.attempt,inputHash:I.inputHash,claimToken:Bg(),capabilities:_.capabilities},!1,A),M=E(W,y.actionId),B;try{rn(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 R=y.maxActions??100;if(!Number.isSafeInteger(R)||R<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(;;){rn(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>=R)return W("action-limit");if(!Ug(_,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 R=await Vs(e.store,y);return k(R.run,Rt),R}async function rr(y){return Km(await Qe(y.runId),y)}function Se(y){return async(...R)=>{let _=R.map(A=>Vg(A));return Oe(await y(..._))}}return{start:Se(J),dispatchCommand:Se(G),inspect:Se(b),inspectProjection:Qe,query:Se(rr),inspectCurrent:async y=>await rr({runId:y,view:"current"}),executeCurrent:async y=>zE(await le(Vg(y))),runUntilBlockedCurrent:async y=>{let R=await Be(Vg(y));return{...R,run:zE(R.run)}},next:Se(K),claim:Se(ze),recordOutcome:Se(F),resolveWait:Se(re),recordEvidence:Se(He),invalidateEvidence:Se(C),reviseWait:Se($),cancel:Se(T),acknowledgeStopped:Se(L),markUnknown:Se(H),retry:Se(ie),execute:Se(y=>le(y)),runUntilBlocked:Se(Be)}}Oo();Ri();import{createHash as sA,randomUUID as o9}from"node:crypto";import{types as YM}from"node:util";import{promises as kr}from"node:fs";import st from"node:path";import{randomUUID as KM}from"node:crypto";import{promises as ci}from"node:fs";import dc from"node:path";import{performance as QE}from"node:perf_hooks";import{createRequire as VM}from"node:module";var UM=VM(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=UM("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new cd(e):new cd(e,t)}import{AsyncLocalStorage as zM}from"node:async_hooks";var GE=new zM,Jg=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}};function YE(e){return Math.max(0,Math.min(e,(GE.getStore()?.deadline??1/0)-performance.now()))}function XE(){let e=GE.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new Jg}async function ZE(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 JM(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(dc.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 eA(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function GM(e,t={}){e=dc.resolve(e),await ci.mkdir(dc.dirname(e),{recursive:!0});let r=await ci.lstat(dc.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+dc.dirname(e));let n=QE.now()+YE(t.timeoutMs??3e4),i;for(;XE(),i=await JM(e),!i;){if(QE.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:KM(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let c=await ZE(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 eA(i),c}let o=!1;return{owner:s,async release(){if(o)return!0;o=!0;let c=!0;try{let l=await ZE(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{eA(i)}return c}}}async function tA(e,t,r={}){let n=await GM(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}$t();ye();nr();var rA=new WeakMap;function nA(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=rA.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)&&rA.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=jR(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 XM(e){return rs(e),sA("sha256").update(JSON.stringify(e)).digest("hex")}function ud(e){if(!Number.isSafeInteger(e)||e<1)throw new v("STORE_INVALID_REVISION","revision 必须是正安全整数")}function QM(e,t,r,n=!0){if(rs(e),YM.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 iA="comet.runtime-store-checkpoint.v1";function ZM(e,t,r){let n=Ge(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 oA(e,t,r){let n=Ge(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 eF(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||yn(e)===yn(oA(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=XM,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 S(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=[],Se=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),Se=Math.max(Se,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(!Se)return w();let R=new Map,_=N=>`${String(N).padStart(16,"0")}.json`,A=N=>Qe.has(_(N));async function I(N){if(R.has(N))return R.get(N);let oe=await k(T,_(N));return(N<=2||N===Se)&&R.set(N,oe),oe}async function W(N,oe=0,Y=Se){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(Se);if(Se===rr.length&&(M?.schema!==iA||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!==iA||"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(oA(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=Se===V?q:Se;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&&Se===B.slot?B.record:M,V,B&&Se===B.slot?B.record.revision:Se)}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 Pa(C)?Rt(C,{cachePrefixes:!1}):j(C)}async function z(C,$){let T=await S(C,!1,d(C),!1),L=await S(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 J(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 G(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 ht(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 J(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 G(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 J(C,T?"closing":"reopening",H),await G(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 $?Gt(ie):ie}if((await S(C,!1,p(C),!1)).record)throw new v("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let H=await S(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 S(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 S(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 kt&&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 ht(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 ht(n,d(C),{label:"RuntimeStore run"}),await ne(st.join(n,a)),await ne(n);try{return e.singleWriter?await $():await tA(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,Se=`{"schema":${JSON.stringify(rr)},${Be.slice(1,-1)},"legacyRevision":${JSON.stringify(ie)},"hash":${JSON.stringify(j(Qe))}}
|
|
159
|
+
`;await Te(st.join(H,l),Se,{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 G(C);let L=await E(C);if(L.marker?.schema===u)throw new v("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await S(C,!1,p(C),!1)).record)throw new v("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let ie=await S(C,!1,d(C),$);if(ie.record&&!L.marker)throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(L.original.kind==="directory"){await S(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 S(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:${sA("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 G(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(ZM(C,$,T));return r(L),ze(C,async()=>{let H=await re(C);return eF(H.record,$,L,t)?(await P(C,L,H),!0):!1})},compareAndSwap:async(C,$,T)=>He(C,$,T)(),prepareCompareAndSwap:He};function He(C,$,T){QM(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 aA}from"node:util";var _t="run_checkpoint",Gg="comet.workflow-run-checkpoint.v1",tF=/^portable-[a-f0-9]{64}$/u;function dd(e){return tF.test(e)?e:`portable-${j(e)}`}function fd(e){let t=nA(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:j(t)}:e}function fc(e,t){return aA(e,t)||aA(e,fd(t))}function cA(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 lA={hash:Rt,visitResults:mu,validateOrigins:hu};function rF(e){let t=Ta(cA(e),e.runId,lA),r=Rt(t);return{schema:Gg,hash:r,run:t,sourceRevision:e.revision,sourceHash:j({hash:r,sourceRevision:e.revision})}}function lo(e){let t=Bs(cA(e),e.runId),r=j(t);return{schema:Gg,hash:r,run:t,sourceRevision:e.revision,sourceHash:j({hash:r,sourceRevision:e.revision})}}function uA(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?Rt:j)(s)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=n?Ta(s,t,lA):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 nn(e,t,r={}){return uA(e,t,r)}function pd(e,t,r={}){return uA(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=rF(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 Yg(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 dA=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],cF={"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 lF(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 It(e,t,r={}){let n=cF[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",lF(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 fA(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 Xg(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=It(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}$t();ye();var uF="@rpamis/comet",o3=`https://registry.npmjs.org/${uF}/latest`;ha();function tw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var as=tw();function kA(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(Pt.caret,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,t)};return n}var dF=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Pt={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}}>`))},fF=/^(?:[ \t]*(?:\n|$))+/,pF=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,mF=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hc=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,hF=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,rw=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,bA=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,RA=ge(bA).replace(/bull/g,rw).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(),gF=ge(bA).replace(/bull/g,rw).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(),nw=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,wF=/^[^\n]+/,iw=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,yF=ge(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",iw).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),vF=ge(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,rw).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",sw=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,kF=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",sw).replace("tag",yd).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),SA=e=>ge(nw).replace("hr",hc).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(),bF=SA(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),RF=SA(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),SF=ge(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",RF).getRegex(),ow={blockquote:SF,code:pF,def:yF,fences:mF,heading:hF,hr:hc,html:kF,lheading:RA,list:vF,newline:fF,paragraph:bF,table:ss,text:wF},pA=ge("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hc).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(),CF={...ow,lheading:gF,table:pA,paragraph:ge(nw).replace("hr",hc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",pA).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()},EF={...ow,html:ge(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",sw).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(nw).replace("hr",hc).replace("heading",` *#{1,6} *[^
|
|
162
|
+
]`).replace("lheading",RA).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},AF=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,xF=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,CA=/^( {2,}|\\)\n(?!\s*$)/,_F=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Cn=/[\p{P}\p{S}]/u,fo=/[\s\p{P}\p{S}]/u,gc=/[^\s\p{P}\p{S}]/u,IF=ge(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,fo).getRegex(),PF=/[\p{Pi}\p{Ps}"']/u,EA=/(?!~)[\p{P}\p{S}]/u,OF=/(?!~)[\s\p{P}\p{S}]/u,TF=/(?:[^\s\p{P}\p{S}]|~)/u,NF=ge(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",dF?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),AA=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,$F=ge(AA,"u").replace(/punct/g,Cn).getRegex(),jF=ge(AA,"u").replace(/punct/g,EA).getRegex(),DF=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,qF=ge(DF,"u").replace(/openQuote/g,PF).replace(/punct/g,Cn).getRegex(),xA="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",LF=ge(xA,"gu").replace(/notPunctSpace/g,gc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),WF=ge(xA,"gu").replace(/notPunctSpace/g,TF).replace(/punctSpace/g,OF).replace(/punct/g,EA).getRegex(),MF="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",FF=ge(MF,"gu").replace(/notPunctSpace/g,gc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),HF=ge("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,gc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),BF="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",VF=ge(BF,"gu").replace(/notPunctSpace/g,gc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),UF=ge(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Cn).getRegex(),zF="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",KF=ge(zF,"gu").replace(/notPunctSpace/g,gc).replace(/punctSpace/g,fo).replace(/punct/g,Cn).getRegex(),JF=ge(/\\(punct)/,"gu").replace(/punct/g,Cn).getRegex(),GF=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(),YF=ge(sw).replace("(?:-->|$)","-->").getRegex(),XF=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",YF).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),hd=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,QF=ge(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",hd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),_A=ge(/^!?\[(label)\]\[(ref)\]/).replace("label",hd).replace("ref",iw).getRegex(),IA=ge(/^!?\[(ref)\](?:\[\])?/).replace("ref",iw).getRegex(),ZF=ge("reflink|nolink(?!\\()","g").replace("reflink",_A).replace("nolink",IA).getRegex(),mA=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,aw={_backpedal:ss,anyPunctuation:JF,autolink:GF,blockSkip:NF,br:CA,code:xF,del:ss,delLDelim:ss,delRDelim:ss,emStrongLDelim:$F,emStrongRDelimAst:LF,emStrongRDelimUnd:HF,escape:AF,link:QF,nolink:IA,punctuation:IF,reflink:_A,reflinkSearch:ZF,tag:XF,text:_F,url:ss},eH={...aw,emStrongLDelim:qF,emStrongRDelimAst:FF,emStrongRDelimUnd:VF,link:ge(/^!?\[(label)\]\((.*?)\)/).replace("label",hd).getRegex(),reflink:ge(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",hd).getRegex()},Qg={...aw,emStrongRDelimAst:WF,emStrongLDelim:jF,delLDelim:UF,delRDelim:KF,url:ge(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mA).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",mA).getRegex()},tH={...Qg,br:ge(CA).replace("{2,}","*").getRegex(),text:ge(Qg.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},md={normal:ow,gfm:CF,pedantic:EF},pc={normal:aw,gfm:Qg,breaks:tH,pedantic:eH},rH={"&":"&","<":"<",">":">",'"':""","'":"'"},hA=e=>rH[e];function sn(e,t){if(t){if(Pt.escapeTest.test(e))return e.replace(Pt.escapeReplace,hA)}else if(Pt.escapeTestNoEncode.test(e))return e.replace(Pt.escapeReplaceNoEncode,hA);return e}function gA(e){try{e=encodeURI(e).replace(Pt.percentDecode,"%")}catch{return null}return e}function wA(e,t){let r=e.replace(Pt.findPipe,(s,o,c)=>{let l=!1,f=o;for(;--f>=0&&c[f]==="\\";)l=!l;return l?"|":" |"}),n=r.split(Pt.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(Pt.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 yA(e){let t=e.split(`
|
|
163
|
+
`),r=t.length-1;for(;r>=0&&Pt.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
164
|
+
`)}function nH(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 iH(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 vA(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 sH(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]:yA(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=sH(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=iH(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),S=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)||S.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=yA(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=wA(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(wA(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=nH(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)),vA(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 vA(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 Zg{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:Pt,block:md.normal,inline:pc.normal};this.options.pedantic?(r.block=md.pedantic,r.inline=pc.pedantic):this.options.gfm&&(r.block=md.gfm,this.options.breaks?r.inline=pc.breaks:r.inline=pc.gfm),this.tokenizer.rules=r}static get rules(){return{block:md,inline:pc}}static lex(t,r){return new Zg(r).lex(t)}static lexInline(t,r){return new Zg(r).inlineTokens(t)}lex(t){t=t.replace(Pt.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(Pt.tabCharGlobal," ").replace(Pt.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(Pt.notSpaceStart)?.[0],i=e.replace(Pt.endingNewline,"")+`
|
|
207
|
+
`;return n?'<pre><code class="language-'+sn(n)+'">'+(r?i:sn(i,!0))+`</code></pre>
|
|
208
|
+
`:"<pre><code>"+(r?i:sn(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>${sn(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=gA(e);if(i===null)return n;e=i;let s='<a href="'+e+'"';return t&&(s+=' title="'+sn(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=gA(e);if(i===null)return sn(r);e=i;let s=`<img src="${e}" alt="${sn(r)}"`;return t&&(s+=` title="${sn(t)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:sn(e.text)}},cw=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 ew{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 cw}static parse(t,r){return new ew(r).parse(t)}static parseInline(t,r){return new ew(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}},mc=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}},oH=class{defaults=tw();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fr;Renderer=wd;TextRenderer=cw;Lexer=br;Tokenizer=gd;Hooks=mc;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 mc;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];mc.passThroughHooks.has(s)?i[o]=f=>{if(this.defaults.async&&mc.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>"+sn(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},os=new oH;function qe(e,t){return os.parse(e,t)}qe.options=qe.setOptions=function(e){return os.setOptions(e),qe.defaults=os.defaults,kA(qe.defaults),qe};qe.getDefaults=tw;qe.defaults=as;function aH(...e){return os.use(...e),qe.defaults=os.defaults,kA(qe.defaults),qe}qe.use=aH;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=cw;qe.Lexer=br;qe.lexer=br.lex;qe.Tokenizer=gd;qe.Hooks=mc;qe.parse=qe;var c3=qe.options,l3=qe.setOptions,cH=qe.walkTokens,u3=qe.parseInline;var d3=Fr.parse,f3=br.lex;ye();$t();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 xo from"node:path";ye();var uV=vt(jt(),1);ye();import{AsyncLocalStorage as mH}from"async_hooks";import{promises as OA}from"fs";import wc from"path";var po=new mH;function hH(e,t){let r=wc.relative(e,t);return r===""||!wc.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${wc.sep}`)}async function gH(e){let t=wc.resolve(e.invocationCwd??process.cwd()),r=wc.resolve(e.projectRoot??await lt(t)),[n,i]=await Promise.all([OA.realpath(t),OA.realpath(r)]);if(!hH(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 wH(e,t){let r=po.getStore();if(r)return t(r);let n=await gH(e);return po.run(n,()=>t(n))}function TA(){let e=po.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}async function NA(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 yc(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 $A(e){return(t,r)=>wH(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 on(e){let t=ho(e);if(t)throw new Error(t)}async function En(e,t){on(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)):lw(c,t)&&r.push(await n(Hr.join(s,c)))}return r}function yH(e,t){return{label:Ae(e,t),directory:t}}async function vc(e,t,r){let n=yH(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 vH=/^\d{4}-\d{2}-\d{2}-/u;function lw(e,t){return e.slice(11)===t&&vH.test(e)}async function Sd(e,t,r){on(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 NA(`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||lw(f,r))});if(!(await n()).exists||await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return c}async function jA(e,t,r,n={}){if(!n.skipExactCompatibility){let o=await vc(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 vc(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()){on(e);let r=await gt(t),n=await vc(r.projectRoot,Hr.join(r.changesDir,e),`Classic active change ${e}`);return{...n.change,exists:n.exists,stateExists:n.stateExists}}async function uw(e,t=process.cwd(),r={}){on(e);let n=await gt(t);if(r.preferredArchiveName!==void 0){let i=r.preferredArchiveName;if(i!==e&&!lw(i,e))throw new Error(`Classic preferred archive name '${i}' does not belong to change '${e}'`);let s=await vc(n.projectRoot,Hr.join(n.archiveDir,i),`Classic preferred archived change ${i}`);return s.exists&&s.stateExists?s.change:null}return jA(n.projectRoot,n.archiveDir,e,r)}async function Cd(e,t=process.cwd()){on(e);let r=await gt(t),n=await vc(r.projectRoot,Hr.join(r.changesDir,e),`Classic active change ${e}`);if(n.exists)return n.change;let i=await jA(r.projectRoot,r.archiveDir,e);return i||n.change}Ri();var jw=vt(jt(),1);import{execFileSync as vi}from"node:child_process";import Er from"node:path";import{isDeepStrictEqual as $w}from"node:util";import{execFileSync as MA}from"node:child_process";import{spawn as p5,execFileSync as EH}from"node:child_process";import fw from"node:path";import{existsSync as dw,readFileSync as kH}from"node:fs";import Rr from"node:path";var bH=/[&|<>()^%"!\r\n]/u,a5=["$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 DA(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function RH(e){let t=(DA(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function SH(e,t,r){let i=Rr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(DA(t,"PATH")??"").split(Rr.delimiter).map(c=>c.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Rr.win32.extname(e)?[e]:RH(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 SH(e,t,r).find(n=>dw(n))??e}function CH(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 qA(e,t,r,n=process.execPath){let i=CH(kH(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(!dw(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??(dw(c)?c:n),args:[o,...t],...i.nodePath?{env:l}:{}}}function LA(e){if(e.some(t=>bH.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var AH=6e4,xH=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 _H(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function WA(e,t,r={}){let n=r.timeoutMs??AH,i=r.maxBufferBytes??xH;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=fw.resolve(r.cwd??process.cwd()),o=r.env??process.env,c=process.platform==="win32"?go(e,o,s):e,l=fw.win32.extname(c).toLowerCase(),f=l===".bat"||l===".cmd";process.platform==="win32"&&f&&LA(t);try{let a=()=>EH(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(fw.win32.basename(e))?Gr(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:_H(a)})}}var PH=3e4,OH=8*1024*1024;function FA(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=Gr(()=>MA("git",["diff-tree","--stdin","--always","--no-renames","--name-status","-r","-z"],{cwd:e,input:t.join(`
|
|
229
|
+
`)+`
|
|
230
|
+
`,encoding:"utf8",timeout:PH,maxBuffer:OH,windowsHide:!0}))}catch(o){if(!["ENOBUFS","ETIMEDOUT"].includes(o.code??""))throw o;return new Map(t.map(c=>[c,Gr(()=>MA("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}Dt();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 JA=vt(jt(),1);import an from"node:path";import{spawnSync as NH}from"child_process";import{accessSync as HA,constants as pw,statSync as BA,existsSync as E5,readFileSync as A5}from"node:fs";import wo from"node:path";function mw(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=qA(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 VA(e,t,r){let n=mw(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 BA(a).isFile()?(HA(a,i==="win32"?pw.F_OK:pw.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(!BA(f).isFile())throw new Error(`Node CLI entry is not a file: ${f}`);HA(f,pw.R_OK)}}var UA=vt(jt(),1);ye();import TH from"path";async function zA(e,t){let r=t??await gt(e),n=TH.join(r.openSpecRoot,"config.yaml"),i=Ae(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,UA.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 KA(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 lt(t),i=await Ni(n);await zA(n,i);let s=process.env.COMET_OPENSPEC||"openspec",o;try{VA(s,r,{cwd:i.openSpecBase}),o=mw(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=NH(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 $H=".comet/archive-requirements.json";async function GA(e,t){let r=an.join(t,$H),n=["proposal.md","design.md","tasks.md"];if(await Lt(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,an.join(t,s),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${s}`);return i}function jH(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=an.join(t,".openspec.yaml");if(!await Lt(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=>an.join(t,d)),problems:[]}}let i=(0,JA.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,an.join(t,"specs")),o=r===void 0?await KA(["status","--change",an.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"||an.resolve(c.changeRoot)!==an.resolve(t))throw new Error("OpenSpec status resolves outside the selected Classic change");let l=jH(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(an.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=[an.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 YA(e){let t=cs(e);return t.missingFields.length===0&&t.invalidFields.length===0}import{randomUUID as OB}from"node:crypto";function kc(e){return e==="zh-CN"?"zh-CN":"en"}function hw(e,t,r){return e==="zh-CN"?r:t}function XA(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:hw(t,"This write was blocked on purpose, not by an error.","这次写入是被有意拦下的,不是发生了错误。"),user_message:hw(t,n.en,n.zh)}}function QA(e){let{name:t,locale:r}=e;return{summary:hw(r,`Handoff context for ${t} was written and recorded; the Build phase can resume from it.`,`需求 ${t} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}xm();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 ZA(e,t,r,n={}){fi(e,t),await dR(e,t,`${JSON.stringify(r)}
|
|
231
|
+
`,ls.trajectory,"Run trajectory",n)}async function ex(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 tx(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 rx(e,t,r,n={}){fi(e,t),await ji(e,t,JSON.stringify(r,null,2)+`
|
|
232
|
+
`,ls.artifacts,"Run artifacts",n)}async function nx(e,t,r,n={}){fi(e,t),await ji(e,t,r,ls.context,"Run context",n)}async function ix(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 sx(e,t,r={}){fi(e,t),await iu(e,t,"Run pending action",r)}async function ox(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 gw(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 lt(e),s=await ba(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 yo(...e){return e[0]=await Ce(e[0]),ZA(...e)}async function xd(...e){let t=await gw(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,ex(...e)}async function ax(...e){let t=await gw(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,tx(...e)}async function _d(...e){return e[0]=await Ce(e[0]),rx(...e)}async function Id(...e){return e[0]=await Ce(e[0]),nx(...e)}async function cx(...e){let t=await gw(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,ix(...e)}async function lx(...e){return e[0]=await Ce(e[0]),sx(...e)}async function ux(...e){return e[0]=await Ce(e[0]),ox(...e)}import{promises as jx}from"fs";import or from"path";import{fileURLToPath as Dx}from"url";ye();import hi from"path";ye();Dt();import bc from"path";function qH(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function dx(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 gt(e),c=`${Ae(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];on(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,Ae(e,u),{label:"Classic archived change directory",expected:"directory"});let g=bc.join(u,".comet",...p),w=Ae(e,g);try{return await ae(e,w,n,{label:"Historical Classic archived handoff artifact"}),w}catch(k){if(qH(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 gt(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 Lt(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 LH=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,WH=/\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=LH.exec(s);if(!c)continue;let l=WH.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=Ae(e,ma(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 MH(e,t,r,n){try{n??=await gt(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 dx(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 ww(e,t,r){return Rc(e,t,Od(e,r))}async function FH(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 HH(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 vo(e,t){return e.some(r=>r.code===t&&r.satisfied)}async function ko(e,t){let r=await lt(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 gt(r)}catch(d){f=d}let a=await Promise.all([ww(r,"openspec.proposal",i),ww(r,"openspec.design",s),ww(r,"openspec.tasks",o),FH(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)}}})(),HH(r,o),Rc(r,"verification.report",n?.verificationReport??null,l,f),MH(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 wB,randomUUID as yB}from"crypto";import{promises as Rw}from"fs";import xn from"path";function BH(e){return e.classicProfile??e.workflow}function VH(e){return e.isolation!==null&&YA(e)}function UH(e){return(e.buildMode==="direct"||e.buildMode==="autonomous")&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function zH(e,t,r){if(e!=="full"&&t.verifyResult==="fail")return`${e}.build.execute`;if(e==="full"){if(vo(r,"build.plan")&&t.buildPause==="plan-ready")return"full.build.plan-ready";if(!VH(t))return"full.build.configure";if(!vo(r,"build.plan"))return"full.build.plan";if(t.verifyResult==="fail")return"full.build.fix"}else if(!UH(t))throw new Error(`${e} build configuration is incomplete`);return vo(r,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function KH(e,t,r){return t.verifyResult!=="pass"||!vo(r,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function JH(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=BH(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 vo(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return zH(r,e,t);case"verify":return KH(r,e,t);case"archive":return JH(r,e)}}function fx(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 Ax,randomUUID as fB}from"crypto";import{promises as dt}from"fs";import ot from"path";var hx=vt(jt(),1);import{promises as yw}from"fs";import Cr from"path";var GH=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],YH=["deterministic","adaptive"],XH=["function","mcp","script","agent"],QH=["none","read","write","external"],ZH=["progress","step","completion"],eB=["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 Ft(e,t,r){if(typeof e!="string")throw fs(t,r,"must be a string")}function Br(e,t,r,n){t in e&&Ft(e[t],r,`${n}.${t}`)}function gx(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)=>{Ft(n,t,`${r}[${i}]`)})}function px(e,t,r){tr(e,t,r),Ft(e.name,t,`${r}.name`),Ft(e.description,t,`${r}.description`),gx(e,"required",t,r)}function tB(e,t,r){tr(e,t,r),Ft(e.id,t,`${r}.id`),Br(e,"source",t,r),Br(e,"version",t,r)}function rB(e,t,r){tr(e,t,r),Ft(e.id,t,`${r}.id`),Ft(e.role,t,`${r}.role`),Br(e,"instructions",t,r)}function nB(e,t,r){tr(e,t,r),Ft(e.id,t,`${r}.id`),wi(e.kind,XH,t,`${r}.kind`),Ft(e.source,t,`${r}.source`),wi(e.sideEffect,QH,t,`${r}.sideEffect`),gx(e,"requiresConfirmation",t,r)}function iB(e,t,r){tr(e,t,r),wi(e.type,GH,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 sB(e,t,r){tr(e,t,r),Ft(e.id,t,`${r}.id`),iB(e.action,t,`${r}.action`),Br(e,"next",t,r),"completionEvals"in e&&Nd(e.completionEvals,t,`${r}.completionEvals`)}function oB(e,t){let r="goal";tr(e,t,r),Ft(e.statement,t,`${r}.statement`),gi(e.inputs,t,`${r}.inputs`),e.inputs.forEach((n,i)=>{px(n,t,`${r}.inputs[${i}]`)}),gi(e.outputs,t,`${r}.outputs`),e.outputs.forEach((n,i)=>{px(n,t,`${r}.outputs[${i}]`)}),Nd(e.success,t,`${r}.success`)}function aB(e,t){let r="orchestration";tr(e,t,r),wi(e.mode,YH,t,`${r}.mode`),Br(e,"entry",t,r),"steps"in e&&(gi(e.steps,t,`${r}.steps`),e.steps.forEach((n,i)=>{sB(n,t,`${r}.steps[${i}]`)}))}function wx(e,t){return tr(e,t),wi(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),wi(e.kind,["Skill"],t,"kind"),tr(e.metadata,t,"metadata"),Ft(e.metadata.name,t,"metadata.name"),Ft(e.metadata.version,t,"metadata.version"),Ft(e.metadata.description,t,"metadata.description"),oB(e.goal,t),aB(e.orchestration,t),gi(e.skills,t,"skills"),e.skills.forEach((r,n)=>{tB(r,t,`skills[${n}]`)}),gi(e.agents,t,"agents"),e.agents.forEach((r,n)=>{rB(r,t,`agents[${n}]`)}),gi(e.tools,t,"tools"),e.tools.forEach((r,n)=>{nB(r,t,`tools[${n}]`)}),e}function yx(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 cB(e,t){return tr(e,t),"runtime"in e&&vx(e.runtime,t,"runtime"),e}function vx(e,t,r){return gi(e,t,r),e.forEach((n,i)=>{let s=`${r}[${i}]`;tr(n,t,s),Ft(n.id,t,`${s}.id`),wi(n.scope,ZH,t,`${s}.scope`),wi(n.type,eB,t,`${s}.type`),Br(n,"artifact",t,s),Br(n,"field",t,s),Br(n,"equals",t,s)}),e}async function vw(e){let t=await yw.readFile(e,"utf8");try{return(0,hx.parse)(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw fs(e,"document",n)}}async function lB(e){try{return await vw(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function mx(e){try{return await yw.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uB(e){let t=Cr.join(e,"checks.yaml"),r=Cr.join(e,"evals.yaml"),[n,i]=await Promise.all([mx(t),mx(r)]);if(i)throw new Error(`${r}: evals.yaml is no longer supported; use checks.yaml`);return n?{document:cB(await vw(t),t)}:{document:null}}async function kx(e){let t=Cr.resolve(e.root),r=Cr.resolve(e.controlRoot);e.requireSkillMarkdown&&await yw.access(Cr.join(t,"SKILL.md"));let n=Cr.join(r,"skill.yaml"),i=Cr.join(r,"guardrails.yaml"),s=wx(await vw(n),n),o=await lB(i),c=o===null?null:yx(o,i),l=await uB(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 bx(e){let t=Cr.resolve(e);return kx({root:t,controlRoot:Cr.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Rx(e){let t=Cr.resolve(e);return kx({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function Sx(e,t,r=Cr.join(t,"package.json")){tr(e,r);let n=e.packageKind==="runtime"?"runtime":void 0,i=wx(e.definition,r),s=yx(e.guardrails,r),o=vx(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 Cx from"path";function dB(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 Ex(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),dB(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=Cx.posix.normalize(o.source.replaceAll("\\","/"));(Cx.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 pB(e){return $d({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function mB(e){return ot.posix.normalize(e.replaceAll("\\","/"))}function bo(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 xx(e,t,r){let n=mB(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("/"));bo(e,i,r);let s;try{s=await dt.realpath(i)}catch(o){throw o.code==="ENOENT"?new Error(`${r} does not exist: ${t}`,{cause:o}):o}if(bo(e,s,r),!(await dt.stat(s)).isFile())throw new Error(`${r} is not a file: ${t}`);return{path:n,content:await dt.readFile(s)}}async function hB(e){let t=await dt.realpath(e.root),r=e.packageKind==="runtime"?[]:[await xx(t,"SKILL.md","SKILL.md")];for(let n of e.definition.tools)n.kind==="script"&&r.push(await xx(t,n.source,`Script tool ${n.id}`));return r.sort((n,i)=>n.path.localeCompare(i.path))}function gB(e,t){let r=t.map(n=>({path:n.path,sha256:Ax("sha256").update(n.content).digest("hex")}));return Ax("sha256").update(JSON.stringify($d({package:e,files:r}))).digest("hex")}function Px(e){return JSON.stringify(e,null,2)+`
|
|
234
|
+
`}async function Ox(e){let t=pB(e),r=await hB(e);return{document:t,files:r,hash:gB(t,r)}}async function jd(e){return(await Ox(e)).hash}async function _x(e){try{return await dt.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ix(e,t){try{if((await dt.readFile(ot.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await dt.readFile(ot.join(e,"package.json"),"utf8")!==Px(t.document))throw new Error("package mismatch");for(let i of t.files)if(!(await dt.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 kw(e,t){let r=await Ox(e),n=ot.resolve(t,".comet","skill-snapshots"),i=ot.join(n,r.hash);if(await dt.mkdir(n,{recursive:!0}),await _x(i))return await Ix(i,r),{hash:r.hash,snapshotDir:i};let s=ot.join(n,`.tmp-${fB()}`);bo(n,s,"Temporary snapshot"),bo(n,i,"Published snapshot");try{await dt.mkdir(s);for(let o of r.files){let c=ot.join(s,...o.path.split("/"));bo(s,c,`Snapshot file ${o.path}`),await dt.mkdir(ot.dirname(c),{recursive:!0}),await dt.writeFile(c,o.content)}await dt.writeFile(ot.join(s,"package.json"),Px(r.document)),await dt.writeFile(ot.join(s,"sha256"),r.hash+`
|
|
235
|
+
`),await dt.rename(s,i)}catch(o){if(await _x(i)){try{await Ix(i,r)}finally{await dt.rm(s,{recursive:!0,force:!0})}return{hash:r.hash,snapshotDir:i}}throw await dt.rm(s,{recursive:!0,force:!0}),o}return{hash:r.hash,snapshotDir:i}}async function bw(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);bo(r,n,"Skill snapshot");try{let i=(await dt.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 dt.readFile(s,"utf8")),c=Sx(o,n,s),l=Ex(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 Tx(e){try{return await Rw.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Nx(e){return wB("sha256").update(e).digest("hex")}function vB(e){return Nx(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)))))}function kB(e){return e.replaceAll(".","_").replaceAll("-","_")}async function bB(e,t){let r=await lt(e),n=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[kB(o.code),o.source])),i=xn.join(e,"subagent-progress.md");await Tx(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 RB(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 SB(e){await Promise.all(e.map(t=>Rw.rm(t,{recursive:!0,force:!0})))}async function $x(e,t){return Nr(e,()=>CB(e,t))}async function CB(e,t){let r=await lt(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 bw(await Ce(e),i.run.skillHash),{classic:s,run:i.run,evidence:await ko(e,i),migrated:!1,snapshotDir:xn.join(await Ce(e),".comet","skill-snapshots",i.run.skillHash)};let m=await kw(t.skillPackage,await Ce(e));return{classic:s,run:i.run,evidence:await ko(e,i),migrated:!1,snapshotDir:m.snapshotDir}}let c=await ko(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 Ce(e),".comet","skill-snapshots",f),d=await Tx(a),p=[];try{let u=await kw(t.skillPackage,await Ce(e)),m=fx(t.skillPackage,t.runId?.()??yB(),u.hash);m.currentStep=l,l==="completed"&&(m.status="completed");let h={...s,classicProfile:o,classicMigration:Li},g=await bB(e,c),w=await lt(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 Ce(e),m.contextRef))),await _d(e,m.artifactsRef,g),p.push(xn.resolve(await Ce(e),m.artifactsRef));let S=(t.now?.()??new Date).toISOString(),E={runId:m.runId,stateVersion:1,trajectoryOffset:2,contextHash:b===null?null:Nx(b),artifactsHash:vB(g),createdAt:S};await ux(e,m.checkpointRef,E),p.push(xn.resolve(await Ce(e),m.checkpointRef)),p.push(xn.resolve(await Ce(e),m.trajectoryRef));for(let O of RB(m,o,S))await yo(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 SB(p),d||await Rw.rm(a,{recursive:!0,force:!0}),u}}async function EB(e){try{return(await jx.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dd(e){try{return(await jx.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function AB(e){return await EB(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 xB(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 _B(){let e=or.dirname(Dx(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 AB(r))return r;return null}async function IB(e){return await Dd(or.join(e,"skill.yaml"))?Rx(e):bx(e)}async function qx(e){let t=await _B();return $x(e,{skillPackage:t?await IB(t):xB(or.dirname(Dx(import.meta.url)))})}async function Lx(e,t,r,n){return Nr(e,()=>PB(e,t,r,n))}async function PB(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 ko(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 yo(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 TB(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 Wx(e){let{projectRoot:t,changeDir:r,change:n}=e,i=Ae(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 Mx(e){let t=Ae(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 Wx(e)).handoffContext===t+"/proposal.md":!1}async function NB(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 Lt(t,c,{label:"Classic handoff source",expected:"file"})&&i.push({reference:Ae(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,TB(n,"full","",i),{label:"Classic handoff view"}),Ae(t,o)}var OX=$A(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=TA(),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 qx(l.directory),p=await cx(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 Wx({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 NB({projectRoot:o,changeDir:l.directory,change:t}):null;await Id(l.directory,d.run.contextRef,h),await _d(l.directory,d.run.artifactsRef,{...await ax(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 Lx(l.directory,w,k,{actionId:p?.id??OB(),kind:"classic-handoff"})),await qs(l.directory,{...f,classic:w,run:k}),p){let S=await xd(l.directory,k.trajectoryRef);S.some(E=>E.type==="recovery_reconciled"&&E.data?.actionId===p.id)||await yo(l.directory,k.trajectoryRef,{sequence:S.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:k.runId,data:{kind:"classic-handoff",actionId:p.id}}),await lx(l.directory,d.run.pendingRef)}let b=QA({name:t,locale:kc(w.language)});return{exitCode:0,envelope:b,stderr:b.summary+`
|
|
241
|
+
[HANDOFF] source `+u.handoffContext+(g?`
|
|
242
|
+
[HANDOFF] view `+g:"")+`
|
|
243
|
+
`}})});import $B from"node:path";async function Fx(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=$B.posix.join(n,i);if(i==="design.md"&&!await Lt(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 So(e){return Fe(Fe(e.input).activation).deliveryRepair}function Ro(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 Sw(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 Cw(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"&&Ro(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`||Ro(e,r[0]))}function Hx(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 Ro(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||!Ro(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,So(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 DB}from"node:fs";import ms from"node:path";Dt();ye();Dt();ye();import{promises as jB}from"node:fs";import qd from"node:path";async function Bx(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 jB.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 Yr(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 Vx=".comet/archive-manifest.json";function Ew(e,t){return j(Yg(e,t))}async function Ux(e){return Mr({singleWriter:!0,rootDir:ms.join(await jn(e),"archive-receipts/classic")})}async function qB(e){return Mr({singleWriter:!0,rootDir:ms.join(await jn(e),"archive-inputs/classic")})}async function zx(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 qB(e)).read(Ew(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 DB.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 LB(e,t,r,n){let i=await(await Ux(e)).read(Ew(t,r));if(!i||i.manifest.archiveRef!==n||i.manifest.execution.actionId!==r.id)throw new Error("原 Archive 执行收据缺失;核对原命令结果并恢复原记录,不能重复执行或用当前文件补造成功");return i}async function Kx(e,t,r,n,i){return await LB(e,t,r,n),Co(e,t,r,n)}async function Co(e,t,r,n,i=r.outcome?.artifacts){await U(e,n+"/"+Vx,{label:"Classic Archive manifest",expected:"file"});let s=await(await Ux(e)).read(Ew(t,r)),o=r.outcome?.output?.archiveManifest,c=s?.manifest??o;if(!c)return Bx(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+"/"+Vx,...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 Rt(e)===Rt(t)}function Jx(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 Eo(e,t,r={}){if(Ld(t.state).archived!==!0||Hx(e,t))return null;let n=(r.projection?pd:nn)(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(Jx(p),Jx(s))||c(),vu(p,Rt(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 MB}from"node:child_process";import Xx from"node:path";Dt();mn();import WB from"node:path";async function Gx(e){let t=await pn(e,{allowPartialProject:!0,allowMissingNativeFields:!0});return t?.native?[WB.posix.join(t.native.artifact_root,"comet","changes")]:[]}function Yx(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function FB(e,t){return MB("git",t,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:Number.MAX_SAFE_INTEGER,stdio:["ignore","pipe","pipe"]})}async function HB(e){let t=await Yr(e);return[".comet",t.openSpecRoot,t.superpowersRoot,...await Gx(e)].map(r=>Xx.isAbsolute(r)?Xx.relative(e,r).replaceAll("\\","/"):r)}async function Qx(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=fA(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 HB(e),a=(c.deliveryPaths??Object.keys(c.deliveryInputs??l??{})).filter(m=>!Yx(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),Aw(e,a)}async function Aw(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?FB(e,["status","--porcelain","--untracked-files=all","--",...n]).trim():"";if(i)throw new Error("Classic 交付路径尚有未提交修改:"+i);return new Set(n)}import{createHash as BB}from"node:crypto";import{execFileSync as _w}from"node:child_process";function xw(e,t,r){let n=_w("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 e_(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=xw(e,t,!1),n=xw(e,t,!0);if(r!==n)throw new Error("Classic delivery remote has different fetch and push URLs");return BB("sha256").update(r).digest("hex")}function t_(e,t,r){let n=`refs/heads/${r}`,i=_w("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 VB(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 Zx(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 r_(e){let t=VB(xw(e.projectRoot,e.remote,!1)),r=t&&Zx(e.prUrl,t);if(!t||!r)return!1;let n=_w("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"&&Zx(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 Iw(e,t,r){let n=await Yr(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}}}},o_={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}}}},Pw={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===o_.id&&s?.contentHash===t.inputHash?{accepted:!0}:{accepted:!1,reason:"Classic Open has no approval for its current SDK request"}}},Ow={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 Mx({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)}}}},Tw={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}}},UB={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 Yr(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 GA(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 Co(i,e,u,o.archiveDirectory):await Kx(i,e,t,o.archiveDirectory,r.artifacts),{accepted:!0}}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}};async function zB(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,jw.parseDocument)(s,{uniqueKeys:!0}),l=(0,jw.parseDocument)(o,{uniqueKeys:!0});if(c.errors.length>0||l.errors.length>0)return!1;let f=c.toJS(),a=l.toJS();return!nn(f[_t],n.runId)||!nn(a[_t],n.runId)||!fc(a[_t],lo(n))&&!Eo(a[_t],n)?!1:(delete f[_t],delete a[_t],$w(f,a))}var KB={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"||e_(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=FA(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("\\","/"),S=f.archiveDirectory.replaceAll("\\","/"),O=Sc(e,t).outputs,z=O["full.build.plan"],D=O["full.design.document"]?.designDoc??z?.designEvidence?.ref,J=z?.plan;if(s==="full"&&(typeof D!="string"||typeof J!="string"))return{accepted:!1,reason:"Classic Archive documents are missing"};let G=Er.posix.basename(S),te=typeof D=="string"?Sr(D,b,S):null,Z=typeof J=="string"?Sr(J,b,S):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 Qx(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 Co(i,e,ze,S);for(let $ of P.optionalPaths){let T=$.startsWith(`${S}/`)?`${b}/${$.slice(S.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 Aw(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 zB(i,S,k,e);return w?k&&!C?{accepted:!1,reason:`Classic 归档目录与交付 HEAD 不一致:${k}`}:[...h].some($=>$.startsWith(`${S}/`))?s==="full"&&(!te||!Z||!h.has(te)||!h.has(Z)||!we?.includes(`archived-with: ${G}`)||!we.includes("status: final")||!K?.includes(`archived-with: ${G}`))?{accepted:!1,reason:`Classic 交付范围缺少已归档的设计或计划,或归档标记不符:${te}, ${Z}`}:l.deliveryAction!=="local"&&t_(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"||!r_({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} 未包含归档目录:${S}`}:{accepted:!1,reason:`Classic 交付 HEAD 缺少归档目录:${S}`}}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 JB(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 a_(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 n_={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 Fx(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)}}}},GB={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 JB(n.projectRoot,t),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},YB={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 a_(n.projectRoot,t,String(e.input.changeDir)),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},i_={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 Iw(n.projectRoot,t,i.language),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},XB=["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"]},s_={type:["boolean","null"]},Nw={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 c_(e){let t=e==="full"?null:c_("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"?[o_]:t.executors,validators:t?.validators??[...e==="full"?[Pw,Ow,Tw]:[],UB,KB,Nw],evidenceValidators:t?.evidenceValidators??(e==="full"?[n_,GB,YB,i_]:[n_,i_]),workflow:{id:`comet-classic-${e}`,version:"2",entry:r,stateSchema:{type:"object",required:XB,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:s_,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:s_,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:Pw.id,version:Pw.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:Ow.id,version:Ow.version}}:{validator:{id:Nw.id,version:Nw.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:Tw.id,version:Tw.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||!$w(c.outputs[l.stepId]?.value,d.outcome?.output)||!$w(d.outcome,l.outcome))&&Dw(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:{...It(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:It(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:It(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:It(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:It(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:It(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:It(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:It(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:It(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:It(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:It(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=It(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:It(c.state,"open-complete").classic,next:[i]}}}}}function Dw(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=c_;import{AsyncLocalStorage as sV}from"node:async_hooks";ha();import{AsyncLocalStorage as ZB}from"node:async_hooks";import{createHash as eV,randomUUID as u_}from"node:crypto";import Lw from"node:path";import{promises as Fd}from"node:fs";import qw from"node:path";async function Hd(e,t){let r=df(e),n=qw.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let o of["","workspaces",r.workspaceId,"observability"]){i=qw.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=qw.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 QB}from"node:util";function l_(e,t=process.env){let r=QB(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 tV=864e5,rV=1e4,Bd=new ZB;function Ww(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 l_(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"?Lw.resolve(s).toLowerCase():Lw.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=eV("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*tV).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(rV),n.exec("COMMIT")}finally{n.close()}}async function d_(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=Lw.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??u_(),spanId:u_(),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 nV=(e,t)=>`workflow:${e}:${t}`,f_=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},p_=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}))}),m_=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function iV(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:s}=e,o=nV(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:f_(p.stepId,t),actionId:p.id,actionType:p.type,ref:p.ref??null,executor:p.claim?.executorId??null,inputFields:m_(p.input),outputFields:p.outcome?m_(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:f_(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return d}function h_(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?p_(s):null}catch{n=null}return s&&Ww({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){Ww({workflow:t,change:i,runId:i});try{await Vd(e,iV({workflow:t,previous:c,next:o,initial:s===null,observedAt:new Date().toISOString()}))}catch{}try{n=p_(o)}catch{n=null}}return l}}}import{promises as oV}from"node:fs";var xc=vt(jt(),1);import{createHash as aV}from"node:crypto";import hs from"node:path";import{isDeepStrictEqual as cV}from"node:util";var g_=new Set(["language","contextCompression","autoTransition","reviewMode"]);var w_=new sV;function lV(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 cV(e,t)}function y_(e,t){return Object.keys(e).filter(r=>!Ar(e[r],t[r]))}function Mw(e){return e.actions.some(kd)}function Ao(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=h_(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 G of await En(e,p)){let te;try{te=await Pe(e,G,{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:G,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=nn(g[_t],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,S=w.workflow.id.replace(/^comet-classic-/u,""),E=k?y_(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(G=>!g_.has(G))||b?.change!==p||b.changeDir!==`openspec/changes/${p}`&&b.changeDir!==`docs/openspec/changes/${p}`||z&&!k.archived&&!Mw(w)||!["full","hotfix","tweak"].includes(S)||w.workflow.id!==`comet-classic-${S}`||k.workflow!==S&&!bd(w,S)||!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,J={...w,revision:D,...u?{state:k}:{}};if(u&&j(u)!==j({...J,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:ua,workflow:"classic",change:p,format:"sdk",application:t.identity?.id??`classic-${S}`,runId:p}),D===1&&!u?await o.compareAndSwap(p,null,J):await o.restoreCheckpoint(p,u?1:null,J),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 oV.stat(h)).isDirectory())return fe(h)}catch(b){if(b.code!=="ENOENT")throw b}if(!p.state.archived&&!Mw(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 yc(()=>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 S;try{S=await Pe(e,k,{label:"Classic state file"})}catch(K){if(K.code!=="ENOENT")throw K;S=null}let E=S===null?new xc.Document:(0,xc.parseDocument)(S,{uniqueKeys:!0});if(E.errors.length>0)throw new Error(`Invalid Classic state file: ${E.errors[0].message}`);let O=E.toJS(),z=S===null?null:ur(O).classic,D=Eo(O?.[_t],g,{projection:r});if(D)return(S===null||!ir(S)||!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=nn(O?.[_t],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=y_(ne,z);if(ze.some(P=>!g_.has(P))){let P=g.input?.recoverySourceHash,F=g.revision===1&&typeof P=="string"&&S!==null&&aV("sha256").update(S).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 yc(()=>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&&Aa(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 yc(()=>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?.[_t],ne=K===void 0;return K!==void 0&&r?ne=ns(K,g):K!==void 0&&(ne=fc(K,lo(g))),(S===null||!ir(S)||!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 J=cu(w),G=O??{};for(let[K,ne]of Object.entries(J))Ar(G[K],ne)||(ne===void 0?E.delete(K):E.set(K,ne));let te=fd(lo(g));Ar(G[_t],te)||E.set(_t,te),t.identity&&!Ar(G.application_checkpoint,t.identity)&&E.set("application_checkpoint",t.identity);let Z=E.toString(),we=ir(Z)?Z:Nm+Z;return S!==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&&w_.getStore()?.has(c(p)))return await s(!0),o.read(p);if(!t.readOnly){await s(!0);try{let u=await Ao(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 Ao(e,{...t,store:o,readOnly:!0},!0).read(p);return await s(!0),u},async compareAndSwap(p,u,m){return yc(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&&Mw(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=w_.getStore(),w=c(p);g&&!t.identity&&m.workflow.version==="2"&&!lV(m)?g.set(w,()=>d(p,!1)):(g?.delete(w),await d(p,!1))}return h})}}}import{isDeepStrictEqual as pV}from"node:util";var v_=vt(jt(),1);import dV 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 Co(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 k_(e,t,r){if(!Cw(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>");Dw(r);let i={checkpointHash:await fV(e,t),archiveActionId:n.archive.id,checkActionId:n.check.id,reports:r};return await Ud(e,t,i,"prepare"),i}}async function fV(e,t){let r=ps(t),n=await Pe(e,await fe(dV.join(e,r.archiveRef)),{label:"Classic archived delivery checkpoint",maxBytes:Number.MAX_SAFE_INTEGER}),i=(0,v_.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)&&Eo(o,t,{projection:!0})===null)throw new Error("Classic archived checkpoint changed after the authoritative Run was read");return j(o)}function b_(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 k_(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||!Ro(l,f)||f.claim?.executorId!=="comet-classic-check")return{accepted:!1,reason:"Classic delivery repair check has the wrong execution owner"};{let p=So(f);if(a.status!=="succeeded"||!pV(a.output,{...p.reports,deliveryPaths:Sw(l,p)}))return{accepted:!1,reason:"Classic delivery repair reports differ from the submitted reports"}}return a.status==="succeeded"&&await Ud(d.projectRoot,l,So(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,So(l),"prepare")},async execute(l,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");{let d=So(l);return{status:"succeeded",output:{...d.reports,deliveryPaths:Sw(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 R_(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=R_(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"}}},S_={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}}}},Fw={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===S_.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 C_(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 Hw={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"&&(C_(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_(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 Bw={id:"comet-classic-archive-repair-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=r,s=E_(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 zx(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 mV(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:Fw.id,version:Fw.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:Hw.id,version:Hw.version}}}:{},...r?{"repair-archive":{stepId:`${t==="full"?"full":e}.open`,validator:{id:Bw.id,version:Bw.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?[Hw]:[],...r?[Bw]:[],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?[S_]:[]],validators:[...o.validators,...i?[Fw]:[]],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 A_(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=mV(e,i==="full"&&e!=="full"?"full":!0);if(t.workflow.hash===j(Wr(s.workflow)))return s;let o=b_(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 Jd(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=Ao(e,r),c=await o.read(i.runId),l=A_(s,c);if(c){let b=Xg(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 S=await o.read(b);return S&&Xg(S,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"?xo.resolve(e,d.input.changeDir):null,m=u?xo.join(xo.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)&&xo.dirname(n)===m&&/^\d{4}-\d{2}-\d{2}-/u.test(xo.basename(n))&&xo.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 eee}from"node:crypto";var O_=vt(jt(),1);import xr from"node:path";var gV=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 wV(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>{let r=t.toUpperCase();return!gV.has(r)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(r)}))}function x_(e){return{...wV(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"}}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 Uw(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 cn(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 yV(e,t,r){let n=xr.join(t,".comet",r);if(await Lt(e,n,{label:"Classic progress",expected:"file"}))return JSON.parse(await Pe(e,n,{label:"Classic progress"}))}function vV(e,t){let r=Qd("sha256").update(t).digest("hex");return xr.join(pt(e),"classic-delivery",`${r}.json`)}async function kV(e,t){let r=vV(e,t);if(!await Lt(e,r,{label:"Classic delivery reauthorization",expected:"file"}))return null;let n=gs(JSON.parse(await Pe(e,r,{label:"Classic delivery reauthorization"})));if(Uw(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=zw({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:cn(n.previousAuthorizationId,"previousAuthorizationId"),authorizationId:cn(n.authorizationId,"authorizationId"),...i,targetBranch:i.targetBranch,...n.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:cn(n.authorizedRemoteUrl,"authorizedRemoteUrl")}}}function zw(e,t=!1){let r=gs(e);if(Uw(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=cn(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=cn(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=cn(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=cn(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 T_(e){let t=(0,O_.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length)throw new Error("Invalid Classic delivery change state");return gs(t.toJS())}function bV(e,t,r){return typeof e.run_id=="string"&&e.run_id?`run:${e.run_id}`:N_(e,t,r)}function N_(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 $_(e,t,r,n){let i=bV(t,r,n);if(e===i)return i;if(typeof e=="string"&&e.startsWith("legacy:")&&e===N_(t,r,n))return e;throw new Error("Classic delivery change identity mismatch")}var RV=je("classicCurrentState",async(e,t)=>SV(e,t));async function SV(e,t){return T_(await Pe(e,await fe(t),{label:"Classic delivery state"}))}async function CV(e,t){return RV(e,t)}var Xd=class extends Error{constructor(t,r){super(`Classic delivery git command timed out: ${[t,...r].join(" ")}`)}};function Vw(e,t,r,n){return WA(t,r,{cwd:e,timeoutMs:5e3,env:x_({authentication:n})}).trim()}function Oc(e,t,r,n=!1){try{return Vw(e,t,r,n)}catch{return null}}function EV(e,t,r,n=!1){try{return Vw(e,t,r,n)}catch(i){if(!(i instanceof di)||!i.timedOut)return null;try{return Vw(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 Gd(e,t){return EV(e,"git",["-C",e,...t])}function __(e,t,r=!1){return Oc(e,"git",["-C",e,"remote","get-url",...r?["--push"]:[],t],!0)}function AV(e,t){let r=xr.relative(e,t).replaceAll("\\","/");return[`:(literal)${r}`,...[".comet-state.lock",".comet-state-transaction.json",...[...$m].map(n=>`.comet/${n}`)].map(n=>`:(exclude,literal)${r}/${n}`)]}function I_(e,t,r,n){let i=xr.relative(e,t).replaceAll("\\","/"),s=AV(e,t),o=Ns.map(l=>Gd(e,["show",`${r}:${i}/${l}`])).filter(l=>l!==null);if(o.length!==1)return!1;let c=o[0];try{let l=T_(c);return l.archived===!0&&$_(n,l,t,e)===n&&Gd(e,["merge-base","--is-ancestor",r,"HEAD"])!==null&&Gd(e,["diff","--quiet","--no-ext-diff","--no-textconv",r,"--",...s])!==null&&Gd(e,["ls-files","--others","--exclude-standard","--",...s])===""}catch(l){if(l instanceof Xd)throw l;return!1}}function xV(e){return Qd("sha256").update(e).digest("hex")+".json"}async function _V(e,t){let r=xV(t);return[{root:xr.dirname(pt(e)),file:xr.join(pt(e),"classic-delivery-receipts",r)}]}function IV(e,t){let r=gs(e);if(Uw(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=zw({action:"local",targetBranch:"main",...r.commit!==void 0?{commit:r.commit}:{},...r.prUrl!==void 0?{prUrl:r.prUrl}:{}});return{schemaVersion:1,changeIdentity:t,authorizationId:cn(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:OV(r.archiveFiles)}}}async function PV(e,t){let r=null;for(let n of await _V(e,t)){if(!await Lt(n.root,n.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=IV(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 OV(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 TV(e){return e.authorizationId===void 0?`legacy:${Qd("sha256").update(JSON.stringify(e)).digest("hex")}`:cn(e.authorizationId,"authorizationId")}function P_(e,t,r){return t===r||Pc(e,["merge-base","--is-ancestor",t,r])!==null}function NV(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 yV(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=zw(s,!0),c=await CV(e,t),l=$_(s.changeIdentity,c,t,e),f=TV(s),a=await kV(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 PV(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:cn(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("\\","/"),S=null;!d.commit&&c.archived===!0&&(S=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)&&I_(e,t,ne,l))??null);let E=d.commit??S,O=!!E&&Pc(e,["cat-file","-t",E])==="commit",z=c.archived===!0&&O&&I_(e,t,E,l),D=k===d.targetBranch&&(!c.bound_branch||a!==null||c.bound_branch===k)&&z,J=!1,G=!1,te=null,Z=r.verifyRemote&&d.action!=="local"?"unavailable":"notChecked",we="notChecked";if(r.verifyRemote&&D&&d.action!=="local"&&d.remote&&g&&__(e,d.remote)===g&&__(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;J=!!E&&!!F&&P_(e,E,F),Z=J?"verified":ne===""?"missing":ne===null||!F||Pc(e,["cat-file","-t",F])!=="commit"?"unavailable":"missing";let re=NV(g),He=re&&d.prUrl?Yd(d.prUrl,re):null,C=J||ne==="",$=T=>T.headRefName===d.targetBranch&&typeof T.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(T.headRefOid)&&(J?T.headRefOid===F&&["OPEN","MERGED"].includes(T.state):ne===""&&T.state==="MERGED"&&!!E&&P_(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;G=!!L&&typeof L.url=="string"&&Yd(L.url,re)===He&&$(L),we=G?"verified":L?"missing":"unavailable"}catch{G=!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),G=!0,we="verified"):we=H.length===0?"missing":"unavailable"}catch{we="unavailable"}}}return{delivery:w,verification:{status:D&&(d.action==="local"||(d.action==="push"?J:G))?"complete":"needsVerification",currentBranch:k,commitExists:O,archiveCommitted:z,observedCommit:S,observedPrUrl:te,remoteVerified:J,prVerified:G,remoteStatus:Z,prStatus:we}}}var LV=vt(jt(),1);import{AsyncLocalStorage as Kw}from"node:async_hooks";var vee=new Kw,kee=new Kw,bee=new Kw;mn();Zl();ye();Dt();$t();import{stripVTControlCharacters as $V}from"node:util";function Jw(e,t={}){return{code:"CLASSIC_COMMAND_FAILED",message:$V(e instanceof Error?e.message:String(e)),...t}}var WV=je("readCometCurrentSelection",e=>js(e)),MV=je("classicHookSdkRun",(e,t)=>Jd(e,t,{readOnly:!0}));async function FV(e,t){let{run:r,state:n}=await MV(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 HV(e,t){on(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 j_(e){let t;try{t=await WV(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 FV(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 HV(e,r.change)}catch(s){try{let o=await uw(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 xa(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}}Dt();Cm();mn();import BV from"os";import ef from"path";function VV(e={}){let t=e.cwd??process.cwd(),r=e.homeDir??BV.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 D_(e,t={}){for(let r of VV(t)){let n=ef.dirname(ef.dirname(r.file)),i=r.scope==="global"?(await Sm(n))?.classic:(await pn(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 D_("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 UV(e,t){return[Ae(e,t.openSpecRoot),Ae(e,t.superpowersRoot)]}async function q_(e,t,r){return await Gw(e)==="strict"?!1:Mb(r,UV(e,t))}var zV=je("classicHookSdkRun",(e,t)=>Jd(e,t,{readOnly:!0})),KV=je("classicHookWritableLayout",e=>Ni(e));function ft(e,t){return{exitCode:e,stderr:t+`
|
|
266
|
+
`}}function Ot(e){return ft(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 sy(t)}function Tc(e){return e.replaceAll("\\","/").replace(/\/+/gu,"/")}function Ht(e){let t=Tc(e);return process.platform==="win32"?t.toLowerCase():t}function GV(e){let t=e.indexOf("--project-root"),r=t>=0?e[t+1]:void 0;return Tt.resolve(r&&!r.startsWith("--")?r:process.cwd())}function L_(e,t){let r=Tc(Tt.relative(t,e));return r===""?"":r.startsWith("../")||r===".."||Tt.isAbsolute(r)?null:r}async function YV(e){let t=Tt.resolve(e),r=Tt.parse(t).root,n=[],i=t;for(;i&&i!==r;)try{let s=await tf.realpath(i);return Tt.join(s,...n.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;n.push(Tt.basename(i)),i=Tt.dirname(i)}try{let s=await tf.realpath(r);return Tt.join(s,...n.reverse())}catch{return null}}async function XV(e,t){let r=Tt.isAbsolute(e)?e:Tt.resolve(t,e),n=Tc(r),i=L_(r,t);if(i!==null)return i;try{let s=await YV(r),o=await tf.realpath(t);if(s){let c=L_(s,o);if(c!==null)return c;n=Tc(s)}}catch{if(!Tt.isAbsolute(e))return Tc(e).replace(/^\.\//u,"")}return n.replace(/^\.\//u,"")}async function Yw(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 xR(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 Xw(e,t,r){let{run:n,state:i}=await zV(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 QV(e){let t=(await gt(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 Xw(e,i.name,s.directory):s.stateExists?await Yw(s.directory):null;!o||o.archived||o.cancelled||r.push(o)}return r}var Qw=je("classicActiveChanges",e=>QV(e)),Zw=je("classicActiveChange",async(e,t)=>{let r=await An(t,e);if(await Tr(e,"classic",t,{readOnly:!0})){let i=await Xw(e,t,r.directory);return i.archived||i.cancelled?null:i}if(!r.exists||!r.stateExists)return null;let n=await Yw(r.directory);return!n||n.archived||n.cancelled?null:n}),H_=je("classicPlanReadiness",mi);function B_(e,t){return`${Ae(e,t.superpowersRoot)}/`}function V_(e,t){return Ht(e).startsWith(Ht(t))}function U_(e,t){return[{prefix:`${Ae(e,t.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${Ae(e,t.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${Ae(e,t.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function z_(e,t){let r=Ht(e),n=t.find(s=>r.startsWith(Ht(s.prefix)));if(!n)return null;let i=r.slice(Ht(n.prefix).length);return!i||i.includes("/")||!i.endsWith(".md")?null:n}function K_(e,t){return e.classic?.[t.field]??null}function ZV(e,t){return e.classic!==null&&e.phase===t.phase&&!K_(e,t)}async function W_(e,t,r){return ZV(t,r)?!0:r.field!=="plan"||t.phase!=="build"?!1:(await H_(e,t.classic?.plan??null,{requireNonempty:t.classic?.buildMode==="autonomous"})).status==="broken"}function J_(e){return e.phase==="design"||e.phase==="build"||e.phase==="verify"}function ki(e){return e.changeDir?Tt.basename(e.changeDir):null}var eU=new Set(["design","plan","verify","verification","verification-report","report"]);function M_(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function tU(e,t){return[t.classic?.designDoc,t.classic?.plan,t.classic?.verificationReport].some(n=>n&&Ht(n)===Ht(e))}function rU(e,t){let n=(e.split("/").at(-1)??e).replace(/\.[^.]+$/u,"");if(n===t)return!0;let i=[...eU].map(M_).join("|");return new RegExp(`(^|[-_.])${M_(t)}[-_.](${i})$`,"u").test(n)}async function nU(e,t,r){let n=r?[await Zw(t,r)].filter(c=>c!==null):await Qw(t),i=n.find(c=>tU(e,c));if(i)return{governing:i,match:"recorded"};let o=n.filter(J_).filter(c=>{let l=ki(c);return l!==null&&rU(e,l)}).sort((c,l)=>(ki(l)?.length??0)-(ki(c)?.length??0))[0];return o?{governing:o,match:"named"}:null}async function F_(e,t,r){if(r)return await Zw(e,r)??{blockedResult:ws(t,`selected change '${r}' is no longer active`)};let n=await Qw(e);if(n.length===0)return null;let i=await j_(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 xa(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:mU(t,n.map(s=>ki(s)).filter(Boolean))}}function iU(e){let r=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(e)?.[1]??e;return ho(r)?null:r}function G_(e,t,r){let n=`${Ae(t,r.changesDir)}/`;if(!Ht(e).startsWith(Ht(n)))return null;let i=e.slice(n.length).split("/").filter(Boolean),[s,o]=i;return s?Ht(s)===Ht("archive")?{kind:"archive",archiveName:o??null,changeName:o?iU(o):null}:{kind:"active",changeName:s}:null}function Y_(e,t,r){return t?.kind==="archive"?gU(e,t.archiveName,t.changeName,r):t?.kind==="active"&&r&&Ht(t.changeName)!==Ht(r)?hU(e,t.changeName,r):null}async function sU(e,t,r,n){let i=G_(e,t,r),s=Y_(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 Xw(t,o,c.directory);return l.archived?{blockedResult:ws(e,`Classic SDK change '${o}' is already archived`)}:l}if(c.stateExists){let l=await Yw(c.directory);return l||{changeDir:c.directory,phase:"open",classic:null,archived:!1}}return{changeDir:c.directory,phase:"open",classic:null,archived:!1}}if(V_(e,B_(t,r))){let o=await nU(e,t,n);if(o?.match==="recorded")return{...o.governing,superpowersArtifact:"matched"};let c=z_(e,U_(t,r));if(o)return c?{...o.governing,superpowersArtifact:await W_(t,o.governing,c)?"matched":"unmatched",superpowersSlot:c}:{...o.governing,superpowersArtifact:"matched"};if(c){let f=await F_(t,e,n);return!f||"blockedResult"in f?f:{...f,superpowersArtifact:await W_(t,f,c)?"matched":"unmatched",superpowersSlot:c}}let l=n?await Zw(t,n):(await Qw(t))[0]??null;return l?{...l,superpowersArtifact:"unmatched"}:null}return F_(t,e,n)}function oU(e){return!e.includes("/")&&e.endsWith(".md")}function aU(e){return e.startsWith(".comet/")||e.includes("/.comet/")}function cU(e){return e===".superpowers"||e.startsWith(".superpowers/")}function lU(e,t,r){let n=Ht(e);if(!n.startsWith(Ht(r)))return null;let i=pa(Tt.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 uU(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 X_(e,t,t,n,i)}function X_(e,t,r,n,i){let s=XA(r,n);return ft(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t}`,` Target file: ${e}`,"",` ${s.summary}`,` RELAY TO USER: ${s.user_message}`,"",...i,""].join(`
|
|
268
|
+
`))}function dU(e,t,r){return X_(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 fU(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?Ae(n,t.changeDir):"<classic-change-dir>",d=Ae(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 ft(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 pU(e,t){let r=t.superpowersSlot,n=r?K_(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 ft(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t.phase}`,` Target file: ${e}`,"",...i,""].join(`
|
|
270
|
+
`))}function mU(e,t){return ft(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 ft(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 hU(e,t,r){return ft(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 gU(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 ft(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 wU(e,t,r,n=Jl,i){try{if((await n(e,[t])).projectTargets.length===0)return Ot(`${t} (outside guarded project)`)}catch(h){return ft(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 XV(t,e),o;try{o=await KV(e)}catch(h){return ft(2,`[COMET-HOOK] blocked: ${h instanceof Error?h.message:String(h)}`)}let c=G_(s,e,o),l=Y_(s,c,r);if(l)return l;if(aU(s))return Ot(`${s} (whitelist: comet config)`);if(gm(s,Tt.relative(e,o.changesDir))&&!s.replaceAll("\\","/").includes("/archive/"))return Ot(`${s} (change walkthrough)`);if(cU(s))return Ot(`${s} (whitelist: superpowers workspace)`);if(await q_(e,o,s))return Ot(`${s} (whitelist: neutral document)`);if(s==="CHANGELOG.md"||s==="README.md"||oU(s)&&!hm(s))return Ot(`${s} (whitelist: root markdown)`);let f=await pm(e,t,[Tt.join(e,".comet"),o.openSpecRoot,o.superpowersRoot]);if(f)return Ot(f);let a;try{a=await sU(s,e,o,r)}catch(h){return ft(2,`[COMET-HOOK] blocked: ${h instanceof Error?h.message:String(h)}`)}if(!a)return Ot("no active comet change");if("blockedResult"in a)return a.blockedResult;if(a.cancellationPending)return ft(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 ft(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 Ot(`${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 xa(a.changeDir,{heal:!1,cwd:e});if(h.status==="drift")return ft(2,Ws(p,h.boundBranch,h.currentBranch));if(h.status==="unbound-detached")return ft(2,Ms(p))}catch(h){return ft(2,h instanceof Error?h.message:String(h))}let u=z_(s,U_(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 ft(2,h.join(`
|
|
276
|
+
`))}let m=lU(s,d,`${Ae(e,o.openSpecRoot)}/`);if(m)return Ot(m);if(V_(s,B_(e,o))){if(a.superpowersArtifact==="matched"&&J_(a))return Ot(`${s} (phase: ${d}, superpowers)`);if(a.superpowersArtifact==="unmatched")return pU(s,a)}if(a.invalidState)return ft(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 Ot(`${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 dU(s,p,kc(a.classic?.language));if(d==="build"&&a.classic?.workflow==="full"){let h=await H_(e,a.classic.plan,{requireNonempty:a.classic.buildMode==="autonomous"});if(h.status!=="ready")return fU(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 ft(2,h.join(`
|
|
277
|
+
`))}return Ot(`${s} (phase: ${d})`)}return d==="verify"&&i?.writes?Ot(s+" (保留当前阶段;由 Agent 判断修改影响,修复实现前通过 Runtime 返回 Build)"):uU(s,d,p,kc(a.classic?.language))}var Q_=async e=>{let t=GV(e),r=await JV();if(!r.targets.length)return Ot("no file path in tool input");let n;for(let i of r.targets){let s=await wU(t,i,void 0,void 0,r);if(s.exitCode!==0)return s;n=s}return r.targets.length===1&&n?n:Ot("all write targets passed the Classic guard")};var yU=new Set([...ka,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),Z_=new Set(Jn.filter(e=>!yU.has(e))),ey={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 vU=`
|
|
278
|
+
Options: --json (machine-readable output), --compact (requires --json), --help
|
|
279
|
+
精简视图用 outputView.references 的 JSON Pointer 定位重复字段;Request 模板保留完整;没有字节收益时返回原完整协议。去掉 --compact 获取完整协议。
|
|
280
|
+
JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
|
|
281
|
+
Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
|
|
282
|
+
`;function eI(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: ${[...Jn,...ka].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):",...[...Z_].map(l=>` ${l}${ey[l]?`: ${ey[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: ${dA.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(`
|
|
283
|
+
`)}
|
|
284
|
+
${vU}Command placeholders must be replaced with actual values.
|
|
285
|
+
`:void 0}function tI(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 kU}from"node:crypto";import{performance as rI}from"node:perf_hooks";var bU=7*864e5,RU=1e4;async function SU(e,t){let r=co(await Hd(e,!0));try{r.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
286
|
+
CREATE TABLE IF NOT EXISTS samples (
|
|
287
|
+
id TEXT PRIMARY KEY, workflow TEXT NOT NULL, kind TEXT NOT NULL, command TEXT NOT NULL,
|
|
288
|
+
occurredAt TEXT NOT NULL, durationMs REAL NOT NULL, exitCode INTEGER NOT NULL,
|
|
289
|
+
gitCommands INTEGER NOT NULL, gitDurationMs REAL NOT NULL);
|
|
290
|
+
CREATE INDEX IF NOT EXISTS samples_time ON samples(occurredAt);
|
|
291
|
+
BEGIN IMMEDIATE;`),r.prepare("DELETE FROM samples WHERE occurredAt < ?").run(new Date(Date.now()-bU).toISOString()),r.prepare("INSERT INTO samples VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(kU(),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(RU),r.exec("COMMIT")}finally{r.close()}}async function nI(e,t){let r=rI.now(),n,i,s=!1,o=1,c=!0,{metrics:l}=await d_({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"}},()=>zb(async()=>{try{n=await t()}catch(a){s=!0,i=a}})),f=Math.max(0,rI.now()-r);try{if(!c)throw new Error("Runtime result classification unavailable");await SU(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 CU(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e,exitCode:t.exitCode,agent:tI(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}})+`
|
|
292
|
+
`,...t.envelope===void 0?{}:{envelope:t.envelope}}}async function EU(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=eI(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 Ub(()=>nI({projectRoot:()=>n.projectRoot??lt(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:[Jw(f)]}}}return o?CU(e,l):l}async function iI(e,t,r=process.argv.slice(2)){let n=await EU(e,t,r);return n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr+(n.stderr.endsWith(`
|
|
293
|
+
`)?"":`
|
|
294
|
+
`)),n.exitCode}process.exitCode=await iI("hook-guard",Q_);
|