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,470 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var Uj=Object.create;var bh=Object.defineProperty;var Jj=Object.getOwnPropertyDescriptor;var zj=Object.getOwnPropertyNames;var Kj=Object.getPrototypeOf,Gj=Object.prototype.hasOwnProperty;var Fu=(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 _=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var O=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Nh=(e,t)=>{for(var r in t)bh(e,r,{get:t[r],enumerable:!0})},Yj=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of zj(t))!Gj.call(e,i)&&i!==r&&bh(e,i,{get:()=>t[i],enumerable:!(n=Jj(t,i))||n.enumerable});return e};var kr=(e,t,r)=>(r=e!=null?Uj(Kj(e)):{},Yj(t||!e||!e.__esModule?bh(r,"default",{value:e,enumerable:!0}):r,e));async function Oa(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let n=new Array(e.length),i=0,o=!1,a=async()=>{for(;!o&&i<e.length;){let l=i;i+=1;try{n[l]=await r(e[l],l)}catch(u){throw o=!0,u}}},c=(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>a()))).find(l=>l.status==="rejected");if(c?.status==="rejected")throw c.reason;return n}var Hu=_(()=>{"use strict"});import{AsyncLocalStorage as Xj}from"node:async_hooks";function Qu(){let e=Rh.getStore();return e?.active?e:null}function mN(){Qu()?.entries.clear()}async function sc(e){if(Qu()!==null)return e();let t={entries:new Map,active:!0};return Rh.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function An(e){return Rh.run({entries:new Map,active:!1},e)}function hN(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function Qt(e,t){return(...r)=>{let n=Qu();if(n===null)return t(...r);let i=hN(`async:${e}`,r),o=n.entries.get(i);if(o)return o.value;let a=t(...r).catch(s=>{throw n.entries.get(i)?.value===a&&n.entries.delete(i),s});return n.entries.set(i,{value:a}),a}}function ai(e,t){return(...r)=>{let n=Qu();if(n===null)return t(...r);let i=hN(`sync:${e}`,r),o=n.entries.get(i);if(o)return o.value;let a=t(...r);return n.entries.set(i,{value:a}),a}}var Rh,bn=_(()=>{"use strict";Rh=new Xj});import{createHash as Zj}from"node:crypto";import{lstatSync as cc,readFileSync as eD,realpathSync as gN}from"node:fs";import tD from"node:os";import sr from"node:path";function Sh(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function Uu(e){return process.platform==="win32"?gN.native(e):gN(e)}function nD(e){return rD(e)}function iD(e){let t=Uu(sr.resolve(e)),r=cc(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=Sh(r),i=(c,l)=>({projectRoot:t,workspaceId:Zj("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,c,l])).digest("hex")}),o=sr.join(t,".git"),a,s;try{let c=cc(o);if(c.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${o}`);if(c.isDirectory())a=Uu(o),s=Sh(cc(a,{bigint:!0}));else if(c.isFile()){let l=/^gitdir: (.+)\r?\n?$/u.exec(eD(o,"utf8"));if(!l)throw new Error(`工作区 .git 文件格式无效:${o}`);a=Uu(sr.resolve(t,l[1].trim()));let u=cc(a,{bigint:!0});if(!u.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${a}`);s=Sh(u)}else throw new Error(`工作区 .git 类型无效:${o}`)}catch(c){if(c.code!=="ENOENT")throw c;try{cc(o)}catch(l){if(l.code==="ENOENT")return i(o,null);throw l}throw c}return i(a,s)}function vN(e){let t=sr.dirname(e);if(t===e)return e;try{return sr.join(Uu(t),sr.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return sr.join(vN(t),sr.basename(e))}}function Eh(e){let t=nD(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!sr.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=oD(r??sr.join(tD.homedir(),".comet")),i=sr.relative(t.projectRoot,n);if(i===""||!sr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${sr.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let o=sr.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:o,runtimeRoot:sr.join(o,"runtime")}}function Ze(e){return Eh(e).runtimeRoot}var rD,oD,Ch=_(()=>{"use strict";bn();rD=ai("workspaceIdentity",iD);oD=ai("workspaceRuntimeParent",vN)});function Ti(e){return e!==0&&e!==0n&&e!=="0"}function lc(e,t){return Ti(e.dev)&&Ti(t.dev)&&Ti(e.ino)&&Ti(t.ino)}function ft(e,t){let r=Ti(e.dev)&&Ti(t.dev);if(r&&e.dev!==t.dev)return!1;let n=Ti(e.ino)&&Ti(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var $a=_(()=>{"use strict"});import{constants as Oi,promises as Ar}from"fs";import{createHash as aD}from"node:crypto";function _h(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ju(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ji(e){return{dev:e.dev,ino:e.ino,birthtime:_h(e)}}function sD(e,t){let r=ji(e),n=ji(t);return lc(r,n)?ft(r,n):ft(r,n)&&_h(e)===_h(t)&&Ju(e)===Ju(t)&&e.size===t.size}function $i(e,t){let r=n=>"mtimeNs"in n?n.mtimeNs:n.mtimeMs;return sD(e,t)&&e.size===t.size&&e.mode===t.mode&&r(e)===r(t)&&Ju(e)===Ju(t)}async function Io(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,o=await Ar.lstat(e,{bigint:i});if(!o.isFile()||o.isSymbolicLink())throw new Ut("not-regular-file",`${n} must be a regular file`);if(BigInt(o.size)>BigInt(t))throw new Ut("too-large",`${n} exceeds ${t} bytes`);let a=await Ar.realpath(e);await r.verify?.("pre-open",{realPath:a,identity:ji(o)});let s=process.platform==="win32"?Oi.O_RDONLY:Oi.O_RDONLY|Oi.O_NOFOLLOW|Oi.O_NONBLOCK,c;try{c=await Ar.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ut("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:i}),Ar.lstat(e,{bigint:i}),Ar.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==a||!$i(o,l)||!$i(o,u))throw new Ut("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:ji(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:A}=await c.read(h,0,Math.min(h.length,w),null);if(A===0)break;if(p+=A,p>t)throw new Ut("too-large",`${n} exceeds ${t} bytes`);d.push(Buffer.from(h.subarray(0,A)))}await r.hooks?.beforeFinalCheck?.();let[m,g,v]=await Promise.all([c.stat({bigint:i}),Ar.lstat(e,{bigint:i}),Ar.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==a||!$i(o,m)||!$i(o,g))throw new Ut("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:ji(m)}),{bytes:Buffer.concat(d,p),stat:m,realPath:v}}finally{await c.close()}}async function wN(e,t={}){let r=t.label??"file",n=t.bigint===!0,i=await Ar.lstat(e,{bigint:n});if(!i.isFile()||i.isSymbolicLink())throw new Ut("not-regular-file",`${r} must be a regular file`);let o=await Ar.realpath(e);await t.verify?.("pre-open",{realPath:o,identity:ji(i)});let a=process.platform==="win32"?Oi.O_RDONLY:Oi.O_RDONLY|Oi.O_NOFOLLOW|Oi.O_NONBLOCK,s;try{s=await Ar.open(e,a)}catch(c){throw c.code==="ELOOP"?new Ut("not-regular-file",`${r} must be a regular file`,{cause:c}):c}try{let[c,l,u]=await Promise.all([s.stat({bigint:n}),Ar.lstat(e,{bigint:n}),Ar.realpath(e)]);if(!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!$i(i,c)||!$i(i,l))throw new Ut("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:ji(c)}),await t.hooks?.afterOpen?.();let f=aD(t.algorithm??"sha256"),d=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:g}=await s.read(d,0,d.length,null);if(g===0)break;f.update(d.subarray(0,g))}await t.hooks?.beforeFinalCheck?.();let[p,h,m]=await Promise.all([s.stat({bigint:n}),Ar.lstat(e,{bigint:n}),Ar.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||m!==o||!$i(i,p)||!$i(i,h))throw new Ut("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:m,identity:ji(p)}),{digest:f.digest("hex"),stat:p,realPath:m}}finally{await s.close()}}var Ut,Di=_(()=>{"use strict";$a();Ut=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{promises as yN}from"node:fs";import cD from"node:path";async function si(e){return Ze(e)}async function Ih(e){return[Ze(e)]}async function kN(e){let t=cD.dirname(e);if(t!==e){await kN(t);try{await yN.mkdir(e,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}}let r=await yN.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function ci(e){let t=Ze(e);return await kN(t),t}var Xr=_(()=>{"use strict";Ch();Di()});import{types as lD}from"node:util";import{createHash as uD}from"node:crypto";function NN(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=bN.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&bN.set(e,n),n}function dD(e,t,r){let n=new WeakMap,i=v=>{let w=n.get(v);if(w)return w;let A=Array.isArray(v)?[...v]:{...v};return n.set(v,A),A},o=i(e),a=[],s=[],c=[],l=new Map,u=new Map,f=new WeakMap,d=new Map,p=new Map,h=new Map,m=v=>{let w=v&&typeof v=="object"?f.get(v):void 0;if(w!==void 0)return w;let A=NN(v,r);return w=l.get(A),w===void 0&&(w=a.length,a.push(v),l.set(A,w)),v&&typeof v=="object"&&f.set(v,w),w},g=v=>{let w=h.get(v);if(w!==void 0)return w;let A=v.base===void 0?void 0:g(v.base),N=s.length;return s.push({...A===void 0?{}:{base:A},entries:v.entries.map(([b,E])=>[b,m(E)]),removed:[...v.removed]}),h.set(v,N),N};for(let v of t){let w=o,A=e;for(let z of v.path.slice(0,-1)){A=A[z];let X=i(A);Object.defineProperty(w,z,{value:X,enumerable:!0,writable:!0,configurable:!0}),w=X}let N=v.path.at(-1),b=w[N];if(!b||typeof b!="object"||Array.isArray(b))continue;if(r?.(b)){let z=AN.get(b);if(!z){let X=b,de=p.get(v.group),se=Object.entries(X),De=de?se.filter(([Ht,B])=>!Object.hasOwn(de.source,Ht)||m(de.source[Ht])!==m(B)):se,Z=de?Object.keys(de.source).filter(Ht=>!Object.hasOwn(X,Ht)):[],Xe=de&&De.length+Z.length<se.length;z={...Xe?{base:de.node}:{},entries:Xe?De:se,removed:Xe?Z:[]},AN.set(b,z)}p.set(v.group,{source:b,node:z}),c.push({path:v.path,map:g(z)}),Object.defineProperty(w,N,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let E=new Map;for(let[z,X]of Object.entries(b)){let de=X&&typeof X=="object"?f.get(X):void 0;if(de===void 0){let se=NN(X,r);de=l.get(se),de===void 0&&(de=a.length,a.push(X),l.set(se,de)),X&&typeof X=="object"&&f.set(X,de)}E.set(z,de)}let V=JSON.stringify([...E]),j=u.get(V);if(j===void 0){let z=d.get(v.group),X=[...E].filter(([De,Z])=>z?.entries.get(De)!==Z),de=z?[...z.entries.keys()].filter(De=>!E.has(De)):[],se=z&&X.length+de.length<E.size;j=s.length,s.push({...se?{base:z.id}:{},entries:se?X:[...E],removed:se?de:[]}),u.set(V,j)}d.set(v.group,{id:j,entries:E}),c.push({path:v.path,map:j}),Object.defineProperty(w,N,{value:{},enumerable:!0,writable:!0,configurable:!0})}return c.length?{record:o,pool:{version:1,values:a,maps:s,bindings:c}}:{record:o}}function fD(){let e=[],t=o=>o===null?0:e[o].height,r=(o,a,s,c)=>{let l=e.length;return e.push({key:o,value:a,left:s,right:c,height:1+Math.max(t(s),t(c))}),l},n=(o,a,s,c)=>{if(t(s)>t(c)+1){let l=e[s];if(t(l.left)>=t(l.right))return r(l.key,l.value,l.left,r(o,a,l.right,c));let u=e[l.right];return r(u.key,u.value,r(l.key,l.value,l.left,u.left),r(o,a,u.right,c))}if(t(c)>t(s)+1){let l=e[c];if(t(l.right)>=t(l.left))return r(l.key,l.value,r(o,a,s,l.left),l.right);let u=e[l.left];return r(u.key,u.value,r(o,a,s,u.left),r(l.key,l.value,u.right,l.right))}return r(o,a,s,c)},i=(o,a,s)=>{if(o===null)return s===void 0?null:r(a,s,null,null);let c=e[o];if(a<c.key){let u=i(c.left,a,s);return u===c.left?o:n(c.key,c.value,u,c.right)}if(a>c.key){let u=i(c.right,a,s);return u===c.right?o:n(c.key,c.value,c.left,u)}if(s!==void 0)return s===c.value?o:r(a,s,c.left,c.right);if(c.left===null)return c.right;if(c.right===null)return c.left;let l=e[c.right];for(;l.left!==null;)l=e[l.left];return n(l.key,l.value,c.left,i(c.right,l.key,void 0))};return{nodes:e,set:i}}function SN(e){let{nodes:t,set:r}=fD(),n=[];for(let c of e.maps){let l=c.base===void 0?null:n[c.base];for(let u of c.removed)l=r(l,u,void 0);for(let[u,f]of c.entries)l=r(l,u,f);n.push(l)}let i=[],o=new Map,a=c=>{if(c===null)return null;let l=o.get(c);if(l!==void 0)return l;let u=t[c],f=a(u.left),d=a(u.right),p=i.length;return i.push({...u,left:f,right:d}),o.set(c,p),p},s=n.map(a);return{version:3,values:e.values,nodes:i,maps:s,bindings:e.bindings}}function EN(e,t,r){let n=dD(e,t,r);return{record:n.record,...n.pool?{pool:SN(n.pool)}:{}}}function*zu(e,t=e.root){if(t===null)return;let r=e.pool.nodes[t];yield*zu(e,r.left),yield[r.key,e.pool.values[r.value]],yield*zu(e,r.right)}function pD(e){let t=n=>{let i=e.root;for(;i!==null;){let o=e.pool.nodes[i];if(n===o.key)return o.value;i=n<o.key?o.left:o.right}},r=new Proxy({},{ownKeys:()=>[...zu(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 li.set(r,e),r}function CN(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return pt("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(o=>!["version","values","maps","bindings"].includes(o))&&pt("JSON 引用池字段无效"),i.maps.forEach((o,a)=>{(!o||!Array.isArray(o.entries)||!Array.isArray(o.removed)||o.base!==void 0&&!ja(o.base,a)||Object.keys(o).some(c=>!["base","entries","removed"].includes(c)))&&pt("JSON 映射引用无效");let s=new Set;for(let c of o.removed)(typeof c!="string"||s.has(c))&&pt("JSON 删除键无效"),s.add(c);for(let c of o.entries)(!Array.isArray(c)||c.length!==2||typeof c[0]!="string"||!ja(c[1],i.values.length)||s.has(c[0]))&&pt("JSON 值引用无效"),s.add(c[0])}),CN(SN(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 pt("JSON 引用池版本或字段无效");let n=[];return r.nodes.forEach((i,o)=>{(!i||typeof i.key!="string"||!ja(i.value,r.values.length)||![i.left,i.right].every(c=>c===null||ja(c,o))||Object.keys(i).some(c=>!["key","value","left","right","height"].includes(c)))&&pt("JSON 树引用无效");let a=i.left===null?void 0:r.nodes[i.left],s=i.right===null?void 0:r.nodes[i.right];(i.height!==1+Math.max(a?.height??0,s?.height??0)||Math.abs((a?.height??0)-(s?.height??0))>1||i.left!==null&&n[i.left].max>=i.key||i.right!==null&&n[i.right].min<=i.key)&&pt("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&&!ja(i,r.nodes.length))&&pt("JSON 映射根无效"),r}function mD(e,t){let r=(h,m=0,g=new Set)=>{if(m>64&&pt("JSON 数据嵌套过深"),!(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"&&Number.isFinite(h))){if(typeof h!="object"||h===null||lD.isProxy(h)||g.has(h))return pt("JSON 数据无效");Object.getPrototypeOf(h)!==Object.prototype&&Object.getPrototypeOf(h)!==null&&!Array.isArray(h)&&pt("JSON 数据必须为普通对象"),g.add(h);for(let v of Reflect.ownKeys(h)){if(Array.isArray(h)&&v==="length")continue;let w=Object.getOwnPropertyDescriptor(h,v);(typeof v!="string"||!w.enumerable||!("value"in w))&&pt("JSON 数据不能包含访问器"),r(w.value,m+1,g)}Array.isArray(h)&&Object.keys(h).length!==h.length&&pt("JSON 数组不能稀疏"),g.delete(h)}};r(e),r(t);let n=CN(structuredClone(t)),i=structuredClone(e),o={validatedNodes:n.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},a=new Set,s=new Set,c=new Set,l=new Map;for(let h of n.bindings){(!h||!Array.isArray(h.path)||h.path.length<1||h.path.length>16||h.path.some(w=>typeof w!="string"||["__proto__","constructor","prototype"].includes(w))||!ja(h.map,n.maps.length)||Object.keys(h).some(w=>!["path","map"].includes(w)))&&pt("JSON 池绑定无效");let m=JSON.stringify(h.path);(s.has(m)||h.path.some((w,A)=>a.has(JSON.stringify(h.path.slice(0,A+1)))))&&pt("JSON 池绑定重复或重叠"),a.add(m),h.path.forEach((w,A)=>s.add(JSON.stringify(h.path.slice(0,A+1))));let g=i;for(let w of h.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,w))&&pt("JSON 池绑定缺失"),g=g[w];let v=h.path.at(-1);(!g||!Object.hasOwn(g,v)||!g[v]||typeof g[v]!="object"||Array.isArray(g[v])||Object.keys(g[v]).length)&&pt("JSON 池绑定必须替换空对象"),Object.defineProperty(g,v,{value:pD({pool:n,root:n.maps[h.map],stats:o,checked:c,origins:l}),enumerable:!0,writable:!0,configurable:!0})}let u=new WeakMap,f=new Map,d=h=>{if(!h||typeof h!="object")return 0;let m=u.get(h);if(m!==void 0)return m;let g=li.get(h),v=A=>{if(A===null)return 0;let N=f.get(A);if(N!==void 0)return N;let b=n.nodes[A],E=Math.max(1+d(n.values[b.value]),v(b.left),v(b.right));return f.set(A,E),E},w=g?v(g.root):Object.values(h).reduce((A,N)=>Math.max(A,1+d(N)),0);return u.set(h,w),w};d(i)>64&&pt("JSON 逻辑数据嵌套超过 64 层"),dc(n),dc(i);let p=h=>{if(!(!h||typeof h!="object"||li.has(h)||uc.has(h))){uc.set(h,o);for(let m of Object.values(h))p(m)}};return p(i),{value:i,stats:o,materialize:(h=[])=>cr(h.reduce((m,g)=>m?.[g],i)),hash:()=>Nn(i)}}function dc(e){let t=new WeakSet,r=n=>{if(!(!n||typeof n!="object"||li.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 cr(e){if(e===null||typeof e!="object")return e;let t=li.get(e);if(t){t.stats.materializedMaps++;let r=[...zu(t)];return t.stats.materializedEntries+=r.length,Object.fromEntries(r.map(([n,i])=>[n,cr(i)]))}return Array.isArray(e)?e.map(cr):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,cr(n)]))}function Ku(e,t){let r=li.get(e);if(!r){for(let[i,o]of Object.entries(e))t(i,o);return}r.stats.validationResultMaps++;let n=i=>{if(i===null||r.checked.has(i))return;let o=r.pool.nodes[i];n(o.left),t(o.key,r.pool.values[o.value]),r.stats.validationEntries++,n(o.right),r.checked.add(i)};n(r.root)}function Gu(e,t,r){let n=li.get(e),i=(s,c)=>{let l=c.sequence;return t.get(l)!==s&&pt("WorkflowRun 结果来源不一致"),l};if(!n){for(let[s,c]of Object.entries(e))i(s,c)>=r&&pt("WorkflowRun 结果序号无效");return}let o=n.origins.get(t);o||(o=new Map,n.origins.set(t,o));let a=s=>{if(s===null)return 0;let c=o.get(s);if(c!==void 0)return c;let l=n.pool.nodes[s],u=Math.max(i(l.key,n.pool.values[l.value]),a(l.left),a(l.right));return o.set(s,u),u};a(n.root)>=r&&pt("WorkflowRun 结果序号无效")}function hD(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})}function Nn(e,t={}){let r=uD("sha256"),n=e&&typeof e=="object"?uc.get(e):void 0,i=l=>{if(!l||typeof l!="object")return;let u=li.get(l)?.stats??uc.get(l);if(u)return u;for(let f of Object.values(l)){let d=i(f);if(d)return d}};n??=i(e);let o=n&&t.cachePrefixes!==!1?RN.get(n):void 0;n&&!o&&t.cachePrefixes!==!1&&(o={root:{hash:r.copy(),next:new Map},size:0},RN.set(n,o));let a=o?.root,s=l=>{let u=Buffer.byteLength(l);n&&(n.logicalHashBytes+=u);let f=a?.next.get(l);if(f){r=f.hash.copy(),a=f;return}if(r.update(l),n&&(n.hashBytes+=u),a&&o&&o.size<1e5){let d={hash:r.copy(),next:new Map};a.next.set(l,d),a=d,o.size++}else a=void 0},c=l=>{if(l===null||typeof l!="object"){s(JSON.stringify(l));return}if(Array.isArray(l)){s("["),l.forEach((u,f)=>{f&&s(","),c(u)}),s("]");return}s("{"),hD(l).forEach((u,f)=>{f&&s(","),s(JSON.stringify(u)+":"),c(l[u])}),s("}")};return c(e),r.digest("hex")}function fc(e){return uc.get(e)??li.get(e)?.stats}function Yu(e,t,r=!0){let n=mD(e,t);return r?n.materialize():n.value}var AN,bN,li,uc,pt,ja,RN,xo=_(()=>{"use strict";AN=new WeakMap,bN=new WeakMap;li=new WeakMap,uc=new WeakMap;pt=e=>{throw new Error(e)},ja=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;RN=new WeakMap});var _N,k,Zr=_(()=>{"use strict";_N=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"}),k=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.name="RuntimeProtocolError",this.recovery=Object.hasOwn(_N,r)?_N[r]:"manual-review"}code;recovery}});import{createHash as gD}from"node:crypto";import{types as vD}from"node:util";function en(e){return xh.has(e)}function Xu(e,t=!0,r=!1,n=!1){let i=new Set,o=new WeakMap;function a(s,c){if(c>64)throw new k("INVALID_JSON","数据嵌套超过 64 层");if(s===null||typeof s=="string"||typeof s=="boolean")return r?JSON.stringify(s):s;if(typeof s=="number"&&Number.isFinite(s))return r?JSON.stringify(s):s===0?0:s;if(typeof s!="object"||s===null)throw new k("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(s))throw new k("INVALID_JSON","数据包含循环引用");if(vD.isProxy(s))throw new k("INVALID_JSON","仅接受无执行行为的 JSON 数据");let l=xh.get(s);if(!t&&!r&&l!==void 0){if(c+l>64)throw new k("INVALID_JSON","数据嵌套超过 64 层");return o.set(s,{value:s,height:l}),s}let u=o.get(s);if(u){if(c+u.height>64)throw new k("INVALID_JSON","数据嵌套超过 64 层");return t?Me(u.value):r?u.value:s}i.add(s);let f=0,d=h=>h&&typeof h=="object"?o.get(h)?.height??0:0,p=h=>(o.set(s,{value:h,height:f}),n&&(Object.freeze(s),xh.set(s,f)),h);try{if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw new k("INVALID_JSON","数组不能包含空洞或额外属性");let v=[];for(let w=0;w<s.length;w+=1){let A=Object.getOwnPropertyDescriptor(s,String(w));if(!A||!("value"in A))throw new k("INVALID_JSON","数组元素必须是普通数据");let N=a(A.value,c+1);f=Math.max(f,1+d(A.value)),(t||r)&&v.push(N)}return p(r?`[${v.join(",")}]`:t?v:s)}let h=Object.getPrototypeOf(s);if(h!==Object.prototype&&h!==null)throw new k("INVALID_JSON","仅接受普通 JSON 对象");let m=[],g=Reflect.ownKeys(s);(t||r)&&g.sort((v,w)=>{let A=String(v),N=String(w),b=String(Number(A))===A&&Number.isInteger(Number(A))&&Number(A)>=0&&Number(A)<4294967295,E=String(Number(N))===N&&Number.isInteger(Number(N))&&Number(N)>=0&&Number(N)<4294967295;return b||E?b&&E?Number(A)-Number(N):b?-1:1:A<N?-1:A>N?1:0});for(let v of g){let w=Object.getOwnPropertyDescriptor(s,v);if(typeof v!="string"||!w.enumerable||!("value"in w))throw new k("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let A=a(w.value,c+1);f=Math.max(f,1+d(w.value)),(t||r)&&m.push([v,A])}return p(r?`{${m.map(([v,w])=>`${JSON.stringify(v)}:${w}`).join(",")}}`:t?Object.fromEntries(m):s)}finally{i.delete(s)}}return a(e,0)}function Mn(e){return Xu(e,!1,!0)}function nt(e){return Xu(e)}function Me(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(Me(e[n]));return r}let t={};for(let r of Object.keys(e)){let n=Me(e[r]);r==="__proto__"?Object.defineProperty(t,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):t[r]=n}return t}function tn(e){Xu(e,!1)}function $(e){let t=e!==null&&typeof e=="object"&&en(e),r=t?IN.get(e):void 0;if(r!==void 0)return r;let n=gD("sha256").update(Mn(e)).digest("hex");return t&&IN.set(e,n),n}function Po(e){return Xu(e,!1,!1,!0),e}var xh,IN,lr=_(()=>{"use strict";Zr();xh=new WeakMap,IN=new WeakMap});function xt(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new k("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function qn(e){return en(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Ph(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new k("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Th(e){return["succeeded","failed","cancelled"].includes(e.status)}function xN(e){return PN(e,e.input)}function PN(e,t,r){for(let a of["id","runId","stepId","type"])xt(e[a],a);e.ref!==void 0&&xt(e.ref,"ref");let n=e.attempt??1;if(!Number.isSafeInteger(n)||n<1)throw new k("INVALID_ACTION","attempt 必须是正安全整数");let i=e.retry??"manual";if(!["idempotent","reconcile","manual"].includes(i))throw new k("INVALID_ACTION","retry 策略无效");let o=e.requiredCapabilities??[];for(let a of o)xt(a,"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??$(t),status:"pending",retry:i,requiredCapabilities:[...new Set(o)],receipts:[],reconciliations:[]}}function Oh(e,t){Ph(e,t.attempt,t.inputHash),xt(t.executorId,"executorId"),xt(t.token,"token"),t.sessionId!==void 0&&xt(t.sessionId,"sessionId");let r={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if($(e.claim)===$(r)&&e.status==="running")return qn(e);throw new k("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new k("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...qn(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Zu(e,t){if(t=td(t),xt(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new k("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&xt(t.event,"event");let r=$(t),n=e.rejectedOutcomes?.find(o=>o.outcome.outcomeId===t.outcomeId);if(n)throw $(n.outcome)!==r?new k("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new k(n.code,n.reason);let i=e.receipts.find(o=>o.outcomeId===t.outcomeId);if(i){if(i.hash!==r)throw new k("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:qn(e),duplicate:!0}}if(Ph(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new k("STALE_ACTION","结果不属于当前 Action");if(Th(e))throw new k("ACTION_TERMINAL","Action 已终止,不能接受新结果");if(!e.claim||!["running","unknown"].includes(e.status))throw new k("ACTION_NOT_RUNNING","Action 尚未交给执行者");if(t.claimToken!==e.claim.token)throw new k("STALE_ACTION","结果不属于当前执行者的领取记录");for(let o of t.artifacts??[])if(xt(o.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(o.sha256))throw new k("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...qn(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function TN(e,t){if(xt(t,"reason"),!["running","unknown"].includes(e.status))throw new k("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...qn(e),status:"unknown",reason:t}}function ON(e,t){if(e.rejectedOutcomes?.some(n=>n.outcome.attempt===e.attempt))throw new k("OUTCOME_ALREADY_RECORDED","当前执行尝试已记录结果,不能声明未执行并重试;请核对并修正同一次结果");if(!["failed","unknown"].includes(e.status))throw new k("ACTION_ACTIVE","仅失败或待核对的 Action 可以重试");if((e.retry!=="idempotent"||e.status==="unknown")&&!t)throw new k("RECONCILIATION_REQUIRED","先核对外部执行结果;不能把断连当作未执行");let r=qn(e);if(t){if(t.resolution!=="not-executed"||t.evidence===null)throw new k("RECONCILIATION_REQUIRED","需要明确的未执行结论与核对证据");r.reconciliations.push({attempt:e.attempt,resolution:"not-executed",evidence:nt(t.evidence)})}if(!Number.isSafeInteger(e.attempt+1))throw new k("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 ed(e,t){return xt(t,"reason"),Th(e)?qn(e):{...qn(e),status:"cancelled",reason:t}}function $N(e,t){Rn(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])xt(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new k("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Ph(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new k("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function $h(e,t){if($N(e,t),e.status!=="cancelled")throw new k("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&$(e.cancellation)!==$(t))throw new k("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...qn(e),cancellation:structuredClone(t)}}function jh(e,t){if($N(e,t),!Th(e))throw new k("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&$(e.executionStop)!==$(t))throw new k("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...qn(e),executionStop:structuredClone(t)}}function Rn(e,t,r="INVALID_ACTION"){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!t.includes(n)))throw new k(r,"执行记录包含无效结构或未知字段")}function td(e){let t=nt(e),r=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(Rn(t,[...r,"artifacts","summary","event"],"INVALID_OUTCOME"),r.some(n=>!Object.hasOwn(t,n)))throw new k("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 k("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(typeof t.attempt!="number"||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new k("INVALID_OUTCOME","attempt 必须是正安全整数");if(t.status!=="succeeded"&&t.status!=="failed")throw new k("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 k("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(t.artifacts!==void 0){if(!Array.isArray(t.artifacts))throw new k("INVALID_OUTCOME","产物引用必须是数组");for(let n of t.artifacts)if(Rn(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 k("INVALID_OUTCOME","产物引用必须包含 URI 与 SHA-256")}return t}function jN(e){return Dh(nt(e))}function Dh(e,t){if(Rn(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 k("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Action 协议版本");if(!Array.isArray(e.requiredCapabilities)||!Array.isArray(e.receipts)||!Array.isArray(e.reconciliations))throw new k("INVALID_ACTION","Action 缺少能力、结果或核对记录");let r=e,n=PN(r,r.input,t);if(r.inputHash!==n.inputHash||r.retry!==n.retry||r.attempt!==n.attempt)throw new k("INVALID_ACTION","Action 输入绑定或执行参数不完整");if(!["pending","running","unknown","succeeded","failed","cancelled"].includes(r.status))throw new k("INVALID_ACTION","Action 状态无效");if(r.reason!==void 0&&xt(r.reason,"reason"),r.claim!==void 0&&(Rn(r.claim,["executorId","sessionId","token"]),xt(r.claim.executorId,"executorId"),xt(r.claim.token,"token"),r.claim.sessionId!==void 0&&xt(r.claim.sessionId,"sessionId")),r.status==="pending"&&r.claim||["running","unknown","succeeded","failed"].includes(r.status)&&!r.claim)throw new k("INVALID_ACTION","Action 状态与执行归属不一致");if(r.executionOrigin!==void 0&&(Rn(r.executionOrigin,["workflow"]),Rn(r.executionOrigin.workflow,["id","version","hash"]),xt(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),xt(r.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!r.claim||!/^[a-f0-9]{64}$/u.test(r.executionOrigin.workflow.hash)))throw new k("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");r.cancellation!==void 0&&$h({...r,input:null},r.cancellation),r.executionStop!==void 0&&jh({...r,input:null},r.executionStop);let i=new Set;for(let a of r.receipts){if(Rn(a,["outcomeId","hash"]),xt(a.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(a.hash)||i.has(a.outcomeId))throw new k("INVALID_ACTION","结果记录的标识或摘要无效");i.add(a.outcomeId)}if(r.rejectedOutcomes!==void 0){if(!Array.isArray(r.rejectedOutcomes))throw new k("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let a=new Set;for(let s of r.rejectedOutcomes){if(Rn(s,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(s.code))throw new k("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof s.reason!="string"||!s.reason.trim())throw new k("INVALID_ACTION","Action 的拒绝结果缺少原因");let c=td(s.outcome),l=r.receipts.find(u=>u.outcomeId===c.outcomeId);if(a.has(c.outcomeId)||!l||l.hash!==$(c)||c.actionId!==r.id||c.inputHash!==r.inputHash||c.attempt>r.attempt||c.attempt===r.attempt&&r.claim?.token!==c.claimToken)throw new k("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");a.add(c.outcomeId)}}let o=new Set;for(let a of r.reconciliations){if(Rn(a,["attempt","resolution","evidence"]),!Number.isSafeInteger(a.attempt)||a.attempt<1||a.attempt>=r.attempt||o.has(a.attempt)||a.resolution!=="not-executed"||a.evidence===null||a.evidence===void 0)throw new k("INVALID_ACTION","核对记录与执行尝试不一致");o.add(a.attempt)}if(r.status==="succeeded"||r.status==="failed"){if(Rn(r.outcome,["actionId","attempt","inputHash","claimToken","outcomeId","status","output","artifacts","summary","event"]),r.outcome.status!==r.status||r.outcome.output===void 0)throw new k("INVALID_ACTION","终态 Action 缺少匹配的结果");let a=r.receipts.find(s=>s.outcomeId===r.outcome.outcomeId);if(!a||a.hash!==$(r.outcome))throw new k("INVALID_ACTION","终态结果与已接受摘要不一致");Zu({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new k("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}var To=_(()=>{"use strict";Zr();lr()});function Bh(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function re(e){throw new k("INVALID_RUN",e)}function At(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&re(`${t} 必须是 JSON 对象`),e}function rn(e,t,r){for(let n of Object.keys(e))t.includes(n)||re(`${r} 包含不支持的字段:${n}`)}function Qe(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&re(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Da(e,t,r=0){return(!Number.isSafeInteger(e)||e<r)&&re(`${t} 必须是大于等于 ${r} 的安全整数`),e}function Bi(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&re(`${t} 必须是 SHA-256 摘要`),e}function BN(e,t,r=!1){let n=At(e,t);rn(n,r?["id","version","hash"]:["id","version"],t);let i={id:Qe(n.id,`${t}.id`),version:Qe(n.version,`${t}.version`)};return r&&(i.hash=Bi(n.hash,`${t}.hash`)),i}function pc(e,t,r){let n=At(e,t);if(!r&&en(n)&&VN.has(n))return n;let i=(o,a)=>{Qe(o,`${t} step id`);let s=At(a,`${t}.${o}`);rn(s,["sequence","value"],`${t}.${o}`),(!Object.hasOwn(s,"sequence")||!Object.hasOwn(s,"value"))&&re(`${t}.${o} 缺少 sequence 或 value`),Da(s.sequence,`${t}.${o}.sequence`,1)};if(r)r.visitResults(n,i);else for(let[o,a]of Object.entries(n))i(o,a);return n}function WN(e,t,r){let n=At(e,t);return rn(n,["from","to","results","activation"],t),(!Object.hasOwn(n,"from")||!Object.hasOwn(n,"to")||!Object.hasOwn(n,"results"))&&re(`${t} 缺少 from、to 或 results`),{from:n.from===null?null:Qe(n.from,`${t}.from`),to:Qe(n.to,`${t}.to`),results:pc(n.results,`${t}.results`,r),...Object.hasOwn(n,"activation")?{activation:n.activation}:{}}}function rd(e,t,r,n){let i=`${t}:`;e.startsWith(i)||re(`${r} 不属于当前 Run`);let o=e.slice(i.length);/^[1-9][0-9]*$/.test(o)||re(`${r} 的步骤序号无效`);let a=Number(o);return(!Number.isSafeInteger(a)||a>n)&&re(`${r} 的步骤序号超出 Run 范围`),a}function wD(e,t,r,n){let i=At(e,"Wait");rn(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let f of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,f)||re(`Wait 缺少 ${f}`);let o=Qe(i.id,"Wait.id"),a=Qe(i.stepId,"Wait.stepId"),s=Da(i.sequence,"Wait.sequence",1);(s>r||rd(o,t,"Wait.id",r)!==s)&&re("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||re("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&re("Wait.choices 必须是非空数组");let c=i.choices.map(f=>Qe(f,"Wait.choices"));new Set(c).size!==c.length&&re("Wait.choices 不能重复");let l=Bi(i.proposalHash,"Wait.proposalHash");$(i.proposal)!==l&&re("Wait.proposal 与 proposalHash 不一致");let u={id:o,stepId:a,sequence:s,status:i.status,proposal:i.proposal,proposalHash:l,choices:c,results:pc(i.results,"Wait.results",n)};if(i.decision!==void 0){let f=At(i.decision,"Wait.decision");rn(f,["id","choice","proposalHash","reason"],"Wait.decision"),f.reason!==void 0&&!Bh(f.reason)&&re("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let d={id:Qe(f.id,"Wait.decision.id"),choice:Qe(f.choice,"Wait.decision.choice"),proposalHash:Bi(f.proposalHash,"Wait.decision.proposalHash"),...f.reason===void 0?{}:{reason:f.reason}};(i.status!=="resolved"||!c.includes(d.choice)||d.proposalHash!==l)&&re("Wait.decision 与 Wait 状态、选择或提案不一致"),u.decision=d}else i.status==="resolved"&&re("已解决的 Wait 必须保存对应 decision");return u}function yD(e,t,r,n){let i=At(e,"EvidenceWait");rn(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let o=Qe(i.id,"EvidenceWait.id"),a=Da(i.sequence,"EvidenceWait.sequence",1);(a>r||rd(o,t,"EvidenceWait.id",r)!==a)&&re("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||re("EvidenceWait.status 无效");let s={id:o,stepId:Qe(i.stepId,"EvidenceWait.stepId"),sequence:a,kind:Qe(i.kind,"EvidenceWait.kind"),status:i.status,results:pc(i.results,"EvidenceWait.results",n)};if(i.receipt!==void 0){let c=At(i.receipt,"EvidenceWait.receipt");rn(c,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),s.receipt={ref:Qe(c.ref,"EvidenceWait.receipt.ref"),contentHash:Bi(c.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Qe(c.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let c=At(i.invalidation,"EvidenceWait.invalidation");rn(c,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),s.invalidation={ref:Qe(c.ref,"EvidenceWait.invalidation.ref"),contentHash:Bi(c.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Qe(c.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Qe(c.reason,"EvidenceWait.invalidation.reason")}}return(s.status==="resolved"!=!!s.receipt||s.status==="invalidated"!=!!s.invalidation)&&re("EvidenceWait.receipt 与状态不一致"),s}function nn(e,t){let r=At(nt(e),"WorkflowRun");return od(r,t)}function MN(e,t){if(e&&typeof e=="object"&&Wh.has(e)&&en(e)){let r=e;return t!==void 0&&r.runId!==t&&re("WorkflowRun.runId 与存储键不一致"),r}return tn(e),qN(od(At(structuredClone(e),"WorkflowRun"),t))}function nd(e,t,r){return od(At(e,"WorkflowRun"),t,void 0,r)}function id(e,t){return tn(e),od(At(e,"WorkflowRun"),e.runId,t&&Wh.has(t)&&en(t)?t:void 0),qN(e)}function qN(e){Po(e),Wh.add(e);for(let r of e.actions)LN.add(r);let t=r=>VN.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 od(e,t,r,n){rn(e,DN,"WorkflowRun");for(let B of DN.filter(ee=>ee!=="reason"&&ee!=="state"&&ee!=="evidenceWaits"&&ee!=="initialStateHash"&&ee!=="commands"))Object.hasOwn(e,B)||re(`WorkflowRun 缺少 ${B}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new k("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Qe(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&re("WorkflowRun.runId 与存储键不一致");let o=Da(e.revision,"WorkflowRun.revision",1),a=Da(e.sequence,"WorkflowRun.sequence"),s=BN(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||re("WorkflowRun.status 无效"),e.reason!==void 0&&Qe(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||re("WorkflowRun 缺少 input");let c=At(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(c).length===0&&re("WorkflowRun.definitionHashes 不能为空");for(let[B,ee]of Object.entries(c)){let pe;try{pe=JSON.parse(B)}catch{re("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(pe)||pe.length!==2||typeof pe[0]!="string"||typeof pe[1]!="string"||JSON.stringify(pe)!==B)&&re("WorkflowRun.definitionHashes 包含非规范的工作流引用"),Bi(ee,`WorkflowRun.definitionHashes.${B}`)}let l=JSON.stringify([s.id,s.version]);c[l]!==s.hash&&re("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&re("WorkflowRun.lineage 必须是最多 32 层的数组");let u=e.lineage.map(B=>Qe(B,"WorkflowRun.lineage"));(new Set(u).size!==u.length||u.includes(i))&&re("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&re("WorkflowRun.actions 和 waits 必须是数组");let f=e.actions.map(B=>{let ee;try{ee=B&&typeof B=="object"&&LN.has(B)&&en(B)?B:Dh(B,n?.hash(B.input))}catch(pe){if(pe instanceof k&&pe.code==="UNSUPPORTED_PROTOCOL")throw pe;re(`WorkflowRun.actions 包含无效 Action:${pe.message}`)}return ee.executionOrigin&&ee.executionOrigin.workflow.id!==s.id&&re("Action 执行来源不属于当前工作流"),ee.runId!==i&&re(`Action ${ee.id} 不属于当前 Run`),new Set(ee.requiredCapabilities).size!==ee.requiredCapabilities.length&&re(`Action ${ee.id} 的 requiredCapabilities 不能重复`),ee}),d=new Map(f.map(B=>[B.id,B]));e.commands!==void 0&&!Array.isArray(e.commands)&&re("WorkflowRun.commands 必须是数组");let p=e.commands?.map(B=>{let ee=At(B,"WorkflowRun.commands item");rn(ee,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let pe={id:Qe(ee.id,"WorkflowRun.commands.id"),name:Qe(ee.name,"WorkflowRun.commands.name"),inputHash:Bi(ee.inputHash,"WorkflowRun.commands.inputHash"),actionId:Qe(ee.actionId,"WorkflowRun.commands.actionId")};return d.has(pe.actionId)||re("WorkflowRun.commands 指向不存在的 Action"),pe});p&&new Set(p.map(B=>B.id)).size!==p.length&&re("WorkflowRun.commands 标识不能重复");let h=e.waits.map(B=>wD(B,i,a,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&re("WorkflowRun.evidenceWaits 必须是数组");let m=e.evidenceWaits?.map(B=>yD(B,i,a,n))??[],g=new Map;for(let B of f){let ee=rd(B.id,i,"Action.id",a);g.has(ee)&&re("WorkflowRun 的步骤序号不能重复"),g.set(ee,B.stepId)}for(let B of h)g.has(B.sequence)&&re("WorkflowRun 的步骤序号不能重复"),g.set(B.sequence,B.stepId);for(let B of m)g.has(B.sequence)&&re("WorkflowRun 的步骤序号不能重复"),g.set(B.sequence,B.stepId);g.size!==a&&re("WorkflowRun.sequence 与已激活步骤数量不一致");let v=At(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(v).length!==f.length&&re("WorkflowRun.actionContexts 必须与 actions 一一对应");let w=new Map,A=r?new Map([...r.actions.map(B=>[r.actionContexts[B.id].sequence,B.stepId]),...r.waits.map(B=>[B.sequence,B.stepId]),...(r.evidenceWaits??[]).map(B=>[B.sequence,B.stepId])]):void 0;if(r&&A&&r.runId===i&&[...A].every(([B,ee])=>g.get(B)===ee)){let B=(ee,pe)=>w.set(ee,Math.min(w.get(ee)??1/0,pe));for(let ee of Object.values(r.actionContexts))B(ee.results,ee.sequence);for(let ee of r.waits)B(ee.results,ee.sequence);for(let ee of r.evidenceWaits??[])B(ee.results,ee.sequence);for(let ee of r.ready)B(ee.results,r.sequence+1);for(let ee of Object.values(r.joins))for(let pe of Object.values(ee))for(let kt of pe)B(kt.results,r.sequence+1);B(r.outputs,r.sequence+1)}let N=new Map;function b(B,ee){let pe=ee??a+1;if(n){n.validateOrigins(B,g,pe);return}let kt=w.get(B);if(!(kt!==void 0&&pe>=kt&&en(B))&&!((N.get(B)??1/0)<=pe)){N.set(B,pe);for(let[C,R]of Object.entries(B))(R.sequence>=(ee??a+1)||g.get(R.sequence)!==C)&&re(`WorkflowRun 结果 ${C} 的序号或来源不一致`)}}for(let B of f){Object.hasOwn(v,B.id)||re(`Action ${B.id} 缺少上下文`);let ee=At(v[B.id],`actionContexts.${B.id}`);rn(ee,["sequence","results"],`actionContexts.${B.id}`);let pe=Da(ee.sequence,`actionContexts.${B.id}.sequence`,1);pe!==rd(B.id,i,"Action.id",a)&&re(`Action ${B.id} 的上下文序号不一致`);let kt=pc(ee.results,`actionContexts.${B.id}.results`,n);b(kt,pe)}for(let B of h)b(B.results,B.sequence);for(let B of m)b(B.results,B.sequence);Array.isArray(e.ready)||re("WorkflowRun.ready 必须是数组");let E=e.ready.map(B=>WN(B,"WorkflowRun.ready token",n));for(let B of E)b(B.results);let V=At(e.joins,"WorkflowRun.joins"),j=Object.fromEntries(Object.entries(V).map(([B,ee])=>{Qe(B,"WorkflowRun.joins step id");let pe=At(ee,`WorkflowRun.joins.${B}`),kt=Object.fromEntries(Object.entries(pe).map(([C,R])=>{Qe(C,"WorkflowRun.joins parent id"),Array.isArray(R)||re(`WorkflowRun.joins.${B}.${C} 必须是数组`);let I=R.map(D=>{let L=WN(D,`WorkflowRun.joins.${B}.${C}`,n);return(L.to!==B||L.from!==C)&&re(`WorkflowRun.joins.${B}.${C} 包含错误来源的 token`),b(L.results),L});return[C,I]}));return[B,kt]})),z=pc(e.outputs,"WorkflowRun.outputs",n);b(z),Array.isArray(e.children)||re("WorkflowRun.children 必须是数组");let X=e.children.map(B=>{let ee=At(B,"WorkflowRun.children item");rn(ee,["actionId","runId","workflow"],"WorkflowRun.children item");let pe=BN(ee.workflow,"WorkflowRun.children.workflow"),kt=Qe(ee.actionId,"WorkflowRun.children.actionId"),C=Qe(ee.runId,"WorkflowRun.children.runId"),R=d.get(kt);return(!R||R.type!=="child_workflow"||R.ref!==`${pe.id}@${pe.version}`||C!==`child-${$(kt)}`||!Object.hasOwn(c,JSON.stringify([pe.id,pe.version])))&&re("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:kt,runId:C,workflow:pe}});(new Set(X.map(B=>B.actionId)).size!==X.length||f.filter(B=>B.type==="child_workflow").length!==X.length)&&re("每个子工作流 Action 必须恰好对应一个 Child Run");let se=f.some(B=>["pending","running","unknown"].includes(B.status)),De=h.some(B=>B.status==="pending"),Z=m.some(B=>B.status==="pending"),Xe=Object.values(j).some(B=>Object.values(B).some(ee=>ee.length>0));return e.status==="running"&&!se&&E.length===0&&re("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(se||!De&&!Z&&!Xe||E.length>0)&&re("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(se||De||Z||Xe||E.length>0)&&re("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&re(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:o,workflow:s,definitionHashes:c,...e.initialStateHash===void 0?{}:{initialStateHash:Bi(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:a,actions:f,...p===void 0?{}:{commands:p},actionContexts:v,waits:h,...e.evidenceWaits===void 0?{}:{evidenceWaits:m},ready:E,joins:j,outputs:z,children:X,lineage:u,...e.reason===void 0?{}:{reason:e.reason}}}var LN,VN,Wh,DN,mc=_(()=>{"use strict";To();Zr();lr();LN=new WeakSet,VN=new WeakSet,Wh=new WeakSet,DN=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"]});import{randomUUID as kD}from"node:crypto";async function Oo(e,t){let r=await(e.readProjection?e.readProjection(t):e.read(t));if(!r)throw new k("RUN_NOT_FOUND",`找不到工作流实例:${t}`);fc(r)||(tn(r),r=structuredClone(r),dc(r));let n="run"in r?r.run:r;if(!n||n.runId!==r.runId||n.revision!==r.revision)throw new k("INVALID_RUN","Run 与存储 envelope 身份不一致");let i;try{i=nd(n,t,{hash:Nn,visitResults:Ku,validateOrigins:Gu})}catch(s){throw s instanceof k?s:new k("INVALID_RUN",s instanceof Error?s.message:String(s))}dc(i);let o=fc(r);o&&(o.validationActions=i.actions.length,o.validationMaterializedEntries=o.materializedEntries);let a=e.queryScope??FN.get(e);return a||(a=kD(),FN.set(e,a)),Object.freeze({record:r,run:i,scope:a,stats:o,materialize:(s=[])=>cr(s.reduce((c,l)=>c?.[l],i)),hash:()=>Nn(i)})}function Lh(e,t){let{run:r,scope:n}=e;["current","summary","history","action","artifact"].includes(t.view)||Wi("query.view 无效");let i={runId:r.runId,revision:r.revision,status:r.status,workflow:r.workflow,sequence:r.sequence},o={actions:r.actions.length,waits:r.waits.length,evidenceWaits:r.evidenceWaits?.length??0},a=r.actions.filter(d=>["pending","running","unknown"].includes(d.status)||d.status==="cancelled"&&d.claim&&!d.executionStop&&!d.cancellation);if(t.view==="summary")return cr({...i,history:o,pending:{actions:a.length,waits:r.waits.filter(d=>d.status==="pending").length,evidenceWaits:(r.evidenceWaits??[]).filter(d=>d.status==="pending").length}});if(t.view==="current")return cr({...i,input:r.input,...r.state===void 0?{}:{state:r.state},...r.reason===void 0?{}:{reason:r.reason},actions:a,waits:r.waits.filter(d=>d.status==="pending"),evidenceWaits:(r.evidenceWaits??[]).filter(d=>d.status==="pending"),outputs:r.outputs,history:o});if(t.view==="action"||t.view==="artifact"){let d=r.actions.find(m=>m.id===t.actionId);if(d||Wi("query.actionId 不属于当前 Run"),t.view==="action")return cr({...i,action:d,context:r.actionContexts[d.id]});let p=(d.outcome?.artifacts??[]).map(m=>({...m,artifactId:$({actionId:d.id,...m})})),h=t.artifactId===void 0?p:p.filter(m=>m.artifactId===t.artifactId);return t.artifactId!==void 0&&!h.length&&Wi("query.artifactId 不属于所选 Action"),cr({...i,actionId:d.id,artifacts:h})}let s=t.limit??25;(!Number.isSafeInteger(s)||s<1||s>100)&&Wi("query.limit 必须在 1–100 之间");let c=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(c)||Wi("query.filter 无效");let l=$({scope:n,runId:r.runId,revision:r.revision,filter:c}),u=0;if(t.cursor)try{let d=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf8"));(d.binding!==l||!Number.isSafeInteger(d.offset)||d.offset<0||Object.keys(d).some(p=>!["binding","offset"].includes(p)))&&Wi("query.cursor 与当前存储、版本或筛选不匹配"),u=d.offset}catch{Wi("query.cursor 无效或已经过期")}let f=[...c==="all"||c==="actions"?r.actions.map((d,p)=>({kind:"action",sequence:r.actionContexts[d.id].sequence,path:["actions",String(p)]})):[],...c==="all"||c==="waits"?r.waits.map((d,p)=>({kind:"wait",sequence:d.sequence,path:["waits",String(p)]})):[],...c==="all"||c==="evidenceWaits"?(r.evidenceWaits??[]).map((d,p)=>({kind:"evidenceWait",sequence:d.sequence,path:["evidenceWaits",String(p)]})):[]].sort((d,p)=>p.sequence-d.sequence);return u>f.length&&Wi("query.cursor 超出历史范围"),{...cr(i),records:f.slice(u,u+s).map(d=>({kind:d.kind,sequence:d.sequence,value:e.materialize(d.path)})),total:f.length,...u+s<f.length?{nextCursor:Buffer.from(JSON.stringify({binding:l,offset:u+s})).toString("base64url")}:{}}}var FN,Wi,Vh=_(()=>{"use strict";xo();Zr();mc();lr();FN=new WeakMap;Wi=e=>{throw new k("INVALID_REQUEST",e)}});var vc=O($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.regexpCode=$e.getEsmExportName=$e.getProperty=$e.safeStringify=$e.stringify=$e.strConcat=$e.addCodeArg=$e.str=$e._=$e.nil=$e._Code=$e.Name=$e.IDENTIFIER=$e._CodeOrName=void 0;var hc=class{};$e._CodeOrName=hc;$e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var $o=class extends hc{constructor(t){if(super(),!$e.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}}};$e.Name=$o;var on=class extends hc{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 $o&&(r[n.str]=(r[n.str]||0)+1),r),{})}};$e._Code=on;$e.nil=new on("");function HN(e,...t){let r=[e[0]],n=0;for(;n<t.length;)qh(r,t[n]),r.push(e[++n]);return new on(r)}$e._=HN;var Mh=new on("+");function QN(e,...t){let r=[gc(e[0])],n=0;for(;n<t.length;)r.push(Mh),qh(r,t[n]),r.push(Mh,gc(e[++n]));return AD(r),new on(r)}$e.str=QN;function qh(e,t){t instanceof on?e.push(...t._items):t instanceof $o?e.push(t):e.push(RD(t))}$e.addCodeArg=qh;function AD(e){let t=1;for(;t<e.length-1;){if(e[t]===Mh){let r=bD(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function bD(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof $o||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 $o))return`"${e}${t.slice(1)}`}function ND(e,t){return t.emptyStr()?e:e.emptyStr()?t:QN`${e}${t}`}$e.strConcat=ND;function RD(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:gc(Array.isArray(e)?e.join(","):e)}function SD(e){return new on(gc(e))}$e.stringify=SD;function gc(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$e.safeStringify=gc;function ED(e){return typeof e=="string"&&$e.IDENTIFIER.test(e)?new on(`.${e}`):HN`[${e}]`}$e.getProperty=ED;function CD(e){if(typeof e=="string"&&$e.IDENTIFIER.test(e))return new on(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}$e.getEsmExportName=CD;function _D(e){return new on(e.toString())}$e.regexpCode=_D});var Qh=O(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.ValueScope=Nr.ValueScopeName=Nr.Scope=Nr.varKinds=Nr.UsedValueState=void 0;var br=vc(),Fh=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},ad;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(ad||(Nr.UsedValueState=ad={}));Nr.varKinds={const:new br.Name("const"),let:new br.Name("let"),var:new br.Name("var")};var sd=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof br.Name?t:this.name(t)}name(t){return new br.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}}};Nr.Scope=sd;var cd=class extends br.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,br._)`.${new br.Name(r)}[${n}]`}};Nr.ValueScopeName=cd;var ID=(0,br._)`\n`,Hh=class extends sd{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?ID:br.nil}}get(){return this._scope}name(t){return new cd(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:o}=i,a=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[o];if(s){let u=s.get(a);if(u)return u}else s=this._values[o]=new Map;s.set(a,i);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:o,itemIndex:l}),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,br._)`${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 o=br.nil;for(let a in t){let s=t[a];if(!s)continue;let c=n[a]=n[a]||new Map;s.forEach(l=>{if(c.has(l))return;c.set(l,ad.Started);let u=r(l);if(u){let f=this.opts.es5?Nr.varKinds.var:Nr.varKinds.const;o=(0,br._)`${o}${f} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,br._)`${o}${u}${this.opts._n}`;else throw new Fh(l);c.set(l,ad.Completed)})}return o}};Nr.ValueScope=Hh});var Re=O(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.or=be.and=be.not=be.CodeGen=be.operators=be.varKinds=be.ValueScopeName=be.ValueScope=be.Scope=be.Name=be.regexpCode=be.stringify=be.getProperty=be.nil=be.strConcat=be.str=be._=void 0;var Ie=vc(),Sn=Qh(),Li=vc();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return Li._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return Li.str}});Object.defineProperty(be,"strConcat",{enumerable:!0,get:function(){return Li.strConcat}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return Li.nil}});Object.defineProperty(be,"getProperty",{enumerable:!0,get:function(){return Li.getProperty}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return Li.stringify}});Object.defineProperty(be,"regexpCode",{enumerable:!0,get:function(){return Li.regexpCode}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return Li.Name}});var fd=Qh();Object.defineProperty(be,"Scope",{enumerable:!0,get:function(){return fd.Scope}});Object.defineProperty(be,"ValueScope",{enumerable:!0,get:function(){return fd.ValueScope}});Object.defineProperty(be,"ValueScopeName",{enumerable:!0,get:function(){return fd.ValueScopeName}});Object.defineProperty(be,"varKinds",{enumerable:!0,get:function(){return fd.varKinds}});be.operators={GT:new Ie._Code(">"),GTE:new Ie._Code(">="),LT:new Ie._Code("<"),LTE:new Ie._Code("<="),EQ:new Ie._Code("==="),NEQ:new Ie._Code("!=="),NOT:new Ie._Code("!"),OR:new Ie._Code("||"),AND:new Ie._Code("&&"),ADD:new Ie._Code("+")};var ui=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Uh=class extends ui{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Sn.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=Wa(this.rhs,t,r)),this}get names(){return this.rhs instanceof Ie._CodeOrName?this.rhs.names:{}}},ld=class extends ui{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 Ie.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Wa(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Ie.Name?{}:{...this.lhs.names};return dd(t,this.rhs)}},Jh=class extends ld{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},zh=class extends ui{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Kh=class extends ui{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Gh=class extends ui{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Yh=class extends ui{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=Wa(this.code,t,r),this}get names(){return this.code instanceof Ie._CodeOrName?this.code.names:{}}},wc=class extends ui{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 o=n[i];o.optimizeNames(t,r)||(xD(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Bo(t,r.names),{})}},di=class extends wc{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Xh=class extends wc{},Ba=class extends di{};Ba.kind="else";var jo=class e extends di{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 Ba(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(UN(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=Wa(this.condition,t,r),this}get names(){let t=super.names;return dd(t,this.condition),this.else&&Bo(t,this.else.names),t}};jo.kind="if";var Do=class extends di{};Do.kind="for";var Zh=class extends Do{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=Wa(this.iteration,t,r),this}get names(){return Bo(super.names,this.iteration.names)}},eg=class extends Do{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?Sn.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=dd(super.names,this.from);return dd(t,this.to)}},ud=class extends Do{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=Wa(this.iterable,t,r),this}get names(){return Bo(super.names,this.iterable.names)}},yc=class extends di{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)}};yc.kind="func";var kc=class extends wc{render(t){return"return "+super.render(t)}};kc.kind="return";var tg=class extends di{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&&Bo(t,this.catch.names),this.finally&&Bo(t,this.finally.names),t}},Ac=class extends di{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Ac.kind="catch";var bc=class extends di{render(t){return"finally"+super.render(t)}};bc.kind="finally";var rg=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
5
|
+
`:""},this._extScope=t,this._scope=new Sn.Scope({parent:t}),this._nodes=[new Xh]}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 o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new Uh(t,o,n)),o}const(t,r,n){return this._def(Sn.varKinds.const,t,r,n)}let(t,r,n){return this._def(Sn.varKinds.let,t,r,n)}var(t,r,n){return this._def(Sn.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ld(t,r,n))}add(t,r){return this._leafNode(new Jh(t,be.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Ie.nil&&this._leafNode(new Yh(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,Ie.addCodeArg)(r,i));return r.push("}"),new Ie._Code(r)}if(t,r,n){if(this._blockNode(new jo(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 jo(t))}else(){return this._elseNode(new Ba)}endIf(){return this._endBlockNode(jo,Ba)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Zh(t),r)}forRange(t,r,n,i,o=this.opts.es5?Sn.varKinds.var:Sn.varKinds.let){let a=this._scope.toName(t);return this._for(new eg(o,a,r,n),()=>i(a))}forOf(t,r,n,i=Sn.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let a=r instanceof Ie.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Ie._)`${a}.length`,s=>{this.var(o,(0,Ie._)`${a}[${s}]`),n(o)})}return this._for(new ud("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?Sn.varKinds.var:Sn.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Ie._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new ud("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Do)}label(t){return this._leafNode(new zh(t))}break(t){return this._leafNode(new Kh(t))}return(t){let r=new kc;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(kc)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new tg;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new Ac(o),r(o)}return n&&(this._currNode=i.finally=new bc,this.code(n)),this._endBlockNode(Ac,bc)}throw(t){return this._leafNode(new Gh(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=Ie.nil,n,i){return this._blockNode(new yc(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(yc)}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 jo))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}};be.CodeGen=rg;function Bo(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function dd(e,t){return t instanceof Ie._CodeOrName?Bo(e,t.names):e}function Wa(e,t,r){if(e instanceof Ie.Name)return n(e);if(!i(e))return e;return new Ie._Code(e._items.reduce((o,a)=>(a instanceof Ie.Name&&(a=n(a)),a instanceof Ie._Code?o.push(...a._items):o.push(a),o),[]));function n(o){let a=r[o.str];return a===void 0||t[o.str]!==1?o:(delete t[o.str],a)}function i(o){return o instanceof Ie._Code&&o._items.some(a=>a instanceof Ie.Name&&t[a.str]===1&&r[a.str]!==void 0)}}function xD(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function UN(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Ie._)`!${ng(e)}`}be.not=UN;var PD=JN(be.operators.AND);function TD(...e){return e.reduce(PD)}be.and=TD;var OD=JN(be.operators.OR);function $D(...e){return e.reduce(OD)}be.or=$D;function JN(e){return(t,r)=>t===Ie.nil?r:r===Ie.nil?t:(0,Ie._)`${ng(t)} ${e} ${ng(r)}`}function ng(e){return e instanceof Ie.Name?e:(0,Ie._)`(${e})`}});var Pe=O(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.checkStrictMode=Se.getErrorPath=Se.Type=Se.useFunc=Se.setEvaluated=Se.evaluatedPropsToName=Se.mergeEvaluated=Se.eachItem=Se.unescapeJsonPointer=Se.escapeJsonPointer=Se.escapeFragment=Se.unescapeFragment=Se.schemaRefOrVal=Se.schemaHasRulesButRef=Se.schemaHasRules=Se.checkUnknownRules=Se.alwaysValidSchema=Se.toHash=void 0;var ze=Re(),jD=vc();function DD(e){let t={};for(let r of e)t[r]=!0;return t}Se.toHash=DD;function BD(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(GN(e,t),!YN(t,e.self.RULES.all))}Se.alwaysValidSchema=BD;function GN(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let o in t)i[o]||eR(e,`unknown keyword: "${o}"`)}Se.checkUnknownRules=GN;function YN(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}Se.schemaHasRules=YN;function WD(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Se.schemaHasRulesButRef=WD;function LD({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ze._)`${r}`}return(0,ze._)`${e}${t}${(0,ze.getProperty)(n)}`}Se.schemaRefOrVal=LD;function VD(e){return XN(decodeURIComponent(e))}Se.unescapeFragment=VD;function MD(e){return encodeURIComponent(og(e))}Se.escapeFragment=MD;function og(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Se.escapeJsonPointer=og;function XN(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Se.unescapeJsonPointer=XN;function qD(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}Se.eachItem=qD;function zN({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,a,s)=>{let c=a===void 0?o:a instanceof ze.Name?(o instanceof ze.Name?e(i,o,a):t(i,o,a),a):o instanceof ze.Name?(t(i,a,o),o):r(o,a);return s===ze.Name&&!(c instanceof ze.Name)?n(i,c):c}}Se.mergeEvaluated={props:zN({mergeNames:(e,t,r)=>e.if((0,ze._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ze._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ze._)`${r} || {}`).code((0,ze._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,ze._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ze._)`${r} || {}`),ag(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:ZN}),items:zN({mergeNames:(e,t,r)=>e.if((0,ze._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ze._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,ze._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ze._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function ZN(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ze._)`{}`);return t!==void 0&&ag(e,r,t),r}Se.evaluatedPropsToName=ZN;function ag(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ze._)`${t}${(0,ze.getProperty)(n)}`,!0))}Se.setEvaluated=ag;var KN={};function FD(e,t){return e.scopeValue("func",{ref:t,code:KN[t.code]||(KN[t.code]=new jD._Code(t.code))})}Se.useFunc=FD;var ig;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ig||(Se.Type=ig={}));function HD(e,t,r){if(e instanceof ze.Name){let n=t===ig.Num;return r?n?(0,ze._)`"[" + ${e} + "]"`:(0,ze._)`"['" + ${e} + "']"`:n?(0,ze._)`"/" + ${e}`:(0,ze._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ze.getProperty)(e).toString():"/"+og(e)}Se.getErrorPath=HD;function eR(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Se.checkStrictMode=eR});var fi=O(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var Zt=Re(),QD={data:new Zt.Name("data"),valCxt:new Zt.Name("valCxt"),instancePath:new Zt.Name("instancePath"),parentData:new Zt.Name("parentData"),parentDataProperty:new Zt.Name("parentDataProperty"),rootData:new Zt.Name("rootData"),dynamicAnchors:new Zt.Name("dynamicAnchors"),vErrors:new Zt.Name("vErrors"),errors:new Zt.Name("errors"),this:new Zt.Name("this"),self:new Zt.Name("self"),scope:new Zt.Name("scope"),json:new Zt.Name("json"),jsonPos:new Zt.Name("jsonPos"),jsonLen:new Zt.Name("jsonLen"),jsonPart:new Zt.Name("jsonPart")};sg.default=QD});var Nc=O(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.extendErrors=er.resetErrorsCount=er.reportExtraError=er.reportError=er.keyword$DataError=er.keywordError=void 0;var Te=Re(),pd=Pe(),ur=fi();er.keywordError={message:({keyword:e})=>(0,Te.str)`must pass "${e}" keyword validation`};er.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Te.str)`"${e}" keyword must be ${t} ($data)`:(0,Te.str)`"${e}" keyword is invalid ($data)`};function UD(e,t=er.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:a,allErrors:s}=i,c=nR(e,t,r);n??(a||s)?tR(o,c):rR(i,(0,Te._)`[${c}]`)}er.reportError=UD;function JD(e,t=er.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:a}=n,s=nR(e,t,r);tR(i,s),o||a||rR(n,ur.default.vErrors)}er.reportExtraError=JD;function zD(e,t){e.assign(ur.default.errors,t),e.if((0,Te._)`${ur.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Te._)`${ur.default.vErrors}.length`,t),()=>e.assign(ur.default.vErrors,null)))}er.resetErrorsCount=zD;function KD({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let a=e.name("err");e.forRange("i",i,ur.default.errors,s=>{e.const(a,(0,Te._)`${ur.default.vErrors}[${s}]`),e.if((0,Te._)`${a}.instancePath === undefined`,()=>e.assign((0,Te._)`${a}.instancePath`,(0,Te.strConcat)(ur.default.instancePath,o.errorPath))),e.assign((0,Te._)`${a}.schemaPath`,(0,Te.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,Te._)`${a}.schema`,r),e.assign((0,Te._)`${a}.data`,n))})}er.extendErrors=KD;function tR(e,t){let r=e.const("err",t);e.if((0,Te._)`${ur.default.vErrors} === null`,()=>e.assign(ur.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${ur.default.vErrors}.push(${r})`),e.code((0,Te._)`${ur.default.errors}++`)}function rR(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,Te._)`new ${e.ValidationError}(${t})`):(r.assign((0,Te._)`${n}.errors`,t),r.return(!1))}var Wo={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function nR(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Te._)`{}`:GD(e,t,r)}function GD(e,t,r={}){let{gen:n,it:i}=e,o=[YD(i,r),XD(e,r)];return ZD(e,t,o),n.object(...o)}function YD({errorPath:e},{instancePath:t}){let r=t?(0,Te.str)`${e}${(0,pd.getErrorPath)(t,pd.Type.Str)}`:e;return[ur.default.instancePath,(0,Te.strConcat)(ur.default.instancePath,r)]}function XD({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,Te.str)`${t}/${e}`;return r&&(i=(0,Te.str)`${i}${(0,pd.getErrorPath)(r,pd.Type.Str)}`),[Wo.schemaPath,i]}function ZD(e,{params:t,message:r},n){let{keyword:i,data:o,schemaValue:a,it:s}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:f}=s;n.push([Wo.keyword,i],[Wo.params,typeof t=="function"?t(e):t||(0,Te._)`{}`]),c.messages&&n.push([Wo.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Wo.schema,a],[Wo.parentSchema,(0,Te._)`${u}${f}`],[ur.default.data,o]),l&&n.push([Wo.propertyName,l])}});var oR=O(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.boolOrEmptySchema=La.topBoolOrEmptySchema=void 0;var eB=Nc(),tB=Re(),rB=fi(),nB={message:"boolean schema is false"};function iB(e){let{gen:t,schema:r,validateName:n}=e;r===!1?iR(e,!1):typeof r=="object"&&r.$async===!0?t.return(rB.default.data):(t.assign((0,tB._)`${n}.errors`,null),t.return(!0))}La.topBoolOrEmptySchema=iB;function oB(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),iR(e)):r.var(t,!0)}La.boolOrEmptySchema=oB;function iR(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,eB.reportError)(i,nB,void 0,t)}});var cg=O(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.getRules=Va.isJSONType=void 0;var aB=["string","number","integer","boolean","null","object","array"],sB=new Set(aB);function cB(e){return typeof e=="string"&&sB.has(e)}Va.isJSONType=cB;function lB(){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:{}}}Va.getRules=lB});var lg=O(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.shouldUseRule=Vi.shouldUseGroup=Vi.schemaHasRulesForType=void 0;function uB({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&aR(e,n)}Vi.schemaHasRulesForType=uB;function aR(e,t){return t.rules.some(r=>sR(e,r))}Vi.shouldUseGroup=aR;function sR(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))}Vi.shouldUseRule=sR});var Rc=O(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.reportTypeError=tr.checkDataTypes=tr.checkDataType=tr.coerceAndCheckDataType=tr.getJSONTypes=tr.getSchemaTypes=tr.DataType=void 0;var dB=cg(),fB=lg(),pB=Nc(),ve=Re(),cR=Pe(),Ma;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ma||(tr.DataType=Ma={}));function mB(e){let t=lR(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}tr.getSchemaTypes=mB;function lR(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(dB.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}tr.getJSONTypes=lR;function hB(e,t){let{gen:r,data:n,opts:i}=e,o=gB(t,i.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,fB.schemaHasRulesForType)(e,t[0]));if(a){let s=dg(t,n,i.strictNumbers,Ma.Wrong);r.if(s,()=>{o.length?vB(e,t,o):fg(e)})}return a}tr.coerceAndCheckDataType=hB;var uR=new Set(["string","number","integer","boolean","null"]);function gB(e,t){return t?e.filter(r=>uR.has(r)||t==="array"&&r==="array"):[]}function vB(e,t,r){let{gen:n,data:i,opts:o}=e,a=n.let("dataType",(0,ve._)`typeof ${i}`),s=n.let("coerced",(0,ve._)`undefined`);o.coerceTypes==="array"&&n.if((0,ve._)`${a} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,ve._)`${i}[0]`).assign(a,(0,ve._)`typeof ${i}`).if(dg(t,i,o.strictNumbers),()=>n.assign(s,i))),n.if((0,ve._)`${s} !== undefined`);for(let l of r)(uR.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),fg(e),n.endIf(),n.if((0,ve._)`${s} !== undefined`,()=>{n.assign(i,s),wB(e,s)});function c(l){switch(l){case"string":n.elseIf((0,ve._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,ve._)`"" + ${i}`).elseIf((0,ve._)`${i} === null`).assign(s,(0,ve._)`""`);return;case"number":n.elseIf((0,ve._)`${a} == "boolean" || ${i} === null
|
|
6
|
+
|| (${a} == "string" && ${i} && ${i} == +${i})`).assign(s,(0,ve._)`+${i}`);return;case"integer":n.elseIf((0,ve._)`${a} === "boolean" || ${i} === null
|
|
7
|
+
|| (${a} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(s,(0,ve._)`+${i}`);return;case"boolean":n.elseIf((0,ve._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(s,!1).elseIf((0,ve._)`${i} === "true" || ${i} === 1`).assign(s,!0);return;case"null":n.elseIf((0,ve._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(s,null);return;case"array":n.elseIf((0,ve._)`${a} === "string" || ${a} === "number"
|
|
8
|
+
|| ${a} === "boolean" || ${i} === null`).assign(s,(0,ve._)`[${i}]`)}}}function wB({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,ve._)`${t} !== undefined`,()=>e.assign((0,ve._)`${t}[${r}]`,n))}function ug(e,t,r,n=Ma.Correct){let i=n===Ma.Correct?ve.operators.EQ:ve.operators.NEQ,o;switch(e){case"null":return(0,ve._)`${t} ${i} null`;case"array":o=(0,ve._)`Array.isArray(${t})`;break;case"object":o=(0,ve._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=a((0,ve._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=a();break;default:return(0,ve._)`typeof ${t} ${i} ${e}`}return n===Ma.Correct?o:(0,ve.not)(o);function a(s=ve.nil){return(0,ve.and)((0,ve._)`typeof ${t} == "number"`,s,r?(0,ve._)`isFinite(${t})`:ve.nil)}}tr.checkDataType=ug;function dg(e,t,r,n){if(e.length===1)return ug(e[0],t,r,n);let i,o=(0,cR.toHash)(e);if(o.array&&o.object){let a=(0,ve._)`typeof ${t} != "object"`;i=o.null?a:(0,ve._)`!${t} || ${a}`,delete o.null,delete o.array,delete o.object}else i=ve.nil;o.number&&delete o.integer;for(let a in o)i=(0,ve.and)(i,ug(a,t,r,n));return i}tr.checkDataTypes=dg;var yB={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,ve._)`{type: ${e}}`:(0,ve._)`{type: ${t}}`};function fg(e){let t=kB(e);(0,pB.reportError)(t,yB)}tr.reportTypeError=fg;function kB(e){let{gen:t,data:r,schema:n}=e,i=(0,cR.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var fR=O(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.assignDefaults=void 0;var qa=Re(),AB=Pe();function bB(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)dR(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>dR(e,o,i.default))}md.assignDefaults=bB;function dR(e,t,r){let{gen:n,compositeRule:i,data:o,opts:a}=e;if(r===void 0)return;let s=(0,qa._)`${o}${(0,qa.getProperty)(t)}`;if(i){(0,AB.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,qa._)`${s} === undefined`;a.useDefaults==="empty"&&(c=(0,qa._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,qa._)`${s} = ${(0,qa.stringify)(r)}`)}});var an=O(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.validateUnion=Ue.validateArray=Ue.usePattern=Ue.callValidateCode=Ue.schemaProperties=Ue.allSchemaProperties=Ue.noPropertyInData=Ue.propertyInData=Ue.isOwnProperty=Ue.hasPropFunc=Ue.reportMissingProp=Ue.checkMissingProp=Ue.checkReportMissingProp=void 0;var tt=Re(),pg=Pe(),Mi=fi(),NB=Pe();function RB(e,t){let{gen:r,data:n,it:i}=e;r.if(hg(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,tt._)`${t}`},!0),e.error()})}Ue.checkReportMissingProp=RB;function SB({gen:e,data:t,it:{opts:r}},n,i){return(0,tt.or)(...n.map(o=>(0,tt.and)(hg(e,t,o,r.ownProperties),(0,tt._)`${i} = ${o}`)))}Ue.checkMissingProp=SB;function EB(e,t){e.setParams({missingProperty:t},!0),e.error()}Ue.reportMissingProp=EB;function pR(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,tt._)`Object.prototype.hasOwnProperty`})}Ue.hasPropFunc=pR;function mg(e,t,r){return(0,tt._)`${pR(e)}.call(${t}, ${r})`}Ue.isOwnProperty=mg;function CB(e,t,r,n){let i=(0,tt._)`${t}${(0,tt.getProperty)(r)} !== undefined`;return n?(0,tt._)`${i} && ${mg(e,t,r)}`:i}Ue.propertyInData=CB;function hg(e,t,r,n){let i=(0,tt._)`${t}${(0,tt.getProperty)(r)} === undefined`;return n?(0,tt.or)(i,(0,tt.not)(mg(e,t,r))):i}Ue.noPropertyInData=hg;function mR(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Ue.allSchemaProperties=mR;function _B(e,t){return mR(t).filter(r=>!(0,pg.alwaysValidSchema)(e,t[r]))}Ue.schemaProperties=_B;function IB({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:a},s,c,l){let u=l?(0,tt._)`${e}, ${t}, ${n}${i}`:t,f=[[Mi.default.instancePath,(0,tt.strConcat)(Mi.default.instancePath,o)],[Mi.default.parentData,a.parentData],[Mi.default.parentDataProperty,a.parentDataProperty],[Mi.default.rootData,Mi.default.rootData]];a.opts.dynamicRef&&f.push([Mi.default.dynamicAnchors,Mi.default.dynamicAnchors]);let d=(0,tt._)`${u}, ${r.object(...f)}`;return c!==tt.nil?(0,tt._)`${s}.call(${c}, ${d})`:(0,tt._)`${s}(${d})`}Ue.callValidateCode=IB;var xB=(0,tt._)`new RegExp`;function PB({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,tt._)`${i.code==="new RegExp"?xB:(0,NB.useFunc)(e,i)}(${r}, ${n})`})}Ue.usePattern=PB;function TB(e){let{gen:t,data:r,keyword:n,it:i}=e,o=t.name("valid");if(i.allErrors){let s=t.let("valid",!0);return a(()=>t.assign(s,!1)),s}return t.var(o,!0),a(()=>t.break()),o;function a(s){let c=t.const("len",(0,tt._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:pg.Type.Num},o),t.if((0,tt.not)(o),s)})}}Ue.validateArray=TB;function OB(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,pg.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let a=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},s);t.assign(a,(0,tt._)`${a} || ${s}`),e.mergeValidEvaluated(u,s)||t.if((0,tt.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}Ue.validateUnion=OB});var vR=O(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.validateKeywordUsage=Fn.validSchemaType=Fn.funcKeywordCode=Fn.macroKeywordCode=void 0;var dr=Re(),Lo=fi(),$B=an(),jB=Nc();function DB(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:a}=e,s=t.macro.call(a.self,i,o,a),c=gR(r,n,s);a.opts.validateSchema!==!1&&a.self.validateSchema(s,!0);let l=r.name("valid");e.subschema({schema:s,schemaPath:dr.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Fn.macroKeywordCode=DB;function BB(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:a,$data:s,it:c}=e;LB(c,t);let l=!s&&t.compile?t.compile.call(c.self,o,a,c):t.validate,u=gR(n,i,l),f=n.let("valid");e.block$data(f,d),e.ok((r=t.valid)!==null&&r!==void 0?r:f);function d(){if(t.errors===!1)m(),t.modifying&&hR(e),g(()=>e.error());else{let v=t.async?p():h();t.modifying&&hR(e),g(()=>WB(e,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,dr._)`await `),w=>n.assign(f,!1).if((0,dr._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,dr._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,dr._)`${u}.errors`;return n.assign(v,null),m(dr.nil),v}function m(v=t.async?(0,dr._)`await `:dr.nil){let w=c.opts.passContext?Lo.default.this:Lo.default.self,A=!("compile"in t&&!s||t.schema===!1);n.assign(f,(0,dr._)`${v}${(0,$B.callValidateCode)(e,u,w,A)}`,t.modifying)}function g(v){var w;n.if((0,dr.not)((w=t.valid)!==null&&w!==void 0?w:f),v)}}Fn.funcKeywordCode=BB;function hR(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,dr._)`${n.parentData}[${n.parentDataProperty}]`))}function WB(e,t){let{gen:r}=e;r.if((0,dr._)`Array.isArray(${t})`,()=>{r.assign(Lo.default.vErrors,(0,dr._)`${Lo.default.vErrors} === null ? ${t} : ${Lo.default.vErrors}.concat(${t})`).assign(Lo.default.errors,(0,dr._)`${Lo.default.vErrors}.length`),(0,jB.extendErrors)(e)},()=>e.error())}function LB({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function gR(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,dr.stringify)(r)})}function VB(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")}Fn.validSchemaType=VB;function MB({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let a=i.dependencies;if(a?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Fn.validateKeywordUsage=MB});var yR=O(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.extendSubschemaMode=qi.extendSubschemaData=qi.getSubschema=void 0;var Hn=Re(),wR=Pe();function qB(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:a}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,Hn._)`${e.schemaPath}${(0,Hn.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,Hn._)`${e.schemaPath}${(0,Hn.getProperty)(t)}${(0,Hn.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,wR.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:a,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}qi.getSubschema=qB;function FB(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:a}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:f}=t,d=s.let("data",(0,Hn._)`${t.data}${(0,Hn.getProperty)(r)}`,!0);c(d),e.errorPath=(0,Hn.str)`${l}${(0,wR.getErrorPath)(r,n,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Hn._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(i!==void 0){let l=i instanceof Hn.Name?i:s.let("data",i,!0);c(l),a!==void 0&&(e.propertyName=a)}o&&(e.dataTypes=o);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}qi.extendSubschemaData=FB;function HB(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}qi.extendSubschemaMode=HB});var gg=O((v3,kR)=>{"use strict";kR.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,o;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(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var a=o[i];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}});var bR=O((w3,AR)=>{"use strict";var Fi=AR.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(){};hd(t,n,i,e,"",e)};Fi.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Fi.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Fi.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Fi.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 hd(e,t,r,n,i,o,a,s,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,o,a,s,c,l);for(var u in n){var f=n[u];if(Array.isArray(f)){if(u in Fi.arrayKeywords)for(var d=0;d<f.length;d++)hd(e,t,r,f[d],i+"/"+u+"/"+d,o,i,u,n,d)}else if(u in Fi.propsKeywords){if(f&&typeof f=="object")for(var p in f)hd(e,t,r,f[p],i+"/"+u+"/"+QB(p),o,i,u,n,p)}else(u in Fi.keywords||e.allKeys&&!(u in Fi.skipKeywords))&&hd(e,t,r,f,i+"/"+u,o,i,u,n)}r(n,i,o,a,s,c,l)}}function QB(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Sc=O(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.getSchemaRefs=Rr.resolveUrl=Rr.normalizeId=Rr._getFullPath=Rr.getFullPath=Rr.inlineRef=void 0;var UB=Pe(),JB=gg(),zB=bR(),KB=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function GB(e,t=!0){return typeof e=="boolean"?!0:t===!0?!vg(e):t?NR(e)<=t:!1}Rr.inlineRef=GB;var YB=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vg(e){for(let t in e){if(YB.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(vg)||typeof r=="object"&&vg(r))return!0}return!1}function NR(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!KB.has(r)&&(typeof e[r]=="object"&&(0,UB.eachItem)(e[r],n=>t+=NR(n)),t===1/0))return 1/0}return t}function RR(e,t="",r){r!==!1&&(t=Fa(t));let n=e.parse(t);return SR(e,n)}Rr.getFullPath=RR;function SR(e,t){return e.serialize(t).split("#")[0]+"#"}Rr._getFullPath=SR;var XB=/#\/?$/;function Fa(e){return e?e.replace(XB,""):""}Rr.normalizeId=Fa;function ZB(e,t,r){return r=Fa(r),e.resolve(t,r)}Rr.resolveUrl=ZB;var eW=/^[a-z_][-a-z0-9._]*$/i;function tW(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Fa(e[r]||t),o={"":i},a=RR(n,i,!1),s={},c=new Set;return zB(e,{allKeys:!0},(f,d,p,h)=>{if(h===void 0)return;let m=a+d,g=o[h];typeof f[r]=="string"&&(g=v.call(this,f[r])),w.call(this,f.$anchor),w.call(this,f.$dynamicAnchor),o[d]=g;function v(A){let N=this.opts.uriResolver.resolve;if(A=Fa(g?N(g,A):A),c.has(A))throw u(A);c.add(A);let b=this.refs[A];return typeof b=="string"&&(b=this.refs[b]),typeof b=="object"?l(f,b.schema,A):A!==Fa(m)&&(A[0]==="#"?(l(f,s[A],A),s[A]=f):this.refs[A]=m),A}function w(A){if(typeof A=="string"){if(!eW.test(A))throw new Error(`invalid anchor "${A}"`);v.call(this,`#${A}`)}}}),s;function l(f,d,p){if(d!==void 0&&!JB(f,d))throw u(p)}function u(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Rr.getSchemaRefs=tW});var _c=O(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.getData=Hi.KeywordCxt=Hi.validateFunctionCode=void 0;var xR=oR(),ER=Rc(),yg=lg(),gd=Rc(),rW=fR(),Cc=vR(),wg=yR(),ae=Re(),fe=fi(),nW=Sc(),pi=Pe(),Ec=Nc();function iW(e){if(OR(e)&&($R(e),TR(e))){sW(e);return}PR(e,()=>(0,xR.topBoolOrEmptySchema)(e))}Hi.validateFunctionCode=iW;function PR({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,ae._)`${fe.default.data}, ${fe.default.valCxt}`,n.$async,()=>{e.code((0,ae._)`"use strict"; ${CR(r,i)}`),aW(e,i),e.code(o)}):e.func(t,(0,ae._)`${fe.default.data}, ${oW(i)}`,n.$async,()=>e.code(CR(r,i)).code(o))}function oW(e){return(0,ae._)`{${fe.default.instancePath}="", ${fe.default.parentData}, ${fe.default.parentDataProperty}, ${fe.default.rootData}=${fe.default.data}${e.dynamicRef?(0,ae._)`, ${fe.default.dynamicAnchors}={}`:ae.nil}}={}`}function aW(e,t){e.if(fe.default.valCxt,()=>{e.var(fe.default.instancePath,(0,ae._)`${fe.default.valCxt}.${fe.default.instancePath}`),e.var(fe.default.parentData,(0,ae._)`${fe.default.valCxt}.${fe.default.parentData}`),e.var(fe.default.parentDataProperty,(0,ae._)`${fe.default.valCxt}.${fe.default.parentDataProperty}`),e.var(fe.default.rootData,(0,ae._)`${fe.default.valCxt}.${fe.default.rootData}`),t.dynamicRef&&e.var(fe.default.dynamicAnchors,(0,ae._)`${fe.default.valCxt}.${fe.default.dynamicAnchors}`)},()=>{e.var(fe.default.instancePath,(0,ae._)`""`),e.var(fe.default.parentData,(0,ae._)`undefined`),e.var(fe.default.parentDataProperty,(0,ae._)`undefined`),e.var(fe.default.rootData,fe.default.data),t.dynamicRef&&e.var(fe.default.dynamicAnchors,(0,ae._)`{}`)})}function sW(e){let{schema:t,opts:r,gen:n}=e;PR(e,()=>{r.$comment&&t.$comment&&DR(e),fW(e),n.let(fe.default.vErrors,null),n.let(fe.default.errors,0),r.unevaluated&&cW(e),jR(e),hW(e)})}function cW(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,ae._)`${r}.evaluated`),t.if((0,ae._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,ae._)`${e.evaluated}.props`,(0,ae._)`undefined`)),t.if((0,ae._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,ae._)`${e.evaluated}.items`,(0,ae._)`undefined`))}function CR(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,ae._)`/*# sourceURL=${r} */`:ae.nil}function lW(e,t){if(OR(e)&&($R(e),TR(e))){uW(e,t);return}(0,xR.boolOrEmptySchema)(e,t)}function TR({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 OR(e){return typeof e.schema!="boolean"}function uW(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&DR(e),pW(e),mW(e);let o=n.const("_errs",fe.default.errors);jR(e,o),n.var(t,(0,ae._)`${o} === ${fe.default.errors}`)}function $R(e){(0,pi.checkUnknownRules)(e),dW(e)}function jR(e,t){if(e.opts.jtd)return _R(e,[],!1,t);let r=(0,ER.getSchemaTypes)(e.schema),n=(0,ER.coerceAndCheckDataType)(e,r);_R(e,r,!n,t)}function dW(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,pi.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function fW(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,pi.checkStrictMode)(e,"default is ignored in the schema root")}function pW(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,nW.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function mW(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function DR({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,ae._)`${fe.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let a=(0,ae.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,ae._)`${fe.default.self}.opts.$comment(${o}, ${a}, ${s}.schema)`)}}function hW(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,ae._)`${fe.default.errors} === 0`,()=>t.return(fe.default.data),()=>t.throw((0,ae._)`new ${i}(${fe.default.vErrors})`)):(t.assign((0,ae._)`${n}.errors`,fe.default.vErrors),o.unevaluated&&gW(e),t.return((0,ae._)`${fe.default.errors} === 0`))}function gW({gen:e,evaluated:t,props:r,items:n}){r instanceof ae.Name&&e.assign((0,ae._)`${t}.props`,r),n instanceof ae.Name&&e.assign((0,ae._)`${t}.items`,n)}function _R(e,t,r,n){let{gen:i,schema:o,data:a,allErrors:s,opts:c,self:l}=e,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,pi.schemaHasRulesButRef)(o,u))){i.block(()=>WR(e,"$ref",u.all.$ref.definition));return}c.jtd||vW(e,t),i.block(()=>{for(let d of u.rules)f(d);f(u.post)});function f(d){(0,yg.shouldUseGroup)(o,d)&&(d.type?(i.if((0,gd.checkDataType)(d.type,a,c.strictNumbers)),IR(e,d),t.length===1&&t[0]===d.type&&r&&(i.else(),(0,gd.reportTypeError)(e)),i.endIf()):IR(e,d),s||i.if((0,ae._)`${fe.default.errors} === ${n||0}`))}}function IR(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,rW.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,yg.shouldUseRule)(n,o)&&WR(e,o.keyword,o.definition,t.type)})}function vW(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(wW(e,t),e.opts.allowUnionTypes||yW(e,t),kW(e,e.dataTypes))}function wW(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{BR(e.dataTypes,r)||kg(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),bW(e,t)}}function yW(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&kg(e,"use allowUnionTypes to allow union type keyword")}function kW(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,yg.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(a=>AW(t,a))&&kg(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function AW(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function BR(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function bW(e,t){let r=[];for(let n of e.dataTypes)BR(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function kg(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,pi.checkStrictMode)(e,t,e.opts.strictTypes)}var vd=class{constructor(t,r,n){if((0,Cc.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,pi.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",LR(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Cc.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",fe.default.errors))}result(t,r,n){this.failResult((0,ae.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,ae.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,ae._)`${r} !== undefined && (${(0,ae.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?Ec.reportExtraError:Ec.reportError)(this,this.def.error,r)}$dataError(){(0,Ec.reportError)(this,this.def.$dataError||Ec.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ec.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=ae.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=ae.nil,r=ae.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:a}=this;n.if((0,ae.or)((0,ae._)`${i} === undefined`,r)),t!==ae.nil&&n.assign(t,!0),(o.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==ae.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,ae.or)(a(),s());function a(){if(n.length){if(!(r instanceof ae.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,ae._)`${(0,gd.checkDataTypes)(c,r,o.opts.strictNumbers,gd.DataType.Wrong)}`}return ae.nil}function s(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,ae._)`!${c}(${r})`}return ae.nil}}subschema(t,r){let n=(0,wg.getSubschema)(this.it,t);(0,wg.extendSubschemaData)(n,this.it,t),(0,wg.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return lW(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=pi.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=pi.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,ae.Name)),!0}};Hi.KeywordCxt=vd;function WR(e,t,r,n){let i=new vd(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,Cc.funcKeywordCode)(i,r):"macro"in r?(0,Cc.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,Cc.funcKeywordCode)(i,r)}var NW=/^\/(?:[^~]|~0|~1)*$/,RW=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function LR(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return fe.default.rootData;if(e[0]==="/"){if(!NW.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=fe.default.rootData}else{let l=RW.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(o=r[t-u],!i)return o}let a=o,s=i.split("/");for(let l of s)l&&(o=(0,ae._)`${o}${(0,ae.getProperty)((0,pi.unescapeJsonPointer)(l))}`,a=(0,ae._)`${a} && ${o}`);return a;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Hi.getData=LR});var wd=O(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var Ag=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};bg.default=Ag});var Ic=O(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var Ng=Sc(),Rg=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ng.resolveUrl)(t,r,n),this.missingSchema=(0,Ng.normalizeId)((0,Ng.getFullPath)(t,this.missingRef))}};Sg.default=Rg});var kd=O(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.resolveSchema=sn.getCompilingSchema=sn.resolveRef=sn.compileSchema=sn.SchemaEnv=void 0;var En=Re(),SW=wd(),Vo=fi(),Cn=Sc(),VR=Pe(),EW=_c(),Ha=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,Cn.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};sn.SchemaEnv=Ha;function Cg(e){let t=MR.call(this,e);if(t)return t;let r=(0,Cn.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,a=new En.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),s;e.$async&&(s=a.scopeValue("Error",{ref:SW.default,code:(0,En._)`require("ajv/dist/runtime/validation_error").default`}));let c=a.scopeName("validate");e.validateName=c;let l={gen:a,allErrors:this.opts.allErrors,data:Vo.default.data,parentData:Vo.default.parentData,parentDataProperty:Vo.default.parentDataProperty,dataNames:[Vo.default.data],dataPathArr:[En.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,En.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:En.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,En._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,EW.validateFunctionCode)(l),a.optimize(this.opts.code.optimize);let f=a.toString();u=`${a.scopeRefs(Vo.default.scope)}return ${f}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Vo.default.self}`,`${Vo.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:a._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof En.Name?void 0:h,items:m instanceof En.Name?void 0:m,dynamicProps:h instanceof En.Name,dynamicItems:m instanceof En.Name},p.source&&(p.source.evaluated=(0,En.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),f}finally{this._compilations.delete(e)}}sn.compileSchema=Cg;function CW(e,t,r){var n;r=(0,Cn.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=xW.call(this,e,r);if(o===void 0){let a=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;a&&(o=new Ha({schema:a,schemaId:s,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=_W.call(this,o)}sn.resolveRef=CW;function _W(e){return(0,Cn.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Cg.call(this,e)}function MR(e){for(let t of this._compilations)if(IW(t,e))return t}sn.getCompilingSchema=MR;function IW(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function xW(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||yd.call(this,e,t)}function yd(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Cn._getFullPath)(this.opts.uriResolver,r),i=(0,Cn.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Eg.call(this,r,e);let o=(0,Cn.normalizeId)(n),a=this.refs[o]||this.schemas[o];if(typeof a=="string"){let s=yd.call(this,e,a);return typeof s?.schema!="object"?void 0:Eg.call(this,r,s)}if(typeof a?.schema=="object"){if(a.validate||Cg.call(this,a),o===(0,Cn.normalizeId)(t)){let{schema:s}=a,{schemaId:c}=this.opts,l=s[c];return l&&(i=(0,Cn.resolveUrl)(this.opts.uriResolver,i,l)),new Ha({schema:s,schemaId:c,root:e,baseId:i})}return Eg.call(this,r,a)}}sn.resolveSchema=yd;var PW=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Eg(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,VR.unescapeFragment)(s)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!PW.has(s)&&l&&(t=(0,Cn.resolveUrl)(this.opts.uriResolver,t,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,VR.schemaHasRulesButRef)(r,this.RULES)){let s=(0,Cn.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=yd.call(this,n,s)}let{schemaId:a}=this.opts;if(o=o||new Ha({schema:r,schemaId:a,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var qR=O((R3,TW)=>{TW.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 Og=O((S3,GR)=>{"use strict";var OW=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ig=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),$W=RegExp.prototype.test.bind(/^\d*$/u),Mo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),xg=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),HR=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Pg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),jW=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Sr=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Sr[t]="%"+e[t>>4]+e[t&15]}function rr(e){return e<2048?Sr[192|e>>6]+Sr[128|e&63]:e<65536?Sr[224|e>>12]+Sr[128|e>>6&63]+Sr[128|e&63]:Sr[240|e>>18]+Sr[128|e>>12&63]+Sr[128|e>>6&63]+Sr[128|e&63]}function DW(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 BW=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),WW=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),LW=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),VW=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function MW(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!LW(e[t])){if(e[t]==="%"&&t+2<e.length&&Mo(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function FR(e){let t=-1,r=0,n=-1,i=0;for(let s=0;s<e.length;s++)e[s]==="0"?(n===-1&&(n=s),i++,i>r&&(r=i,t=n)):(n=-1,i=0);if(r<2)return e.join(":");let o=e.slice(0,t).join(":"),a=e.slice(t+r).join(":");return o+"::"+a}function qW(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),o=0;for(let s=0;s<i.length;s++){let c=i[s];if(c==="")return;if(c.indexOf(".")!==-1){if(s!==i.length-1||t!==-1&&n.length===0||!Ig(c))return;o+=2;continue}if(!BW(c))return;i[s]=parseInt(c,16).toString(16),o++}if(t===-1)return o!==8?void 0:FR(i);if(o>=8)return;let a=i.slice(0,r.length);for(let s=o;s<8;s++)a.push("0");for(let s=r.length;s<i.length;s++)a.push(i[s]);return FR(a)}function _g(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&&WW(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(FW(n,":")<2)return{host:e,isIPV6:!1,error:t};let i="",o=n.indexOf("%");if(o!==-1){let s=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(i=n.slice(o+s),!MW(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,o)}let a=qW(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(i?"%"+i:""),escapedHost:a+(i?"%25"+i:""),isIPV6:!0}}function FW(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function QR(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 HW(e){if(e===""||e[0]==="/")return QR(e);let t=e.split("/"),r=t.length-1,n=[],i=!1;for(let o=0;o<=r;o++){let a=t[o];a==="."||a===".."?(a===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),i=o===r):n.push(a)}return i&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var QW={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},UW=/[@/?#:]/g,JW=/[@/?#]/g;function UR(e,t){let r=t?JW:UW;return r.lastIndex=0,e.replace(r,n=>QW[n])}function JR(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(Mo(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));t&&xg(a)?r+=a:r+="%"+o,n+=2;continue}}r+=e[n]}return r}function zW(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(Mo(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));a!=="."&&xg(a)?t+=a:t+="%"+o,r+=2;continue}}if(HR(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=KR(i)?n:Sr[i];else if(i<55296||i>57343)t+=rr(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=rr(65536+(i-55296<<10)+(o-56320)),r++):t+=rr(65533)}else t+=rr(65533)}}return t}function KW(e,t=!1){let r="",n=t&&e[0]!=="/";for(let i=0;i<e.length;i++){let o=e[i];if(o==="%"&&i+2<e.length){let a=e.slice(i+1,i+3);if(Mo(a)){r+="%"+a.toUpperCase(),i+=2;continue}}if(o==="/"&&(n=!1),HR(o)&&(o!==":"||!n))r+=o;else{let a=e.charCodeAt(i);if(a<128)r+=Sr[a];else if(a<55296||a>57343)r+=rr(a);else if(a<=56319&&i+1<e.length){let s=e.charCodeAt(i+1);s>=56320&&s<=57343?(r+=rr(65536+(a-55296<<10)+(s-56320)),i++):r+=rr(65533)}else r+=rr(65533)}}return r}function Tg(e,t){let r="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Mo(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{let o=e.charCodeAt(n);if(o<128)r+=Sr[o];else if(o<55296||o>57343)r+=rr(o);else if(o<=56319&&n+1<e.length){let a=e.charCodeAt(n+1);a>=56320&&a<=57343?(r+=rr(65536+(o-55296<<10)+(a-56320)),n++):r+=rr(65533)}else r+=rr(65533)}}return r}function zR(e){return Tg(e,jW)}function GW(e){return Tg(e,Pg)}function YW(e){return Tg(e,Pg)}function KR(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 XW(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(Mo(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));xg(a)?t+=a:t+="%"+o,r+=2;continue}}if(Pg(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=KR(i)?n:Sr[i];else if(i<55296||i>57343)t+=rr(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=rr(65536+(i-55296<<10)+(o-56320)),r++):t+=rr(65533)}else t+=rr(65533)}}return t}function ZW(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(Mo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function eL(e){let t=[];if(e.userinfo!==void 0&&(t.push(zR(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!Ig(r)){let n=_g(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=JR(r,!0),n=_g(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=UR(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!$W(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}GR.exports={nonSimpleDomain:VW,recomposeAuthority:eL,reescapeHostDelimiters:UR,normalizePercentEncoding:JR,normalizePathEncoding:zW,serializePathEncoding:KW,normalizeQueryFragmentEncoding:XW,encodeUserinfo:zR,encodeQuery:GW,encodeFragment:YW,escapePreservingEscapes:ZW,removeDotSegments:QR,removeDotSegmentsRelative:HW,isIPv4:Ig,isUUID:OW,normalizeIPv6:_g,stringArrayToHexStripped:DW}});var tS=O((E3,eS)=>{"use strict";var{isUUID:tL}=Og(),rL=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,nL=["http","https","ws","wss","urn","urn:uuid"];function iL(e){return nL.indexOf(e)!==-1}function $g(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 YR(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function XR(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 oL(e){return e.secure=$g(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function aL(e){if((e.port===($g(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 sL(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(rL);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}`,o=jg(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function cL(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}`,o=jg(i);o&&(e=o.serialize(e,t));let a=e,s=e.nss;return a.path=`${n||t.nid}:${s}`,t.skipEscape=!0,a}function lL(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!tL(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function uL(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var ZR={scheme:"http",domainHost:!0,parse:YR,serialize:XR},dL={scheme:"https",domainHost:ZR.domainHost,parse:YR,serialize:XR},Ad={scheme:"ws",domainHost:!0,parse:oL,serialize:aL},fL={scheme:"wss",domainHost:Ad.domainHost,parse:Ad.parse,serialize:Ad.serialize},pL={scheme:"urn",parse:sL,serialize:cL,skipNormalize:!0},mL={scheme:"urn:uuid",parse:lL,serialize:uL,skipNormalize:!0},bd={http:ZR,https:dL,ws:Ad,wss:fL,urn:pL,"urn:uuid":mL};Object.setPrototypeOf(bd,null);function jg(e){return e&&(bd[e]||bd[e.toLowerCase()])||void 0}eS.exports={wsIsSecure:$g,SCHEMES:bd,isValidSchemeName:iL,getSchemeHandler:jg}});var gS=O((C3,Cd)=>{"use strict";var{normalizeIPv6:aS,removeDotSegments:Pc,removeDotSegmentsRelative:sS,recomposeAuthority:hL,normalizePercentEncoding:Dg,normalizePathEncoding:gL,serializePathEncoding:rS,normalizeQueryFragmentEncoding:nS,encodeQuery:vL,encodeFragment:wL,reescapeHostDelimiters:yL,isIPv4:cS,nonSimpleDomain:kL}=Og(),{SCHEMES:lS,getSchemeHandler:Bg}=tS(),uS=/^[A-Za-z][A-Za-z0-9+.-]*$/u,dS="URI scheme is malformed.",Nd="URI host is malformed.",AL=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function iS(e){let t=String(e);if(!uS.test(t))throw new TypeError(dS);return t}function bL(e,t){return typeof e=="string"?e=PL(e,t):typeof e=="object"&&(e=Sd(qo(e,t),t)),e}function NL(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:o,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:c,malformedScheme:l}=Rd(e,n),{parsed:u,malformedAuthorityOrPort:f,malformedPercentEncoding:d,malformedSchemeSpecific:p,malformedHost:h,malformedScheme:m}=Rd(t,n);if(o||f||a||d||s||p||c||h||l||m)throw new Error(i.error||u.error||"URI is malformed.");let g=fS(i,u,n,!0),v=Bg(r&&r.scheme||g.scheme),w=g.host,A=w!==void 0&&w!==""&&(cS(w)||aS(w).isIPV6);if(mS(g,r||{},v,A))throw new Error(Nd);pS(g,r||{},v,A);let N=w&&w.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(w);if(g.error&&!N)throw new Error(g.error);return n.skipEscape=!0,qo(g,n)}function fS(e,t,r,n){let i={};if(n||(e=Sd(qo(e,r),r),t=Sd(qo(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=Pc(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=Pc(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=Pc(t.path);else{let o=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;o&&!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&&!o&&i.path[0]!=="/"?sS(i.path):Pc(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 RL(e,t,r){let n=oS(e,r),i=oS(t,r);return n!==void 0&&i!==void 0&&n===i}function qo(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=iS(r.scheme));let o=Bg(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n);let a=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,s=(r.scheme===void 0||n.reference==="suffix")&&!a,c=!n.skipEscape&&s;r.path!==void 0&&(n.skipEscape?r.path=Dg(r.path):r.path=rS(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=iS(r.scheme),i.push(r.scheme,":"));let l=hL(r);if(l!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(l),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(u=s&&u[0]!=="/"?sS(u):Pc(u)),s&&(u=rS(u,!0)),l===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),i.push(u)}return r.query!==void 0&&i.push("?",vL(r.query)),r.fragment!==void 0&&i.push("#",wL(r.fragment)),i.join("")}var SL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,EL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,CL=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function _L(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 xc(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 Ed(e){return e[0]==="["&&e[e.length-1]==="]"}function IL(e){let t=e[4];return xc(e[3])||t!==void 0&&!Ed(t)&&xc(t)||xc(e[6])||xc(e[7])||xc(e[8])}function pS(e,t,r,n){if(mS(e,t,r,n))return e.error=e.error||Nd,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Ed(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&kL(e.host)){let i;try{i=new URL("http://"+e.host)}catch(o){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+o,!0}if(!xL(i))return e.error=e.error||Nd,!0;e.host=i.hostname}return!1}function mS(e,t,r,n){return!!(e.host&&n===!1&&!Ed(e.host)&&(t.domainHost||r&&r.domainHost)&&AL.test(e.host))}function xL(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Rd(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,o=!1,a=!1,s=!1,c=!1,l=!1,u=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let f=e.match(EL);f!==null&&f[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let d=e.match(CL);if(d!==null){let h=d[1],m=h.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):h.length!==m.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=e.match(SL);if(p){n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0&&(uS.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||dS,l=!0)),o=IL(p),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let h=_L(n,p);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(cS(n.host)===!1){let v=Ed(n.host),w=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,A=aS(n.host);u=A.isIPV6||A.isIPVFuture===!0,c=w&&(!v||A.error===!0),n.host=u?A.host:A.host.toLowerCase(),c&&(n.error=n.error||Nd,i=!0)}else u=!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 m=Bg(r.scheme||n.scheme);if(c||(s=pS(n,r,m,u)),e.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=u?n.host:Dg(n.host,!0);u||(g=Dg(g.toLowerCase())),n.host=u||r.scheme!=="null"?yL(g,u):g}(!m||m&&!m.skipNormalize)&&(n.path&&(n.path=gL(n.path)),n.query&&(n.query=nS(n.query)),n.fragment&&(n.fragment=nS(n.fragment))),m&&m.parse&&(m.parse(n,r),m===lS.urn&&n.nid===void 0&&(a=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:l}}function Sd(e,t){return Rd(e,t).parsed}function PL(e,t){return hS(e,t).normalized}function hS(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}=Rd(e,t);return{normalized:n||i||o||a||s?e:qo(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}}function oS(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:qo(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:c}=hS(r,t);return i||o||a||s||c?void 0:n}var Wg={SCHEMES:lS,normalize:bL,resolve:NL,resolveComponent:fS,equal:RL,serialize:qo,parse:Sd};Cd.exports=Wg;Cd.exports.default=Wg;Cd.exports.fastUri=Wg});var wS=O(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var vS=gS();vS.code='require("ajv/dist/runtime/uri").default';Lg.default=vS});var ES=O(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.CodeGen=Jt.Name=Jt.nil=Jt.stringify=Jt.str=Jt._=Jt.KeywordCxt=void 0;var TL=_c();Object.defineProperty(Jt,"KeywordCxt",{enumerable:!0,get:function(){return TL.KeywordCxt}});var Qa=Re();Object.defineProperty(Jt,"_",{enumerable:!0,get:function(){return Qa._}});Object.defineProperty(Jt,"str",{enumerable:!0,get:function(){return Qa.str}});Object.defineProperty(Jt,"stringify",{enumerable:!0,get:function(){return Qa.stringify}});Object.defineProperty(Jt,"nil",{enumerable:!0,get:function(){return Qa.nil}});Object.defineProperty(Jt,"Name",{enumerable:!0,get:function(){return Qa.Name}});Object.defineProperty(Jt,"CodeGen",{enumerable:!0,get:function(){return Qa.CodeGen}});var OL=wd(),NS=Ic(),$L=cg(),Tc=kd(),jL=Re(),Oc=Sc(),_d=Rc(),Mg=Pe(),yS=qR(),DL=wS(),RS=(e,t)=>new RegExp(e,t);RS.code="new RegExp";var BL=["removeAdditional","useDefaults","coerceTypes"],WL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),LL={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."},VL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},kS=200;function ML(e){var t,r,n,i,o,a,s,c,l,u,f,d,p,h,m,g,v,w,A,N,b,E,V,j,z;let X=e.strict,de=(t=e.code)===null||t===void 0?void 0:t.optimize,se=de===!0||de===void 0?1:de||0,De=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:RS,Z=(i=e.uriResolver)!==null&&i!==void 0?i:DL.default;return{strictSchema:(a=(o=e.strictSchema)!==null&&o!==void 0?o:X)!==null&&a!==void 0?a:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:X)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:X)!==null&&u!==void 0?u:"log",strictTuples:(d=(f=e.strictTuples)!==null&&f!==void 0?f:X)!==null&&d!==void 0?d:"log",strictRequired:(h=(p=e.strictRequired)!==null&&p!==void 0?p:X)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:se,regExp:De}:{optimize:se,regExp:De},loopRequired:(m=e.loopRequired)!==null&&m!==void 0?m:kS,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:kS,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(A=e.inlineRefs)!==null&&A!==void 0?A:!0,schemaId:(N=e.schemaId)!==null&&N!==void 0?N:"$id",addUsedSchema:(b=e.addUsedSchema)!==null&&b!==void 0?b:!0,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(V=e.validateFormats)!==null&&V!==void 0?V:!0,unicodeRegExp:(j=e.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(z=e.int32range)!==null&&z!==void 0?z:!0,uriResolver:Z}}var $c=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,...ML(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new jL.ValueScope({scope:{},prefixes:WL,es5:r,lines:n}),this.logger=JL(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,$L.getRules)(),AS.call(this,LL,t,"NOT SUPPORTED"),AS.call(this,VL,t,"DEPRECATED","warn"),this._metaOpts=QL.call(this),t.formats&&FL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&HL.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),qL.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=yS;n==="id"&&(i={...yS},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(u,f){await o.call(this,u.$schema);let d=this._addSchema(u,f);return d.validate||a.call(this,d)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function a(u){try{return this._compileSchemaEnv(u)}catch(f){if(!(f instanceof NS.default))throw f;return s.call(this,f),await c.call(this,f.missingSchema),a.call(this,u)}}function s({missingSchema:u,missingRef:f}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${f} cannot be resolved`)}async function c(u){let f=await l.call(this,u);this.refs[u]||await o.call(this,f.$schema),this.refs[u]||this.addSchema(f,u,r)}async function l(u){let f=this._loading[u];if(f)return f;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let a of t)this.addSchema(a,void 0,n,i);return this}let o;if(typeof t=="object"){let{schemaId:a}=this.opts;if(o=t[a],o!==void 0&&typeof o!="string")throw new Error(`schema ${a} must be string`)}return r=(0,Oc.normalizeId)(r||o),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 o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(t){let r;for(;typeof(r=bS.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Tc.SchemaEnv({schema:{},schemaId:n});if(r=Tc.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=bS.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,Oc.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(KL.call(this,n,r),!r)return(0,Mg.eachItem)(n,o=>Vg.call(this,o)),this;YL.call(this,r);let i={...r,type:(0,_d.getJSONTypes)(r.type),schemaType:(0,_d.getJSONTypes)(r.schemaType)};return(0,Mg.eachItem)(n,i.type.length===0?o=>Vg.call(this,o,i):o=>i.type.forEach(a=>Vg.call(this,o,i,a))),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(o=>o.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,o)=>i+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let o=i.split("/").slice(1),a=t;for(let s of o)a=a[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:l}=c.definition,u=a[s];l&&u&&(a[s]=SS(u))}}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,o=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof t=="object")a=t[s];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 c=this._cache.get(t);if(c!==void 0)return c;n=(0,Oc.normalizeId)(a||n);let l=Oc.getSchemaRefs.call(this,t,n);return c=new Tc.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(t,!0),c}_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):Tc.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{Tc.compileSchema.call(this,t)}finally{this.opts=r}}};$c.ValidationError=OL.default;$c.MissingRefError=NS.default;Jt.default=$c;function AS(e,t,r,n="error"){for(let i in e){let o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function bS(e){return e=(0,Oc.normalizeId)(e),this.schemas[e]||this.refs[e]}function qL(){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 FL(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function HL(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 QL(){let e={...this.opts};for(let t of BL)delete e[t];return e}var UL={log(){},warn(){},error(){}};function JL(e){if(e===!1)return UL;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 zL=/^[a-z_$][a-z0-9_$:-]*$/i;function KL(e,t){let{RULES:r}=this;if((0,Mg.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!zL.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 Vg(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,a=i?o.post:o.rules.find(({type:c})=>c===r);if(a||(a={type:r,rules:[]},o.rules.push(a)),o.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,_d.getJSONTypes)(t.type),schemaType:(0,_d.getJSONTypes)(t.schemaType)}};t.before?GL.call(this,a,s,t.before):a.rules.push(s),o.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function GL(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 YL(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=SS(t)),e.validateSchema=this.compile(t,!0))}var XL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function SS(e){return{anyOf:[e,XL]}}});var CS=O(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var ZL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qg.default=ZL});var PS=O(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.callRef=Fo.getValidate=void 0;var eV=Ic(),_S=an(),Er=Re(),Ua=fi(),IS=kd(),Id=Pe(),tV={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:o,validateName:a,opts:s,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&i===l.baseId)return f();let u=IS.resolveRef.call(c,l,i,r);if(u===void 0)throw new eV.default(n.opts.uriResolver,i,r);if(u instanceof IS.SchemaEnv)return d(u);return p(u);function f(){if(o===l)return xd(e,a,o,o.$async);let h=t.scopeValue("root",{ref:l});return xd(e,(0,Er._)`${h}.validate`,l,l.$async)}function d(h){let m=xS(e,h);xd(e,m,h,h.$async)}function p(h){let m=t.scopeValue("schema",s.code.source===!0?{ref:h,code:(0,Er.stringify)(h)}:{ref:h}),g=t.name("valid"),v=e.subschema({schema:h,dataTypes:[],schemaPath:Er.nil,topSchemaRef:m,errSchemaPath:r},g);e.mergeEvaluated(v),e.ok(g)}}};function xS(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Er._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Fo.getValidate=xS;function xd(e,t,r,n){let{gen:i,it:o}=e,{allErrors:a,schemaEnv:s,opts:c}=o,l=c.passContext?Ua.default.this:Er.nil;n?u():f();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,Er._)`await ${(0,_S.callValidateCode)(e,t,l)}`),p(t),a||i.assign(h,!0)},m=>{i.if((0,Er._)`!(${m} instanceof ${o.ValidationError})`,()=>i.throw(m)),d(m),a||i.assign(h,!1)}),e.ok(h)}function f(){e.result((0,_S.callValidateCode)(e,t,l),()=>p(t),()=>d(t))}function d(h){let m=(0,Er._)`${h}.errors`;i.assign(Ua.default.vErrors,(0,Er._)`${Ua.default.vErrors} === null ? ${m} : ${Ua.default.vErrors}.concat(${m})`),i.assign(Ua.default.errors,(0,Er._)`${Ua.default.vErrors}.length`)}function p(h){var m;if(!o.opts.unevaluated)return;let g=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=Id.mergeEvaluated.props(i,g.props,o.props));else{let v=i.var("props",(0,Er._)`${h}.evaluated.props`);o.props=Id.mergeEvaluated.props(i,v,o.props,Er.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=Id.mergeEvaluated.items(i,g.items,o.items));else{let v=i.var("items",(0,Er._)`${h}.evaluated.items`);o.items=Id.mergeEvaluated.items(i,v,o.items,Er.Name)}}}Fo.callRef=xd;Fo.default=tV});var TS=O(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var rV=CS(),nV=PS(),iV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rV.default,nV.default];Fg.default=iV});var OS=O(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var Pd=Re(),Qi=Pd.operators,Td={maximum:{okStr:"<=",ok:Qi.LTE,fail:Qi.GT},minimum:{okStr:">=",ok:Qi.GTE,fail:Qi.LT},exclusiveMaximum:{okStr:"<",ok:Qi.LT,fail:Qi.GTE},exclusiveMinimum:{okStr:">",ok:Qi.GT,fail:Qi.LTE}},oV={message:({keyword:e,schemaCode:t})=>(0,Pd.str)`must be ${Td[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Pd._)`{comparison: ${Td[e].okStr}, limit: ${t}}`},aV={keyword:Object.keys(Td),type:"number",schemaType:"number",$data:!0,error:oV,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Pd._)`${r} ${Td[t].fail} ${n} || isNaN(${r})`)}};Hg.default=aV});var $S=O(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});var jc=Re(),sV={message:({schemaCode:e})=>(0,jc.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,jc._)`{multipleOf: ${e}}`},cV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:sV,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,a=t.let("res"),s=o?(0,jc._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${o}`:(0,jc._)`${a} !== parseInt(${a})`;e.fail$data((0,jc._)`(${n} === 0 || (${a} = ${r}/${n}, ${s}))`)}};Qg.default=cV});var DS=O(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});function jS(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}Ug.default=jS;jS.code='require("ajv/dist/runtime/ucs2length").default'});var BS=O(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var Ho=Re(),lV=Pe(),uV=DS(),dV={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Ho.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Ho._)`{limit: ${e}}`},fV={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:dV,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?Ho.operators.GT:Ho.operators.LT,a=i.opts.unicode===!1?(0,Ho._)`${r}.length`:(0,Ho._)`${(0,lV.useFunc)(e.gen,uV.default)}(${r})`;e.fail$data((0,Ho._)`${a} ${o} ${n}`)}};Jg.default=fV});var WS=O(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var pV=an(),mV=Pe(),Ja=Re(),hV={message:({schemaCode:e})=>(0,Ja.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Ja._)`{pattern: ${e}}`},gV={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:hV,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:a}=e,s=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=a.opts.code,l=c.code==="new RegExp"?(0,Ja._)`new RegExp`:(0,mV.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,Ja._)`${l}(${o}, ${s}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,Ja._)`!${u}`)}else{let c=(0,pV.usePattern)(e,i);e.fail$data((0,Ja._)`!${c}.test(${r})`)}}};zg.default=gV});var LS=O(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var Dc=Re(),vV={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Dc.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Dc._)`{limit: ${e}}`},wV={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:vV,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?Dc.operators.GT:Dc.operators.LT;e.fail$data((0,Dc._)`Object.keys(${r}).length ${i} ${n}`)}};Kg.default=wV});var VS=O(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var Bc=an(),Wc=Re(),yV=Pe(),kV={message:({params:{missingProperty:e}})=>(0,Wc.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Wc._)`{missingProperty: ${e}}`},AV={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kV,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:o,it:a}=e,{opts:s}=a;if(!o&&r.length===0)return;let c=r.length>=s.loopRequired;if(a.allErrors?l():u(),s.strictRequired){let p=e.parentSchema.properties,{definedProperties:h}=e.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let g=a.schemaEnv.baseId+a.errSchemaPath,v=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,yV.checkStrictMode)(a,v,a.opts.strictRequired)}}function l(){if(c||o)e.block$data(Wc.nil,f);else for(let p of r)(0,Bc.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(c||o){let h=t.let("valid",!0);e.block$data(h,()=>d(p,h)),e.ok(h)}else t.if((0,Bc.checkMissingProp)(e,r,p)),(0,Bc.reportMissingProp)(e,p),t.else()}function f(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Bc.noPropertyInData)(t,i,p,s.ownProperties),()=>e.error())})}function d(p,h){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(h,(0,Bc.propertyInData)(t,i,p,s.ownProperties)),t.if((0,Wc.not)(h),()=>{e.error(),t.break()})},Wc.nil)}}};Gg.default=AV});var MS=O(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var Lc=Re(),bV={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Lc.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Lc._)`{limit: ${e}}`},NV={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:bV,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?Lc.operators.GT:Lc.operators.LT;e.fail$data((0,Lc._)`${r}.length ${i} ${n}`)}};Yg.default=NV});var Od=O(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});var qS=gg();qS.code='require("ajv/dist/runtime/equal").default';Xg.default=qS});var FS=O(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});var Zg=Rc(),zt=Re(),RV=Pe(),SV=Od(),EV={message:({params:{i:e,j:t}})=>(0,zt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,zt._)`{i: ${e}, j: ${t}}`},CV={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:EV,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:o,schemaCode:a,it:s}=e;if(!n&&!i)return;let c=t.let("valid"),l=o.items?(0,Zg.getSchemaTypes)(o.items):[];e.block$data(c,u,(0,zt._)`${a} === false`),e.ok(c);function u(){let h=t.let("i",(0,zt._)`${r}.length`),m=t.let("j");e.setParams({i:h,j:m}),t.assign(c,!0),t.if((0,zt._)`${h} > 1`,()=>(f()?d:p)(h,m))}function f(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function d(h,m){let g=t.name("item"),v=(0,Zg.checkDataTypes)(l,g,s.opts.strictNumbers,Zg.DataType.Wrong),w=t.const("indices",(0,zt._)`{}`);t.for((0,zt._)`;${h}--;`,()=>{t.let(g,(0,zt._)`${r}[${h}]`),t.if(v,(0,zt._)`continue`),l.length>1&&t.if((0,zt._)`typeof ${g} == "string"`,(0,zt._)`${g} += "_"`),t.if((0,zt._)`typeof ${w}[${g}] == "number"`,()=>{t.assign(m,(0,zt._)`${w}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,zt._)`${w}[${g}] = ${h}`)})}function p(h,m){let g=(0,RV.useFunc)(t,SV.default),v=t.name("outer");t.label(v).for((0,zt._)`;${h}--;`,()=>t.for((0,zt._)`${m} = ${h}; ${m}--;`,()=>t.if((0,zt._)`${g}(${r}[${h}], ${r}[${m}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};ev.default=CV});var HS=O(rv=>{"use strict";Object.defineProperty(rv,"__esModule",{value:!0});var tv=Re(),_V=Pe(),IV=Od(),xV={message:"must be equal to constant",params:({schemaCode:e})=>(0,tv._)`{allowedValue: ${e}}`},PV={keyword:"const",$data:!0,error:xV,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,tv._)`!${(0,_V.useFunc)(t,IV.default)}(${r}, ${i})`):e.fail((0,tv._)`${o} !== ${r}`)}};rv.default=PV});var QS=O(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});var Vc=Re(),TV=Pe(),OV=Od(),$V={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Vc._)`{allowedValues: ${e}}`},jV={keyword:"enum",schemaType:"array",$data:!0,error:$V,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:a}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let s=i.length>=a.opts.loopEnum,c,l=()=>c??(c=(0,TV.useFunc)(t,OV.default)),u;if(s||n)u=t.let("valid"),e.block$data(u,f);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=t.const("vSchema",o);u=(0,Vc.or)(...i.map((h,m)=>d(p,m)))}e.pass(u);function f(){t.assign(u,!1),t.forOf("v",o,p=>t.if((0,Vc._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function d(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,Vc._)`${l()}(${r}, ${p}[${h}])`:(0,Vc._)`${r} === ${m}`}}};nv.default=jV});var US=O(iv=>{"use strict";Object.defineProperty(iv,"__esModule",{value:!0});var DV=OS(),BV=$S(),WV=BS(),LV=WS(),VV=LS(),MV=VS(),qV=MS(),FV=FS(),HV=HS(),QV=QS(),UV=[DV.default,BV.default,WV.default,LV.default,VV.default,MV.default,qV.default,FV.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},HV.default,QV.default];iv.default=UV});var av=O(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.validateAdditionalItems=void 0;var Qo=Re(),ov=Pe(),JV={message:({params:{len:e}})=>(0,Qo.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Qo._)`{limit: ${e}}`},zV={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JV,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ov.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}JS(e,n)}};function JS(e,t){let{gen:r,schema:n,data:i,keyword:o,it:a}=e;a.items=!0;let s=r.const("len",(0,Qo._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Qo._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,ov.alwaysValidSchema)(a,n)){let l=r.var("valid",(0,Qo._)`${s} <= ${t.length}`);r.if((0,Qo.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,s,u=>{e.subschema({keyword:o,dataProp:u,dataPropType:ov.Type.Num},l),a.allErrors||r.if((0,Qo.not)(l),()=>r.break())})}}Mc.validateAdditionalItems=JS;Mc.default=zV});var sv=O(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.validateTuple=void 0;var zS=Re(),$d=Pe(),KV=an(),GV={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return KS(e,"additionalItems",t);r.items=!0,!(0,$d.alwaysValidSchema)(r,t)&&e.ok((0,KV.validateArray)(e))}};function KS(e,t,r=e.schema){let{gen:n,parentSchema:i,data:o,keyword:a,it:s}=e;u(i),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=$d.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),l=n.const("len",(0,zS._)`${o}.length`);r.forEach((f,d)=>{(0,$d.alwaysValidSchema)(s,f)||(n.if((0,zS._)`${l} > ${d}`,()=>e.subschema({keyword:a,schemaProp:d,dataProp:d},c)),e.ok(c))});function u(f){let{opts:d,errSchemaPath:p}=s,h=r.length,m=h===f.minItems&&(h===f.maxItems||f[t]===!1);if(d.strictTuples&&!m){let g=`"${a}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,$d.checkStrictMode)(s,g,d.strictTuples)}}}qc.validateTuple=KS;qc.default=GV});var GS=O(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});var YV=sv(),XV={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,YV.validateTuple)(e,"items")};cv.default=XV});var XS=O(lv=>{"use strict";Object.defineProperty(lv,"__esModule",{value:!0});var YS=Re(),ZV=Pe(),eM=an(),tM=av(),rM={message:({params:{len:e}})=>(0,YS.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,YS._)`{limit: ${e}}`},nM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rM,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,ZV.alwaysValidSchema)(n,t)&&(i?(0,tM.validateAdditionalItems)(e,i):e.ok((0,eM.validateArray)(e)))}};lv.default=nM});var ZS=O(uv=>{"use strict";Object.defineProperty(uv,"__esModule",{value:!0});var cn=Re(),jd=Pe(),iM={message:({params:{min:e,max:t}})=>t===void 0?(0,cn.str)`must contain at least ${e} valid item(s)`:(0,cn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,cn._)`{minContains: ${e}}`:(0,cn._)`{minContains: ${e}, maxContains: ${t}}`},oM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iM,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e,a,s,{minContains:c,maxContains:l}=n;o.opts.next?(a=c===void 0?1:c,s=l):a=1;let u=t.const("len",(0,cn._)`${i}.length`);if(e.setParams({min:a,max:s}),s===void 0&&a===0){(0,jd.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&a>s){(0,jd.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,jd.alwaysValidSchema)(o,r)){let m=(0,cn._)`${u} >= ${a}`;s!==void 0&&(m=(0,cn._)`${m} && ${u} <= ${s}`),e.pass(m);return}o.items=!0;let f=t.name("valid");s===void 0&&a===1?p(f,()=>t.if(f,()=>t.break())):a===0?(t.let(f,!0),s!==void 0&&t.if((0,cn._)`${i}.length > 0`,d)):(t.let(f,!1),d()),e.result(f,()=>e.reset());function d(){let m=t.name("_valid"),g=t.let("count",0);p(m,()=>t.if(m,()=>h(g)))}function p(m,g){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:jd.Type.Num,compositeRule:!0},m),g()})}function h(m){t.code((0,cn._)`${m}++`),s===void 0?t.if((0,cn._)`${m} >= ${a}`,()=>t.assign(f,!0).break()):(t.if((0,cn._)`${m} > ${s}`,()=>t.assign(f,!1).break()),a===1?t.assign(f,!0):t.if((0,cn._)`${m} >= ${a}`,()=>t.assign(f,!0)))}}};uv.default=oM});var rE=O(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.validateSchemaDeps=Qn.validatePropertyDeps=Qn.error=void 0;var dv=Re(),aM=Pe(),Fc=an();Qn.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,dv.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,dv._)`{property: ${e},
|
|
9
|
+
missingProperty: ${n},
|
|
10
|
+
depsCount: ${t},
|
|
11
|
+
deps: ${r}}`};var sM={keyword:"dependencies",type:"object",schemaType:"object",error:Qn.error,code(e){let[t,r]=cM(e);eE(e,t),tE(e,r)}};function cM({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 eE(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let a in t){let s=t[a];if(s.length===0)continue;let c=(0,Fc.propertyInData)(r,n,a,i.opts.ownProperties);e.setParams({property:a,depsCount:s.length,deps:s.join(", ")}),i.allErrors?r.if(c,()=>{for(let l of s)(0,Fc.checkReportMissingProp)(e,l)}):(r.if((0,dv._)`${c} && (${(0,Fc.checkMissingProp)(e,s,o)})`),(0,Fc.reportMissingProp)(e,o),r.else())}}Qn.validatePropertyDeps=eE;function tE(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,a=r.name("valid");for(let s in t)(0,aM.alwaysValidSchema)(o,t[s])||(r.if((0,Fc.propertyInData)(r,n,s,o.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:s},a);e.mergeValidEvaluated(c,a)},()=>r.var(a,!0)),e.ok(a))}Qn.validateSchemaDeps=tE;Qn.default=sM});var iE=O(fv=>{"use strict";Object.defineProperty(fv,"__esModule",{value:!0});var nE=Re(),lM=Pe(),uM={message:"property name must be valid",params:({params:e})=>(0,nE._)`{propertyName: ${e.propertyName}}`},dM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:uM,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,lM.alwaysValidSchema)(i,r))return;let o=t.name("valid");t.forIn("key",n,a=>{e.setParams({propertyName:a}),e.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},o),t.if((0,nE.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};fv.default=dM});var mv=O(pv=>{"use strict";Object.defineProperty(pv,"__esModule",{value:!0});var Dd=an(),_n=Re(),fM=fi(),Bd=Pe(),pM={message:"must NOT have additional properties",params:({params:e})=>(0,_n._)`{additionalProperty: ${e.additionalProperty}}`},mM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:pM,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:o,it:a}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=a;if(a.props=!0,c.removeAdditional!=="all"&&(0,Bd.alwaysValidSchema)(a,r))return;let l=(0,Dd.allSchemaProperties)(n.properties),u=(0,Dd.allSchemaProperties)(n.patternProperties);f(),e.ok((0,_n._)`${o} === ${fM.default.errors}`);function f(){t.forIn("key",i,g=>{!l.length&&!u.length?h(g):t.if(d(g),()=>h(g))})}function d(g){let v;if(l.length>8){let w=(0,Bd.schemaRefOrVal)(a,n.properties,"properties");v=(0,Dd.isOwnProperty)(t,w,g)}else l.length?v=(0,_n.or)(...l.map(w=>(0,_n._)`${g} === ${w}`)):v=_n.nil;return u.length&&(v=(0,_n.or)(v,...u.map(w=>(0,_n._)`${(0,Dd.usePattern)(e,w)}.test(${g})`))),(0,_n.not)(v)}function p(g){t.code((0,_n._)`delete ${i}[${g}]`)}function h(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,Bd.alwaysValidSchema)(a,r)){let v=t.name("valid");c.removeAdditional==="failing"?(m(g,v,!1),t.if((0,_n.not)(v),()=>{e.reset(),p(g)})):(m(g,v),s||t.if((0,_n.not)(v),()=>t.break()))}}function m(g,v,w){let A={keyword:"additionalProperties",dataProp:g,dataPropType:Bd.Type.Str};w===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(A,v)}}};pv.default=mM});var sE=O(gv=>{"use strict";Object.defineProperty(gv,"__esModule",{value:!0});var hM=_c(),oE=an(),hv=Pe(),aE=mv(),gM={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&aE.default.code(new hM.KeywordCxt(o,aE.default,"additionalProperties"));let a=(0,oE.allSchemaProperties)(r);for(let f of a)o.definedProperties.add(f);o.opts.unevaluated&&a.length&&o.props!==!0&&(o.props=hv.mergeEvaluated.props(t,(0,hv.toHash)(a),o.props));let s=a.filter(f=>!(0,hv.alwaysValidSchema)(o,r[f]));if(s.length===0)return;let c=t.name("valid");for(let f of s)l(f)?u(f):(t.if((0,oE.propertyInData)(t,i,f,o.opts.ownProperties)),u(f),o.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function l(f){return o.opts.useDefaults&&!o.compositeRule&&r[f].default!==void 0}function u(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};gv.default=gM});var dE=O(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});var cE=an(),Wd=Re(),lE=Pe(),uE=Pe(),vM={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:o}=e,{opts:a}=o,s=(0,cE.allSchemaProperties)(r),c=s.filter(m=>(0,lE.alwaysValidSchema)(o,r[m]));if(s.length===0||c.length===s.length&&(!o.opts.unevaluated||o.props===!0))return;let l=a.strictSchema&&!a.allowMatchingProperties&&i.properties,u=t.name("valid");o.props!==!0&&!(o.props instanceof Wd.Name)&&(o.props=(0,uE.evaluatedPropsToName)(t,o.props));let{props:f}=o;d();function d(){for(let m of s)l&&p(m),o.allErrors?h(m):(t.var(u,!0),h(m),t.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,lE.checkStrictMode)(o,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){t.forIn("key",n,g=>{t.if((0,Wd._)`${(0,cE.usePattern)(e,m)}.test(${g})`,()=>{let v=c.includes(m);v||e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:uE.Type.Str},u),o.opts.unevaluated&&f!==!0?t.assign((0,Wd._)`${f}[${g}]`,!0):!v&&!o.allErrors&&t.if((0,Wd.not)(u),()=>t.break())})})}}};vv.default=vM});var fE=O(wv=>{"use strict";Object.defineProperty(wv,"__esModule",{value:!0});var wM=Pe(),yM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,wM.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"}};wv.default=yM});var pE=O(yv=>{"use strict";Object.defineProperty(yv,"__esModule",{value:!0});var kM=an(),AM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kM.validateUnion,error:{message:"must match a schema in anyOf"}};yv.default=AM});var mE=O(kv=>{"use strict";Object.defineProperty(kv,"__esModule",{value:!0});var Ld=Re(),bM=Pe(),NM={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Ld._)`{passingSchemas: ${e.passing}}`},RM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:NM,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 o=r,a=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(l),e.result(a,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((u,f)=>{let d;(0,bM.alwaysValidSchema)(i,u)?t.var(c,!0):d=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,Ld._)`${c} && ${a}`).assign(a,!1).assign(s,(0,Ld._)`[${s}, ${f}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(s,f),d&&e.mergeEvaluated(d,Ld.Name)})})}}};kv.default=RM});var hE=O(Av=>{"use strict";Object.defineProperty(Av,"__esModule",{value:!0});var SM=Pe(),EM={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((o,a)=>{if((0,SM.alwaysValidSchema)(n,o))return;let s=e.subschema({keyword:"allOf",schemaProp:a},i);e.ok(i),e.mergeEvaluated(s)})}};Av.default=EM});var wE=O(bv=>{"use strict";Object.defineProperty(bv,"__esModule",{value:!0});var Vd=Re(),vE=Pe(),CM={message:({params:e})=>(0,Vd.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Vd._)`{failingKeyword: ${e.ifClause}}`},_M={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CM,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,vE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=gE(n,"then"),o=gE(n,"else");if(!i&&!o)return;let a=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),i&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(s,l("then",u),l("else",u))}else i?t.if(s,l("then")):t.if((0,Vd.not)(s),l("else"));e.pass(a,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(u)}function l(u,f){return()=>{let d=e.subschema({keyword:u},s);t.assign(a,s),e.mergeValidEvaluated(d,a),f?t.assign(f,(0,Vd._)`${u}`):e.setParams({ifClause:u})}}}};function gE(e,t){let r=e.schema[t];return r!==void 0&&!(0,vE.alwaysValidSchema)(e,r)}bv.default=_M});var yE=O(Nv=>{"use strict";Object.defineProperty(Nv,"__esModule",{value:!0});var IM=Pe(),xM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,IM.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Nv.default=xM});var kE=O(Rv=>{"use strict";Object.defineProperty(Rv,"__esModule",{value:!0});var PM=av(),TM=GS(),OM=sv(),$M=XS(),jM=ZS(),DM=rE(),BM=iE(),WM=mv(),LM=sE(),VM=dE(),MM=fE(),qM=pE(),FM=mE(),HM=hE(),QM=wE(),UM=yE();function JM(e=!1){let t=[MM.default,qM.default,FM.default,HM.default,QM.default,UM.default,BM.default,WM.default,DM.default,LM.default,VM.default];return e?t.push(TM.default,$M.default):t.push(PM.default,OM.default),t.push(jM.default),t}Rv.default=JM});var AE=O(Sv=>{"use strict";Object.defineProperty(Sv,"__esModule",{value:!0});var ht=Re(),zM={message:({schemaCode:e})=>(0,ht.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ht._)`{format: ${e}}`},KM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:zM,code(e,t){let{gen:r,data:n,$data:i,schema:o,schemaCode:a,it:s}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:f}=s;if(!c.validateFormats)return;i?d():p();function d(){let h=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),m=r.const("fDef",(0,ht._)`${h}[${a}]`),g=r.let("fType"),v=r.let("format");r.if((0,ht._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,(0,ht._)`${m}.type || "string"`).assign(v,(0,ht._)`${m}.validate`),()=>r.assign(g,(0,ht._)`"string"`).assign(v,m)),e.fail$data((0,ht.or)(w(),A()));function w(){return c.strictSchema===!1?ht.nil:(0,ht._)`${a} && !${v}`}function A(){let N=u.$async?(0,ht._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ht._)`${v}(${n})`,b=(0,ht._)`(typeof ${v} == "function" ? ${N} : ${v}.test(${n}))`;return(0,ht._)`${v} && ${v} !== true && ${g} === ${t} && !${b}`}}function p(){let h=f.formats[o];if(!h){w();return}if(h===!0)return;let[m,g,v]=A(h);m===t&&e.pass(N());function w(){if(c.strictSchema===!1){f.logger.warn(b());return}throw new Error(b());function b(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function A(b){let E=b instanceof RegExp?(0,ht.regexpCode)(b):c.code.formats?(0,ht._)`${c.code.formats}${(0,ht.getProperty)(o)}`:void 0,V=r.scopeValue("formats",{key:o,ref:b,code:E});return typeof b=="object"&&!(b instanceof RegExp)?[b.type||"string",b.validate,(0,ht._)`${V}.validate`]:["string",b,V]}function N(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ht._)`await ${v}(${n})`}return typeof g=="function"?(0,ht._)`${v}(${n})`:(0,ht._)`${v}.test(${n})`}}}};Sv.default=KM});var bE=O(Ev=>{"use strict";Object.defineProperty(Ev,"__esModule",{value:!0});var GM=AE(),YM=[GM.default];Ev.default=YM});var NE=O(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.contentVocabulary=za.metadataVocabulary=void 0;za.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];za.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var SE=O(Cv=>{"use strict";Object.defineProperty(Cv,"__esModule",{value:!0});var XM=TS(),ZM=US(),e1=kE(),t1=bE(),RE=NE(),r1=[XM.default,ZM.default,(0,e1.default)(),t1.default,RE.metadataVocabulary,RE.contentVocabulary];Cv.default=r1});var CE=O(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.DiscrError=void 0;var EE;(function(e){e.Tag="tag",e.Mapping="mapping"})(EE||(Md.DiscrError=EE={}))});var IE=O(Iv=>{"use strict";Object.defineProperty(Iv,"__esModule",{value:!0});var Ka=Re(),_v=CE(),_E=kd(),n1=Ic(),i1=Pe(),o1={message:({params:{discrError:e,tagName:t}})=>e===_v.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Ka._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},a1={keyword:"discriminator",type:"object",schemaType:"object",error:o1,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:o}=e,{oneOf:a}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Ka._)`${r}${(0,Ka.getProperty)(s)}`);t.if((0,Ka._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:_v.DiscrError.Tag,tag:l,tagName:s})),e.ok(c);function u(){let p=d();t.if(!1);for(let h in p)t.elseIf((0,Ka._)`${l} === ${h}`),t.assign(c,f(p[h]));t.else(),e.error(!1,{discrError:_v.DiscrError.Mapping,tag:l,tagName:s}),t.endIf()}function f(p){let h=t.name("valid"),m=e.subschema({keyword:"oneOf",schemaProp:p},h);return e.mergeEvaluated(m,Ka.Name),h}function d(){var p;let h={},m=v(i),g=!0;for(let N=0;N<a.length;N++){let b=a[N];if(b?.$ref&&!(0,i1.schemaHasRulesButRef)(b,o.self.RULES)){let V=b.$ref;if(b=_E.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,V),b instanceof _E.SchemaEnv&&(b=b.schema),b===void 0)throw new n1.default(o.opts.uriResolver,o.baseId,V)}let E=(p=b?.properties)===null||p===void 0?void 0:p[s];if(typeof E!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);g=g&&(m||v(b)),w(E,N)}if(!g)throw new Error(`discriminator: "${s}" must be required`);return h;function v({required:N}){return Array.isArray(N)&&N.includes(s)}function w(N,b){if(N.const)A(N.const,b);else if(N.enum)for(let E of N.enum)A(E,b);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function A(N,b){if(typeof N!="string"||N in h)throw new Error(`discriminator: "${s}" values must be unique strings`);h[N]=b}}}};Iv.default=a1});var xE=O((h6,s1)=>{s1.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 Fd=O((rt,xv)=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.MissingRefError=rt.ValidationError=rt.CodeGen=rt.Name=rt.nil=rt.stringify=rt.str=rt._=rt.KeywordCxt=rt.Ajv=void 0;var c1=ES(),l1=SE(),u1=IE(),PE=xE(),d1=["/properties"],qd="http://json-schema.org/draft-07/schema",Ga=class extends c1.default{_addVocabularies(){super._addVocabularies(),l1.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(u1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(PE,d1):PE;this.addMetaSchema(t,qd,!1),this.refs["http://json-schema.org/schema"]=qd}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qd)?qd:void 0)}};rt.Ajv=Ga;xv.exports=rt=Ga;xv.exports.Ajv=Ga;Object.defineProperty(rt,"__esModule",{value:!0});rt.default=Ga;var f1=_c();Object.defineProperty(rt,"KeywordCxt",{enumerable:!0,get:function(){return f1.KeywordCxt}});var Ya=Re();Object.defineProperty(rt,"_",{enumerable:!0,get:function(){return Ya._}});Object.defineProperty(rt,"str",{enumerable:!0,get:function(){return Ya.str}});Object.defineProperty(rt,"stringify",{enumerable:!0,get:function(){return Ya.stringify}});Object.defineProperty(rt,"nil",{enumerable:!0,get:function(){return Ya.nil}});Object.defineProperty(rt,"Name",{enumerable:!0,get:function(){return Ya.Name}});Object.defineProperty(rt,"CodeGen",{enumerable:!0,get:function(){return Ya.CodeGen}});var p1=wd();Object.defineProperty(rt,"ValidationError",{enumerable:!0,get:function(){return p1.default}});var m1=Ic();Object.defineProperty(rt,"MissingRefError",{enumerable:!0,get:function(){return m1.default}})});var TE,OE=_(()=>{"use strict";TE=new Map});function Hd(e){let t=Mn(e),r=Uo.get(t);if(r)return Uo.delete(t),Uo.set(t,r),r;let i=TE.get(t)??new Tv.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),o={validate:i,errorsText:()=>Tv.Ajv.prototype.errorsText(i.errors)};if(t.length<=$E){for(;Uo.size>=h1||Pv+t.length>$E;){let a=Uo.keys().next().value;Uo.delete(a),Pv-=a.length}Uo.set(t,o),Pv+=t.length}return o}var Tv,h1,$E,Uo,Pv,Ov=_(()=>{"use strict";Tv=kr(Fd(),1);OE();lr();h1=128,$E=1024*1024,Uo=new Map,Pv=0});function bt(e){throw new k("INVALID_WORKFLOW",e)}function Ui(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&bt(`${t} 必须是 JSON 对象`),e}function Hc(e,t,r){for(let n of Object.keys(e))t.includes(n)||bt(`${r} 包含不支持的字段:${n}`)}function nr(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&bt(`${t} 必须是非空字符串且不超过 4096 字符`),e}function $v(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&bt(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>nr(i,t));return new Set(n).size!==n.length&&bt(`${t} 不能包含重复值`),n}function jv(e,t){return $v(typeof e=="string"?[e]:e,t)}function Qc(e,t){let r=Ui(e,t);return Hc(r,["id","version"],t),{id:nr(r.id,`${t}.id`),version:nr(r.version,`${t}.version`)}}function DE(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))DE(t);Object.freeze(e)}return e}function BE(e,t){try{let r=typeof e=="boolean"?e:Ui(e,t);typeof r!="boolean"&&r.$async===!0&&bt(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),Hd(r)}catch(r){bt(`${t} 不是受支持的 JSON Schema:${r.message}`)}}function v1(e){let t=Ui(e,"step"),r=nr(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(r)||bt(`不支持的步骤类型:${r}`);let n=r==="ask_user"?["proposalFrom","choices"]:r==="child_workflow"?["workflow"]:r==="await_evidence"?["kind"]:[];Hc(t,[...g1,...n],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&bt("step.retry 必须是 manual、idempotent 或 reconcile");let o={...t.ref===void 0?{}:{ref:nr(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:Qc(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:$v(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:$v(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&BE(t.outputSchema,"outputSchema"),r==="ask_user"?{...o,type:r,proposalFrom:jv(t.proposalFrom,"step.proposalFrom"),choices:jv(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...o,type:r,workflow:Qc(t.workflow,"step.workflow")}:r==="await_evidence"?(o.validator||bt("await_evidence 必须声明验证器"),{...o,type:r,kind:nr(t.kind,"step.kind"),validator:o.validator}):{...o,type:r,ref:nr(t.ref,"step.ref")}}function ln(e){if(jE.has(e))return e;let t=Ui(nt(e),"workflow");Hc(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=nr(t.id,"workflow.id"),n=nr(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&bt("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&bt("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&BE(t.stateSchema,"stateSchema");let i=Ui(t.steps,"workflow.steps");Object.keys(i).length===0&&bt("workflow.steps 必须至少包含一个步骤");let o=Object.fromEntries(Object.entries(i).map(([m,g])=>(nr(m,"step id"),[m,v1(g)])));function a(m,g){Object.hasOwn(o,m)||bt(`${g} 引用了不存在的步骤:${m}`)}let s=jv(t.entry,"workflow.entry");for(let m of s)a(m,"workflow.entry");let c=t.commands===void 0?{}:Ui(t.commands,"workflow.commands"),l={};for(let[m,g]of Object.entries(c)){nr(m,"workflow command name");let v=typeof g=="string"?{stepId:nr(g,`workflow.commands.${m}`)}:Ui(g,`workflow.commands.${m}`);Hc(v,["stepId","validator"],`workflow.commands.${m}`);let w=nr(v.stepId,`workflow.commands.${m}.stepId`);a(w,`workflow.commands.${m}`);let A=o[w];(A.join||!["invoke_skill","call_tool","handoff"].includes(A.type))&&bt(`workflow.commands.${m} 必须指向不带 join 的执行步骤`),Object.defineProperty(l,m,{value:{stepId:w,...v.validator===void 0?{}:{validator:Qc(v.validator,`workflow.commands.${m}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let u=t.transitions===void 0?[]:t.transitions;Array.isArray(u)||bt("workflow.transitions 必须是数组");let f=new Set,d=u.map(m=>{let g=Ui(m,"transition");Hc(g,["from","to","on"],"transition");let v=nr(g.from,"transition.from"),w=nr(g.to,"transition.to"),A=nr(g.on===void 0?"succeeded":g.on,"transition.on");a(v,"transition.from"),a(w,"transition.to");let N=JSON.stringify([v,w,A]);return f.has(N)&&bt(`重复的状态转移:${v} -> ${w} (${A})`),f.add(N),{from:v,to:w,on:A}});for(let[m,g]of Object.entries(o)){if(g.join){let v=new Set(d.filter(w=>w.to===m).map(w=>w.from));for(let w of g.join)a(w,`${m}.join`),v.has(w)||bt(`${m}.join 依赖缺少对应的进入边:${w}`);v.size!==g.join.length&&bt(`${m}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let v of g.proposalFrom)a(v,`${m}.proposalFrom`)}let p=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof p!="number"||!Number.isSafeInteger(p)||p<1)&&bt("workflow.maxTransitions 必须是正安全整数");let h=DE({id:r,version:n,entry:s,steps:o,...t.commands===void 0?{}:{commands:l},transitions:d,maxTransitions:p,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:Qc(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:Qc(t.transitionHandler,"workflow.transitionHandler")}});return jE.add(h),h}var g1,jE,Dv=_(()=>{"use strict";Zr();lr();Ov();g1=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];jE=new WeakSet});function Uc(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!0,enumerable:!0,writable:!0})}function Qd(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value]))}function w1(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 mi(e,t){if(e.status==="cancelled"||e.status==="failed")return;for(;e.ready.length>0;){let o=e.ready.shift(),a=t.steps[o.to],s=o.results;if(a.join?.length){if(o.from===null||!a.join.includes(o.from))throw new k("INVALID_JOIN","join 必须由其声明的父节点触发");Object.hasOwn(e.joins,o.to)||Uc(e.joins,o.to,Object.fromEntries(a.join.map(d=>[d,[]])));let f=e.joins[o.to];if(f[o.from].push(o),a.join.some(d=>f[d].length===0))continue;s=w1(a.join.map(d=>f[d].shift()))}if(e.sequence>=t.maxTransitions){e.ready.unshift(o),e.status="failed",e.reason="TRANSITION_LIMIT: 工作流已达到允许的步骤激活次数";return}let c=++e.sequence,l=`${e.runId}:${c}`,u={input:a.input===void 0?e.input:a.input,outputs:Qd(s),...o.activation===void 0?{}:{activation:o.activation}};if(a.type==="ask_user"){let f=Object.fromEntries(a.proposalFrom.map(p=>{if(!Object.hasOwn(s,p))throw new k("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${p}`);return[p,s[p].value]})),d={input:u.input,outputs:f,...o.activation===void 0?{}:{activation:o.activation}};e.waits.push({id:l,stepId:o.to,sequence:c,status:"pending",proposal:d,proposalHash:$(d),choices:[...a.choices],results:s})}else if(a.type==="await_evidence")e.evidenceWaits??=[],e.evidenceWaits.push({id:l,stepId:o.to,sequence:c,kind:a.kind,status:"pending",results:s});else{let f=a.type==="child_workflow"?`${a.workflow.id}@${a.workflow.version}`:a.ref,d=xN({id:l,runId:e.runId,stepId:o.to,type:a.type,ref:f,input:u,retry:a.retry,requiredCapabilities:a.requiredCapabilities});e.actions.push(d),Uc(e.actionContexts,l,{sequence:c,results:s}),a.type==="child_workflow"&&e.children.push({actionId:l,runId:`child-${$(l)}`,workflow:a.workflow})}}let r=e.actions.some(o=>["pending","running","unknown"].includes(o.status)),n=e.waits.some(o=>o.status==="pending")||(e.evidenceWaits?.some(o=>o.status==="pending")??!1),i=Object.values(e.joins).some(o=>Object.values(o).some(a=>a.length>0));e.status=r?"running":n||i?"waiting":"completed"}function Xa(e,t,r,n,i,o,a,s){let c={sequence:n,value:o},l={...i};Uc(l,r,c),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&Uc(e.outputs,r,c);let u=t.transitions.filter(p=>p.from===r),f=u.filter(p=>p.on===a),d=s??f.map(p=>p.to);if(d.length===0&&a==="failed"){e.status="failed",e.reason=`ACTION_FAILED: ${r}`;return}if(d.length===0&&s===void 0&&u.length>0)throw new k("TRANSITION_UNAVAILABLE",`步骤 ${r} 未声明 ${a} 的后续转换`);for(let p of d){let h=typeof p=="string"?p:p.stepId;if(!f.some(m=>m.to===h))throw new k("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:r,to:h,results:l,...typeof p=="string"?{}:{activation:p.input}})}}var WE=_(()=>{"use strict";To();Zr();lr()});import{randomUUID as Bv}from"node:crypto";import{types as Vv}from"node:util";function LE(e){return Me({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 it(e){return JSON.stringify([e.id,e.version])}function qr(e){if(e===void 0)return;if(!e||typeof e!="object"||Vv.isProxy(e))throw new k("INVALID_JSON","context 必须是普通对象");let t={},r;for(let i of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new k("INVALID_JSON","context 必须使用普通数据属性");i==="signal"?r=o.value:o.value!==void 0&&Object.defineProperty(t,i,{value:o.value,enumerable:!0})}let n=nt(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new k("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function Mv(e,t=new Set){if(e===null||typeof e!="object")return e;if(Vv.isProxy(e))throw new k("INVALID_JSON","请求不能包含代理对象");if(t.size>64)throw new k("INVALID_JSON","请求数据嵌套超过 64 层");if(t.has(e))throw new k("INVALID_JSON","请求包含循环引用");let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw new k("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 o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new k("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(n,i,{enumerable:!0,writable:!0,configurable:!0,value:Mv(o.value,t)})}return t.delete(e),n}function Wv(e){if(e===null||typeof e!="object")return e;if(Vv.isProxy(e))throw new k("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 k("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(t,r,{enumerable:!0,writable:!0,configurable:!0,value:r==="context"?qr(n.value):Mv(n.value)})}return t}function Jo(e){let t=Mv(e),r=nt(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 k("INVALID_VALIDATION","验证器必须返回布尔 accepted 和有效原因");return r}function Lv(e,t){let r=e.supports(Me(t));if(typeof r!="boolean")throw new k("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function Un(e){if(e?.signal?.aborted)throw new k("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function zo(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)&&zo(e[n],t[n]))}function VE(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]}}function Pt(e){let t=new Map,r=new Map;for(let y of e.workflows){let S=ln(y),T=it(S);if(t.has(T))throw new k("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(T,S);let x=ME.get(S);x===void 0&&(x=$(S),ME.set(S,x)),r.set(S,x)}let n=new Map;for(let y of e.validators??[]){let S=it(y);if(n.has(S))throw new k("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(S,y)}let i=new Map;for(let y of e.stateValidators??[]){let S=it(y);if(i.has(S))throw new k("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(S,y)}let o=new Map;function a(y){let S=o.get(y);return S||(S=Hd(y),o.set(y,S)),S}let s=new Map,c=new Map;for(let y of e.transitionHandlers??[]){let S=it(y);if(c.has(S))throw new k("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");c.set(S,y)}let l=new Map;for(let y of e.evidenceValidators??[]){let S=it(y);if(l.has(S))throw new k("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");l.set(S,y)}let u=new Map;for(let y of e.commandValidators??[]){let S=it(y);if(u.has(S))throw new k("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");u.set(S,y)}for(let y of e.executors??[]){if(s.has(y.id))throw new k("DUPLICATE_EXECUTOR","不能重复注册同一执行器");s.set(y.id,y)}function f(y){let S=t.get(it(y));if(!S)throw new k("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(y.hash!==void 0&&y.hash!==r.get(S))throw new k("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return S}function d(y){if(y.transitionHandler&&!c.has(it(y.transitionHandler)))throw new k("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function p(y){if(y.stateValidator&&!i.has(it(y.stateValidator)))throw new k("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function h(y){for(let S of Object.values(y.steps))if(S.type==="await_evidence"&&!l.has(it(S.validator)))throw new k("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function m(y){for(let S of Object.values(y.commands??{}))if(S.validator&&!u.has(it(S.validator)))throw new k("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(y,S,T){if(y.stateSchema!==void 0){let x=a(y.stateSchema);if(!x.validate(S))throw new k(T,x.errorsText())}if(y.stateValidator){let x=i.get(it(y.stateValidator));if(!x)throw new k("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let P=Jo(x.validate({state:nt(S)}));if(!P.accepted)throw new Error(P.reason??"业务状态未通过验证")}catch(P){throw new k(T,P instanceof Error?P.message:String(P))}}}function v(y,S,T,x){if(!S.transitionHandler)return;let P=c.get(it(S.transitionHandler));if(!P)throw new k("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let Q=nt(P.apply({run:Me(y),event:Me(T)})),J=nt(Q.state);g(S,J,"TRANSITION_STATE_INVALID");let K=new Set(S.transitions.filter(ie=>ie.from===T.stepId&&ie.on===x).map(ie=>ie.to));if(!Array.isArray(Q.next))throw new k("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let U=[],G=new Set;for(let ie of Q.next){let W;if(typeof ie=="string")W=ie;else if(ie!==null&&typeof ie=="object"&&!Array.isArray(ie)){let Ae=Object.keys(ie);if(Ae.length!==2||!Ae.includes("stepId")||!Ae.includes("input")||typeof ie.stepId!="string")throw new k("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");W={stepId:ie.stepId,input:nt(ie.input)}}else throw new k("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let me=typeof W=="string"?W:W.stepId,te=$(W);if(!K.has(me)||G.has(te))throw new k("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");G.add(te),U.push(W)}return y.state=J,U}function w(y,S=$){if(t.size>0)for(let[T,x]of Object.entries(y.definitionHashes)){let[P,Q]=JSON.parse(T),J=f({id:P,version:Q,hash:x});if(d(J),p(J),h(J),m(J),P===y.workflow.id&&Q===y.workflow.version){let K=new Map(y.actions.map(U=>[U.id,U]));for(let U of y.commands??[]){let G=K.get(U.actionId),ie=Object.hasOwn(J.commands??{},U.name),W=G&&!ie&&!Object.hasOwn(J.steps,G.stepId)&&["succeeded","failed","cancelled"].includes(G.status);if(!G||!W&&(!ie||J.commands?.[U.name].stepId!==G.stepId)||G.input===null||typeof G.input!="object"||!Object.hasOwn(G.input,"activation")||S(G.input.activation)!==U.inputHash)throw new k("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(J.stateSchema!==void 0&&J.initialState===void 0&&y.initialStateHash===void 0)throw new k("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(J,y.state,"RUN_STATE_INVALID");for(let U of y.ready){let G=()=>{throw new k("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(J.steps,U.to)||G(),U.from===null){(!J.entry.includes(U.to)||Object.keys(U.results).length>0||y.sequence!==0&&!(y.status==="failed"&&y.reason?.startsWith("TRANSITION_LIMIT:")))&&G();continue}let ie=U.results[U.from];ie||G();let W=y.actions.find(yr=>yr.stepId===U.from&&y.actionContexts[yr.id].sequence===ie.sequence),me=y.waits.find(yr=>yr.stepId===U.from&&yr.sequence===ie.sequence),te=y.evidenceWaits?.find(yr=>yr.stepId===U.from&&yr.sequence===ie.sequence),Ae=W?.outcome?W.outcome.status==="failed"?"failed":W.outcome.event??"succeeded":me?.decision?.choice??(te?.invalidation?"invalidated":te?.receipt?"succeeded":void 0),at=W?y.actionContexts[W.id].results:me?.results??te?.results,ac=W?.outcome?W.outcome.output:me?.decision?{choice:me.decision.choice,proposal:me.proposal}:te?.invalidation?{ref:te.invalidation.ref,contentHash:te.invalidation.contentHash,reason:te.invalidation.reason}:te?.receipt?{ref:te.receipt.ref,contentHash:te.receipt.contentHash}:void 0;(!Ae||!at||W&&!["succeeded","failed"].includes(W.status)||me&&me.status!=="resolved"||te&&!["resolved","invalidated"].includes(te.status)||ac===void 0||S(U.results)!==S({...at,[U.from]:{sequence:ie.sequence,value:ac}})||!J.transitions.some(yr=>yr.from===U.from&&yr.to===U.to&&yr.on===Ae))&&G()}for(let U of y.evidenceWaits??[]){let G=J.steps[U.stepId];if(!(!G&&U.status!=="pending")&&(!G||G.type!=="await_evidence"||G.kind!==U.kind))throw new k("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function A(y){let S=await e.store.read(y);if(!S)throw new k("RUN_NOT_FOUND",`找不到工作流实例:${y}`);let T=MN(S,y);return w(T),Po(T)}async function N(y,S,T){for(let x=0;x<32;x+=1){Un(y.context);let P=x===0&&T?T:await A(y.runId),Q=f(P.workflow);if(y.expectedRevision!==void 0&&y.expectedRevision!==P.revision)throw new k("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let J=VE(P);if(await S(J,Q),tn(J),zo(J,P))return P;if(J.revision=P.revision+1,id(J,P),w(J),Po(J),Un(y.context),await e.store.compareAndSwap(y.runId,P.revision,J))return J}throw new k("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function b(y,S){let T=y.actions.find(x=>x.id===S);if(!T)throw new k("ACTION_NOT_FOUND","Run 不包含此 Action");return T}function E(y){if(y.status==="cancelled")throw new k("RUN_CANCELLED","Run 已取消,不能继续推进")}function V(y,S={}){let T=it(y);if(Object.hasOwn(S,T))return S;S[T]=r.get(y);for(let x of Object.values(y.steps))x.type==="child_workflow"&&V(f(x.workflow),S);return S}async function j(y,S){if(Un(y.context),S.length>32)throw new k("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let T=f(y.workflow);d(T),p(T),h(T),m(T);let x=Object.hasOwn(y,"initialState");if(x&&T.initialState!==void 0)throw new k("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let P=x?nt(y.initialState):T.initialState;if(T.stateSchema!==void 0&&P===void 0)throw new k("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");P!==void 0&&g(T,P,"INITIAL_STATE_INVALID");let Q=P===void 0?void 0:$(P),J=y.runId??Bv(),K=nt(y.input),U={id:T.id,version:T.version,hash:r.get(T)},G=await e.store.read(J);if(G){if($(G.workflow)!==$(U)||$(G.input)!==$(K)||$(G.lineage)!==$(S)||(G.initialStateHash??(T.initialState===void 0?void 0:$(T.initialState)))!==Q)throw new k("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return A(J)}let ie={protocolVersion:1,schemaVersion:1,runId:J,revision:1,workflow:U,definitionHashes:V(T),input:K,...P===void 0?{}:{state:nt(P),initialStateHash:Q},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:T.entry.map(W=>({from:null,to:W,results:{}})),joins:{},outputs:{},children:[],lineage:S};return mi(ie,T),Po(ie),Un(y.context),id(ie),w(ie),await e.store.compareAndSwap(J,null,ie)?Me(ie):j({...y,runId:J},S)}async function z(y){return j(y,[])}async function X(y){let S=nt(y.input),T=$(S);if(!y.commandId.trim()||y.commandId.length>4096||!y.name.trim()||y.name.length>4096)throw new k("INVALID_COMMAND","命令标识和名称不能为空");for(let x=0;x<32;x+=1){Un(y.context);let P=await A(y.runId),Q=P.commands?.find(te=>te.id===y.commandId);if(Q){if(Q.name!==y.name||Q.inputHash!==T)throw new k("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return P}if(y.expectedRevision!==P.revision)throw new k("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let J=f(P.workflow),K=Object.hasOwn(J.commands??{},y.name)?J.commands?.[y.name]:void 0;if(!K)throw new k("COMMAND_NOT_FOUND","工作流未声明此命令");let U=K.stepId;if(P.status==="cancelled")throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.actions.some(te=>["running","unknown"].includes(te.status)))throw new k("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let G=!1,ie=!1;if(K.validator){let te=u.get(it(K.validator));if(!te)throw new k("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let Ae;try{Ae=Jo(await te.validate({run:Me(P),name:y.name,input:Me(S),context:qr(y.context)}))}catch(at){throw new k("COMMAND_VALIDATION_ERROR",at instanceof Error?at.message:String(at))}if(G=Ae.accepted&&Ae.allowCompleted===!0,ie=Ae.accepted&&Ae.allowFailed===!0,P.status==="failed"&&!ie)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="completed"&&!G)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!Ae.accepted)throw new k("COMMAND_REJECTED",Ae.reason??"命令未通过当前工作流状态验证")}if(P.status==="completed"&&!G)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="failed"&&!ie)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");let W=Me(P);P.status==="failed"&&(W.status="running",delete W.reason),W.actions=W.actions.map(te=>te.status==="pending"?ed(te,`命令 ${y.name} 已取代待执行 Action`):te);for(let te of W.waits)te.status==="pending"&&(te.status="cancelled");for(let te of W.evidenceWaits??[])te.status==="pending"&&(te.status="cancelled");W.ready=[{from:null,to:U,results:{},activation:S}],W.joins={},mi(W,J);let me=W.actions.at(-1);if(!me||me.stepId!==U||me.status!=="pending")throw new k("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(W.commands=[...W.commands??[],{id:y.commandId,name:y.name,inputHash:T,actionId:me.id}],W.revision=P.revision+1,id(W,P),w(W),Po(W),Un(y.context),await e.store.compareAndSwap(y.runId,P.revision,W))return Me(W)}throw new k("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function de(y){for(let S of y.children)await e.store.read(S.runId)&&await I({runId:S.runId,reason:y.reason??"父工作流已取消"})}function se(y,S,T){let x=f(y.workflow),P=Object.hasOwn(x.steps,T.stepId)?x.steps[T.stepId]:void 0;if(!P||P.type!=="child_workflow"||it(P.workflow)!==it(S.workflow)||T.type!==P.type||T.ref!==`${P.workflow.id}@${P.workflow.version}`||T.attempt!==1||T.retry!==P.retry||!zo(T.requiredCapabilities,P.requiredCapabilities??[])||T.claim&&(T.claim.executorId!=="comet-child-workflow"||T.claim.sessionId!==void 0||![S.runId,`portable-${$(S.runId)}`].includes(T.claim.token)))throw new k("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let Q=T.input;if(!Q||typeof Q!="object"||Array.isArray(Q)||!zo(Q,{input:P.input===void 0?y.input:P.input,outputs:Qd(y.actionContexts[T.id].results),...Object.hasOwn(Q,"activation")?{activation:Q.activation}:{}}))throw new k("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let J=f({...S.workflow,hash:y.definitionHashes[it(S.workflow)]});if(Object.entries(V(J)).some(([K,U])=>y.definitionHashes[K]!==U))throw new k("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return J}function De(y,S,T,x,P){let Q=x.initialState===void 0?void 0:$(x.initialState);if(P.runId!==S.runId||it(P.workflow)!==it(S.workflow)||P.workflow.hash!==y.definitionHashes[it(S.workflow)]||!zo(P.definitionHashes,V(x))||!zo(P.input,T.input)||!zo(P.lineage,[...y.lineage,y.runId])||(P.initialStateHash??Q)!==Q)throw new k("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function Z(y){let S=await N(y,(T,x)=>mi(T,x));if(S.status==="cancelled")return await de(S),S;if(S.status==="failed"||S.children.length===0)return S;for(let T of S.children){let x=b(S,T.actionId);if(!["pending","running","unknown"].includes(x.status))continue;let P=se(S,T,x);x.status==="pending"&&(S=await Xe({runId:S.runId,actionId:x.id,attempt:x.attempt,inputHash:x.inputHash,executorId:"comet-child-workflow",claimToken:T.runId,capabilities:["child-workflow"],context:qr(y.context)},!0),x=b(S,T.actionId));let Q=x.status==="unknown"?await A(T.runId):await j({runId:T.runId,workflow:T.workflow,input:x.input,context:qr(y.context)},[...S.lineage,S.runId]);De(S,T,x,P,Q);let J=await A(S.runId);if(J.status==="cancelled")return await de(J),J;let K=await Z({runId:T.runId,context:y.context});De(S,T,x,P,K),["completed","failed","cancelled"].includes(K.status)&&(S=await B({runId:S.runId,context:qr(y.context),outcome:{actionId:x.id,attempt:x.attempt,inputHash:x.inputHash,claimToken:x.claim.token,outcomeId:`${T.runId}:${K.revision}`,status:K.status==="completed"?"succeeded":"failed",output:Qd(K.outputs)}},!0))}return A(S.runId)}async function Xe(y,S=!1,T){let x=y.claimToken??(y.context?.requestId?$({runId:y.runId,actionId:y.actionId,attempt:y.attempt,executorId:y.executorId,requestId:y.context.requestId}):Bv());return N(y,async P=>{if(E(P),P.status==="failed")throw new k("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let Q=b(P,y.actionId);if(Q.type==="child_workflow"&&!S)throw new k("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let J=Oh(Q,{executionOrigin:{workflow:{...P.workflow}},attempt:y.attempt,inputHash:y.inputHash,executorId:y.executorId,token:x,...y.sessionId===void 0?{}:{sessionId:y.sessionId}});if(!Q.claim){let K=new Set(y.capabilities??[]);if(Q.requiredCapabilities.some(G=>!K.has(G)))throw new k("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let U=s.get(y.executorId);if(U&&Lv(U,Q)){if(Q.requiredCapabilities.some(G=>!U.capabilities.includes(G)))throw new k("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await U.preflight?.(Me(Q),qr(y.context),U.includeRun===!1?void 0:Me(P)),Un(y.context)}}P.actions[P.actions.indexOf(Q)]=J},T)}async function Ht(y){return Xe(y)}async function B(y,S=!1,T){let x,P;try{x=td(y.outcome)}catch(K){P=K}y={...y,outcome:x};let Q,J=await N(y,async(K,U)=>{if(Q=void 0,E(K),!x)throw P;let G=b(K,y.outcome.actionId);if(G.type==="child_workflow"&&!S)throw new k("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let ie=Zu(G,y.outcome);if(ie.duplicate)return;let W=ie.action.outcome,me=K.actions.indexOf(G);try{if(e.validateOutcome){let Ae=Jo(await e.validateOutcome({run:Me(K),action:Me(G),outcome:Me(W),context:qr(y.context)}));Ae.accepted||(Q={code:"OUTCOME_REJECTED",reason:Ae.reason??"应用结果契约拒绝此结果"})}let te=U.steps[G.stepId];if(!Q&&W.status==="succeeded"&&te.outputSchema!==void 0){let Ae=a(te.outputSchema);Ae.validate(W.output)||(Q={code:"OUTPUT_INVALID",reason:Ae.errorsText()})}if(!Q&&te.validator){let Ae=n.get(it(te.validator));if(!Ae)throw new k("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let at=Jo(await Ae.validate({run:Me(K),action:Me(G),outcome:Me(W),context:qr(y.context)}));at.accepted||(Q={code:"OUTCOME_REJECTED",reason:at.reason?.trim()?at.reason:"结果未满足业务验收条件"})}if(!Q){let Ae=VE(K);Ae.actions[me]=ie.action;let at=Ae.actionContexts[G.id],ac=W.status==="failed"?"failed":W.event??"succeeded",yr=v(Ae,U,{kind:"action-outcome",stepId:G.stepId,outcome:W},ac);Xa(Ae,U,G.stepId,at.sequence,at.results,W.output,ac,yr),mi(Ae,U),Object.assign(K,Ae)}}catch(te){Q={code:"OUTCOME_PROCESSING_ERROR",reason:te instanceof Error&&te.message.trim()?te.message:"结果处理失败,请检查验证器或工作流定义"}}Q&&(K.actions[me]={...G,receipts:ie.action.receipts,rejectedOutcomes:[...G.rejectedOutcomes??[],{outcome:ie.action.outcome,...Q}]})},T);if(Q)throw new k(Q.code,Q.reason);return J}async function ee(y){return B(y)}async function pe(y){if(y.reason!==void 0&&!Bh(y.reason))throw new k("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return N(y,(S,T)=>{E(S);let x=S.waits.find(Q=>Q.id===y.waitId);if(!x)throw new k("WAIT_NOT_FOUND","Run 不包含此等待项");if(x.decision){if(x.decision.id!==y.decisionId||x.decision.choice!==y.choice||x.decision.proposalHash!==y.proposalHash||x.decision.reason!==y.reason)throw new k("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(x.status!=="pending"||x.proposalHash!==y.proposalHash)throw new k("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!y.decisionId.trim()||!x.choices.includes(y.choice))throw new k("INVALID_DECISION","决定标识或选择不符合当前等待项");x.status="resolved",x.decision={id:y.decisionId,choice:y.choice,proposalHash:y.proposalHash,...y.reason===void 0?{}:{reason:y.reason}};let P=v(S,T,{kind:"wait-resolved",stepId:x.stepId,choice:y.choice,proposalHash:y.proposalHash,decisionId:y.decisionId},y.choice);Xa(S,T,x.stepId,x.sequence,x.results,{choice:y.choice,proposal:x.proposal},y.choice,P),mi(S,T)})}async function kt(y){return N(y,async(S,T)=>{if(E(S),S.status==="failed")throw new k("RUN_FAILED","Run 已因失败停止,不能提交证据");let x=S.evidenceWaits?.find(U=>U.id===y.evidenceId);if(!x)throw new k("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(x.status!=="pending")throw new k("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(x.kind!==y.kind)throw new k("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 k("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let P=T.steps[x.stepId];if(!P||P.type!=="await_evidence"||P.kind!==y.kind)throw new k("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let Q=l.get(it(P.validator));if(!Q)throw new k("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let J=Jo(await Q.validate({run:Me(S),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:qr(y.context)}));if(!J.accepted||J.actualHash!==y.contentHash)throw new k("EVIDENCE_REJECTED",J.reason??"证据未通过验证或内容已改变");x.status="resolved",x.receipt={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId};let K=v(S,T,{kind:"evidence-recorded",stepId:x.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId},"succeeded");Xa(S,T,x.stepId,x.sequence,x.results,{ref:y.ref,contentHash:y.contentHash},"succeeded",K),mi(S,T)})}async function C(y){return N(y,async(S,T)=>{if(E(S),S.status==="failed")throw new k("RUN_FAILED","Run 已因失败停止,不能使证据失效");let x=S.evidenceWaits?.find(G=>G.id===y.evidenceId);if(!x)throw new k("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(x.status!=="pending")throw new k("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(x.kind!==y.kind)throw new k("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 k("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let P=T.steps[x.stepId];if(!P||P.type!=="await_evidence"||P.kind!==y.kind)throw new k("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!T.transitions.some(G=>G.from===x.stepId&&G.on==="invalidated"))throw new k("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let Q=l.get(it(P.validator));if(!Q)throw new k("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let J=Jo(await Q.validate({run:Me(S),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:qr(y.context)}));if(J.accepted&&J.actualHash===y.contentHash)throw new k("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let K=(J.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);x.status="invalidated",x.invalidation={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:K};let U=v(S,T,{kind:"evidence-invalidated",stepId:x.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:K},"invalidated");Xa(S,T,x.stepId,x.sequence,x.results,{ref:y.ref,contentHash:y.contentHash,reason:K},"invalidated",U),mi(S,T)})}async function R(y){return N(y,S=>{E(S);let T=S.waits.find(x=>x.id===y.waitId);if(!T||T.status!=="pending"||T.proposalHash!==y.proposalHash)throw new k("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");T.proposal=nt(y.proposal),T.proposalHash=$(T.proposal)})}async function I(y){let S=await N(y,T=>{if(T.status==="completed"){if(y.stoppedActions?.length)throw new k("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let x=T.status==="cancelled";if(x||(T.actions=T.actions.map(P=>ed(P,y.reason))),y.stoppedActions!==void 0){if(!Array.isArray(y.stoppedActions))throw new k("INVALID_ACTION","stoppedActions 必须是停止确认数组");let P=new Set;for(let Q of y.stoppedActions){if(!Q||typeof Q!="object"||P.has(Q.actionId))throw new k("INVALID_ACTION","停止确认重复或无效");P.add(Q.actionId);let J=b(T,Q.actionId);T.actions[T.actions.indexOf(J)]=$h(J,Q)}}if(!x){for(let P of T.waits)P.status==="pending"&&(P.status="cancelled");for(let P of T.evidenceWaits??[])P.status==="pending"&&(P.status="cancelled");T.ready=[],T.status="cancelled",T.reason=y.reason}});return S.status==="cancelled"&&await de(S),S}async function D(y){return N(y,S=>{if(!Array.isArray(y.stoppedActions)||!y.stoppedActions.length)throw new k("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let T=new Set;for(let x of y.stoppedActions){if(!x||typeof x!="object"||T.has(x.actionId))throw new k("INVALID_ACTION","停止确认重复或无效");T.add(x.actionId);let P=b(S,x.actionId);S.actions[S.actions.indexOf(P)]=jh(P,x)}})}async function L(y){return N(y,S=>{E(S);let T=b(S,y.actionId);if(T.attempt!==y.attempt)throw new k("STALE_ACTION","Action 执行尝试已经改变");S.actions[S.actions.indexOf(T)]=TN(T,y.reason)})}async function q(y){return N(y,async(S,T)=>{E(S);let x=b(S,y.actionId);if(x.attempt!==y.attempt)throw new k("STALE_ACTION","Action 执行尝试已经改变");if(x.type==="child_workflow")throw new k("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(x.status==="succeeded"&&e.validateRecovery){if(y.expectedRevision===void 0)throw new k("REVISION_CONFLICT","恢复已提交结果必须绑定当前 Run 版本");if(y.reconciliation!==void 0)throw new k("OUTCOME_ALREADY_RECORDED","已提交结果不能声明未执行;请使用应用的语义恢复");if(typeof y.proposalHash!="string"||!y.proposalHash.trim())throw new k("INVALID_REQUEST","恢复已提交结果必须绑定当前应用决定");if(S.actions.some(U=>["running","unknown"].includes(U.status)))throw new k("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(S.status!=="completed"||S.ready.length>0||S.actions.some(U=>U.status==="pending")||S.waits.some(U=>U.status==="pending")||S.evidenceWaits?.some(U=>U.status==="pending")||Object.values(S.joins).some(U=>Object.values(U).some(G=>G.length>0))||!x.outcome||x.outcome.status!=="succeeded")throw new k("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let P=Jo(await e.validateRecovery({run:Me(S),action:Me(x),outcome:Me(x.outcome),context:qr(y.context),proposalHash:y.proposalHash}));if(!P.accepted)throw new k("ACTION_TERMINAL",P.reason??"应用拒绝恢复此结果");let Q=x.outcome.event??"succeeded",J=v(S,T,{kind:"action-outcome",stepId:x.stepId,outcome:x.outcome},Q);if(J?.length===0||J===void 0&&!T.transitions.some(U=>U.from===x.stepId&&U.on===Q))throw new k("ACTION_TERMINAL","应用未声明可恢复的后续工作");let K=S.actionContexts[x.id];Xa(S,T,x.stepId,K.sequence,K.results,x.outcome.output,Q,J),mi(S,T);return}if(x.status==="failed"){let P=S.actionContexts[x.id].sequence,Q=K=>Object.hasOwn(K,x.stepId)&&K[x.stepId].sequence===P;if(Object.values(S.actionContexts).some(K=>Q(K.results))||S.waits.some(K=>Q(K.results))||S.evidenceWaits?.some(K=>Q(K.results))||S.ready.some(K=>Q(K.results))||Object.values(S.joins).some(K=>Object.values(K).some(U=>U.some(G=>Q(G.results)))))throw new k("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}S.actions[S.actions.indexOf(x)]=ON(x,y.reconciliation),S.status="running",delete S.reason})}async function H(y,S){let T=s.get(y.executorId);if(!T)throw new k("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let x=S??await A(y.runId),P=b(x,y.actionId);if(P.status!=="pending")throw new k("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!Lv(T,P))throw new k("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");Un(y.context);let Q=await Xe({...y,attempt:P.attempt,inputHash:P.inputHash,claimToken:Bv(),capabilities:T.capabilities},!1,x),J=b(Q,y.actionId),K;try{Un(y.context),K=await T.execute(Me(J),qr(y.context),T.includeRun===!1?void 0:Me(Q))}catch(G){let ie=await A(y.runId),W=b(ie,J.id);throw ie.status!=="cancelled"&&W.status==="running"&&W.attempt===J.attempt&&await L({runId:y.runId,actionId:J.id,attempt:J.attempt,reason:G instanceof Error?G.message:String(G)}),new k("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let U=`${J.id}:${J.attempt}:executor-result`;try{return await B({runId:y.runId,context:qr(y.context),outcome:{...K,actionId:J.id,attempt:J.attempt,inputHash:J.inputHash,claimToken:J.claim.token,outcomeId:U}},!1,Q)}catch(G){let ie=await A(y.runId),W=b(ie,J.id);if(W.receipts.some(me=>me.outcomeId===U)){if(W.rejectedOutcomes?.some(me=>me.outcome.outcomeId===U))throw G;if(W.outcome?.outcomeId===U)return ie}throw ie.status!=="cancelled"&&W.status==="running"&&W.attempt===J.attempt&&await L({runId:y.runId,actionId:J.id,attempt:J.attempt,reason:G instanceof Error?G.message.slice(0,4096):"执行结果无法提交"}),new k("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function ne(y){let S=y.maxActions??100;if(!Number.isSafeInteger(S)||S<1)throw new k("INVALID_REQUEST","maxActions 必须是正安全整数");let T=s.get(y.executorId);if(!T)throw new k("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let x=0,P=await A(y.runId),Q=K=>({reason:K,run:P,actionsExecuted:x}),J=K=>{if(P.status==="completed"||P.status==="failed"||P.status==="cancelled")return P.status;if(P.actions.some(U=>U.status==="unknown"&&(!K||U.type!=="child_workflow")))return"execution-unknown";if(P.actions.some(U=>U.status==="running"&&(!K||U.type!=="child_workflow")))return"action-in-flight";if(P.waits.some(U=>U.status==="pending"))return"approval-required";if(P.evidenceWaits?.some(U=>U.status==="pending"))return"evidence-required"};for(;;){Un(y.context);let K=J(!0);if(K)return Q(K);(P.ready.length||P.children.length)&&(P=await Z({runId:y.runId,context:y.context}));let U=J(!1);if(U)return Q(U);let G=P.actions.find(ie=>ie.status==="pending");if(!G)return Q("idle");if(x>=S)return Q("action-limit");if(!Lv(T,G)||G.requiredCapabilities.some(ie=>!T.capabilities.includes(ie)))return Q("executor-required");x++;try{P=await H({...y,actionId:G.id},P)}catch(ie){if(!(ie instanceof k)||ie.code!=="EXECUTION_UNKNOWN"||(P=await A(y.runId),!P.actions.some(W=>W.status==="unknown")))throw ie;return Q("execution-unknown")}}}async function Y(y){let S=await Oo(e.store,y);return w(S.run,Nn),S}async function ue(y){return Lh(await Y(y.runId),y)}function le(y){return async(...S)=>{let T=S.map(x=>Wv(x));return Me(await y(...T))}}return{start:le(z),dispatchCommand:le(X),inspect:le(A),inspectProjection:Y,query:le(ue),inspectCurrent:async y=>await ue({runId:y,view:"current"}),executeCurrent:async y=>LE(await H(Wv(y))),runUntilBlockedCurrent:async y=>{let S=await ne(Wv(y));return{...S,run:LE(S.run)}},next:le(Z),claim:le(Ht),recordOutcome:le(ee),resolveWait:le(pe),recordEvidence:le(kt),invalidateEvidence:le(C),reviseWait:le(R),cancel:le(I),acknowledgeStopped:le(D),markUnknown:le(L),retry:le(q),execute:le(y=>H(y)),runUntilBlocked:le(ne)}}var ME,qE=_(()=>{"use strict";Vh();xo();To();Zr();lr();Ov();mc();Dv();WE();ME=new WeakMap});var FE=_(()=>{"use strict";Zr();lr()});import{createRequire as y1}from"node:module";function Jd(e,t){if(!Ud){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{Ud=k1("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new Ud(e):new Ud(e,t)}var k1,Ud,qv=_(()=>{"use strict";k1=y1(import.meta.url??__filename)});import{AsyncLocalStorage as A1}from"node:async_hooks";function QE(e){return Math.max(0,Math.min(e,(HE.getStore()?.deadline??1/0)-performance.now()))}function UE(){let e=HE.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new Fv}var HE,Fv,JE=_(()=>{"use strict";HE=new A1,Fv=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}}});import{randomUUID as b1}from"node:crypto";import{promises as Ji}from"node:fs";import Jc from"node:path";import{performance as zE}from"node:perf_hooks";async function KE(e){let t,r;try{let n=await Ji.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 Ji.readFile(e,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{let n=JSON.parse(t),i=n.nonce??n.id,o=typeof n.createdAt=="number"?n.createdAt:Date.parse(n.createdAt);if(typeof i=="string"&&i&&Number.isFinite(o))return{owner:{nonce:i,createdAt:o,...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 N1(e){let t=e+".sqlite";try{let n=await Ji.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=Jd(Jc.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 GE(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function R1(e,t={}){e=Jc.resolve(e),await Ji.mkdir(Jc.dirname(e),{recursive:!0});let r=await Ji.lstat(Jc.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+Jc.dirname(e));let n=zE.now()+QE(t.timeoutMs??3e4),i;for(;UE(),i=await N1(e),!i;){if(zE.now()>=n)throw new Error("Timed out waiting for file lock: "+e);await new Promise(s=>setTimeout(s,t.retryMs??20))}let o={protocolVersion:2,nonce:b1(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let s=await KE(e);if(s?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
|
|
12
|
+
Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));s&&await Ji.unlink(e),await Ji.writeFile(e,JSON.stringify(o),{mode:384,flag:"wx"})}catch(s){throw GE(i),s}let a=!1;return{owner:o,async release(){if(a)return!0;a=!0;let s=!0;try{let c=await KE(e);c?.token===o.nonce?c.owner?.createdAt===o.createdAt&&c.owner.operation===o.operation?await Ji.unlink(e):(s=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
|
|
13
|
+
`)):c&&(s=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
|
|
14
|
+
`))}finally{GE(i)}return s}}}async function YE(e,t,r={}){let n=await R1(e,r),i;try{i=await t()}catch(o){try{await n.release()}catch(a){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(a)+`
|
|
15
|
+
`)}throw o}return await n.release(),i}var XE=_(()=>{"use strict";qv();JE()});import{promises as Qv}from"node:fs";async function Uv(e,t){let r;for(let n=0;n<=Hv.length;n+=1)try{return await e()}catch(i){r=i;let o=i.code;if(n===Hv.length||!S1.has(o??""))throw i;await new Promise(a=>setTimeout(a,Hv[n]))}throw r}async function Ko(e,t){await Uv(()=>Qv.rename(e,t),`rename ${t}`)}async function zc(e){await Uv(()=>Qv.unlink(e),`unlink ${e}`)}async function Za(e,t){await Uv(()=>Qv.link(e,t),`link ${t}`)}var S1,Hv,zd=_(()=>{"use strict";S1=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Hv=[50,100,200]});import{randomUUID as ZE}from"crypto";import{constants as E1,promises as ot}from"fs";import st from"path";async function Jv(e,t){try{return await Za(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await ot.copyFile(e,t,E1.COPYFILE_EXCL),{linked:!1}}function Yo(e,t){let r=st.relative(e,t);return r===""||!st.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${st.sep}`)}function Kd(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function C1(e,t){return ft(e,Kd(t))}function Go(e,t){return ft(Kd(e),Kd(t))}function eC(e,t){return Go(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Gd(e){let t=await ot.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 ot.realpath(e),...Kd(t)}}async function ir(e){for(let t of e){let r=await ot.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!C1(t,r)||await ot.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function _1(e,t,r){let[n,i]=await Promise.all([ot.lstat(e),ot.realpath(e),ir(r)]);if(!n.isFile()||n.isSymbolicLink()||!Go(n,t)||!Yo(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function tC(e,t){let r=await zv(e,t);if(r)return r;let n=st.resolve(e),i=st.resolve(t);if(!Yo(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let o=[await Gd(n)],a=st.relative(n,i).split(st.sep).filter(Boolean),s=n;for(let c of a){await ir(o),s=st.join(s,c);try{await ot.mkdir(s)}catch(u){if(u.code!=="EEXIST")throw u}let l=await Gd(s);if(!Yo(o[0].realPath,l.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${s}`);o.push(l)}return await ir(o),o}async function zv(e,t){let r=st.resolve(e),n=st.resolve(t);if(!Yo(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await Gd(r)],o=st.relative(r,n).split(st.sep).filter(Boolean),a=r;for(let s of o){a=st.join(a,s);try{let c=await Gd(a);if(!Yo(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${a}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await ir(i),i}async function Kv(e){let t;try{t=await ot.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 I1(e,t,r){let n=st.dirname(e),i=await tC(r.containedRoot,n),o=st.join(n,`.${st.basename(e)}.${ZE()}.tmp`),a,s,c;try{await r.beforeTemporaryOpen?.(),a=await ot.open(o,"wx"),s=await a.stat();let[l,u]=await Promise.all([ot.lstat(o),ot.realpath(o)]);if(await ir(i),!l.isFile()||l.isSymbolicLink()||!Go(s,l)||!Yo(i[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await a.writeFile(t,"utf8"):await a.writeFile(t),await a.sync(),c=await a.stat(),!Go(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await a.close(),a=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await _1(o,c,i),await r.beforeCommit?.(),await ir(i);let f=await ot.lstat(o);if(!f.isFile()||f.isSymbolicLink()||!c||!eC(f,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(r.requireAtomicPublication?await Za(o,e):await Jv(o,e),await ot.unlink(o)):await Ko(o,e),await Kv(n)}catch(l){await a?.close();try{await ir(i),await ot.rm(o,{force:!0})}catch{}throw l}}async function Lt(e,t,r){await I1(e,t,r)}async function rC(e,t,r){let n=await zv(r.containedRoot,st.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await tC(r.containedRoot,st.dirname(t)),o=await ot.lstat(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("Contained link source must be a regular file");let a=st.join(st.dirname(t),`.${st.basename(t)}.${ZE()}.tmp`);try{await ir(n),await ir(i),await Za(e,a),await r.beforeCommit?.(),await ir(n),await ir(i);let s=await ot.lstat(a),c=await ot.lstat(e);if(!s.isFile()||s.isSymbolicLink()||!c.isFile()||c.isSymbolicLink()||!Go(o,c)||!Go(c,s)||o.size!==c.size||o.mtimeMs!==c.mtimeMs)throw new Error("Contained link source changed before publication");let l=await ot.lstat(t).catch(u=>{if(u.code==="ENOENT")return null;throw u});l?.isFile()&&!l.isSymbolicLink()&&Go(c,l)?await zc(a):await Ko(a,t),await Kv(st.dirname(t)),await ir(n),await ir(i)}catch(s){try{await ir(i),await ot.unlink(a)}catch{}throw s}}async function Xo(e,t){let r=st.dirname(e),n=await zv(t.containedRoot,r);if(!n)return!1;let i,o;try{i=await ot.lstat(e),o=await ot.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Yo(n[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await ir(n);let[a,s]=await Promise.all([ot.lstat(e),ot.realpath(e)]);if(!a.isFile()||a.isSymbolicLink()||!eC(i,a)||s!==o)throw new Error("Contained file removal target changed before removal");return await zc(e),await ir(n),await Kv(r),!0}var Jn=_(()=>{"use strict";zd();$a()});var Oe=O(Kt=>{"use strict";var Gv=Symbol.for("yaml.alias"),nC=Symbol.for("yaml.document"),Yd=Symbol.for("yaml.map"),iC=Symbol.for("yaml.pair"),Yv=Symbol.for("yaml.scalar"),Xd=Symbol.for("yaml.seq"),hi=Symbol.for("yaml.node.type"),x1=e=>!!e&&typeof e=="object"&&e[hi]===Gv,P1=e=>!!e&&typeof e=="object"&&e[hi]===nC,T1=e=>!!e&&typeof e=="object"&&e[hi]===Yd,O1=e=>!!e&&typeof e=="object"&&e[hi]===iC,oC=e=>!!e&&typeof e=="object"&&e[hi]===Yv,$1=e=>!!e&&typeof e=="object"&&e[hi]===Xd;function aC(e){if(e&&typeof e=="object")switch(e[hi]){case Yd:case Xd:return!0}return!1}function j1(e){if(e&&typeof e=="object")switch(e[hi]){case Gv:case Yd:case Yv:case Xd:return!0}return!1}var D1=e=>(oC(e)||aC(e))&&!!e.anchor;Kt.ALIAS=Gv;Kt.DOC=nC;Kt.MAP=Yd;Kt.NODE_TYPE=hi;Kt.PAIR=iC;Kt.SCALAR=Yv;Kt.SEQ=Xd;Kt.hasAnchor=D1;Kt.isAlias=x1;Kt.isCollection=aC;Kt.isDocument=P1;Kt.isMap=T1;Kt.isNode=j1;Kt.isPair=O1;Kt.isScalar=oC;Kt.isSeq=$1});var Kc=O(Xv=>{"use strict";var Tt=Oe(),Cr=Symbol("break visit"),sC=Symbol("skip children"),zn=Symbol("remove node");function Zd(e,t){let r=cC(t);Tt.isDocument(e)?es(null,e.contents,r,Object.freeze([e]))===zn&&(e.contents=null):es(null,e,r,Object.freeze([]))}Zd.BREAK=Cr;Zd.SKIP=sC;Zd.REMOVE=zn;function es(e,t,r,n){let i=lC(e,t,r,n);if(Tt.isNode(i)||Tt.isPair(i))return uC(e,n,i),es(e,i,r,n);if(typeof i!="symbol"){if(Tt.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=es(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===Cr)return Cr;a===zn&&(t.items.splice(o,1),o-=1)}}}else if(Tt.isPair(t)){n=Object.freeze(n.concat(t));let o=es("key",t.key,r,n);if(o===Cr)return Cr;o===zn&&(t.key=null);let a=es("value",t.value,r,n);if(a===Cr)return Cr;a===zn&&(t.value=null)}}return i}async function ef(e,t){let r=cC(t);Tt.isDocument(e)?await ts(null,e.contents,r,Object.freeze([e]))===zn&&(e.contents=null):await ts(null,e,r,Object.freeze([]))}ef.BREAK=Cr;ef.SKIP=sC;ef.REMOVE=zn;async function ts(e,t,r,n){let i=await lC(e,t,r,n);if(Tt.isNode(i)||Tt.isPair(i))return uC(e,n,i),ts(e,i,r,n);if(typeof i!="symbol"){if(Tt.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=await ts(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===Cr)return Cr;a===zn&&(t.items.splice(o,1),o-=1)}}}else if(Tt.isPair(t)){n=Object.freeze(n.concat(t));let o=await ts("key",t.key,r,n);if(o===Cr)return Cr;o===zn&&(t.key=null);let a=await ts("value",t.value,r,n);if(a===Cr)return Cr;a===zn&&(t.value=null)}}return i}function cC(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 lC(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Tt.isMap(t))return r.Map?.(e,t,n);if(Tt.isSeq(t))return r.Seq?.(e,t,n);if(Tt.isPair(t))return r.Pair?.(e,t,n);if(Tt.isScalar(t))return r.Scalar?.(e,t,n);if(Tt.isAlias(t))return r.Alias?.(e,t,n)}function uC(e,t,r){let n=t[t.length-1];if(Tt.isCollection(n))n.items[e]=r;else if(Tt.isPair(n))e==="key"?n.key=r:n.value=r;else if(Tt.isDocument(n))n.contents=r;else{let i=Tt.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Xv.visit=Zd;Xv.visitAsync=ef});var Zv=O(fC=>{"use strict";var dC=Oe(),B1=Kc(),W1={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},L1=e=>e.replace(/[!,[\]{}]/g,t=>W1[t]),Gc=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[o,a]=n;return this.tags[o]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let a=/^\d+\.\d+$/.test(o);return r(6,`Unsupported YAML version ${o}`,a),!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 a=t.slice(2,-1);return a==="!"||a==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),a)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(i)}catch(a){return r(String(a)),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+L1(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&&dC.isNode(t.contents)){let o={};B1.visit(t.contents,(a,s)=>{dC.isNode(s)&&s.tag&&(o[s.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,a]of n)o==="!!"&&a==="tag:yaml.org,2002:"||(!t||i.some(s=>s.startsWith(a)))&&r.push(`%TAG ${o} ${a}`);return r.join(`
|
|
16
|
+
`)}};Gc.defaultYaml={explicit:!1,version:"1.2"};Gc.defaultTags={"!!":"tag:yaml.org,2002:"};fC.Directives=Gc});var tf=O(Yc=>{"use strict";var pC=Oe(),V1=Kc();function M1(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 mC(e){let t=new Set;return V1.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function hC(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function q1(e,t){let r=[],n=new Map,i=null;return{onAnchor:o=>{r.push(o),i??(i=mC(e));let a=hC(t,i);return i.add(a),a},setAnchors:()=>{for(let o of r){let a=n.get(o);if(typeof a=="object"&&a.anchor&&(pC.isScalar(a.node)||pC.isCollection(a.node)))a.node.anchor=a.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=o,s}}},sourceObjects:n}}Yc.anchorIsValid=M1;Yc.anchorNames=mC;Yc.createNodeAnchors=q1;Yc.findNewAnchor=hC});var ew=O(gC=>{"use strict";function Xc(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,o=n.length;i<o;++i){let a=n[i],s=Xc(e,n,String(i),a);s===void 0?delete n[i]:s!==a&&(n[i]=s)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let o=n.get(i),a=Xc(e,n,i,o);a===void 0?n.delete(i):a!==o&&n.set(i,a)}else if(n instanceof Set)for(let i of Array.from(n)){let o=Xc(e,n,i,i);o===void 0?n.delete(i):o!==i&&(n.delete(i),n.add(o))}else for(let[i,o]of Object.entries(n)){let a=Xc(e,n,i,o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}return e.call(t,r,n)}gC.applyReviver=Xc});var zi=O(wC=>{"use strict";var F1=Oe();function vC(e,t,r){if(Array.isArray(e))return e.map((n,i)=>vC(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!F1.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=o=>{n.res=o,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}wC.toJS=vC});var rf=O(kC=>{"use strict";var H1=ew(),yC=Oe(),Q1=zi(),tw=class{constructor(t){Object.defineProperty(this,yC.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:o}={}){if(!yC.isDocument(t))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=Q1.toJS(this,"",a);if(typeof i=="function")for(let{count:c,res:l}of a.anchors.values())i(l,c);return typeof o=="function"?H1.applyReviver(o,{"":s},"",s):s}};kC.NodeBase=tw});var Zc=O(AC=>{"use strict";var U1=tf(),J1=Kc(),rs=Oe(),z1=rf(),K1=zi(),rw=class extends z1.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=[],J1.visit(t,{Node:(o,a)=>{(rs.isAlias(a)||rs.hasAnchor(a))&&n.push(a)}}),r&&(r.aliasResolveCache=n));let i;for(let o of n){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:o}=r,a=this.resolve(i,r);if(!a){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(a);if(s||(K1.toJS(a,null,r),s=n.get(a)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=nf(i,a,n)),s.count*s.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(U1.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${i} `}return i}};function nf(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 o=nf(e,i,r);o>n&&(n=o)}return n}else if(rs.isPair(t)){let n=nf(e,t.key,r),i=nf(e,t.value,r);return Math.max(n,i)}return 1}AC.Alias=rw});var Nt=O(nw=>{"use strict";var G1=Oe(),Y1=rf(),X1=zi(),Z1=e=>!e||typeof e!="function"&&typeof e!="object",Ki=class extends Y1.NodeBase{constructor(t){super(G1.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:X1.toJS(this.value,t,r)}toString(){return String(this.value)}};Ki.BLOCK_FOLDED="BLOCK_FOLDED";Ki.BLOCK_LITERAL="BLOCK_LITERAL";Ki.PLAIN="PLAIN";Ki.QUOTE_DOUBLE="QUOTE_DOUBLE";Ki.QUOTE_SINGLE="QUOTE_SINGLE";nw.Scalar=Ki;nw.isScalarValue=Z1});var el=O(NC=>{"use strict";var eq=Zc(),Zo=Oe(),bC=Nt(),tq="tag:yaml.org,2002:";function rq(e,t,r){if(t){let n=r.filter(o=>o.tag===t),i=n.find(o=>!o.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function nq(e,t,r){if(Zo.isDocument(e)&&(e=e.contents),Zo.isNode(e))return e;if(Zo.isPair(e)){let f=r.schema[Zo.MAP].createNode?.(r.schema,null,r);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:o,schema:a,sourceObjects:s}=r,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new eq.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=tq+t.slice(2));let l=rq(e,t,a.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new bC.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?a[Zo.MAP]:Symbol.iterator in Object(e)?a[Zo.SEQ]:a[Zo.MAP]}o&&(o(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new bC.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}NC.createNode=nq});var af=O(of=>{"use strict";var iq=el(),Kn=Oe(),oq=rf();function iw(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let o=t[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let a=[];a[o]=n,n=a}else n=new Map([[o,n]])}return iq.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 RC=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ow=class extends oq.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=>Kn.isNode(n)||Kn.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(RC(t))this.add(r);else{let[n,...i]=t,o=this.get(n,!0);if(Kn.isCollection(o))o.addIn(i,r);else if(o===void 0&&this.schema)this.set(n,iw(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(Kn.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,o=this.get(n,!0);return i.length===0?!r&&Kn.isScalar(o)?o.value:o:Kn.isCollection(o)?o.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Kn.isPair(r))return!1;let n=r.value;return n==null||t&&Kn.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 Kn.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let o=this.get(n,!0);if(Kn.isCollection(o))o.setIn(i,r);else if(o===void 0&&this.schema)this.set(n,iw(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};of.Collection=ow;of.collectionFromPath=iw;of.isEmptyPath=RC});var tl=O(sf=>{"use strict";var aq=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function aw(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var sq=(e,t,r)=>e.endsWith(`
|
|
17
|
+
`)?aw(r,t):r.includes(`
|
|
18
|
+
`)?`
|
|
19
|
+
`+aw(r,t):(e.endsWith(" ")?"":" ")+r;sf.indentComment=aw;sf.lineComment=sq;sf.stringifyComment=aq});var EC=O(rl=>{"use strict";var cq="flow",sw="block",cf="quoted";function lq(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:o=20,onFold:a,onOverflow:s}={}){if(!i||i<0)return e;i<o&&(o=0);let c=Math.max(1+o,1+i-t.length);if(e.length<=c)return e;let l=[],u={},f=i-t.length;typeof n=="number"&&(n>i-Math.max(2,o)?l.push(0):f=i-n);let d,p,h=!1,m=-1,g=-1,v=-1;r===sw&&(m=SC(e,m,t.length),m!==-1&&(f=m+c));for(let A;A=e[m+=1];){if(r===cf&&A==="\\"){switch(g=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}v=m}if(A===`
|
|
20
|
+
`)r===sw&&(m=SC(e,m,t.length)),f=m+t.length+c,d=void 0;else{if(A===" "&&p&&p!==" "&&p!==`
|
|
21
|
+
`&&p!==" "){let N=e[m+1];N&&N!==" "&&N!==`
|
|
22
|
+
`&&N!==" "&&(d=m)}if(m>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===cf){for(;p===" "||p===" ";)p=A,A=e[m+=1],h=!0;let N=m>v+1?m-2:g-1;if(u[N])return e;l.push(N),u[N]=!0,f=N+c,d=void 0}else h=!0}p=A}if(h&&s&&s(),l.length===0)return e;a&&a();let w=e.slice(0,l[0]);for(let A=0;A<l.length;++A){let N=l[A],b=l[A+1]||e.length;N===0?w=`
|
|
23
|
+
${t}${e.slice(0,b)}`:(r===cf&&u[N]&&(w+=`${e[N]}\\`),w+=`
|
|
24
|
+
${t}${e.slice(N+1,b)}`)}return w}function SC(e,t,r){let n=t,i=t+1,o=e[i];for(;o===" "||o===" ";)if(t<i+r)o=e[++t];else{do o=e[++t];while(o&&o!==`
|
|
25
|
+
`);n=t,i=t+1,o=e[i]}return n}rl.FOLD_BLOCK=sw;rl.FOLD_FLOW=cq;rl.FOLD_QUOTED=cf;rl.foldFlowLines=lq});var il=O(CC=>{"use strict";var In=Nt(),Gi=EC(),uf=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),df=e=>/^(%|---|\.\.\.)/m.test(e);function uq(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let o=0,a=0;o<i;++o)if(e[o]===`
|
|
26
|
+
`){if(o-a>n)return!0;if(a=o+1,i-a<=n)return!1}return!0}function nl(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(df(e)?" ":""),a="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(a+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{a+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:u.substr(0,2)==="00"?a+="\\x"+u.substr(2):a+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(a+=r.slice(s,c)+`
|
|
27
|
+
|
|
28
|
+
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)a+=`
|
|
29
|
+
`,c+=2;a+=o,r[c+2]===" "&&(a+="\\"),c+=1,s=c+1}break;default:c+=1}return a=s?a+r.slice(s):r,n?a:Gi.foldFlowLines(a,o,Gi.FOLD_QUOTED,uf(t,!1))}function cw(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
30
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return nl(e,t);let r=t.indent||(df(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
31
|
+
${r}`)+"'";return t.implicitKey?n:Gi.foldFlowLines(n,r,Gi.FOLD_FLOW,uf(t,!1))}function ns(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=nl;else{let i=e.includes('"'),o=e.includes("'");i&&!o?n=cw:o&&!i?n=nl:n=r?cw:nl}return n(e,t)}var lw;try{lw=new RegExp(`(^|(?<!
|
|
32
|
+
))
|
|
33
|
+
+(?!
|
|
34
|
+
|$)`,"g")}catch{lw=/\n+(?!\n|$)/g}function lf({comment:e,type:t,value:r},n,i,o){let{blockQuote:a,commentString:s,lineWidth:c}=n.options;if(!a||/\n[\t ]+$/.test(r))return ns(r,n);let l=n.indent||(n.forceBlockIndent||df(r)?" ":""),u=a==="literal"?!0:a==="folded"||t===In.Scalar.BLOCK_FOLDED?!1:t===In.Scalar.BLOCK_LITERAL?!0:!uq(r,c,l.length);if(!r)return u?`|
|
|
35
|
+
`:`>
|
|
36
|
+
`;let f,d;for(d=r.length;d>0;--d){let b=r[d-1];if(b!==`
|
|
37
|
+
`&&b!==" "&&b!==" ")break}let p=r.substring(d),h=p.indexOf(`
|
|
38
|
+
`);h===-1?f="-":r===p||h!==p.length-1?(f="+",o&&o()):f="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
39
|
+
`&&(p=p.slice(0,-1)),p=p.replace(lw,`$&${l}`));let m=!1,g,v=-1;for(g=0;g<r.length;++g){let b=r[g];if(b===" ")m=!0;else if(b===`
|
|
40
|
+
`)v=g;else break}let w=r.substring(0,v<g?v+1:g);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let N=(m?l?"2":"1":"")+f;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let b=r.replace(/\n+/g,`
|
|
41
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,V=uf(n,!0);a!=="folded"&&t!==In.Scalar.BLOCK_FOLDED&&(V.onOverflow=()=>{E=!0});let j=Gi.foldFlowLines(`${w}${b}${p}`,l,Gi.FOLD_BLOCK,V);if(!E)return`>${N}
|
|
42
|
+
${l}${j}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
|
|
43
|
+
${l}${w}${r}${p}`}function dq(e,t,r,n){let{type:i,value:o}=e,{actualString:a,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&o.includes(`
|
|
44
|
+
`)||u&&/[[\]{},]/.test(o))return ns(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return s||u||!o.includes(`
|
|
45
|
+
`)?ns(o,t):lf(e,t,r,n);if(!s&&!u&&i!==In.Scalar.PLAIN&&o.includes(`
|
|
46
|
+
`))return lf(e,t,r,n);if(df(o)){if(c==="")return t.forceBlockIndent=!0,lf(e,t,r,n);if(s&&c===l)return ns(o,t)}let f=o.replace(/\n+/g,`$&
|
|
47
|
+
${c}`);if(a){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(f),{compat:p,tags:h}=t.doc.schema;if(h.some(d)||p?.some(d))return ns(o,t)}return s?f:Gi.foldFlowLines(f,c,Gi.FOLD_FLOW,uf(t,!1))}function fq(e,t,r,n){let{implicitKey:i,inFlow:o}=t,a=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==In.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(s=In.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case In.Scalar.BLOCK_FOLDED:case In.Scalar.BLOCK_LITERAL:return i||o?ns(a.value,t):lf(a,t,r,n);case In.Scalar.QUOTE_DOUBLE:return nl(a.value,t);case In.Scalar.QUOTE_SINGLE:return cw(a.value,t);case In.Scalar.PLAIN:return dq(a,t,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=t.options,d=i&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}CC.stringifyString=fq});var ol=O(uw=>{"use strict";var pq=tf(),Yi=Oe(),mq=tl(),hq=il();function gq(e,t){let r=Object.assign({blockQuote:!0,commentString:mq.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 vq(e,t){if(t.tag){let i=e.filter(o=>o.tag===t.tag);if(i.length>0)return i.find(o=>o.format===t.format)??i[0]}let r,n;if(Yi.isScalar(t)){n=t.value;let i=e.filter(o=>o.identify?.(n));if(i.length>1){let o=i.filter(a=>a.test);o.length>0&&(i=o)}r=i.find(o=>o.format===t.format)??i.find(o=>!o.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 wq(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],o=(Yi.isScalar(e)||Yi.isCollection(e))&&e.anchor;o&&pq.anchorIsValid(o)&&(r.add(o),i.push(`&${o}`));let a=e.tag??(t.default?null:t.tag);return a&&i.push(n.directives.tagString(a)),i.join(" ")}function yq(e,t,r,n){if(Yi.isPair(e))return e.toString(t,r,n);if(Yi.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,o=Yi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=vq(t.doc.schema.tags,o));let a=wq(o,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart??0)+a.length+1);let s=typeof i.stringify=="function"?i.stringify(o,t,r,n):Yi.isScalar(o)?hq.stringifyString(o,t,r,n):o.toString(t,r,n);return a?Yi.isScalar(o)||s[0]==="{"||s[0]==="["?`${a} ${s}`:`${a}
|
|
48
|
+
${t.indent}${s}`:s}uw.createStringifyContext=gq;uw.stringify=yq});var PC=O(xC=>{"use strict";var gi=Oe(),_C=Nt(),IC=ol(),al=tl();function kq({key:e,value:t},r,n,i){let{allNullValues:o,doc:a,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=gi.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(gi.isCollection(e)||!gi.isNode(e)&&typeof e=="object"){let V="With simple keys, collection cannot be used as a key value";throw new Error(V)}}let p=!f&&(!e||d&&t==null&&!r.inFlow||gi.isCollection(e)||(gi.isScalar(e)?e.type===_C.Scalar.BLOCK_FOLDED||e.type===_C.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(f||!o),indent:s+c});let h=!1,m=!1,g=IC.stringify(e,r,()=>h=!0,()=>m=!0);if(!p&&!r.inFlow&&g.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(o||t==null)return h&&n&&n(),g===""?"?":p?`? ${g}`:g}else if(o&&!f||t==null&&p)return g=`? ${g}`,d&&!h?g+=al.lineComment(g,r.indent,l(d)):m&&i&&i(),g;h&&(d=null),p?(d&&(g+=al.lineComment(g,r.indent,l(d))),g=`? ${g}
|
|
49
|
+
${s}:`):(g=`${g}:`,d&&(g+=al.lineComment(g,r.indent,l(d))));let v,w,A;gi.isNode(t)?(v=!!t.spaceBefore,w=t.commentBefore,A=t.comment):(v=!1,w=null,A=null,t&&typeof t=="object"&&(t=a.createNode(t))),r.implicitKey=!1,!p&&!d&&gi.isScalar(t)&&(r.indentAtStart=g.length+1),m=!1,!u&&c.length>=2&&!r.inFlow&&!p&&gi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,b=IC.stringify(t,r,()=>N=!0,()=>m=!0),E=" ";if(d||v||w){if(E=v?`
|
|
50
|
+
`:"",w){let V=l(w);E+=`
|
|
51
|
+
${al.indentComment(V,r.indent)}`}b===""&&!r.inFlow?E===`
|
|
52
|
+
`&&A&&(E=`
|
|
53
|
+
|
|
54
|
+
`):E+=`
|
|
55
|
+
${r.indent}`}else if(!p&&gi.isCollection(t)){let V=b[0],j=b.indexOf(`
|
|
56
|
+
`),z=j!==-1,X=r.inFlow??t.flow??t.items.length===0;if(z||!X){let de=!1;if(z&&(V==="&"||V==="!")){let se=b.indexOf(" ");V==="&"&&se!==-1&&se<j&&b[se+1]==="!"&&(se=b.indexOf(" ",se+1)),(se===-1||j<se)&&(de=!0)}de||(E=`
|
|
57
|
+
${r.indent}`)}}else(b===""||b[0]===`
|
|
58
|
+
`)&&(E="");return g+=E+b,r.inFlow?N&&n&&n():A&&!N?g+=al.lineComment(g,r.indent,l(A)):m&&i&&i(),g}xC.stringifyPair=kq});var fw=O(dw=>{"use strict";var TC=Fu("process");function Aq(e,...t){e==="debug"&&console.log(...t)}function bq(e,t){(e==="debug"||e==="warn")&&(typeof TC.emitWarning=="function"?TC.emitWarning(t):console.warn(t))}dw.debug=Aq;dw.warn=bq});var gf=O(hf=>{"use strict";var mf=Oe(),OC=Nt(),ff="<<",pf={identify:e=>e===ff||typeof e=="symbol"&&e.description===ff,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new OC.Scalar(Symbol(ff)),{addToJSMap:$C}),stringify:()=>ff},Nq=(e,t)=>(pf.identify(t)||mf.isScalar(t)&&(!t.type||t.type===OC.Scalar.PLAIN)&&pf.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===pf.tag&&r.default);function $C(e,t,r){let n=jC(e,r);if(mf.isSeq(n))for(let i of n.items)pw(e,t,i);else if(Array.isArray(n))for(let i of n)pw(e,t,i);else pw(e,t,n)}function pw(e,t,r){let n=jC(e,r);if(!mf.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[o,a]of i)t instanceof Map?t.has(o)||t.set(o,a):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0});return t}function jC(e,t){return e&&mf.isAlias(t)?t.resolve(e.doc,e):t}hf.addMergeToJSMap=$C;hf.isMergeKey=Nq;hf.merge=pf});var hw=O(WC=>{"use strict";var Rq=fw(),DC=gf(),Sq=ol(),BC=Oe(),mw=zi();function Eq(e,t,{key:r,value:n}){if(BC.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(DC.isMergeKey(e,r))DC.addMergeToJSMap(e,t,n);else{let i=mw.toJS(r,"",e);if(t instanceof Map)t.set(i,mw.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let o=Cq(r,i,e),a=mw.toJS(n,o,e);o in t?Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0}):t[o]=a}}return t}function Cq(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(BC.isNode(e)&&r?.doc){let n=Sq.createStringifyContext(r.doc,{});n.anchors=new Set;for(let o of r.anchors.keys())n.anchors.add(o.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),Rq.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}WC.addPairToJSMap=Eq});var Xi=O(gw=>{"use strict";var LC=el(),_q=PC(),Iq=hw(),vf=Oe();function xq(e,t,r){let n=LC.createNode(e,void 0,r),i=LC.createNode(t,void 0,r);return new wf(n,i)}var wf=class e{constructor(t,r=null){Object.defineProperty(this,vf.NODE_TYPE,{value:vf.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return vf.isNode(r)&&(r=r.clone(t)),vf.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return Iq.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?_q.stringifyPair(this,t,r,n):JSON.stringify(this)}};gw.Pair=wf;gw.createPair=xq});var vw=O(MC=>{"use strict";var ea=Oe(),VC=ol(),yf=tl();function Pq(e,t,r){return(t.inFlow??e.flow?Oq:Tq)(e,t,r)}function Tq({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:o,onChompKeep:a,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:o,type:null}),f=!1,d=[];for(let h=0;h<t.length;++h){let m=t[h],g=null;if(ea.isNode(m))!f&&m.spaceBefore&&d.push(""),kf(r,d,m.commentBefore,f),m.comment&&(g=m.comment);else if(ea.isPair(m)){let w=ea.isNode(m.key)?m.key:null;w&&(!f&&w.spaceBefore&&d.push(""),kf(r,d,w.commentBefore,f))}f=!1;let v=VC.stringify(m,u,()=>g=null,()=>f=!0);g&&(v+=yf.lineComment(v,o,l(g))),f&&g&&(f=!1),d.push(n+v)}let p;if(d.length===0)p=i.start+i.end;else{p=d[0];for(let h=1;h<d.length;++h){let m=d[h];p+=m?`
|
|
59
|
+
${c}${m}`:`
|
|
60
|
+
`}}return e?(p+=`
|
|
61
|
+
`+yf.indentComment(l(e),c),s&&s()):f&&a&&a(),p}function Oq({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:o,flowCollectionPadding:a,options:{commentString:s}}=t;n+=o;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let h=0;h<e.length;++h){let m=e[h],g=null;if(ea.isNode(m))m.spaceBefore&&f.push(""),kf(t,f,m.commentBefore,!1),m.comment&&(g=m.comment);else if(ea.isPair(m)){let w=ea.isNode(m.key)?m.key:null;w&&(w.spaceBefore&&f.push(""),kf(t,f,w.commentBefore,!1),w.comment&&(l=!0));let A=ea.isNode(m.value)?m.value:null;A?(A.comment&&(g=A.comment),A.commentBefore&&(l=!0)):m.value==null&&w?.comment&&(g=w.comment)}g&&(l=!0);let v=VC.stringify(m,c,()=>g=null);l||(l=f.length>u||v.includes(`
|
|
62
|
+
`)),h<e.length-1?v+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((w,A)=>w+A.length+2,2)+(v.length+2)>t.options.lineWidth)),l&&(v+=",")),g&&(v+=yf.lineComment(v,n,s(g))),f.push(v),u=f.length}let{start:d,end:p}=r;if(f.length===0)return d+p;if(!l){let h=f.reduce((m,g)=>m+g.length+2,2);l=t.options.lineWidth>0&&h>t.options.lineWidth}if(l){let h=d;for(let m of f)h+=m?`
|
|
63
|
+
${o}${i}${m}`:`
|
|
64
|
+
`;return`${h}
|
|
65
|
+
${i}${p}`}else return`${d}${a}${f.join(" ")}${a}${p}`}function kf({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let o=yf.indentComment(t(n),e);r.push(o.trimStart())}}MC.stringifyCollection=Pq});var eo=O(yw=>{"use strict";var $q=vw(),jq=hw(),Dq=af(),Zi=Oe(),Af=Xi(),Bq=Nt();function sl(e,t){let r=Zi.isScalar(t)?t.value:t;for(let n of e)if(Zi.isPair(n)&&(n.key===t||n.key===r||Zi.isScalar(n.key)&&n.key.value===r))return n}var ww=class extends Dq.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Zi.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:o}=n,a=new this(t),s=(c,l)=>{if(typeof o=="function")l=o.call(r,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||i)&&a.items.push(Af.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&a.items.sort(t.sortMapEntries),a}add(t,r){let n;Zi.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Af.Pair(t,t?.value):n=new Af.Pair(t.key,t.value);let i=sl(this.items,n.key),o=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Zi.isScalar(i.value)&&Bq.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(o){let a=this.items.findIndex(s=>o(n,s)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(t){let r=sl(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=sl(this.items,t)?.value;return(!r&&Zi.isScalar(i)?i.value:i)??void 0}has(t){return!!sl(this.items,t)}set(t,r){this.add(new Af.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let o of this.items)jq.addPairToJSMap(r,i,o);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Zi.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})),$q.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};yw.YAMLMap=ww;yw.findPair=sl});var is=O(FC=>{"use strict";var Wq=Oe(),qC=eo(),Lq={collection:"map",default:!0,nodeClass:qC.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Wq.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>qC.YAMLMap.from(e,t,r)};FC.map=Lq});var to=O(HC=>{"use strict";var Vq=el(),Mq=vw(),qq=af(),Nf=Oe(),Fq=Nt(),Hq=zi(),kw=class extends qq.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Nf.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=bf(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=bf(t);if(typeof n!="number")return;let i=this.items[n];return!r&&Nf.isScalar(i)?i.value:i}has(t){let r=bf(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=bf(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];Nf.isScalar(i)&&Fq.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let o of this.items)n.push(Hq.toJS(o,String(i++),r));return n}toString(t,r,n){return t?Mq.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,o=new this(t);if(r&&Symbol.iterator in Object(r)){let a=0;for(let s of r){if(typeof i=="function"){let c=r instanceof Set?s:String(a++);s=i.call(r,c,s)}o.items.push(Vq.createNode(s,void 0,n))}}return o}};function bf(e){let t=Nf.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}HC.YAMLSeq=kw});var os=O(UC=>{"use strict";var Qq=Oe(),QC=to(),Uq={collection:"seq",default:!0,nodeClass:QC.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Qq.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>QC.YAMLSeq.from(e,t,r)};UC.seq=Uq});var cl=O(JC=>{"use strict";var Jq=il(),zq={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),Jq.stringifyString(e,t,r,n)}};JC.string=zq});var Rf=O(GC=>{"use strict";var zC=Nt(),KC={identify:e=>e==null,createNode:()=>new zC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zC.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&KC.test.test(e)?e:t.options.nullStr};GC.nullTag=KC});var Aw=O(XC=>{"use strict";var Kq=Nt(),YC={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Kq.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&YC.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};XC.boolTag=YC});var as=O(ZC=>{"use strict";function Gq({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 o=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let a=o.indexOf(".");a<0&&(a=o.length,o+=".");let s=t-(o.length-a-1);for(;s-- >0;)o+="0"}return o}ZC.stringifyNumber=Gq});var Nw=O(Sf=>{"use strict";var Yq=Nt(),bw=as(),Xq={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:bw.stringifyNumber},Zq={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():bw.stringifyNumber(e)}},eF={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 Yq.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:bw.stringifyNumber};Sf.float=eF;Sf.floatExp=Zq;Sf.floatNaN=Xq});var Sw=O(Cf=>{"use strict";var e_=as(),Ef=e=>typeof e=="bigint"||Number.isInteger(e),Rw=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function t_(e,t,r){let{value:n}=e;return Ef(n)&&n>=0?r+n.toString(t):e_.stringifyNumber(e)}var tF={identify:e=>Ef(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Rw(e,2,8,r),stringify:e=>t_(e,8,"0o")},rF={identify:Ef,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Rw(e,0,10,r),stringify:e_.stringifyNumber},nF={identify:e=>Ef(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Rw(e,2,16,r),stringify:e=>t_(e,16,"0x")};Cf.int=rF;Cf.intHex=nF;Cf.intOct=tF});var n_=O(r_=>{"use strict";var iF=is(),oF=Rf(),aF=os(),sF=cl(),cF=Aw(),Ew=Nw(),Cw=Sw(),lF=[iF.map,aF.seq,sF.string,oF.nullTag,cF.boolTag,Cw.intOct,Cw.int,Cw.intHex,Ew.floatNaN,Ew.floatExp,Ew.float];r_.schema=lF});var a_=O(o_=>{"use strict";var uF=Nt(),dF=is(),fF=os();function i_(e){return typeof e=="bigint"||Number.isInteger(e)}var _f=({value:e})=>JSON.stringify(e),pF=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:_f},{identify:e=>e==null,createNode:()=>new uF.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_f},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:_f},{identify:i_,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})=>i_(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:_f}],mF={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},hF=[dF.map,fF.seq].concat(pF,mF);o_.schema=hF});var Iw=O(s_=>{"use strict";var ll=Fu("buffer"),_w=Nt(),gF=il(),vF={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ll.Buffer=="function")return ll.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,o){if(!r)return"";let a=r,s;if(typeof ll.Buffer=="function")s=a instanceof ll.Buffer?a.toString("base64"):ll.Buffer.from(a.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<a.length;++l)c+=String.fromCharCode(a[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=_w.Scalar.BLOCK_LITERAL),t!==_w.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(t===_w.Scalar.BLOCK_LITERAL?`
|
|
66
|
+
`:" ")}return gF.stringifyString({comment:e,type:t,value:s},n,i,o)}};s_.binary=vF});var Pf=O(xf=>{"use strict";var If=Oe(),xw=Xi(),wF=Nt(),yF=to();function c_(e,t){if(If.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!If.isPair(n)){if(If.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new xw.Pair(new wF.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
67
|
+
${i.key.commentBefore}`:n.commentBefore),n.comment){let o=i.value??i.key;o.comment=o.comment?`${n.comment}
|
|
68
|
+
${o.comment}`:n.comment}n=i}e.items[r]=If.isPair(n)?n:new xw.Pair(n)}}else t("Expected a sequence for this tag");return e}function l_(e,t,r){let{replacer:n}=r,i=new yF.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let a of t){typeof n=="function"&&(a=n.call(t,String(o++),a));let s,c;if(Array.isArray(a))if(a.length===2)s=a[0],c=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){let l=Object.keys(a);if(l.length===1)s=l[0],c=a[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=a;i.items.push(xw.createPair(s,c,r))}return i}var kF={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:c_,createNode:l_};xf.createPairs=l_;xf.pairs=kF;xf.resolvePairs=c_});var Ow=O(Tw=>{"use strict";var u_=Oe(),Pw=zi(),ul=eo(),AF=to(),d_=Pf(),ta=class e extends AF.YAMLSeq{constructor(){super(),this.add=ul.YAMLMap.prototype.add.bind(this),this.delete=ul.YAMLMap.prototype.delete.bind(this),this.get=ul.YAMLMap.prototype.get.bind(this),this.has=ul.YAMLMap.prototype.has.bind(this),this.set=ul.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 o,a;if(u_.isPair(i)?(o=Pw.toJS(i.key,"",r),a=Pw.toJS(i.value,o,r)):o=Pw.toJS(i,"",r),n.has(o))throw new Error("Ordered maps must not include duplicate keys");n.set(o,a)}return n}static from(t,r,n){let i=d_.createPairs(t,r,n),o=new this;return o.items=i.items,o}};ta.tag="tag:yaml.org,2002:omap";var bF={collection:"seq",identify:e=>e instanceof Map,nodeClass:ta,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=d_.resolvePairs(e,t),n=[];for(let{key:i}of r.items)u_.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ta,r)},createNode:(e,t,r)=>ta.from(e,t,r)};Tw.YAMLOMap=ta;Tw.omap=bF});var g_=O($w=>{"use strict";var f_=Nt();function p_({value:e,source:t},r){return t&&(e?m_:h_).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var m_={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 f_.Scalar(!0),stringify:p_},h_={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 f_.Scalar(!1),stringify:p_};$w.falseTag=h_;$w.trueTag=m_});var v_=O(Tf=>{"use strict";var NF=Nt(),jw=as(),RF={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:jw.stringifyNumber},SF={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():jw.stringifyNumber(e)}},EF={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 NF.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:jw.stringifyNumber};Tf.float=EF;Tf.floatExp=SF;Tf.floatNaN=RF});var y_=O(fl=>{"use strict";var w_=as(),dl=e=>typeof e=="bigint"||Number.isInteger(e);function Of(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 a=BigInt(e);return i==="-"?BigInt(-1)*a:a}let o=parseInt(e,r);return i==="-"?-1*o:o}function Dw(e,t,r){let{value:n}=e;if(dl(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return w_.stringifyNumber(e)}var CF={identify:dl,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Of(e,2,2,r),stringify:e=>Dw(e,2,"0b")},_F={identify:dl,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Of(e,1,8,r),stringify:e=>Dw(e,8,"0")},IF={identify:dl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Of(e,0,10,r),stringify:w_.stringifyNumber},xF={identify:dl,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Of(e,2,16,r),stringify:e=>Dw(e,16,"0x")};fl.int=IF;fl.intBin=CF;fl.intHex=xF;fl.intOct=_F});var Ww=O(Bw=>{"use strict";var Df=Oe(),$f=Xi(),jf=eo(),ra=class e extends jf.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Df.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new $f.Pair(t.key,null):r=new $f.Pair(t,null),jf.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=jf.findPair(this.items,t);return!r&&Df.isPair(n)?Df.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=jf.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new $f.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,o=new this(t);if(r&&Symbol.iterator in Object(r))for(let a of r)typeof i=="function"&&(a=i.call(r,a,a)),o.items.push($f.createPair(a,null,n));return o}};ra.tag="tag:yaml.org,2002:set";var PF={collection:"map",identify:e=>e instanceof Set,nodeClass:ra,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ra.from(e,t,r),resolve(e,t){if(Df.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ra,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Bw.YAMLSet=ra;Bw.set=PF});var Vw=O(Bf=>{"use strict";var TF=as();function Lw(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=a=>t?BigInt(a):Number(a),o=n.replace(/_/g,"").split(":").reduce((a,s)=>a*i(60)+i(s),i(0));return r==="-"?i(-1)*o:o}function k_(e){let{value:t}=e,r=a=>a;if(typeof t=="bigint")r=a=>BigInt(a);else if(isNaN(t)||!isFinite(t))return TF.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),o=[t%i];return t<60?o.unshift(0):(t=(t-o[0])/i,o.unshift(t%i),t>=60&&(t=(t-o[0])/i,o.unshift(t))),n+o.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var OF={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})=>Lw(e,r),stringify:k_},$F={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=>Lw(e,!1),stringify:k_},A_={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(A_.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,o,a,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,o||0,a||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=Lw(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Bf.floatTime=$F;Bf.intTime=OF;Bf.timestamp=A_});var R_=O(N_=>{"use strict";var jF=is(),DF=Rf(),BF=os(),WF=cl(),LF=Iw(),b_=g_(),Mw=v_(),Wf=y_(),VF=gf(),MF=Ow(),qF=Pf(),FF=Ww(),qw=Vw(),HF=[jF.map,BF.seq,WF.string,DF.nullTag,b_.trueTag,b_.falseTag,Wf.intBin,Wf.intOct,Wf.int,Wf.intHex,Mw.floatNaN,Mw.floatExp,Mw.float,LF.binary,VF.merge,MF.omap,qF.pairs,FF.set,qw.intTime,qw.floatTime,qw.timestamp];N_.schema=HF});var $_=O(Qw=>{"use strict";var __=is(),QF=Rf(),I_=os(),UF=cl(),JF=Aw(),Fw=Nw(),Hw=Sw(),zF=n_(),KF=a_(),x_=Iw(),pl=gf(),P_=Ow(),T_=Pf(),S_=R_(),O_=Ww(),Lf=Vw(),E_=new Map([["core",zF.schema],["failsafe",[__.map,I_.seq,UF.string]],["json",KF.schema],["yaml11",S_.schema],["yaml-1.1",S_.schema]]),C_={binary:x_.binary,bool:JF.boolTag,float:Fw.float,floatExp:Fw.floatExp,floatNaN:Fw.floatNaN,floatTime:Lf.floatTime,int:Hw.int,intHex:Hw.intHex,intOct:Hw.intOct,intTime:Lf.intTime,map:__.map,merge:pl.merge,null:QF.nullTag,omap:P_.omap,pairs:T_.pairs,seq:I_.seq,set:O_.set,timestamp:Lf.timestamp},GF={"tag:yaml.org,2002:binary":x_.binary,"tag:yaml.org,2002:merge":pl.merge,"tag:yaml.org,2002:omap":P_.omap,"tag:yaml.org,2002:pairs":T_.pairs,"tag:yaml.org,2002:set":O_.set,"tag:yaml.org,2002:timestamp":Lf.timestamp};function YF(e,t,r){let n=E_.get(t);if(n&&!e)return r&&!n.includes(pl.merge)?n.concat(pl.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(E_.keys()).filter(a=>a!=="yaml11").map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)i=i.concat(o);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(pl.merge)),i.reduce((o,a)=>{let s=typeof a=="string"?C_[a]:a;if(!s){let c=JSON.stringify(a),l=Object.keys(C_).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return o.includes(s)||o.push(s),o},[])}Qw.coreKnownTags=GF;Qw.getTags=YF});var zw=O(j_=>{"use strict";var Uw=Oe(),XF=is(),ZF=os(),eH=cl(),Vf=$_(),tH=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Jw=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:o,sortMapEntries:a,toStringDefaults:s}){this.compat=Array.isArray(t)?Vf.getTags(t,"compat"):t?Vf.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?Vf.coreKnownTags:{},this.tags=Vf.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Uw.MAP,{value:XF.map}),Object.defineProperty(this,Uw.SCALAR,{value:eH.string}),Object.defineProperty(this,Uw.SEQ,{value:ZF.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?tH:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};j_.Schema=Jw});var B_=O(D_=>{"use strict";var rH=Oe(),Kw=ol(),ml=tl();function nH(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=Kw.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=o(e.commentBefore);r.unshift(ml.indentComment(c,""))}let a=!1,s=null;if(e.contents){if(rH.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let u=o(e.contents.commentBefore);r.push(ml.indentComment(u,""))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>a=!0,l=Kw.stringify(e.contents,i,()=>s=null,c);s&&(l+=ml.lineComment(l,"",o(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Kw.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
|
|
69
|
+
`)?(r.push("..."),r.push(ml.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&a&&(c=c.replace(/^\n+/,"")),c&&((!a||s)&&r[r.length-1]!==""&&r.push(""),r.push(ml.indentComment(o(c),"")))}return r.join(`
|
|
70
|
+
`)+`
|
|
71
|
+
`}D_.stringifyDocument=nH});var hl=O(W_=>{"use strict";var iH=Zc(),ss=af(),un=Oe(),oH=Xi(),aH=zi(),sH=zw(),cH=B_(),Gw=tf(),lH=ew(),uH=el(),Yw=Zv(),Xw=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,un.NODE_TYPE,{value:un.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=o;let{version:a}=o;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new Yw.Directives({version:a}),this.setSchema(a,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[un.NODE_TYPE]:{value:un.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=un.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){cs(this.contents)&&this.contents.add(t)}addIn(t,r){cs(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=Gw.anchorNames(this);t.anchor=!r||n.has(r)?Gw.findNewAnchor(r||"a",n):r}return new iH.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=w=>typeof w=="number"||w instanceof String||w instanceof Number,v=r.filter(g).map(String);v.length>0&&(r=r.concat(v)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:o,anchorPrefix:a,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:d,sourceObjects:p}=Gw.createNodeAnchors(this,a||"a"),h={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=uH.createNode(t,u,h);return s&&un.isCollection(m)&&(m.flow=!0),d(),m}createPair(t,r,n={}){let i=this.createNode(t,null,n),o=this.createNode(r,null,n);return new oH.Pair(i,o)}delete(t){return cs(this.contents)?this.contents.delete(t):!1}deleteIn(t){return ss.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):cs(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return un.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return ss.isEmptyPath(t)?!r&&un.isScalar(this.contents)?this.contents.value:this.contents:un.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return un.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return ss.isEmptyPath(t)?this.contents!==void 0:un.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=ss.collectionFromPath(this.schema,[t],r):cs(this.contents)&&this.contents.set(t,r)}setIn(t,r){ss.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=ss.collectionFromPath(this.schema,Array.from(t),r):cs(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 Yw.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 Yw.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 sH.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:o,reviver:a}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=aH.toJS(this.contents,r??"",s);if(typeof o=="function")for(let{count:l,res:u}of s.anchors.values())o(u,l);return typeof a=="function"?lH.applyReviver(a,{"":c},"",c):c}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 cH.stringifyDocument(this,t)}};function cs(e){if(un.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}W_.Document=Xw});var wl=O(vl=>{"use strict";var gl=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Zw=class extends gl{constructor(t,r,n){super("YAMLParseError",t,r,n)}},ey=class extends gl{constructor(t,r,n){super("YAMLWarning",t,r,n)}},dH=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let o=i-1,a=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(o>=60&&a.length>80){let s=Math.min(o-39,a.length-79);a="…"+a.substring(s),o-=s-1}if(a.length>80&&(a=a.substring(0,79)+"…"),n>1&&/^ *$/.test(a.substring(0,o))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
72
|
+
`),a=s+a}if(/[^ ]/.test(a)){let s=1,c=r.linePos[1];c?.line===n&&c.col>i&&(s=Math.max(1,Math.min(c.col-i,80-o)));let l=" ".repeat(o)+"^".repeat(s);r.message+=`:
|
|
73
|
+
|
|
74
|
+
${a}
|
|
75
|
+
${l}
|
|
76
|
+
`}};vl.YAMLError=gl;vl.YAMLParseError=Zw;vl.YAMLWarning=ey;vl.prettifyError=dH});var yl=O(L_=>{"use strict";function fH(e,{flow:t,indicator:r,next:n,offset:i,onError:o,parentIndent:a,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,h=!1,m=null,g=null,v=null,w=null,A=null,N=null,b=null;for(let j of e)switch(h&&(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma"&&o(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(l&&j.type!=="comment"&&j.type!=="newline"&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),j.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&j.source.includes(" ")&&(m=j),u=!0;break;case"comment":{u||o(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let z=j.source.substring(1)||" ";f?f+=d+z:f=z,d="",l=!1;break}case"newline":l?f?f+=j.source:(!N||r!=="seq-item-ind")&&(c=!0):d+=j.source,l=!0,p=!0,(g||v)&&(w=j),u=!0;break;case"anchor":g&&o(j,"MULTIPLE_ANCHORS","A node can have at most one anchor"),j.source.endsWith(":")&&o(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=j,b??(b=j.offset),l=!1,u=!1,h=!0;break;case"tag":{v&&o(j,"MULTIPLE_TAGS","A node can have at most one tag"),v=j,b??(b=j.offset),l=!1,u=!1,h=!0;break}case r:(g||v)&&o(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`),N&&o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${t??"collection"}`),N=j,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){A&&o(j,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),A=j,l=!1,u=!1;break}default:o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),l=!1,u=!1}let E=e[e.length-1],V=E?E.offset+E.source.length:i;return h&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&o(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=a||n?.type==="block-map"||n?.type==="block-seq")&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:N,spaceBefore:c,comment:f,hasNewline:p,anchor:g,tag:v,newlineAfterProp:w,end:V,start:b??V}}L_.resolveProps=fH});var Mf=O(V_=>{"use strict";function ty(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
77
|
+
`))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(ty(t.key)||ty(t.value))return!0}return!1;default:return!0}}V_.containsNewline=ty});var ry=O(M_=>{"use strict";var pH=Mf();function mH(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&pH.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}M_.flowIndentCheck=mH});var ny=O(F_=>{"use strict";var q_=Oe();function hH(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(o,a)=>o===a||q_.isScalar(o)&&q_.isScalar(a)&&o.value===a.value;return t.some(o=>i(o.key,r))}F_.mapIncludes=hH});var K_=O(z_=>{"use strict";var H_=Xi(),gH=eo(),Q_=yl(),vH=Mf(),U_=ry(),wH=ny(),J_="All mapping items must start at the same column";function yH({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??gH.YAMLMap,s=new a(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:d,sep:p,value:h}=u,m=Q_.resolveProps(f,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!m.found;if(g){if(d&&(d.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&i(c,"BAD_INDENT",J_)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(s.comment?s.comment+=`
|
|
78
|
+
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||vH.containsNewline(d))&&i(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&i(c,"BAD_INDENT",J_);r.atKey=!0;let v=m.end,w=d?e(r,d,m,i):t(r,v,f,null,m,i);r.schema.compat&&U_.flowIndentCheck(n.indent,d,i),r.atKey=!1,wH.mapIncludes(r,s.items,w)&&i(v,"DUPLICATE_KEY","Map keys must be unique");let A=Q_.resolveProps(p??[],{indicator:"map-value-ind",next:h,offset:w.range[2],onError:i,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=A.end,A.found){g&&(h?.type==="block-map"&&!A.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<A.found.offset-1024&&i(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=h?e(r,h,A,i):t(r,c,p,null,A,i);r.schema.compat&&U_.flowIndentCheck(n.indent,h,i),c=N.range[2];let b=new H_.Pair(w,N);r.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}else{g&&i(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(w.comment?w.comment+=`
|
|
79
|
+
`+A.comment:w.comment=A.comment);let N=new H_.Pair(w);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}z_.resolveBlockMap=yH});var Y_=O(G_=>{"use strict";var kH=to(),AH=yl(),bH=ry();function NH({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??kH.YAMLSeq,s=new a(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let d=AH.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?i(d.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?e(r,f,d,i):t(r,d.end,u,null,d,i);r.schema.compat&&bH.flowIndentCheck(n.indent,f,i),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}G_.resolveBlockSeq=NH});var ls=O(X_=>{"use strict";function RH(e,t,r,n){let i="";if(e){let o=!1,a="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":o=!0;break;case"comment":{r&&!o&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=a+u:i=u,a="";break}case"newline":i&&(a+=c),o=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:i,offset:t}}X_.resolveEnd=RH});var rI=O(tI=>{"use strict";var SH=Oe(),EH=Xi(),Z_=eo(),CH=to(),_H=ls(),eI=yl(),IH=Mf(),xH=ny(),iy="Block collections are not allowed within flow collections",oy=e=>e&&(e.type==="block-map"||e.type==="block-seq");function PH({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=n.start.source==="{",s=a?"flow map":"flow sequence",c=o?.nodeClass??(a?Z_.YAMLMap:CH.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let v=n.items[g],{start:w,key:A,sep:N,value:b}=v,E=eI.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:A??N?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!N&&!b){g===0&&E.comma?i(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<n.items.length-1&&i(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
|
|
80
|
+
`+E.comment:l.comment=E.comment),f=E.end;continue}!a&&r.options.strict&&IH.containsNewline(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)E.comma&&i(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||i(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let V="";e:for(let j of w)switch(j.type){case"comma":case"space":break;case"comment":V=j.source.substring(1);break e;default:break e}if(V){let j=l.items[l.items.length-1];SH.isPair(j)&&(j=j.value??j.key),j.comment?j.comment+=`
|
|
81
|
+
`+V:j.comment=V,E.comment=E.comment.substring(V.length+1)}}if(!a&&!N&&!E.found){let V=b?e(r,b,E,i):t(r,E.end,N,null,E,i);l.items.push(V),f=V.range[2],oy(b)&&i(V.range,"BLOCK_IN_FLOW",iy)}else{r.atKey=!0;let V=E.end,j=A?e(r,A,E,i):t(r,V,w,null,E,i);oy(A)&&i(j.range,"BLOCK_IN_FLOW",iy),r.atKey=!1;let z=eI.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:b,offset:j.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(z.found){if(!a&&!E.found&&r.options.strict){if(N)for(let se of N){if(se===z.found)break;if(se.type==="newline"){i(se,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<z.found.offset-1024&&i(z.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else b&&("source"in b&&b.source?.[0]===":"?i(b,"MISSING_CHAR",`Missing space after : in ${s}`):i(z.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let X=b?e(r,b,z,i):z.found?t(r,z.end,N,null,z,i):null;X?oy(b)&&i(X.range,"BLOCK_IN_FLOW",iy):z.comment&&(j.comment?j.comment+=`
|
|
82
|
+
`+z.comment:j.comment=z.comment);let de=new EH.Pair(j,X);if(r.options.keepSourceTokens&&(de.srcToken=v),a){let se=l;xH.mapIncludes(r,se.items,j)&&i(V,"DUPLICATE_KEY","Map keys must be unique"),se.items.push(de)}else{let se=new Z_.YAMLMap(r.schema);se.flow=!0,se.items.push(de);let De=(X??j).range;se.range=[j.range[0],De[1],De[2]],l.items.push(se)}f=X?X.range[2]:z.end}}let d=a?"}":"]",[p,...h]=n.end,m=f;if(p?.source===d)m=p.offset+p.source.length;else{let g=s[0].toUpperCase()+s.substring(1),v=u?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;i(f,u?"MISSING_CHAR":"BAD_INDENT",v),p&&p.source.length!==1&&h.unshift(p)}if(h.length>0){let g=_H.resolveEnd(h,m,r.options.strict,i);g.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+g.comment:l.comment=g.comment),l.range=[n.offset,m,g.offset]}else l.range=[n.offset,m,m];return l}tI.resolveFlowCollection=PH});var iI=O(nI=>{"use strict";var TH=Oe(),OH=Nt(),$H=eo(),jH=to(),DH=K_(),BH=Y_(),WH=rI();function ay(e,t,r,n,i,o){let a=r.type==="block-map"?DH.resolveBlockMap(e,t,r,n,o):r.type==="block-seq"?BH.resolveBlockSeq(e,t,r,n,o):WH.resolveFlowCollection(e,t,r,n,o),s=a.constructor;return i==="!"||i===s.tagName?(a.tag=s.tagName,a):(i&&(a.tag=i),a)}function LH(e,t,r,n,i){let o=n.tag,a=o?t.directives.tagName(o.source,d=>i(o,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,h=d&&o?d.offset>o.offset?d:o:d??o;h&&(!p||p.offset<h.offset)&&i(h,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!o||!a||a==="!"||a===$H.YAMLMap.tagName&&s==="map"||a===jH.YAMLSeq.tagName&&s==="seq")return ay(e,t,r,i,a);let c=t.schema.tags.find(d=>d.tag===a&&d.collection===s);if(!c){let d=t.schema.knownTags[a];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?i(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${a}`,!0),ay(e,t,r,i,a)}let l=ay(e,t,r,i,a,c),u=c.resolve?.(l,d=>i(o,"TAG_RESOLVE_FAILED",d),t.options)??l,f=TH.isNode(u)?u:new OH.Scalar(u);return f.range=l.range,f.tag=a,c?.format&&(f.format=c.format),f}nI.composeCollection=LH});var cy=O(oI=>{"use strict";var sy=Nt();function VH(e,t,r){let n=t.offset,i=MH(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let o=i.mode===">"?sy.Scalar.BLOCK_FOLDED:sy.Scalar.BLOCK_LITERAL,a=t.source?qH(t.source):[],s=a.length;for(let m=a.length-1;m>=0;--m){let g=a[m][1];if(g===""||g==="\r")s=m;else break}if(s===0){let m=i.chomp==="+"&&a.length>0?`
|
|
84
|
+
`.repeat(Math.max(1,a.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:m,type:o,comment:i.comment,range:[n,g,g]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let m=0;m<s;++m){let[g,v]=a[m];if(v===""||v==="\r")i.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&r(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=g.length),u=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+v.length+1}for(let m=a.length-1;m>=s;--m)a[m][0].length>c&&(s=m+1);let f="",d="",p=!1;for(let m=0;m<u;++m)f+=a[m][0].slice(c)+`
|
|
85
|
+
`;for(let m=u;m<s;++m){let[g,v]=a[m];l+=g.length+v.length+1;let w=v[v.length-1]==="\r";if(w&&(v=v.slice(0,-1)),v&&g.length<c){let N=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-v.length-(w?2:1),"BAD_INDENT",N),g=""}o===sy.Scalar.BLOCK_LITERAL?(f+=d+g.slice(c)+v,d=`
|
|
86
|
+
`):g.length>c||v[0]===" "?(d===" "?d=`
|
|
87
|
+
`:!p&&d===`
|
|
88
|
+
`&&(d=`
|
|
89
|
+
|
|
90
|
+
`),f+=d+g.slice(c)+v,d=`
|
|
91
|
+
`,p=!0):v===""?d===`
|
|
92
|
+
`?f+=`
|
|
93
|
+
`:d=`
|
|
94
|
+
`:(f+=d+v,d=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let m=s;m<a.length;++m)f+=`
|
|
95
|
+
`+a[m][0].slice(c);f[f.length-1]!==`
|
|
96
|
+
`&&(f+=`
|
|
97
|
+
`);break;default:f+=`
|
|
98
|
+
`}let h=n+i.length+t.source.length;return{value:f,type:o,comment:i.comment,range:[n,h,h]}}function MH({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],o=i[0],a=0,s="",c=-1;for(let d=1;d<i.length;++d){let p=i[d];if(!s&&(p==="-"||p==="+"))s=p;else{let h=Number(p);!a&&h?a=h:c===-1&&(c=e+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",f=i.length;for(let d=1;d<t.length;++d){let p=t[d];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":r&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,u=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let h=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",h);let m=p.source;m&&typeof m=="string"&&(f+=m.length)}}}return{mode:o,indent:a,chomp:s,comment:u,length:f}}function qH(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),o=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let a=1;a<t.length;a+=2)o.push([t[a],t[a+1]]);return o}oI.resolveBlockScalar=VH});var uy=O(sI=>{"use strict";var ly=Nt(),FH=ls();function HH(e,t,r){let{offset:n,type:i,source:o,end:a}=e,s,c,l=(d,p,h)=>r(n+d,p,h);switch(i){case"scalar":s=ly.Scalar.PLAIN,c=QH(o,l);break;case"single-quoted-scalar":s=ly.Scalar.QUOTE_SINGLE,c=UH(o,l);break;case"double-quoted-scalar":s=ly.Scalar.QUOTE_DOUBLE,c=JH(o,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+o.length,n+o.length]}}let u=n+o.length,f=FH.resolveEnd(a,u,t,r);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function QH(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}`),aI(e)}function UH(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),aI(e.slice(1,-1)).replace(/''/g,"'")}function aI(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
99
|
+
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
100
|
+
`,"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],o=" ",a=t.lastIndex;for(r.lastIndex=a;n=r.exec(e);)n[1]===""?o===`
|
|
101
|
+
`?i+=o:o=`
|
|
102
|
+
`:(i+=o+n[1],o=" "),a=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=a,n=s.exec(e),i+o+(n?.[1]??"")}function JH(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
|
|
103
|
+
`))if(i===`
|
|
104
|
+
`){let{fold:o,offset:a}=zH(e,n);r+=o,n=a}else if(i==="\\"){let o=e[++n],a=KH[o];if(a)r+=a;else if(o===`
|
|
105
|
+
`)for(o=e[n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="\r"&&e[n+1]===`
|
|
106
|
+
`)for(o=e[++n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="x"||o==="u"||o==="U"){let s=o==="x"?2:o==="u"?4:8;r+=GH(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let o=n,a=e[n+1];for(;a===" "||a===" ";)a=e[++n+1];a!==`
|
|
107
|
+
`&&!(a==="\r"&&e[n+2]===`
|
|
108
|
+
`)&&(r+=n>o?e.slice(o,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function zH(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
|
|
109
|
+
`||n==="\r")&&!(n==="\r"&&e[t+2]!==`
|
|
110
|
+
`);)n===`
|
|
111
|
+
`&&(r+=`
|
|
112
|
+
`),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var KH={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
113
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function GH(e,t,r,n){let i=e.substr(t,r),a=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let s=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}sI.resolveFlowScalar=HH});var uI=O(lI=>{"use strict";var na=Oe(),cI=Nt(),YH=cy(),XH=uy();function ZH(e,t,r,n){let{value:i,type:o,comment:a,range:s}=t.type==="block-scalar"?YH.resolveBlockScalar(e,t,n):XH.resolveFlowScalar(t,e.options.strict,n),c=r?e.directives.tagName(r.source,f=>n(r,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[na.SCALAR]:c?l=eQ(e.schema,i,c,r,n):t.type==="scalar"?l=tQ(e,i,t,n):l=e.schema[na.SCALAR];let u;try{let f=l.resolve(i,d=>n(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=na.isScalar(f)?f:new cI.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(r??t,"TAG_RESOLVE_FAILED",d),u=new cI.Scalar(i)}return u.range=s,u.source=i,o&&(u.type=o),c&&(u.tag=c),l.format&&(u.format=l.format),a&&(u.comment=a),u}function eQ(e,t,r,n,i){if(r==="!")return e[na.SCALAR];let o=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)o.push(s);else return s;for(let s of o)if(s.test?.test(t))return s;let a=e.knownTags[r];return a&&!a.collection?(e.tags.push(Object.assign({},a,{default:!1,test:void 0})),a):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[na.SCALAR])}function tQ({atKey:e,directives:t,schema:r},n,i,o){let a=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||r[na.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[na.SCALAR];if(a.tag!==s.tag){let c=t.tagString(a.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;o(i,"TAG_RESOLVE_FAILED",u,!0)}}return a}lI.composeScalar=ZH});var fI=O(dI=>{"use strict";function rQ(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}dI.emptyScalarPosition=rQ});var hI=O(fy=>{"use strict";var nQ=Zc(),iQ=Oe(),oQ=iI(),pI=uI(),aQ=ls(),sQ=fI(),cQ={composeNode:mI,composeEmptyNode:dy};function mI(e,t,r,n){let i=e.atKey,{spaceBefore:o,comment:a,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=lQ(e,t,n),(s||c)&&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":l=pI.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=oQ.composeCollection(cQ,e,t,r,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=dy(e,t.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!iQ.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),a&&(t.type==="scalar"&&t.source===""?l.comment=a:l.commentBefore=a),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function dy(e,t,r,n,{spaceBefore:i,comment:o,anchor:a,tag:s,end:c},l){let u={type:"scalar",offset:sQ.emptyScalarPosition(t,r,n),indent:-1,source:""},f=pI.composeScalar(e,u,s,l);return a&&(f.anchor=a.source.substring(1),f.anchor===""&&l(a,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),o&&(f.comment=o,f.range[2]=c),f}function lQ({options:e},{offset:t,source:r,end:n},i){let o=new nQ.Alias(r.substring(1));o.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let a=t+r.length,s=aQ.resolveEnd(n,a,e.strict,i);return o.range=[t,a,s.offset],s.comment&&(o.comment=s.comment),o}fy.composeEmptyNode=dy;fy.composeNode=mI});var wI=O(vI=>{"use strict";var uQ=hl(),gI=hI(),dQ=ls(),fQ=yl();function pQ(e,t,{offset:r,start:n,value:i,end:o},a){let s=Object.assign({_directives:t},e),c=new uQ.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=fQ.resolveProps(n,{indicator:"doc-start",next:i??o?.[0],offset:r,onError:a,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&a(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?gI.composeNode(l,i,u,a):gI.composeEmptyNode(l,u.end,n,null,u,a);let f=c.contents.range[2],d=dQ.resolveEnd(o,f,!1,a);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}vI.composeDoc=pQ});var my=O(AI=>{"use strict";var mQ=Fu("process"),hQ=Zv(),gQ=hl(),kl=wl(),yI=Oe(),vQ=wI(),wQ=ls();function Al(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 kI(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let o=e[i];switch(o[0]){case"#":t+=(t===""?"":n?`
|
|
114
|
+
|
|
115
|
+
`:`
|
|
116
|
+
`)+(o.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 py=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,o)=>{let a=Al(r);o?this.warnings.push(new kl.YAMLWarning(a,n,i)):this.errors.push(new kl.YAMLParseError(a,n,i))},this.directives=new hQ.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=kI(this.prelude);if(n){let o=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
117
|
+
${n}`:n;else if(i||t.directives.docStart||!o)t.commentBefore=n;else if(yI.isCollection(o)&&!o.flow&&o.items.length>0){let a=o.items[0];yI.isPair(a)&&(a=a.key);let s=a.commentBefore;a.commentBefore=s?`${n}
|
|
118
|
+
${s}`:n}else{let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
119
|
+
${a}`:n}}if(r){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:kI(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(mQ.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let o=Al(t);o[0]+=r,this.onError(o,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=vQ.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 kl.YAMLParseError(Al(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 kl.YAMLParseError(Al(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=wQ.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}
|
|
120
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new kl.YAMLParseError(Al(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 gQ.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}}};AI.Composer=py});var RI=O(qf=>{"use strict";var yQ=cy(),kQ=uy(),AQ=wl(),bI=il();function bQ(e,t=!0,r){if(e){let n=(i,o,a)=>{let s=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(s,o,a);else throw new AQ.YAMLParseError([s,s+1],o,a)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return kQ.resolveFlowScalar(e,t,n);case"block-scalar":return yQ.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function NQ(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:o=-1,type:a="PLAIN"}=t,s=bI.stringifyString({type:a,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
121
|
+
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
122
|
+
`),u=s.substring(0,l),f=s.substring(l+1)+`
|
|
123
|
+
`,d=[{type:"block-scalar-header",offset:o,indent:n,source:u}];return NI(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
124
|
+
`}),{type:"block-scalar",offset:o,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:o,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:n,source:s,end:c};default:return{type:"scalar",offset:o,indent:n,source:s,end:c}}}function RQ(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:o=!1,type:a}=r,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!a)switch(e.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}let c=bI.stringifyString({type:a,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":SQ(e,c);break;case'"':hy(e,c,"double-quoted-scalar");break;case"'":hy(e,c,"single-quoted-scalar");break;default:hy(e,c,"scalar")}}function SQ(e,t){let r=t.indexOf(`
|
|
125
|
+
`),n=t.substring(0,r),i=t.substring(r+1)+`
|
|
126
|
+
`;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=n,e.source=i}else{let{offset:o}=e,a="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:o,indent:a,source:n}];NI(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:a,source:`
|
|
127
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:a,props:s,source:i})}}function NI(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 hy(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 o of n)o.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:`
|
|
128
|
+
`};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(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}qf.createScalarToken=NQ;qf.resolveAsScalar=bQ;qf.setScalarValue=RQ});var EI=O(SI=>{"use strict";var EQ=e=>"type"in e?Hf(e):Ff(e);function Hf(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Hf(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Ff(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Ff(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Ff(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 Ff({start:e,key:t,sep:r,value:n}){let i="";for(let o of e)i+=o.source;if(t&&(i+=Hf(t)),r)for(let o of r)i+=o.source;return n&&(i+=Hf(n)),i}SI.stringify=EQ});var xI=O(II=>{"use strict";var gy=Symbol("break visit"),CQ=Symbol("skip children"),CI=Symbol("remove item");function ia(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),_I(Object.freeze([]),e,t)}ia.BREAK=gy;ia.SKIP=CQ;ia.REMOVE=CI;ia.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let o=r?.[n];if(o&&"items"in o)r=o.items[i];else return}return r};ia.parentCollection=(e,t)=>{let r=ia.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 _I(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let o=t[i];if(o&&"items"in o){for(let a=0;a<o.items.length;++a){let s=_I(Object.freeze(e.concat([[i,a]])),o.items[a],r);if(typeof s=="number")a=s-1;else{if(s===gy)return gy;s===CI&&(o.items.splice(a,1),a-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}II.visit=ia});var Qf=O(_r=>{"use strict";var vy=RI(),_Q=EI(),IQ=xI(),wy="\uFEFF",yy="",ky="",Ay="",xQ=e=>!!e&&"items"in e,PQ=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function TQ(e){switch(e){case wy:return"<BOM>";case yy:return"<DOC>";case ky:return"<FLOW_END>";case Ay:return"<SCALAR>";default:return JSON.stringify(e)}}function OQ(e){switch(e){case wy:return"byte-order-mark";case yy:return"doc-mode";case ky:return"flow-error-end";case Ay:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
129
|
+
`:case`\r
|
|
130
|
+
`: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}_r.createScalarToken=vy.createScalarToken;_r.resolveAsScalar=vy.resolveAsScalar;_r.setScalarValue=vy.setScalarValue;_r.stringify=_Q.stringify;_r.visit=IQ.visit;_r.BOM=wy;_r.DOCUMENT=yy;_r.FLOW_END=ky;_r.SCALAR=Ay;_r.isCollection=xQ;_r.isScalar=PQ;_r.prettyToken=TQ;_r.tokenType=OQ});var Ry=O(TI=>{"use strict";var bl=Qf();function xn(e){switch(e){case void 0:case" ":case`
|
|
131
|
+
`:case"\r":case" ":return!0;default:return!1}}var PI=new Set("0123456789ABCDEFabcdef"),$Q=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Uf=new Set(",[]{}"),jQ=new Set(` ,[]{}
|
|
132
|
+
\r `),by=e=>!e||jQ.has(e),Ny=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===`
|
|
133
|
+
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
134
|
+
`:!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===`
|
|
135
|
+
`||!i&&!this.atEnd)return t+n+1}return r===`
|
|
136
|
+
`||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&xn(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(`
|
|
137
|
+
`,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]===bl.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let o=t[n-1];if(o===" "||o===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let o=t[r-1];if(o===" "||o===" ")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 bl.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==="...")&&xn(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&&!xn(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===":")&&xn(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(by),"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("..."))&&xn(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield bl.FLOW_END,yield*this.parseLineStart();let o=0;for(;i[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),i[o]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-o),"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(by),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||xn(a)||a===",")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 o=0;for(;this.buffer[r-1-o]==="\\";)o+=1;if(o%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
|
|
138
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=n.indexOf(`
|
|
139
|
+
`,o)}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=>xn(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let o=this.pos;n=this.buffer[o];++o)switch(n){case" ":r+=1;break;case`
|
|
140
|
+
`:t=o,r=0;break;case"\r":{let a=this.buffer[o+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if(a===`
|
|
141
|
+
`)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 o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
|
|
142
|
+
`,o)}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===`
|
|
143
|
+
`;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let o=t-1,a=this.buffer[o];a==="\r"&&(a=this.buffer[--o]);let s=o;for(;a===" ";)a=this.buffer[--o];if(a===`
|
|
144
|
+
`&&o>=this.pos&&o+1+r>s)t=o;else break}while(!0);return yield bl.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 o=this.buffer[n+1];if(xn(o)||t&&Uf.has(o))break;r=n}else if(xn(i)){let o=this.buffer[n+1];if(i==="\r"&&(o===`
|
|
145
|
+
`?(n+=1,i=`
|
|
146
|
+
`,o=this.buffer[n+1]):r=n),o==="#"||t&&Uf.has(o))break;if(i===`
|
|
147
|
+
`){let a=this.continueScalar(n+1);if(a===-1)break;n=Math.max(n,a-2)}}else{if(t&&Uf.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield bl.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(by),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(xn(n)||r&&Uf.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(;!xn(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($Q.has(r))r=this.buffer[++t];else if(r==="%"&&PI.has(this.buffer[t+1])&&PI.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===`
|
|
148
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
149
|
+
`?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)}};TI.Lexer=Ny});var Ey=O(OI=>{"use strict";var Sy=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 o=r+n>>1;this.lineStarts[o]<t?r=o+1:n=o}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}}}};OI.LineCounter=Sy});var _y=O(WI=>{"use strict";var DQ=Fu("process"),$I=Qf(),BQ=Ry();function ro(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function jI(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 BI(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 Jf(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 us(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 zf(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 DI(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!ro(t.start,"explicit-key-ind")&&!ro(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,BI(t.value)?t.value.end?zf(t.value.end,t.sep):t.value.end=t.sep:zf(t.start,t.sep),delete t.sep)}var Cy=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 BQ.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,DQ.env.LOG_TOKENS&&console.log("|",$I.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=$I.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"&&DI(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&&jI(i.start)===-1&&(r.indent===0||i.start.every(o=>o.type!=="comment"||o.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":{jI(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=Jf(this.peek(2)),n=us(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let o={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]=o}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(`
|
|
150
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
151
|
+
`,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)){zf(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",o=[];if(i&&r.sep&&!r.value){let a=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":a.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=r.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(o.push(this.sourceToken),t.items.push({start:o}),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?(o.push(this.sourceToken),t.items.push({start:o,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(ro(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(BI(r.key)&&!ro(r.sep,"newline")){let a=us(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:s,sep:c}]})}else o.length>0?r.sep=r.sep.concat(o,this.sourceToken):r.sep.push(this.sourceToken);else if(ro(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let a=us(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:o,key:null,sep:[this.sourceToken]}):ro(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 a=this.flowScalar(this.type);i||r.value?(t.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(a):(Object.assign(r,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(t);if(a){if(a.type==="block-seq"){if(!r.explicitKey&&r.sep&&!ro(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:o});this.stack.push(a);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)){zf(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||ro(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=Jf(n),o=us(i);DI(t);let a=t.end.splice(1,t.end.length);a.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:a}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
152
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
153
|
+
`,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=Jf(t),n=us(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=Jf(t),n=us(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())}}};WI.Parser=Cy});var FI=O(Rl=>{"use strict";var LI=my(),WQ=hl(),Nl=wl(),LQ=fw(),VQ=Oe(),MQ=Ey(),VI=_y();function MI(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new MQ.LineCounter||null,prettyErrors:t}}function qQ(e,t={}){let{lineCounter:r,prettyErrors:n}=MI(t),i=new VI.Parser(r?.addNewLine),o=new LI.Composer(t),a=Array.from(o.compose(i.parse(e)));if(n&&r)for(let s of a)s.errors.forEach(Nl.prettifyError(e,r)),s.warnings.forEach(Nl.prettifyError(e,r));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function qI(e,t={}){let{lineCounter:r,prettyErrors:n}=MI(t),i=new VI.Parser(r?.addNewLine),o=new LI.Composer(t),a=null;for(let s of o.compose(i.parse(e),!0,e.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new Nl.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(a.errors.forEach(Nl.prettifyError(e,r)),a.warnings.forEach(Nl.prettifyError(e,r))),a}function FQ(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=qI(e,r);if(!i)return null;if(i.warnings.forEach(o=>LQ.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function HQ(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 VQ.isDocument(e)&&!n?e.toString(r):new WQ.Document(e,n,r).toString(r)}Rl.parse=FQ;Rl.parseAllDocuments=qQ;Rl.parseDocument=qI;Rl.stringify=HQ});var dn=O(We=>{"use strict";var QQ=my(),UQ=hl(),JQ=zw(),Iy=wl(),zQ=Zc(),no=Oe(),KQ=Xi(),GQ=Nt(),YQ=eo(),XQ=to(),ZQ=Qf(),eU=Ry(),tU=Ey(),rU=_y(),Kf=FI(),HI=Kc();We.Composer=QQ.Composer;We.Document=UQ.Document;We.Schema=JQ.Schema;We.YAMLError=Iy.YAMLError;We.YAMLParseError=Iy.YAMLParseError;We.YAMLWarning=Iy.YAMLWarning;We.Alias=zQ.Alias;We.isAlias=no.isAlias;We.isCollection=no.isCollection;We.isDocument=no.isDocument;We.isMap=no.isMap;We.isNode=no.isNode;We.isPair=no.isPair;We.isScalar=no.isScalar;We.isSeq=no.isSeq;We.Pair=KQ.Pair;We.Scalar=GQ.Scalar;We.YAMLMap=YQ.YAMLMap;We.YAMLSeq=XQ.YAMLSeq;We.CST=ZQ;We.Lexer=eU.Lexer;We.LineCounter=tU.LineCounter;We.Parser=rU.Parser;We.parse=Kf.parse;We.parseAllDocuments=Kf.parseAllDocuments;We.parseDocument=Kf.parseDocument;We.stringify=Kf.stringify;We.visit=HI.visit;We.visitAsync=HI.visitAsync});import io from"path";import{isDeepStrictEqual as QI}from"node:util";function XI(e,t){return oa[t][e]}function iU(e,t,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let i=n[1].length,o=n[2];if(i===0&&o in oa.en)return o;if(i===2&&t){let a=`${t}.${o}`;if(a in oa.en)return a}if(i===4&&t==="knowledge"&&r==="remote"){let a=`knowledge.remote.${o}`;if(a in oa.en)return a}if(i===4&&t==="knowledge"&&r==="local"){let a=`knowledge.local.${o}`;if(a in oa.en)return a}return i===2&&t===null&&o==="hook"?"hook":i===2&&t==="hook"&&o==="allow_paths"?"hook.allow_paths":null}function Cl(e,t,r){let n=[],i=null,o=null;for(let g of(0,we.stringify)(e).trimEnd().split(`
|
|
154
|
+
`)){let v=iU(g,i,o);if(v){let w=g.match(/^\s*/u)?.[0]??"";for(let A of XI(v,t).split(`
|
|
155
|
+
`))n.push(`${w}${A}`)}n.push(g),/^[a-z_]+:/u.test(g)?(g.startsWith("native:")?i="native":g.startsWith("classic:")?i="classic":g.startsWith("hook:")?i="hook":g.startsWith("memory:")?i="memory":g.startsWith("knowledge:")?i="knowledge":i=null,o=null):/^ {2}[a-z_]+:/u.test(g)&&i==="knowledge"&&(o=g.startsWith(" local:")?"local":g.startsWith(" remote:")?"remote":null)}n.push("");let a=n.join(`
|
|
156
|
+
`);if(!r)return a;let s=(0,we.parseDocument)(r,{uniqueKeys:!0});if(s.errors.length>0)throw new Error(s.errors[0].message);let c=(0,we.parseDocument)(a);if(!(0,we.isMap)(s.contents)||!(0,we.isMap)(c.contents))return a;let l=g=>{if(!(0,we.isMap)(g))return;let v=g.items[0];g.commentBefore&&v&&(0,we.isScalar)(v.key)&&(v.key.commentBefore=[g.commentBefore,v.key.commentBefore].filter(Boolean).join(`
|
|
157
|
+
`),g.commentBefore=void 0);for(let w of g.items)l(w.value)};l(s.contents),l(c.contents);let u=s.toJS(),f=c.get("classic",!0);if((0,we.isMap)(f))for(let g of[...s.contents.items]){if(!(0,we.isScalar)(g.key)||c.has(g.key))continue;let v=String(g.key.value);if(!Object.hasOwn(oa.en,`classic.${v}`)||!f.has(v))continue;let w=s.get("classic",!0);if(!(0,we.isMap)(w)){let N=s.createPair("classic",{});s.contents.items.push(N),w=N.value}if(!(0,we.isMap)(w))continue;let A=w.items.find(N=>(0,we.isScalar)(N.key)&&N.key.value===v);A?((0,we.isScalar)(A.key)&&(A.key.commentBefore=[g.key.commentBefore,A.key.commentBefore].filter(Boolean).join(`
|
|
158
|
+
`)||void 0),(0,we.isNode)(A.value)&&(0,we.isNode)(g.value)&&(A.value.comment=[g.value.comment,A.value.comment].filter(Boolean).join(`
|
|
159
|
+
`)||void 0)):(w.items.push(g),u.classic={...u.classic,[v]:u[v]})}let d=new Set(Object.values(oa).flatMap(g=>Object.values(g).flatMap(v=>v.split(`
|
|
160
|
+
`).map(w=>w.replace(/^#\s?/u,"").trim())))),p=(g,v,w,A)=>{for(let N of[...g.items])v.has(N.key)||g.delete(N.key);for(let N of v.items){let b=String((0,we.isScalar)(N.key)?N.key.value:N.key),E=g.items.find(V=>(0,we.isScalar)(V.key)&&(0,we.isScalar)(N.key)?V.key.value===N.key.value:!1);if(!E){let V=s.createPair(b,A[b]);(0,we.isScalar)(V.key)&&(0,we.isScalar)(N.key)&&(V.key.commentBefore=N.key.commentBefore),g.items.push(V),(0,we.isMap)(V.value)&&(0,we.isMap)(N.value)&&p(V.value,N.value,A[b],A[b]);continue}if((0,we.isScalar)(E.key)&&(0,we.isScalar)(N.key)){let V=E.key.commentBefore?.split(`
|
|
161
|
+
`).filter(j=>!d.has(j.trim())).join(`
|
|
162
|
+
`);E.key.commentBefore=[N.key.commentBefore,V].filter(Boolean).join(`
|
|
163
|
+
`)||void 0}if((0,we.isMap)(E.value)&&(0,we.isMap)(N.value))p(E.value,N.value,w[b]??{},A[b]);else if(!QI(w[b],A[b])){let V=E.value;E.value=s.createNode(A[b]),(0,we.isNode)(V)&&(0,we.isNode)(E.value)&&(E.value.comment=V.comment,E.value.commentBefore=V.commentBefore,E.value.spaceBefore=V.spaceBefore)}}};p(s.contents,c.contents,u,e);let h=(g,v)=>{if((0,we.isAlias)(g)){let w=!1;try{w=QI(g.toJS(s),v)}catch{}if(w)return g;let A=s.createNode(v);return A.comment=g.comment,A.commentBefore=g.commentBefore,A.spaceBefore=g.spaceBefore,A}if((0,we.isMap)(g))for(let w of g.items){let A=String((0,we.isScalar)(w.key)?w.key.value:w.key);w.value=h(w.value,v[A])}else(0,we.isSeq)(g)&&Array.isArray(v)&&(g.items=g.items.map((w,A)=>h(w,v[A])));return g};h(s.contents,e);let m=s.toString();return r.includes(`\r
|
|
164
|
+
`)?m.replaceAll(`
|
|
165
|
+
`,`\r
|
|
166
|
+
`):m}function oU(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||io.posix.isAbsolute(r)||io.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 ds(e){let t=oU(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ZI(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 ao(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||io.posix.isAbsolute(n)||io.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(o=>o===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(o=>o===""||o==="."))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 oo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ex(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 aU(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 GI(e,t,r){let n=aU(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 sU(e){if(e===void 0)return;let t=oo(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,o=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(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let a;if(t.cleanup!==void 0){let s=oo(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");a={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:ds(n),toArtifactRoot:ds(i),stage:o,...a?{cleanup:a}:{}}}function cU(e){if(e===void 0)return;let t=oo(e,"native.finish");if(t.pull_request===void 0)return{};let r=oo(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((o,a)=>{if(typeof o!="string"||o.trim().length===0||o.length>4096||/[\0\r\n]/u.test(o))throw new Error(`native.finish.pull_request.command[${a}] must be a non-empty single-line string of at most 4096 characters`);return o});if(io.posix.isAbsolute(n[0])||io.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??nU;if(!Number.isSafeInteger(i)||i<1||i>KI)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${KI}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function lU(e,t={}){let r=oo(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 o=r.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let a=r.max_verify_failures??El;if(!Number.isSafeInteger(a)||a<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.max_parallel_children===void 0?Xf:r.max_parallel_children;if(!Number.isSafeInteger(s)||s<1)throw new Error("native.max_parallel_children must be a positive integer");let c=r.document_writes??"allow";if(c!=="allow"&&c!=="revert")throw new Error("native.document_writes must be allow or revert");let l=sU(r.pending_root_move),u=cU(r.finish);return{artifact_root:ds(n),language:ex(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:o,max_verify_failures:a,max_parallel_children:s,...c==="revert"?{document_writes:c}:{},...u?{finish:u}:{},...l?{pending_root_move:l}:{}}}function uU(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>zI)throw new Error(`${t} must be an integer between 1 and ${zI} milliseconds`);return e}function dU(e){let t=oo(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&&uU(t.check_timeout_ms,"classic.check_timeout_ms");let o=t.document_evidence??"neutral";if(o!=="neutral"&&o!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:ZI(t.artifact_layout),language:ex(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...o==="strict"?{document_evidence:o}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function fU(e){let r=oo(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)=>ao(n,`hook.allow_paths[${i}]`)))]}}function pU(e){if(e===void 0)return{...Gf};let t=oo(e,"memory"),r=t.learning??Gf.learning,n=t.retrieval??Gf.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 xy(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mU(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")||io.posix.isAbsolute(r)||io.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>UI)throw new Error(`${t} exceeds ${UI} 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>JI)throw new Error(`${t} contains more than ${JI} wildcard tokens`);return r}function hU(e){let t=xy(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,o)=>mU(i,`knowledge.local.include[${o}]`)))],max_file_mb:GI(t.max_file_mb,Yf.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:GI(t.max_total_mb,Yf.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 gU(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 vU(e){let t=xy(e,"knowledge.remote"),r=gU(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 o=t.timeout_ms??5e3;if(typeof o!="number"||!Number.isSafeInteger(o)||o<100||o>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:o}}function wU(e){if(e===void 0)return{...YI};let t=xy(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:hU(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:vU(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 Py(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function yU(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function kU(e,t,r,n,i,o,a,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let f=[...new Set(u)];if(!f.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(f.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:f,ambient_resume:a,change_walkthrough:Py(e.change_walkthrough),...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...o?{classic:o}:{}}}function fs(e,t={}){let r=(0,we.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,o=yU(i.ambient_resume),a=Py(i.change_walkthrough),s=i.hook===void 0?void 0:fU(i.hook),c=pU(i.memory),l=wU(i.knowledge),u=i.native===void 0?void 0:lU(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=i.classic===void 0?void 0:dU(i.classic),d=kU(i,s,c,l,u,f,o,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:d,ambient_resume:o,change_walkthrough:a,memory:c,knowledge:l,...s?{hook:s}:{},...u?{native:u}:{},...f?{classic:f}:{}}}function tx(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function rx(e){let t=e.knowledge??{...YI};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,change_walkthrough:e.change_walkthrough??!0,memory:e.memory??{...Gf},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??Yf.max_file_mb,max_total_mb:t.local.max_total_mb??Yf.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,max_parallel_children:e.native.max_parallel_children??Xf,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:tx(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.check_timeout_ms!==void 0?{check_timeout_ms:e.classic.check_timeout_ms}:{},...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function Fr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function _l(e,t){let r=rx({...t,change_walkthrough:t.change_walkthrough??Py(e.change_walkthrough)}),n=fs((0,we.stringify)(r)).config;if(!n)throw new Error("Unsupported Comet project schema");let i={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume,change_walkthrough:n.change_walkthrough??!0};if(n.hook&&(i.hook={...Fr(e.hook),allow_paths:[...n.hook.allow_paths]}),n.memory){let o=Fr(e.memory);i.memory={...o,learning:n.memory.learning,retrieval:n.memory.retrieval}}if(n.knowledge){let o=Fr(e.knowledge),a={...o,provider:n.knowledge.provider};if(n.knowledge.local?a.local={...Fr(o.local),include:[...n.knowledge.local.include],max_file_mb:n.knowledge.local.max_file_mb,max_total_mb:n.knowledge.local.max_total_mb}:delete a.local,n.knowledge.remote){let c={...Fr(o.remote),endpoint:n.knowledge.remote.endpoint,timeout_ms:n.knowledge.remote.timeout_ms,...n.knowledge.remote.token_env===void 0?{}:{token_env:n.knowledge.remote.token_env},...n.knowledge.remote.scope===void 0?{}:{scope:n.knowledge.remote.scope}};n.knowledge.remote.token_env===void 0&&delete c.token_env,n.knowledge.remote.scope===void 0&&delete c.scope,a.remote=c}else delete a.remote;i.knowledge=a}if(n.native){let o=Fr(e.native),a={...o,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,max_parallel_children:n.native.max_parallel_children,...n.native.document_writes?{document_writes:n.native.document_writes}:{}};if(t.native?.document_writes==="allow"&&delete a.document_writes,n.native.finish?.pull_request){let s=Fr(o.finish);a.finish={...s,pull_request:{...Fr(s.pull_request),provider:n.native.finish.pull_request.provider,command:[...n.native.finish.pull_request.command],timeout_ms:n.native.finish.pull_request.timeout_ms}}}else{let s={...Fr(o.finish)};delete s.pull_request,Object.keys(s).length>0?a.finish=s:delete a.finish}if(delete a.snapshot,n.native.pending_root_move){let s=Fr(o.pending_root_move),c=tx(n.native.pending_root_move),l=Fr(s.cleanup),u=Fr(c.cleanup);a.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete a.pending_root_move;i.native=a}return n.classic&&(i.classic={...Fr(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition,...n.classic.check_timeout_ms!==void 0?{check_timeout_ms:n.classic.check_timeout_ms}:{},...n.classic.document_evidence?{document_evidence:n.classic.document_evidence}:{}}),i}var we,Sl,UI,JI,El,Xf,Gf,Yf,YI,zI,nU,KI,oa,vi=_(()=>{"use strict";we=kr(dn(),1),Sl=Number.MAX_SAFE_INTEGER,UI=1024,JI=64,El=5,Xf=2,Gf={learning:!0,retrieval:!0},Yf={include:[],max_file_mb:1,max_total_mb:32},YI={provider:"local"},zI=36e5,nU=12e4,KI=6e5,oa={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",change_walkthrough:`# Generate a standalone HTML change walkthrough for Native and Classic. Enabling it uses extra explanation tokens.
|
|
167
|
+
# change_walkthrough: true | false (default: true)`,ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
168
|
+
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
169
|
+
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
170
|
+
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
171
|
+
# provider: local | remote`,"knowledge.local":"# Additional project-relative Markdown globs used by the local provider.","knowledge.local.include":"# One project-relative Markdown glob per list item; appended to the built-in corpus.","knowledge.local.max_file_mb":"# Maximum size in MB for one local Markdown document. Increase it for long specifications or verification reports.","knowledge.local.max_total_mb":"# Maximum total size in MB of the local Markdown retrieval corpus.","knowledge.remote":"# Fixed Comet Retrieval API v1 settings used when provider is remote.","knowledge.remote.endpoint":"# HTTPS endpoint; loopback HTTP is allowed.","knowledge.remote.token_env":"# Optional environment variable containing the bearer token.","knowledge.remote.scope":"# Optional opaque remote knowledge scope.","knowledge.remote.timeout_ms":"# Remote request timeout in milliseconds (100-30000).",hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
|
|
172
|
+
# language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
|
|
173
|
+
# clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
|
|
174
|
+
# archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.max_parallel_children":"# Maximum dispatched Supervisor children awaiting integration and archive. Defaults to 2; single-session always uses 1. Changes apply at the next dispatch.","native.document_writes":`# Controls documentation file writes during Shape, Verify, and Archive: allow treats them as neutral instead of returning the change to Build, revert restores the strict behavior.
|
|
175
|
+
# document_writes: allow | revert`,"native.finish":"# Optional repository-owned finish providers. Native keeps commit, push, generic remote verification, and recovery ownership.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
|
|
176
|
+
# artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
|
|
177
|
+
# language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
|
|
178
|
+
# context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
|
|
179
|
+
# review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
|
|
180
|
+
# auto_transition: true | false`,"classic.check_timeout_ms":"# Default check timeout in milliseconds (1-3600000); --timeout-ms overrides it. Default: 300000.","classic.document_evidence":`# Controls how documentation edits affect recorded check evidence: neutral keeps build and verify evidence valid when only documentation files changed, strict binds every working-tree file again.
|
|
181
|
+
# document_evidence: neutral | strict`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",change_walkthrough:`# 是否生成可直接打开的 HTML 变更说明,同时作用于 Native 和 Classic;开启会增加讲解内容的 token 消耗。
|
|
182
|
+
# change_walkthrough: true | false(默认 true)`,ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
|
|
183
|
+
# ambient_resume: true | false`,memory:"# 当前项目的个人记忆自动学习与注入策略。","memory.learning":`# 是否允许当前项目通过工作流事件自动沉淀新的个人记忆。
|
|
184
|
+
# 可选值:true | false`,"memory.retrieval":`# 是否允许当前项目把个人记忆自动注入 Agent 上下文。
|
|
185
|
+
# 可选值:true | false`,knowledge:"# 普通 Comet 任务使用的项目知识检索 Provider。","knowledge.provider":`# 项目知识 Provider。
|
|
186
|
+
# 可选值:local | remote`,"knowledge.local":"# Local Provider 额外加载的项目相对 Markdown 路径。","knowledge.local.include":"# 每项填写一个项目相对 Markdown glob;会追加到内置语料。","knowledge.local.max_file_mb":"# 单个本地 Markdown 文档允许参与检索的最大 MB 数;较长的规格或验证报告可按需提高。","knowledge.local.max_total_mb":"# 本地 Markdown 检索语料允许读取的总 MB 数。","knowledge.remote":"# provider 为 remote 时使用的固定 Comet Retrieval API v1 配置。","knowledge.remote.endpoint":"# HTTPS 地址;loopback 地址允许使用 HTTP。","knowledge.remote.token_env":"# 可选的 Bearer Token 环境变量名。","knowledge.remote.scope":"# 可选的不透明远端知识库范围。","knowledge.remote.timeout_ms":"# 远端请求超时时间(毫秒,100-30000)。",hook:"# Native 和 Classic 共享的 Hook 写入策略;路径必须是项目相对路径。","hook.allow_paths":"# 在受保护阶段允许写入的项目相对目录;每项填写一个目录,默认为空。",native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
|
|
187
|
+
# 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
|
|
188
|
+
# 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
|
|
189
|
+
# 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.max_parallel_children":"# Supervisor 已派发且尚未完成集成归档的子任务上限;默认 2,single-session 固定为 1;调整从下一轮派发生效。","native.document_writes":`# Shape、Verify 和 Archive 阶段的文档类写入处理方式:allow 视为中性写入、不再把 change 打回 Build,revert 恢复严格行为。
|
|
190
|
+
# 可选值:allow | revert`,"native.finish":"# 可选的仓库自有收尾 provider;提交、推送、通用远端核验和恢复仍由 Native 负责。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
|
|
191
|
+
# 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
|
|
192
|
+
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
193
|
+
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
194
|
+
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
195
|
+
# 可选值:true | false`,"classic.check_timeout_ms":"# 检查命令默认超时,单位毫秒,范围 1-3600000,缺省为 300000;命令行 --timeout-ms 优先。","classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
196
|
+
# 可选值:neutral | strict`}}});import{promises as Ir}from"fs";import Le from"path";import{AsyncLocalStorage as AU}from"node:async_hooks";async function Zf(e,t,r={}){let n=Le.resolve(e),i=await Oy(n,t),o=new Map,a=!1,s=d=>[d.dev,d.ino,d.mode,d.birthtimeNs,d.mtimeNs,d.ctimeNs].join(":"),c=d=>[d.dev,d.ino,d.mode,d.birthtimeNs].join(":"),l=async(d,p)=>JSON.stringify((await Ir.readdir(d,{withFileTypes:!0})).filter(h=>!p(h)).map(h=>[h.name,h.isDirectory(),h.isSymbolicLink()]).sort((h,m)=>String(h[0]).localeCompare(String(m[0]),"en"))),u=d=>{let p=o.get(d);return p||(p=(async()=>{let h=await Ir.lstat(d,{bigint:!0});if(!h.isDirectory()||h.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Le.relative(n,d)||"."}`);let m=await Ir.realpath(d);if(!ps(i,m))throw new Error(`${t} resolves outside the project root`);let g=r.ignoredDirectoryEntries?.(Le.relative(n,d).replaceAll("\\","/")||".");return{stat:h,real:m,...g?{ignoreEntry:g,namespace:await l(d,g)}:{}}})(),p=p.catch(h=>{throw o.delete(d),h}),o.set(d,p)),p};await u(n);let f=async d=>{if(a)throw new Error(`${t} read session is already finished`);let p=ao(d,t),h=n;for(let m of p.split("/").slice(0,-1))h=Le.join(h,m),await u(h);return Le.resolve(n,...p.split("/"))};return{observePath:f,async observeDirectory(d){let p=await f(d);return await u(p),p},async stat(d){let p=await f(d),h=await Ir.lstat(p,{bigint:!0});if(!h.isFile()||h.isSymbolicLink())throw new Error(`${t} must be a real file: ${d}`);return{target:p,stat:h}},async hash(d){let p=await f(d);return wN(p,{bigint:!0,label:`${t} ${d}`,verify:async(h,m)=>{if(!ps(i,m.realPath))throw new Error(`${t} resolves outside the project root`);let g=n,v=[n];for(let w of Le.relative(n,Le.dirname(p)).split(Le.sep).filter(Boolean))g=Le.join(g,w),v.push(g);for(let w of v){let A=await o.get(w),N=await Ir.lstat(w,{bigint:!0});if(!N.isDirectory()||N.isSymbolicLink()||c(N)!==c(A.stat))throw new Error(`${t} directory changed while reading: ${Le.relative(n,w)||"."}`)}}})},async read(d,p,h={}){let m=await f(d);return Io(m,p,{...h,label:`${t} ${d}`,verify:async(g,v)=>{if(!ps(i,v.realPath))throw new Error(`${t} resolves outside the project root`);if(r.deferDirectoryChecks)return;let w=n,A=[n];for(let N of Le.relative(n,Le.dirname(m)).split(Le.sep).filter(Boolean))w=Le.join(w,N),A.push(w);for(let N of A){let b=await o.get(N),E=await Ir.lstat(N,{bigint:!0});if(!E.isDirectory()||E.isSymbolicLink()||c(E)!==c(b.stat))throw new Error(`${t} directory changed while reading: ${Le.relative(n,N)||"."}`)}}})},async finish(d={}){if(a)throw new Error(`${t} read session is already finished`);a=!0;let p=[];for(let[h,m]of o){let g=await m,v=await Ir.lstat(h,{bigint:!0});if(!v.isDirectory()||v.isSymbolicLink()||c(g.stat)!==c(v)||!d.allowDirectoryContentChanges&&s(g.stat)!==s(v)&&(!g.ignoreEntry||await l(h,g.ignoreEntry)!==g.namespace)||await Ir.realpath(h)!==g.real)throw new Error(`${t} directory changed while observing: ${Le.relative(n,h)||"."}`);s(g.stat)!==s(v)&&p.push(Le.relative(n,h).replaceAll("\\","/")||".")}return{changedDirectories:p}}}}function nx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ps(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}async function Oy(e,t){let r=Le.resolve(e),n=await ix(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ox(r)}async function ax(e,t,r,n){let i=e;for(let o=0;o<r.length;o++){i=Le.join(i,r[o]);let a;try{a=await ix(i)}catch(l){if(nx(l))return{exists:!1,kind:"missing"};throw l}if(a.isSymbolicLink()){let l=Le.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} crosses a symbolic link or junction at ${l}`)}let s=o===r.length-1;if(!s&&!a.isDirectory()){let l=Le.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} ancestor ${l} must be a real directory`)}if(s&&(n.expected==="file"&&!a.isFile()||n.expected==="directory"&&!a.isDirectory()||n.expected==="any"&&!a.isFile()&&!a.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let c=await ox(i);if(!NU(t,c))throw new Error(`${n.label} resolves outside the project root`);if(s)return{exists:!0,kind:a.isFile()?"file":a.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function sx(e,t,r){let n=ao(t,r.label),i=Le.resolve(e),o=await Oy(i,r.label),a=n.split("/"),s=Le.resolve(i,...a);if(!ps(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await ax(i,o,a,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function oe(e,t,r){if(r.expected===void 0)return sx(e,t,r);try{return await RU(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 Vt(e,t,r){let n=ao(t,r.label),i=Le.resolve(e),o=await Oy(i,r.label),a=n.split("/"),s=i;for(let c of a){s=Le.join(s,c);let l;try{l=await Ir.lstat(s)}catch(d){if(!nx(d))throw d;try{await Ir.mkdir(s)}catch(p){if(p.code!=="EEXIST")throw p}l=await Ir.lstat(s)}let u=Le.relative(i,s).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${u}`);if(!l.isDirectory())throw new Error(`${r.label} directory ${u} must be a real directory`);let f=await Ir.realpath(s);if(!ps(o,f))throw new Error(`${r.label} resolves outside the project root`)}return await ax(i,o,a,{label:r.label,expected:"directory"}),s}async function cx(e,t,r,n){let i=!n.hooks&&!n.bigint?bU.getStore():void 0;if(i){let s=Le.resolve(e),c=i.get(s);return c||(c=Zf(s,n.label,{deferDirectoryChecks:!0}).catch(l=>{throw i.delete(s),l}),i.set(s,c)),(await c).read(t,r,n)}let o=await Zf(e,n.label),a=await o.read(t,r,n);return await o.finish({allowDirectoryContentChanges:!0}),a}async function qe(e,t,r,n){if(n.hooks||n.bigint)return cx(e,t,r,n);try{return await SU(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(Ty)&&(i.message=i.message.replaceAll(Ty,n.label)),i}}var bU,ix,ox,NU,RU,Ty,SU,ct=_(()=>{"use strict";Di();vi();bn();bU=new AU;ix=Qt("protectedChainLstat",e=>Ir.lstat(e)),ox=Qt("protectedChainRealpath",e=>Ir.realpath(e)),NU=ai("protectedChainInside",ps);RU=Qt("protectedInspectPath",(e,t,r)=>sx(e,t,{label:"Protected project path",expected:r}));Ty="Cached protected project read",SU=Qt("protectedReadFile",(e,t,r)=>cx(e,t,r,{label:Ty}))});function ux(e){return ep(e).encoded}function ep(e){let t=new WeakMap,r=new Map,n=u=>{if(typeof u=="string"){let h=r.get(u);return h===void 0&&(h=JSON.stringify(u).length,r.set(u,h)),h}if(u===null||typeof u!="object")return JSON.stringify(u).length;let f=lx.get(u)??t.get(u);if(f!==void 0)return f;let d=Object.entries(u),p=2+Math.max(0,d.length-1)+d.reduce((h,[m,g])=>h+(Array.isArray(u)?0:n(m)+1)+n(g),0);return t.set(u,p),en(u)&&lx.set(u,p),p},i=n(e),o=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return o();let a=[],s=(u,f)=>{if(!u||typeof u!="object")return;let d=u;if(!(d.protocolVersion!==1||!Array.isArray(d.actions)||!d.actionContexts)){for(let[p,h]of d.actions.entries())h.input&&typeof h.input=="object"&&Object.hasOwn(h.input,"outputs")&&a.push({path:[...f,"actions",String(p),"input","outputs"],group:"outputs"});for(let[p,h]of Object.entries(d.actionContexts))h?.results&&a.push({path:[...f,"actionContexts",p,"results"],group:"results"});d.outputs&&a.push({path:[...f,"outputs"],group:"results"});for(let p of["ready","waits","evidenceWaits"])for(let[h,m]of(d[p]??[]).entries())m.results&&a.push({path:[...f,p,String(h),"results"],group:"results"})}};if(s(e,[]),s(e.run,["run"]),!a.length)return o();let c=EN(e,a,en),l=JSON.stringify(c);return l.length<i*.9?{encoded:c,json:l}:o()}var lx,$y=_(()=>{"use strict";xo();lr();lx=new WeakMap});import{createHash as fx,randomUUID as qX}from"node:crypto";import{types as EU}from"node:util";import{promises as fn}from"node:fs";import Rt from"node:path";function aa(e){if(typeof e!="string"||e.trim().length===0)throw new k("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function CU(e){return aa(e),fx("sha256").update(JSON.stringify(e)).digest("hex")}function tp(e){if(!Number.isSafeInteger(e)||e<1)throw new k("STORE_INVALID_REVISION","revision 必须是正安全整数")}function _U(e,t,r,n=!0){if(aa(e),EU.isProxy(r))throw new k("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&tp(t),tn(r);let i=n?structuredClone(r):r;if(!i||typeof i!="object"||Array.isArray(i)||i.runId!==e)throw new k("STORE_INVALID_RUN_ID","next.runId 必须与目标 runId 一致");if(tp(i.revision),i.revision!==(t??0)+1)throw new k("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}function IU(e,t,r){let n=nt(r);if(aa(e),!n||n.runId!==e)throw new k("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(tp(n.revision),t!==null&&t!==1||n.revision<=(t??0))throw new k("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(n)}function px(e,t,r){let n=nt(e);n.revision=t;for(let i of r){let o=n;for(let a of i.slice(0,-1))o=o[a];o[i.at(-1)]=t}return n}function xU(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||Mn(e)===Mn(px(r,1,n)))}function St(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new k("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(C=>{if(C!=="run.revision")throw new k("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function r(C){for(let R of t){let I=C;for(let D of R){if(!I||typeof I!="object"||Array.isArray(I)||!Object.hasOwn(I,D))throw new k("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");I=I[D]}if(I!==C.revision)throw new k("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let n=Rt.resolve(e.rootDir),i=Rt.parse(n).root,o=Rt.relative(i,n).replaceAll("\\","/");if(!o)throw new k("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let a={label:"RuntimeStore root",expected:"directory"},s=CU,c="checkpoint.json",l="comet.runtime-store-format.v2",u=".runtime-store-v2",f=C=>`${u}/${s(C)}`,d=C=>`.runtime-store-history/${s(C)}`,p="comet.runtime-store-format.v3",h="comet.runtime-store-snapshot.v2",m=".write.lock",g=/^[0-9]{16}\.json$/u;function v(){return{record:null,compacted:!1,legacyRevision:null,formatPresent:!1}}async function w(C,R){let I=await qe(n,C?`${C}/${R}`:R,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let D=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(I.bytes));return tn(D),D}catch{throw new k("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function A(C,R,I){if(!C||typeof C!="object"||Array.isArray(C)||C.runId!==R||C.revision!==I||!Number.isSafeInteger(I)||I<1)throw new k("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");r(C)}async function N(C,R=!1,I=s(C),D=!0){if(aa(C),!(await oe(i,o,a)).exists)return v();let L=await oe(n,I,{label:"RuntimeStore run",expected:"directory"});if(!L.exists)return v();let q=await fn.lstat(L.target),H=await fn.readdir(L.target,{withFileTypes:!0}),ne=await fn.lstat(L.target);if(await oe(i,`${o}/${I}`,a),!q.isDirectory()||q.isSymbolicLink()||!ne.isDirectory()||ne.isSymbolicLink()||!ft({dev:q.dev,ino:q.ino,birthtime:q.birthtimeMs},{dev:ne.dev,ino:ne.ino,birthtime:ne.birthtimeMs}))throw new k("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let Y=new Set,ue=[],le=0;for(let W of H){if((W.name===`${m}.contenders`||W.name==="legacy"&&I===f(C))&&W.isDirectory()&&!W.isSymbolicLink())continue;if(!W.isFile()||W.isSymbolicLink())throw new k("STORE_INVALID_ENTRY",`版本文件无效:${W.name}`);if(/^\..+\.tmp$/u.test(W.name)||W.name===m||[m+".sqlite",m+".sqlite-journal",m+".sqlite-wal",m+".sqlite-shm"].includes(W.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(W.name)||(Y.add(W.name),W.name===c))continue;if(!g.test(W.name))throw new k("STORE_INVALID_ENTRY",`版本文件无效:${W.name}`);let me=Number(W.name.slice(0,-5));if(!Number.isSafeInteger(me)||me<1)throw new k("STORE_INVALID_ENTRY",`版本文件无效:${W.name}`);ue.push(W.name),le=Math.max(le,me)}let y=!1;if([f(C),d(C)].includes(I)&&ue.length>0)throw new k("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(Y.has(c)){if(![f(C),d(C)].includes(I))throw new k("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let W=await w(I,c),me=W?.record,te=W?.legacyRevision;if(!W||![h,"comet.runtime-store-snapshot.v3"].includes(String(W.schema))||!me||Object.keys(W).some(at=>!["schema","record","hash","legacyRevision",...W.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(at))||te!==null&&(!Number.isSafeInteger(te)||te<1||te>me.revision)||W.hash!==$({record:me,legacyRevision:te,...W.schema==="comet.runtime-store-snapshot.v3"?{pool:W.pool}:{}}))throw new k("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let Ae;try{Ae=W.schema==="comet.runtime-store-snapshot.v3"?Yu(me,W.pool,D):me}catch(at){throw new k("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${at instanceof Error?at.message:String(at)}`)}return A(Ae,C,Ae.revision),{record:Ae,compacted:!0,legacyRevision:te,formatPresent:y}}if(!le)return v();let S=new Map,T=W=>`${String(W).padStart(16,"0")}.json`,x=W=>Y.has(T(W));async function P(W){if(S.has(W))return S.get(W);let me=await w(I,T(W));return(W<=2||W===le)&&S.set(W,me),me}async function Q(W,me=0,te=le){if(A(W,C,te),R)for(let Ae of ue){let at=Number(Ae.slice(0,-5));at!==me&&A(await P(at),C,at)}return{record:W,compacted:!1,legacyRevision:W.revision,formatPresent:!1}}let J=await P(le);if(le===ue.length&&(J?.schema!==dx||J?.runId!==void 0))return Q(J);if(!x(1))throw new k("STORE_MISSING_REVISION","版本历史缺少 revision 1");let K=null;for(let W of[1,2]){if(!x(W))break;let me=await P(W);if(me?.schema!==dx||"runId"in me)continue;let te=me.record;if(te&&r(te),!te||te.runId!==C||!Number.isSafeInteger(te.revision)||te.revision<W||me.hash!==$(te)||Object.keys(me).some(Ae=>!["schema","record","hash"].includes(Ae))||W===2&&Mn(await P(1))!==Mn(px(te,1,t)))throw new k("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");K={slot:W,record:te};break}let U=K?.record.revision??0,G=K?.slot??0,ie=le===G?U:le;if(ie<U||ue.length!==ie-U+G||ue.some(W=>{let me=Number(W.slice(0,-5));return me>G&&me<=U})){let W=U+1;for(;x(W);)W+=1;throw new k("STORE_MISSING_REVISION",`版本历史缺少 revision ${W}`)}return Q(K&&le===K.slot?K.record:J,G,K&&le===K.slot?K.record.revision:le)}async function b(C){let R=await oe(n,s(C),{label:"RuntimeStore format",expected:"any"}),I=await oe(n,`${f(C)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(R.kind==="directory"&&I.exists&&(R=await oe(n,s(C),{label:"RuntimeStore format",expected:"any"})),R.kind==="directory"&&I.exists)throw new k("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let D=null;if(R.kind==="file"){let L=await w("",s(C));if(!L||L.runId!==C||(L.schema===l?!["pending","ready"].includes(L.state)||Object.keys(L).some(q=>!["schema","runId","state","writerProtocol"].includes(q)):L.schema!==p||!["closing","closed","reopening"].includes(L.state)||!Number.isSafeInteger(L.revision)||L.revision<1||typeof L.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(L.recordHash)||Object.keys(L).some(q=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(q))))throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(L.writerProtocol!==void 0&&L.writerProtocol!=="application-holder-v1")throw new k("STORE_WRITER_FENCED","存储协议版本不受支持");D=L}return{original:R,staged:I,marker:D}}function E(C){return fc(C)?Nn(C,{cachePrefixes:!1}):$(C)}async function V(C,R){let I=await N(C,!1,f(C),!1),D=await N(C,!1,d(C),!1);if(!I.record&&!D.record||R.state==="closed"&&(I.record||!D.record))throw new k("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(I.record&&D.record){let q=await fn.lstat(Rt.join(n,f(C),c)),H=await fn.lstat(Rt.join(n,d(C),c)),ne={dev:q.dev,ino:q.ino,birthtime:q.birthtimeMs},Y={dev:H.dev,ino:H.ino,birthtime:H.birthtimeMs};if(!lc(ne,Y)||!ft(ne,Y))throw new k("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let L=D.record??I.record;if(L.revision!==R.revision||E(L)!==R.recordHash||I.record&&I.record!==L&&E(I.record)!==R.recordHash)throw new k("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:L,active:!!I.record,history:!!D.record}}async function j(C){if(aa(C),!(await oe(i,o,a)).exists)return"missing";let R=await b(C),I=await oe(n,`${f(C)}/${c}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),D=await oe(n,`${d(C)}/${c}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(R.marker?.schema===p){if(!I.exists&&!D.exists||R.marker.state==="closed"&&(I.exists||!D.exists))throw new k("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return R.marker.state}if(D.exists)throw new k("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return R.marker||I.exists||R.original.kind==="directory"||R.staged.exists?"active":"missing"}async function z(C,R,I){await Lt(Rt.join(n,s(C)),JSON.stringify({schema:p,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:C,state:R,revision:I.revision,recordHash:E(I)})+`
|
|
197
|
+
`,{containedRoot:n,requireAtomicPublication:!0})}async function X(C){let R=(await b(C)).marker;if(!R||!["closing","reopening"].includes(R.state))return;let I=R.state==="closing",D=(await V(C,R)).record,L=await V(C,R),q=I?f(C):d(C),H=I?d(C):f(C);await Vt(n,H,{label:"RuntimeStore 历史目标"});let ne=Rt.join(n,q,c),Y=Rt.join(n,H,c),ue=I?L.active:L.history;(I?L.history:L.active)||(await oe(n,`${q}/${c}`,{label:"RuntimeStore 历史源",expected:"file"}),await oe(n,H,{label:"RuntimeStore 历史目标",expected:"directory"}),await fn.link(ne,Y),await V(C,R)),await Xe(Rt.dirname(Y)),await Xe(Rt.dirname(Rt.dirname(Y))),await Xe(n),ue&&(await V(C,R),await Xo(ne,{containedRoot:n,beforeRemove:async()=>{await V(C,R)}}),await Xe(Rt.dirname(ne))),I?await z(C,"closed",D):await Z(C,"ready",!1);let y=await se(C,!1);if(!y||y.revision!==D.revision||E(y)!==E(D))throw new k("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function de(C,R,I){return aa(C),tp(R),Ht(C,async()=>{await X(C);let D=(await b(C)).marker,L;if(D?.schema===p){if(I&&D.state==="reopening")throw new k("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!I&&D.state==="closing")throw new k("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(L=(await V(C,D)).record,L.revision!==R)return!1;if(I&&D.state==="closed")return!0}else{if(L=(await pe(C,!1)).record,!L||L.revision!==R)return!1;if(!I)return!0}return await z(C,I?"closing":"reopening",L),await X(C),!0})}async function se(C,R=!0){if(aa(C),!(await oe(i,o,a)).exists)return null;let I=await b(C);if(I.marker?.schema===p){let{record:q}=await V(C,I.marker);return R?cr(q):q}if((await N(C,!1,d(C),!1)).record)throw new k("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let L=await N(C,!1,f(C),R);if(L.record){if(!I.marker&&!(await b(C)).marker)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return L.record}if(I.original.kind==="directory"){let q=(await N(C)).record;if(!q&&(await b(C)).original.kind!=="directory")throw new k("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return q}if(I.marker?.state==="ready")throw new k("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(I.staged.exists){let q;try{q=(await N(C,!1,`${f(C)}/legacy`)).record}catch(H){throw(await b(C)).marker?.state==="ready"?new k("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):H}if(!q){let H=await b(C);if(!H.staged.exists||H.marker?.state==="ready")throw new k("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return q}return null}async function De(C,R=!0){for(let I=0;;I+=1)try{return await se(C,R)}catch(D){let L=D instanceof Ut&&D.reason==="changed",q=["ENOENT","ENOTDIR"].includes(D.code??""),H=D instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(D.message);if(!L&&!q&&!H||I>=15)throw D}}async function Z(C,R,I){await Lt(Rt.join(n,s(C)),JSON.stringify({schema:l,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:C,state:R})+`
|
|
198
|
+
`,{containedRoot:n,exclusive:I,requireAtomicPublication:!0})}async function Xe(C){let R;try{R=await fn.open(C,"r"),await R.sync()}catch(I){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(I.code??""))throw I}finally{await R?.close()}}async function Ht(C,R){if(await Vt(i,o,a),(await oe(n,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new k("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await Vt(n,f(C),{label:"RuntimeStore run"}),await Xe(Rt.join(n,u)),await Xe(n);try{return e.singleWriter?await R():await YE(Rt.join(n,f(C),m),R)}catch(D){throw["ENOTSUP","EOPNOTSUPP"].includes(D.code??"")?new k("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):D}}async function B(C,R,I,D=ep(R)){let L=Rt.join(n,f(C)),q=I.legacyRevision,{encoded:H,json:ne}=D,Y=H.pool?{record:H.record,legacyRevision:q,pool:H.pool}:{record:R,legacyRevision:q},ue=H.pool?"comet.runtime-store-snapshot.v3":h,le=`{"schema":${JSON.stringify(ue)},${ne.slice(1,-1)},"legacyRevision":${JSON.stringify(q)},"hash":${JSON.stringify($(Y))}}
|
|
199
|
+
`;await Lt(Rt.join(L,c),le,{containedRoot:n,exclusive:!I.compacted,requireAtomicPublication:!0}),I.formatPresent||await Z(C,"ready",!1)}async function ee(C,R){if(R===null)return;let I=`${f(C)}/legacy`,D=await oe(n,I,{label:"RuntimeStore legacy",expected:"directory"});if(D.exists)try{for(let L of await fn.readdir(D.target,{withFileTypes:!0}))L.isFile()&&!L.isSymbolicLink()&&g.test(L.name)&&Number(L.name.slice(0,-5))<=R&&await Xo(Rt.join(D.target,L.name),{containedRoot:n});await oe(n,I,{label:"RuntimeStore legacy",expected:"directory"}),await fn.rmdir(D.target).catch(L=>{if(L.code!=="ENOTEMPTY"&&L.code!=="EEXIST")throw L})}catch(L){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${L instanceof Error?L.message:String(L)}
|
|
200
|
+
`)}}async function pe(C,R=!0){let I=(await b(C)).marker;if(I?.writerProtocol&&I.writerProtocol!==e.writerProtocol)throw new k("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await X(C);let D=await b(C);if(D.marker?.schema===p)throw new k("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await N(C,!1,d(C),!1)).record)throw new k("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let q=await N(C,!1,f(C),R);if(q.record&&!D.marker)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(D.original.kind==="directory"){await N(C,!0);let ne=await fn.lstat(D.original.target);await oe(i,`${o}/${s(C)}`,a),await oe(n,f(C),a),await fn.rename(D.original.target,D.staged.target);let Y=await fn.lstat(D.staged.target);if(!Y.isDirectory()||Y.isSymbolicLink()||!ft({dev:ne.dev,ino:ne.ino,birthtime:ne.birthtimeMs},{dev:Y.dev,ino:Y.ino,birthtime:Y.birthtimeMs}))throw new k("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await Xe(Rt.join(n,f(C))),await Xe(n),D=await b(C)}if(!D.marker){try{await Z(C,"pending",!0)}catch(ne){throw["EEXIST","EISDIR","ENOTDIR"].includes(ne.code??"")?new k("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):ne}D=await b(C)}let H=q;if(!H.record&&D.marker?.state==="ready")throw new k("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!H.record&&D.staged.exists?(H=await N(C,!0,`${f(C)}/legacy`),H.record&&(await B(C,H.record,H),H={...H,compacted:!0,formatPresent:!0})):H.record&&D.marker?.state==="pending"&&await Z(C,"ready",!1),H.record&&(H.formatPresent=!0,await ee(C,H.legacyRevision)),H}return{queryScope:`file:${fx("sha256").update(n).digest("hex")}`,read:De,readProjection:C=>De(C,!1),readPartitionMetadata:j,settleRun:C=>An(async()=>await j(C)==="missing"?"missing":Ht(C,async()=>{await X(C);let R=(await b(C)).marker;return R&&e.writerProtocol&&R.writerProtocol!==e.writerProtocol&&await Lt(Rt.join(n,s(C)),JSON.stringify({...R,writerProtocol:e.writerProtocol})+`
|
|
201
|
+
`,{containedRoot:n,requireAtomicPublication:!0}),j(C)})),closeRun:(C,R)=>An(()=>de(C,R,!0)),reopenRun:(C,R)=>An(()=>de(C,R,!1)),async readDisposition(C){if(!await De(C,!1))return"missing";let I=(await b(C)).marker;return I?.schema===p?I.state:"active"},async restoreCheckpoint(C,R,I){let D=JSON.parse(IU(C,R,I));return r(D),Ht(C,async()=>{let L=await pe(C);return xU(L.record,R,D,t)?(await B(C,D,L),!0):!1})},compareAndSwap:async(C,R,I)=>kt(C,R,I)(),prepareCompareAndSwap:kt};function kt(C,R,I){_U(C,R,I,!1),r(I);let{json:D}=ep(I),L=JSON.parse(D);return()=>Ht(C,async()=>{let q=await pe(C,!1);return(q.record?.revision??null)!==R?!1:(await B(C,L.record,q,{encoded:L,json:D}),!0)})}}var dx,jy=_(()=>{"use strict";$a();Di();XE();Jn();ct();lr();bn();Zr();$y();xo();dx="comet.runtime-store-checkpoint.v1"});import{createHash as mx}from"node:crypto";import{promises as wi}from"node:fs";import so from"node:path";async function Dy(e){let t=so.resolve(e.rootDir),r=so.parse(t).root,n=so.relative(r,t).replaceAll("\\","/");if(!n)throw new k("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");if(!(await oe(r,n,{label:"RuntimeStore discovery",expected:"directory"})).exists)return[];let i=[];for(let o of await wi.readdir(t,{withFileTypes:!0}))if(!(/^\.[a-f0-9]{64}\.[a-f0-9-]{36}\.tmp$/u.test(o.name)&&o.isFile()&&!o.isSymbolicLink())&&o.name!==".runtime-store-coordination"){if([".runtime-store-v2",".runtime-store-history"].includes(o.name)){let a=await oe(t,o.name,{label:"RuntimeStore checkpoint directory",expected:"directory"});for(let s of await wi.readdir(a.target))i.push(s);continue}i.push(o.name)}return[...new Set(i)].sort((o,a)=>o.localeCompare(a))}async function PU(e,t,r,n=!1){let i=so.resolve(e.rootDir),o=r?[...new Set(r)].filter(d=>d&&d!=="."&&d!==".."&&!d.includes("/")&&!d.includes("\\")):await Dy(e),a=r?new Set(r):null,s=[],c=async d=>{let p=await oe(i,d,{label:"RuntimeStore source",expected:"file"});if(!p.exists)return null;let h=await wi.lstat(p.target);return[d,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.dev]},l=async d=>{let p=await oe(i,d,{label:"RuntimeStore source directory",expected:"directory"});if(!p.exists)return null;let h=await wi.lstat(p.target),m=(await wi.readdir(p.target,{withFileTypes:!0})).map(g=>[g.name,g.isFile(),g.isDirectory(),g.isSymbolicLink()]).sort((g,v)=>String(g[0]).localeCompare(String(v[0])));return[d,h.mtimeMs,h.ctimeMs,h.ino,h.dev,m]},u=async d=>JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await qe(i,d,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore discovery record"})).bytes)),f=n?8:1;for(let d=0;d<o.length;d+=f)await Promise.all(o.slice(d,d+f).map(async p=>{if(a&&!a.has(p))return;let h=await wi.lstat(so.join(i,p)).catch(()=>null),m={name:p,isFile:()=>h?.isFile(),isDirectory:()=>h?.isDirectory(),isSymbolicLink:()=>h?.isSymbolicLink()},g=null,v=!1;try{if(!/^[a-f0-9]{64}$/u.test(m.name)||m.isSymbolicLink())throw new k("STORE_INVALID_ENTRY","RuntimeStore 目录含异常项目");let w;if(m.isFile()){let b=await u(m.name);if(!["comet.runtime-store-format.v2","comet.runtime-store-format.v3"].includes(b.schema))throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记无效");if(w=b.runId,n&&b.schema==="comet.runtime-store-format.v3"&&b.state==="closed"){if(!Number.isSafeInteger(b.revision)||b.revision<1||b.writerProtocol!==void 0&&b.writerProtocol!=="application-holder-v1"||typeof b.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(b.recordHash)||Object.keys(b).some(j=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(j)))throw new k("STORE_CORRUPT_RECORD","RuntimeStore 历史标记损坏");let E=await oe(i,`.runtime-store-v2/${m.name}/checkpoint.json`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),V=await oe(i,`.runtime-store-history/${m.name}/checkpoint.json`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(E.exists||!V.exists)throw new k("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");v=!0}}else if(m.isDirectory()){await oe(i,m.name,{label:"RuntimeStore legacy directory",expected:"directory"});let b=(await wi.readdir(so.join(i,m.name))).filter(V=>/^[0-9]{16}\.json$/u.test(V)).sort();if(!b.length)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 旧记录缺少版本");let E=await u(`${m.name}/${b.at(-1)}`);w=E.schema==="comet.runtime-store-checkpoint.v1"?E.record?.runId:E.runId}else throw new k("STORE_INVALID_ENTRY","RuntimeStore 项目类型无效");if(typeof w!="string"||!w.trim()||mx("sha256").update(JSON.stringify(w)).digest("hex")!==m.name)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 记录身份与目录不匹配");if(g=w,v)return;let A=t?m.isFile()?[m.name,`.runtime-store-v2/${m.name}/checkpoint.json`,`.runtime-store-history/${m.name}/checkpoint.json`]:(await wi.readdir(so.join(i,m.name))).filter(b=>/^[0-9]{16}\.json$/u.test(b)).sort().map(b=>`${m.name}/${b}`):[],N=mx("sha256").update(JSON.stringify({files:await Promise.all(A.map(c)),directories:t?await Promise.all((m.isFile()?[`.runtime-store-v2/${m.name}`,`.runtime-store-history/${m.name}`]:[m.name]).map(l)):[]})).digest("hex");s.push({storageKey:m.name,runId:g,fingerprint:N,error:null})}catch(w){s.push({storageKey:m.name,runId:g,fingerprint:JSON.stringify(await wi.lstat(so.join(i,m.name)).then(A=>[A.size,A.mtimeMs,A.ctimeMs,A.ino]).catch(()=>null)),error:{code:w instanceof k?w.code:"STORE_UNREADABLE",message:w instanceof Error?w.message:String(w)}})}}));return s.sort((d,p)=>d.storageKey.localeCompare(p.storageKey))}async function By(e){return PU(e,!0)}var hx=_(()=>{"use strict";ct();jy();Zr()});function rp(e){return TU.test(e)?e:`portable-${$(e)}`}function Wy(e){let t=ux(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:$(t)}:e}function OU(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=rp(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 o=n.receipts.find(a=>a.outcomeId===t.outcome.outcomeId);o&&(o.hash=$(n.outcome))}}return t.status==="running"&&(n.status="unknown",n.reason="Portable recovery requires reconciliation of external execution"),n})}}function Ly(e){let t=nn(OU(e),e.runId),r=$(t);return{schema:gx,hash:r,run:t,sourceRevision:e.revision,sourceHash:$({hash:r,sourceRevision:e.revision})}}function jU(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`);tn(e);let i=e;if(![gx,"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(s=>!["schema","hash","run","sourceRevision","sourceHash",...i.schema==="comet.workflow-run-checkpoint.v2"?["pool","storageHash"]:[]].includes(s))||i.schema==="comet.workflow-run-checkpoint.v2"&&$({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=i.schema==="comet.workflow-run-checkpoint.v2"?Yu(i.run,i.pool,!n):i.run;if((n?Nn:$)(o)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let a=n?nd(o,t,$U):nn(o,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==$({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(r.preserveSourceRevision)return{...a,revision:i.sourceRevision}}return a}function np(e,t,r={}){return jU(e,t,r)}function Vy(e){let t=structuredClone(e);for(let r of t.actions)r.claim&&!r.executionOrigin&&(r.executionOrigin={workflow:{...e.workflow}});return t}var yi,gx,TU,$U,vx=_(()=>{"use strict";mc();lr();$y();xo();yi="run_checkpoint",gx="comet.workflow-run-checkpoint.v1",TU=/^portable-[a-f0-9]{64}$/u;$U={hash:Nn,visitResults:Ku,validateOrigins:Gu}});var et=_(()=>{"use strict";qE();FE();Dv();jy();hx();mc();Zr();lr();vx();Vh()});import{promises as wx}from"node:fs";import LU from"node:path";function sa(e){throw new k("STORE_INDEX_CORRUPT",e)}async function ms(e,t){let r=await oe(e,`applications/${t}`,{expected:"directory",label:"应用 Store 身份"});if(!r.exists)return null;let n=await wx.lstat(r.target,{bigint:!0});return`${n.dev}:${n.ino}:${n.birthtimeNs}`}async function Il(e){if(!(await oe(e,My,{expected:"file",label:"工作区应用成员清单"})).exists)return null;try{let{checksum:t,...r}=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await qe(e,My,Number.MAX_SAFE_INTEGER,{label:"工作区应用成员清单"})).bytes));return(r.schema!==yx||!Array.isArray(r.applications)||!r.applications.every(qy)||new Set(r.applications).size!==r.applications.length||!r.identities||typeof r.identities!="object"||Array.isArray(r.identities)||!r.claims||typeof r.claims!="object"||Array.isArray(r.claims)||Object.keys(r.identities).length!==r.applications.length||Object.keys(r.claims).length!==r.applications.length||r.applications.some(n=>typeof r.identities[n]!="string"||!Array.isArray(r.claims[n])||r.claims[n].some(i=>!i||typeof i.runId!="string"||typeof i.applicationContentHash!="string"||typeof i.actionId!="string"||!Number.isSafeInteger(i.attempt)||typeof i.inputHash!="string"||i.claimToken!==null&&typeof i.claimToken!="string"))||$(r)!==t)&&sa("工作区应用成员清单损坏"),r}catch(t){return sa(`工作区应用成员清单无法读取:${t instanceof Error?t.message:String(t)}`)}}async function Hy(e,t){await Lt(LU.join(e,My),JSON.stringify({...t,checksum:$(t)})+`
|
|
202
|
+
`,{containedRoot:e,requireAtomicPublication:!0})}async function kx(e,t,r,n=!1){let i=await Vt(e,"applications",{label:"工作区应用 Store"}),o=await wx.readdir(i,{withFileTypes:!0});!n&&o.some(u=>!qy(u.name)||!u.isDirectory())&&sa("工作区应用分区无法确认;请保留现场并检查,不能忽略可能仍占用资源的应用");let a=o.filter(u=>qy(u.name)&&u.isDirectory()).map(u=>u.name).sort(),s=await Il(e),c=s??{schema:yx,applications:[],identities:{},claims:{}};for(let u of c.applications)n||await ms(e,u)!==c.identities[u]&&sa(`已登记应用 ${u} 的 Store 目录缺失或身份改变;请恢复原目录或完整的 portable checkpoint`);a.includes(t)||(await Vt(e,`applications/${t}`,{label:"当前应用 Store"}),a.push(t),a.sort());let l=!s;for(let u of a)c.applications.includes(u)||(c.claims[u]=await r(u),c.identities[u]=await ms(e,u),c.applications.push(u),l=!0);return l&&(c.applications.sort(),await Hy(e,c)),c.applications}async function Qy(e,t,r,n=!1){if(!r.length)return;let i=await Il(e);(!i||!n&&await ms(e,t)!==i.identities[t])&&sa("领取前必须确认工作区应用成员身份");for(let o of r)i.claims[t].some(a=>Fy(a,o))||i.claims[t].push(o);await Hy(e,i)}async function Ax(e,t,r,n){let i=await Il(e);if(!(!i||await ms(e,t)===i.identities[t]))for(let o of i.claims[t]??[])o.runId===r&&!n.some(a=>Fy(o,a))&&sa(`portable checkpoint 缺少原执行身份:${r} / ${o.actionId};必须保留未知执行并核对停止事实`)}async function Uy(e,t,r,n=!1){let i=await Il(e);if(!i||!i.applications.includes(t))return;let o=await ms(e,t),a=await r(t);if(o!==i.identities[t]){if((!n||!o)&&sa("工作区应用 Store 身份已改变"),i.claims[t].some(s=>!a.some(c=>Fy(s,c))))return;i.identities[t]=o}i.claims[t]=a,await Hy(e,i)}async function bx(e,t){let r=await Il(e);if(!r?.applications.includes(t))return!1;try{return await ms(e,t)===r.identities[t]}catch{return!1}}var My,yx,qy,Fy,Nx=_(()=>{"use strict";et();Jn();ct();My="application-scope-locks/workspace-applications.json",yx="comet.workspace-applications.v1",qy=e=>typeof e=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e);Fy=(e,t)=>e.applicationContentHash===t.applicationContentHash&&e.runId===t.runId&&e.actionId===t.actionId&&e.attempt===t.attempt&&e.inputHash===t.inputHash&&e.claimToken===t.claimToken});function Jy(e,t="@"){if(!Ee)return zy.then(()=>Jy(e,t));let r=e.length+1,n=(Ee.__heap_base.value||Ee.__heap_base)+4*r-Ee.memory.buffer.byteLength;n>0&&Ee.memory.grow(Math.ceil(n/65536));let i=Ee.sa(r-1);if(typeof Buffer<"u"?Buffer.from(Ee.memory.buffer,i,2*(r-1)).write(e,"utf16le"):(VU?qU:MU)(e,new Uint16Array(Ee.memory.buffer,i,r)),!Ee.parse())throw Object.assign(new Error(`Parse error ${t}:${e.slice(0,Ee.e()).split(`
|
|
203
|
+
`).length}:${Ee.e()-e.lastIndexOf(`
|
|
204
|
+
`,Ee.e()-1)}`),{idx:Ee.e()});let o=[],a=[];for(;Ee.ri();){let l=Ee.is(),u=Ee.ie(),f=Ee.it(),d=Ee.ai(),p=Ee.id(),h=Ee.ss(),m=Ee.se(),g;Ee.ip()&&(g=s(e.slice(p===-1?l-1:l,p===-1?u+1:u)));let v=null;for(v=[],Ee.rsa();Ee.ra();){let w=Ee.aks(),A=Ee.ake(),N=Ee.avs(),b=Ee.ave();v.push([c(e.slice(w,A)),c(e.slice(N,b))])}v.length===0&&(v=null),o.push({n:g,t:f,s:l,e:u,ss:h,se:m,d:p,a:d,at:v})}for(;Ee.re();){let l=Ee.es(),u=Ee.ee(),f=Ee.els(),d=Ee.ele(),p=f<0?void 0:c(e.slice(f,d)),h=c(e.slice(l,u));a.push({s:l,e:u,ls:f,le:d,ss:Ee.ess(),n:h,ln:p})}function s(l){try{return(0,eval)(l)}catch{}}function c(l){if(!l)return l;let u=l[0];return(u==='"'||u==="'")&&s(l)||l}return[o,a,!!Ee.f(),!!Ee.ms()]}function MU(e,t){let r=e.length,n=0;for(;n<r;){let i=e.charCodeAt(n);t[n++]=(255&i)<<8|i>>>8}}function qU(e,t){let r=e.length,n=0;for(;n<r;)t[n]=e.charCodeAt(n++)}var U5,VU,Ee,FU,zy,Rx=_(()=>{"use strict";U5=(function(e){return e[e.Static=1]="Static",e[e.Dynamic=2]="Dynamic",e[e.ImportMeta=3]="ImportMeta",e[e.StaticSourcePhase=4]="StaticSourcePhase",e[e.DynamicSourcePhase=5]="DynamicSourcePhase",e[e.StaticDeferPhase=6]="StaticDeferPhase",e[e.DynamicDeferPhase=7]="DynamicDeferPhase",e})({}),VU=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;FU=()=>{return e="AGFzbQEAAAABKwhgAAF/YAF/AX9gAABgAn9/AX9gBH9/f38AYAN/f38Bf2ABfwBgA39/fwADPj0CAgEEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgABBQICAgYBAQYBAQEFAQEBAQECAgIBAQEDAQEHAQMDBAUBcAECAgUHAQGCAoCAAgYPAn8BQaCLBAt/AEGgiwQLB80BHgZtZW1vcnkCAAJzYQACAWUABQJpcwAGAmllAAcCc3MACAJzZQAJAml0AAoCYWkACwJpZAAMAmlwAA0CZXMADgJlZQAPA2VscwAQA2VsZQARA2VzcwASAnJpABMCcmUAFAFmABUCbXMAFgJyYQAXA2FrcwAYA2FrZQAZA2F2cwAaA2F2ZQAbA3JzYQAcBXBhcnNlAB0LX19oZWFwX2Jhc2UDAQtfaW5pdGlhbGl6ZQABGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAkHAQBBAQsBAAwBAQrZVz0oAEHYCkGAwAA2AgBB0ApBoIsENgIAQbgKQSo2AgBB1ApBgIAENgIACwQAEAALWQBB6AkgADYCACAAQQF0IgBBADsBoIsEQewJIABBoosEajYCAEHECUEANgIAQdQJQQA2AgBBzAlBADYCAEHICUEANgIAQdwJQQA2AgBB0AlBADYCAEGgiwQLuAEBAn9B7AlB7AkoAgAiBEEoajYCAAJAQdQJKAIAIgVFBEBBxAkgBDYCAAwBCyAFIAQ2AiQLQdQJIAQ2AgBB2AkgBTYCACAEIAA2AgggBEIANwIgIAQgA0EBRiIAOgAYIAQgAzYCFCAEQQA2AhAgBCACNgIEIAQgATYCACAEQQNBAUECIAAbIANBAkYiARs2AhwgBCACIAJBAmpBACAAGyABGzYCDCADQQFrQQFNBEBB8AlBAToAAAsLdwECf0HsCUHsCSgCACIEQRhqNgIAAkBB3AkoAgAiBUUEQEHICSAENgIADAELIAUgBDYCFAtB3AkgBDYCACAEIAM2AgwgBCACNgIIIAQgATYCBCAEIAA2AgBB4AkoAgAhACAEQQA2AhQgBCAANgIQQfAJQQE6AAALCABB9AkoAgALEwBBzAkoAgAoAgBBoIsEa0EBdQscAQF/QcwJKAIAKAIEIgBBoIsEa0EBdUF/IAAbCxMAQcwJKAIAKAIIQaCLBGtBAXULHAEBf0HMCSgCACgCDCIAQaCLBGtBAXVBfyAAGwsLAEHMCSgCACgCHAscAQF/QcwJKAIAKAIQIgBBoIsEa0EBdUF/IAAbCzUBAn9BfyEAAkACQAJAQcwJKAIAKAIUIgFBAWsOAgIBAAsgAUGgiwRrQQF1DwtBfiEACyAACwsAQcwJKAIALQAYCxMAQdAJKAIAKAIAQaCLBGtBAXULEwBB0AkoAgAoAgRBoIsEa0EBdQscAQF/QdAJKAIAKAIIIgBBoIsEa0EBdUF/IAAbCxwBAX9B0AkoAgAoAgwiAEGgiwRrQQF1QX8gABsLEwBB0AkoAgAoAhBBoIsEa0EBdQslAQF/QcwJQcwJKAIAIgBBJGpBxAkgABsoAgAiADYCACAAQQBHCyUBAX9B0AlB0AkoAgAiAEEUakHICSAAGygCACIANgIAIABBAEcLCABB+AktAAALCABB8AktAAALKwEBf0H8CUH8CSgCACIAQRBqQcwJKAIAQSBqIAAbKAIAIgA2AgAgAEEARwsTAEH8CSgCACgCAEGgiwRrQQF1CxMAQfwJKAIAKAIEQaCLBGtBAXULEwBB/AkoAgAoAghBoIsEa0EBdQsTAEH8CSgCACgCDEGgiwRrQQF1CwoAQfwJQQA2AgAL3g8BBn8jAEGA0ABrIgQkAEH4CUEBOgAAQYAIIQBBhApBgAg2AgBBnApBnosEIgJB6AkoAgBBAXRqIgU2AgBB8AlBADoAAEGACkEAOwEAQYIKQQA7AQBBiApBADoAAEH0CUEANgIAQeQJQQA6AABBjAogBEGAEGo2AgBBkAogBDYCAEGUCkEAOgAAA0AgACEBQZgKIAJBAmoiADYCAAJAAkACfwJAAkAgAiAFSQRAIAAvAQAiA0EJa0EFSQ0EAkACQAJAAkACQCADQeUAaw4FAQYGBgIACyADQSBGDQggA0EvRg0DIANBO0YNAgwFC0GCCi8BAA0BIAAQHkUNASACQQRqQYIIQQoQHw0BECBBmAooAgAhAEH4CS0AAA0BQYQKIAA2AgAgACIBIQIMBQsgAi8BBEHtAEcNACAAEB5FDQAgAikABkLwgLyDoI6AOlINABAhQZgKKAIAIQALQYQKIAA2AgAMBgsgAi8BBCIAQSpHBEAgAEEvRw0CECIMBQtBARAjDAQLIAAhAkEAQeQJLQAADQIaDAELQfgJQQA6AAALA0ACQEGYCiACQQJqIgA2AgACQAJAAkACQCACIAVJBEACQAJAAkACQAJAAkACQAJAAkACQAJAIAAvAQAiA0Egaw4QDwgFCAgICAUKAggIAQgIBgALAkACQAJAAkACQAJAIANB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACyADQQlrQQVJDRMgA0H7AGsOAwcMCAwLQYIKLwEADQwgABAeRQ0MIAJBBGpBgghBChAfDQwQIAwRCyACLwEEQe0ARw0LIAAQHkUNCyACKQAGQvCAvIOgjoA6Ug0LECEMEAsgAi8BBEHsAEcNCiAAEB5FDQogAkEGakGyCEEGEB8NCiACLwEMECRFDQpBlApBAToAAAwKC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBCDYCACAAIAE2AgQMDgtBggovAQAiAEUND0GCCiAAQQFrOwEADA0LQYAKLwEAIgBFDQxBggovAQAiA0UNDCADQQN0IARqQfgPaigCAEEFRw0MIAQgAEECdGpBBGsoAgAiACgCBA0MIAAgAUECajYCBEGYCiACQQRqNgIAQQEQJRogAEGYCigCACIANgIQQZgKIABBAms2AgAMDAtBggovAQAiAEUNDUGCCiAAQQFrIgM7AQBBgAovAQAiAEUNCyAEQYAQaiADQf//A3FBA3RqKAIAQQVHDQsgBCAAQQJ0akEEaygCACIDKAIERQRAIAMgAUECajYCBAsgAyACQQRqNgIMQYAKIABBAWs7AQAMCwsCQCABLwEAQSlHDQBB1AkoAgAiAEUNACAAKAIMIAFBAmpHDQBB1AlB2AkoAgAiADYCACAABEAgAEEANgIkDAELQcQJQQA2AgALQYIKQYIKLwEAIgBBAWo7AQAgBEGAEGogAEEDdGoiAEEGQQJBlAotAAAbNgIAIAAgATYCBEGUCkEAOgAADAoLQYIKLwEAIgBFDQtBggogAEEBayIAOwEAIARBgBBqIABB//8DcUEDdGooAgBBBEcNCQwICyADECYMCAsCQCACLwEEIgBBKkcEQCAAQS9HDQEQIgwKC0EBECMMCQsCQCABLwEAIgAQJwRAAkACQAJAIABBK2sOBAEKAgAKCyABQQJrLwEAQTBrQf//A3FBCkkNAwwJCyABQQJrLwEAQStGDQIMCAsgAUECay8BAEEtRg0BDAcLIABBKUcNACAEQYAQakGCCi8BAEEDdGooAgQQKA0GCwJAAkBBggovAQAiAkUgAEHmAEdyDQAgBEGAEGogAkEDdGoiA0EIaygCAEEBRw0AIAFBAmsvAQBB7wBHDQEgAUEEaxApRQ0BIANBBGsoAgBBnglBAxAqRQ0BDAcLIABB/QBHDQAgBEGAEGogAkEDdGoiAigCBBArDQYgAigCAEEGRg0GCyABECwNBUGICi0AACAAQS9GcSAAQQBHc0UNBQJAQdwJKAIAIgJFDQAgASACKAIASQ0AIAEgAigCBE0NBgsDQCABQaCLBEsEQEGECiABQQJrIgE2AgAgAS8BACIAEC1FDQELCyAAQf//A3EQLgRAA0AgAUGgiwRLBEBBhAogAUECayIBNgIAIAEvAQAQLg0BCwsgARAvDQYLQYgKQQE6AAAMBwtBggpBggovAQAiAEEBajsBACAEQYAQaiAAQQN0aiIAIAE2AgQgAEEDNgIADAULIANBMGtB//8DcUEKSSADQSByQeEAa0H//wNxQRpJcg0AAkACQCADQdwAaw4EAgEBAgALIANBJEYNAQsgA0GgAUYgA0GAAUlyDQULA0AgAC8BAiIBQSByQeEAayECAkAgAUEwa0H//wNxQQpJIAJB//8DcUEaSXINAAJAAkAgAUHcAGsOBAIBAQIACyABQSRGDQELIAFBoAFGIAFBgAFJcg0GC0GYCiAAQQJqIgA2AgAMAAsAC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBATYCACAAIAE2AgQMAwtBgAovAQBFQYIKLwEARUHkCS0AAEF/c3FxDAYLEDBBiApBADoAAAwBCxAxC0GECkGYCigCACIBNgIAC0GYCigCACECDAELCxAyQQALIQMgBEGA0ABqJAAgAw8LIAEhAAtBmAooAgAhAgwACwALFgAgAEGgiwRGBEBBAQ8LIABBAmsQMwtDAQN/AkAgAkUNAANAIAAtAAAiBCABLQAAIgVGBEAgAUEBaiEBIABBAWohACACQQFrIgINAQwCCwsgBCAFayEDCyADC9IIAQV/QZgKQZgKKAIAIgRBDGoiATYCAEHcCSgCACEDQQEQJSECAkACQAJAAkACQAJAIAFBmAooAgAiAEYEQCACEDRFDQELQeAJIAQ2AgACQAJAAkAgAkEqRwRAIAJB+wBHDQFBmAogAEECajYCAEEBECUhAkGcCigCACEBQZgKKAIAIQADQAJAIAJB//8DcSICQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlGiAAIAIQNiICQSxGBEBBmApBmAooAgBBAmo2AgBBARAlIQILIAJB/QBGDQMgAEGYCigCACIARg0IIAAgAU0NAAsMBwtBmAogAEECajYCAEEBECUaQZgKKAIAIgAgABA2GgwCC0H4CUEAOgAAAkACQAJAAkACQAJAIAJB4QBrDgwCCAQBCAMICAgICAUACyACQfYARg0EDAcLQZgKIABBDmoiBDYCAAJAAkACQAJAQQEQJUHhAGsOBgAMAgwMAQwLQZgKKAIAIgEpAAJC84Dkg+CNwDFSDQsgAS8BChAuRQ0LQZgKIAFBCmo2AgBBABAlGgtBmAooAgAiA0ECakGiCEEOEB8NCgJAIAMvARAiARAkDQAgAUEoaw4DAAsACwtBmAogA0EQajYCAEEBECUiAUEqRgRAQZgKQZgKKAIAQQJqNgIAQQEQJSEBCyABQShHDQEMCgtBmAooAgAiAykAAkLsgISDsI7AOVINCSADLwEKIgEQJEUgAUH7AEdxDQlBmAogA0EKajYCAEEBECUiAUH7AEYNCQtBmAooAgAhAyABEDUaQZgKKAIAIgEgA00NCCAAIAQgAyABEAQMCgtBmAogAEEKajYCAEEAECUaQZgKKAIAIQALQZgKIABBEGo2AgBBARAlIgBBKkYEQEGYCkGYCigCAEECajYCAEEBECUhAAsMCQsCQCAAKQACQuyAhIOwjsA5Ug0AIAAvAQoQLUUNAEGYCiAAQQpqNgIAQQEQJSEADAkLIABBBGohAAtBmAogAEEGajYCAEGcCigCACEDA0BBARAlIQBBmAooAgAiASADSw0HIAAQNyECQZgKKAIAIgAgAUYNBCACQT1GBEBBARA4IQJBmAooAgAhAAsgAkEsRw0EQZgKIABBAmo2AgAMAAsAC0HwCUEBOgAAQZgKQZgKKAIAQQJqNgIAC0EBECUhAEGYCigCACEBAkAgAEHmAEcNACABQQJqQZwIQQYQHw0AQZgKIAFBCGo2AgAgBEEBECVBABA5IANBFGpByAkgAxshAgNAIAIoAgAiAEUNAiAAQgA3AgggAEEUaiECDAALAAtBmAogAUECazYCAAsPCyAAIQEMAgsgACAEQQBBABAEQZgKIABBDGo2AgAPCxAyDwtBmAogAUECazYCAA8LQZgKKAIAIQEgABA1GiABQZgKKAIAIgAgASAAEARBmAogAEECazYCAAuKCwEKf0GYCkGYCigCACIGQQxqIgk2AgBBARAlIQBBmAooAgAhAgJAAkACQAJAAkACQAJ/IABBLkYEQEGYCiACQQJqNgIAQQEQJSIAQeQARwRAIABB8wBHBEAgAEHtAEcNB0GYCigCACIAQQJqQYwIQQYQHw0HQYQKKAIAIgEQOkUEQCABLwEAQS5GDQgLIAYgBiAAQQhqQQIQAw8LQZgKKAIAIgBBAmpBkghBChAfDQZBhAooAgAiARA6RQRAIAEvAQBBLkYNBwtBmAogAEEMajYCAEEBIQhBBSEEQQEQJSEAQQEMAgtBmAooAgAiACkAAkLlgJiD0IyAOVINBUGECigCACIBEDpFBEAgAS8BAEEuRg0GC0GYCiAAQQpqNgIAQQchBEEBIQVBARAlIQBBASEIQQIMAQsCQAJAIABB8wBHIAIgCU1yRQRAQfMAIQAgAkECakGSCEEKEB8NASACLwEMECRFDQFBmAogAkEMaiIANgIAQQEhCEEBECUhASAAQZgKKAIAIgRHBEBB5gAhACABQeYARwRAQQUhBCABIQBBAQwFC0EBIQMgBEECakGcCEEGEB8NBSAELwEIEC1FDQULQZgKIAI2AgBBByEEQQEhB0EAIQggASEAQQAMAwtBByEEQQEhByAAQeQARyACIAZBCmpNcg0BQeQAIQAgAikAAkLlgJiD0IyAOVINACACLwEKECRFDQBBmAogAkEKajYCAEEqIQBBASEFQQIhA0EBECUiAUEqRg0EQZgKIAI2AgBBACEFIAEhAEEADAILIAIhBAwCC0EACyEDIABBKEYEQEGMCigCAEGCCi8BACIFQQN0aiIAQQU2AgBBggogBUEBajsBACAAQZgKKAIAIgI2AgRBhAooAgAvAQBBLkYNBEGYCiACQQJqNgIAQQEQJSEAIAZBmAooAgAiAUEAIAIQA0HUCSgCACEDIAgEQCADIAQ2AhwLQYAKQYAKLwEAIgRBAWo7AQBBkAooAgAgBEECdGogAzYCAAJAIABBIkYgAEEnRnJFBEACQCAAQeAARw0AQZwKKAIAIQYgASEAA0AgACICIAZPDQECQAJAIABBAmoiAC8BACIHQdwAaw4FAAICAgUBCyACQQRqIQAMAQsgB0EkRw0AIAIvAQRB+wBHDQALC0GYCiABQQJrNgIADwsgABAmQZgKKAIAIQALQZgKIABBAmoiADYCAAJAAkACQEEBECVBKWsOBAECAgACC0GYCkGYCigCAEECajYCAEEBECUaIAMgADYCBEGYCigCACEAIANBAToAGCADIAA2AhAMCAtBggogBTsBACADIAA2AgRBmAooAgAhACADQQE6ABggAyAAQQJqNgIMQYAKIAQ7AQAPC0GYCkGYCigCAEECazYCAA8LIAdFIABB+wBHckUEQEGYCigCACEAQYIKLwEADQZBnAooAgAhAQNAAkACQCAAIAFJBEBBARAlIgBBIkYgAEEnRnINASAAQf0ARw0CQZgKQZgKKAIAQQJqNgIAC0EBECUhAUGYCigCACEAIAFB5gBGBEAgAEECakGcCEEGEB8NBwtBmAogAEEIajYCAEEBECUiAEEiRyAAQSdHcQ0GIAYgAEEAEDkPCyAAECYLQZgKQZgKKAIAQQJqIgA2AgAMAAsACwJAAkAgAEEnaw4EAwEBAwALIABBIkYNAgtBmAooAgAhBAsgBCAJRw0AQZgKIARBAms2AgAPCyAAQSpHIAVxDQJBggovAQANAkGYCigCACEAQZwKKAIAIQIDQCAAIAJPDQEgAC8BACIBQSdHIAFBIkdxBEBBmAogAEECaiIANgIADAEFIAYgASADEDkPCwALAAsQMgsPC0GYCkGYCigCAEECazYCAA8LQZgKIABBAms2AgALQwEDf0GYCigCACEAQZwKKAIAIQIDQAJAIABBAmohASAAIAJPDQAgASEAIAEvAQBBCmsOBAABAQABCwtBmAogATYCAAtwAQR/QZgKKAIAQQJqIQFBnAooAgAhBAJAA0AgASICQQJqIQEgAiAETw0BIAEvAQAhAwJAIABFBEAgA0EqRg0BIANBCmsOBAMCAgMCCyADQSpHDQELIAIvAQRBL0cNAAsgAkEEaiEBC0GYCiABNgIACwsAIABBn4CABBA8C30BBH9BnAooAgAhA0GYCigCACEBA0ACQAJAAkAgAS8BACICQS9GBEAgAS8BAiIBQSpHBEAgAUEvRg0CQS8PCyAAECMMAgsgAARAIAIQJA0CDAMLIAIQLg0BDAILECILQZgKQZgKKAIAIgRBAmoiATYCACADIARLDQELCyACC4YBAQR/QZgKKAIAIQFBnAooAgAhBAJAA0ACQCABIgJBAmohASACIARPDQAgAS8BACIDIABGDQIgA0HcAEcEQCADQQprDgQBAgIBAgsgAkEEaiEBIAIvAQRBDUcNASACQQZqIAEgAi8BBkEKRhshAQwBCwtBmAogATYCABAyDwtBmAogATYCAAtuAQF/AkAgAEEpRyAAQShrQf//A3FBB0lxIABBIWsiAUEFTUEAQQEgAXRBMXEbckUEQCAAQTprIgFB//8DcUElT0K/gICAoAIgAa2Ip0EBcUVyDQELQQEPCyAAQf0ARyAAQfsAa0H//wNxQQRJcQsuAQF/QQEhAQJAIABBlAlBBRAqDQAgAEGeCUEDECoNACAAQaQJQQIQKiEBCyABC28BAX8CfyAALwEAIgEQJCABQSlGciABQf0ARnJFBEBBACABQd0ARw0BGgsDQAJAIABBoIsETQ0AIAEQJEUNACAAQQJrIgAvAQAhAQwBCwtBASABQSlGIAFB3QBGciABQf0ARnINABogARA0QQFzCws+AQJ/AkAgACACQQF0IgJrIgRBAmoiAEGgiwRJDQAgACABIAIQHw0AIABBoIsERgRAQQEPCyAEEDMhAwsgAwuDAQECf0EBIQICQAJAAkACQAJAAkAgAC8BACIBQTtrDgQFBAQBAAsCQCABQeUAaw4EAwQEAgALIAFBKUYNBCABQfkARw0DIABBAmtBsAlBBhAqDwsgAEECay8BAEE9Rg8LIABBAmtBqAlBBBAqDwsgAEECa0G8CUEDECoPC0EAIQILIAILqgMBAn8CQAJAAkACQAJAAkACQAJAAkACQCAALwEAQeQAaw4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEECay8BAEHpAGsOBAAKCgEKCyAAQQRrQbgIQQIQKg8LIABBBGtBvAhBAxAqDwsCQAJAAkAgAEECay8BAEHzAGsOAwABAgoLIABBBGsvAQAiAUHhAEcEQCABQewARw0KIABBBmtB5QAQOw8LIABBBmtB4wAQOw8LIABBBGtBwghBBBAqDwsgAEEEa0HKCEEGECoPCyAAQQJrLwEAQe8ARw0GIABBBGsvAQBB5QBHDQYgAEEGay8BACIBQfAARwRAIAFB4wBHDQcgAEEIa0HWCEEGECoPCyAAQQhrQeIIQQIQKg8LIABBAmtB5ghBBBAqDwtBASECIABBAmsiAEHpABA7DQQgAEHuCEEFECoPCyAAQQJrQeQAEDsPCyAAQQJrQfgIQQcQKg8LIABBAmtBhglBBBAqDwsgAEECay8BACIBQe8ARwRAIAFB5QBHDQEgAEEEa0HuABA7DwsgAEEEa0GOCUEDECohAgsgAgs0AQF/IABBoAFGIABBCWsiAUEXTUEAQQEgAXRBn4CABHEbckUEQCAAEDQgAEEuR3EPC0EBCwsAIABBjYCABBA8C0gBAn8CQCAALwEAIgJB5QBHBEAgAkHrAEcNASAAQQJrQeYIQQQQKg8LIABBAmsvAQBB9QBHDQAgAEEEa0HKCEEGECohAQsgAQvbAQEEf0GYCigCACEAQZwKKAIAIQMDQCAAQQJqIQECQAJAIAAgA08NAAJAAkACQCABLwEAIgJB2wBrDgIBAgALIAEhACACQQprDgQCBAQCAwsCQANAAkAgAUECaiEAIAEgA08NAAJAAkAgAC8BACICQdwAaw4CAAQBCyABQQRqIQEMAgsgACEBIAJBCmsOBAABAQABCwtBmAogADYCABAyQZgKKAIAIQAMBAtBmAogADYCAAwDCyAAQQRqIQAMAgtBmAogATYCABAyDwsgAkEvRw0AC0GYCiAANgIAC94BAQR/QZgKKAIAIQBBnAooAgAhAwJAAkADQAJAIAAiAUECaiEAIAEgA08NAAJAAkACQCAALwEAIgJB3ABrDgUCBAQEAQALIAJBJEcNAyABLwEEQfsARw0DQZgKIAFBBGoiAjYCAEGMCigCAEGCCi8BACIAQQN0aiIBQQQ2AgBBggogAEEBajsBACABIAI2AgQPC0GYCiAANgIAQYIKQYIKLwEAQQFrIgE7AQBBjAooAgAgAUH//wNxQQN0aigCAEEDRw0DDAQLIAFBBGohAAwBCwtBmAogADYCAAsQMgsLMwEBf0HkCUEBOgAAQZgKKAIAIQBBmApBnAooAgBBAmo2AgBB9AkgAEGgiwRrQQF1NgIACz0BAX8Cf0EBIAAvAQAiAUEJa0H//wNxQQVJIAFBgAFyQaABRnINABpBACABEDRFDQAaIAAQOiABQS5HcgsLXgEBfwJAIABB+P8DcUEoRiAAQSFrIgFBBU1BAEEBIAF0QTFxG3JFBEAgAEE6ayIBQf//A3FBJU9Cv4CAgKADIAGtiKdBAXFFcg0BC0EBDwsgAEH7AGtB//8DcUEESQtXAQN/QZgKKAIAIQEDQAJAIABB//8DcSICECQEQCAAIQMMAQsgACEDIAIQNA0AQQAhA0GYCiABQQJqIgI2AgAgAS8BAiEAIAIhASAADQELCyADQf//A3ELpQEBBH8CQEGYCigCACIDLwEAIgVB4QBHBEAgASECIAAhBAwBC0GYCiADQQRqNgIAQQEQJSECQZgKKAIAIQQCQCACQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlIQVBmAooAgAhAwsgAyAERwRAIAQgAkEAIAAgACABRiIAG0EAIAEgABsQBAsgBQvTBAEHf0GYCigCACEBAkAgAEHf/wNxQdsARgRAIAEvAQAhBUGYCiABQQJqNgIAQf0AQd0AIAVB+wBGGyEGQQEQJSEDQZwKKAIAIQcDQAJAIAYgA0H//wNxIgJGQZgKKAIAIgEgB0tyDQACQCACQS5HDQAgAS8BAkEuRw0AIAEvAQRBLkcNAEGYCiABQQZqNgIAQQEQJRA3IQMMAgsCQAJ/AkAgBUH7AEYEQAJAIAJBIkYgAkEnRnJFBEAgAkHbAEcNAUEAEDgaQZgKQZgKKAIAQQJqNgIAIAEMBAsgAhAmQZgKQZgKKAIAQQJqNgIAIAEMAwsgASEAIANBMGtB//8DcUEJSw0BA0AgACICQQJqIQAgAi8BAiIDQTBrQf//A3FBCkkNACADQcEAayIEQR5NQQBBASAEdEG/gIGEBHEbDQAgA0HhAGsiBEEXTUEAQQEgBHRBv8CBBHEbDQACQAJAIANBK2sOBAABAAIBCyACLwEAQSByQeUARg0BCwtBmAogADYCACABDAILIAJBLEYEQEGYCiABQQJqNgIAQQEQJSEDDAULIAIQNyECDAILIAIQNRpBmAooAgALIQBBARAlIgJBOkYEQEGYCkGYCigCAEECajYCAEEBECUQNyECDAELIAAgAU0NACABIAAgASAAEAQLIAJBPUYEQEEAEDghAgtBmAooAgAhASACQSxHDQBBmAogAUECajYCAEEBECUhAwwBCwtBmAogAUECajYCAAwBCyAAEDUaQZgKKAIAIgAgAU0NACABIAAgASAAEAQLQQEQJQvgDgEMf0GECkGYCigCACIBNgIAQZAKKAIAIQpBjAooAgAhB0GcCigCACEMQYIKLwEAIQsgASIDIQUCQANAQZgKIAVBAmoiBDYCACAFIAxPBEBBACEIDAILAkACQCAELwEAIgIQLg0AAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQEGCCi8BACIGIAtHDQAgAiEIAkACQCACQSlrDgQcAQEcAAsgAkE7RiACQd0ARnIgAkH9AEZyDRkLIAAgCXFBAUcNAAJAIAJBImsODgsODg4OCxAIDg4HDg4MAAsCQCACQdsAaw4PBQ4GDg4NDg4EDgIODg4DAAsCQCACQfsAaw4DCQ4KAAsgAkEKaw4EGg0NGg0LAkAgAkEiaw4OCg0NDQ0KDwcNDQYNDQsACwJAIAJB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACwJAIAJBCmsOBBcNDRcACyACQfsAaw4DBwwIDAsgBg0MIAQQHkUNDCAFQQRqQYIIQQoQHw0MECAMEgsgBS8BBEHtAEcNCyAEEB5FDQsgBSkABkLwgLyDoI6AOlINCxAhDBELIAUvAQRB7ABHDQogBBAeRQ0KIAVBBmpBsghBBhAfDQogBS8BDBAkRQ0KQZQKQQE6AAAMCgsgByAGQQN0aiIBQQg2AgBBggogBkEBajsBACABIAM2AgQMDwsgBkUND0GCCiAGQQFrOwEADA4LIAZFDQ1BgAovAQAiAUUNDSAHIAZBA3RqQQhrKAIAQQVHDQ0gCiABQQJ0akEEaygCACIBKAIEDQ0gASADQQJqNgIEQZgKIAVBBGo2AgBBARAlGiABQZgKKAIAIgE2AhBBmAogAUECazYCAAwNCyAGRQ0NQYIKIAZBAWsiBDsBAEGACi8BACIBRQ0MIAcgBEH//wNxQQN0aigCAEEFRw0MIAogAUECdGpBBGsoAgAiBCgCBEUEQCAEIANBAmo2AgQLIAQgBUEEajYCDEGACiABQQFrOwEADAwLAkAgAy8BAEEpRw0AQdQJKAIAIgFFDQAgASgCDCADQQJqRw0AQdQJQdgJKAIAIgE2AgAgAQRAIAFBADYCJAwBC0HECUEANgIACyAHIAZBA3RqIgFBBkECQZQKLQAAGzYCAEGCCiAGQQFqOwEAIAEgAzYCBEGUCkEAOgAADAsLIAZFDQtBggogBkEBayIBOwEAIAcgAUH//wNxQQN0aigCAEEERw0KDAkLIAIQJgwJCwJAIAUvAQQiBEEqRwRAIARBL0cNARAiDAwLQQEQIwwLCwJAIAMvAQAiBRAnBEACQAJAAkAgBUEraw4EAQsCAAsLIANBAmsvAQBBMGtB//8DcUEKSQ0DDAoLIANBAmsvAQBBK0YNAgwJCyADQQJrLwEAQS1GDQEMCAsgBUEpRw0AIAcgBkEDdGooAgQQKA0HCwJAAkAgBkUgBUHmAEdyDQAgByAGQQN0aiIBQQhrKAIAQQFHDQAgA0ECay8BAEHvAEcNASADQQRrEClFDQEgAUEEaygCAEGeCUEDECpFDQEMCAsgBUH9AEcNACAHIAZBA3RqIgEoAgQQKw0HIAEoAgBBBkYNBwsgAxAsDQZBiAotAAAgBUEvRnEgBUEAR3NFDQZB3AkoAgAiAUUNBCADIAEoAgBJDQQgAyEEIAMgASgCBE0NBgwFCyAHIAZBA3RqIgEgAzYCBEGCCiAGQQFqOwEAIAFBAzYCAAwGCyACQTBrQf//A3FBCkkgAkEgckHhAGtB//8DcUEaSXINAAJAAkAgAkHcAGsOBAIBAQIACyACQSRGDQELIAJBoAFGIAJBgAFJcg0GCwNAIAQvAQIiAUEgckHhAGshCAJAIAFBMGtB//8DcUEKSSAIQf//A3FBGklyDQACQAJAIAFB3ABrDgQCAQECAAsgAUEkRg0BCyABQaABRiABQYABSXINBwtBmAogBEECaiIENgIADAALAAsgByAGQQN0aiIBQQE2AgBBggogBkEBajsBACABIAM2AgQMBAsgAyEECwNAIARBoIsESwRAIARBAmsiBC8BACIFEC1FDQELCyAFQf//A3EQLgRAA0AgBEGgiwRLBEBBhAogBEECayIENgIAIAQvAQAQLg0BCwsgBBAvDQELQYgKQQE6AAAMAgsQMEGICkEAOgAADAELEDELQYQKQZgKKAIAIgE2AgAMAQsQMgtBACEIQeQJLQAADQMCQCABIANGBEAgAEUNAUGCCi8BACALRiAJcUUNAUEBIQkgASEDQZgKKAIALwEAIghBCmsOBAUCAgUCCyACQS9GBEBBiAotAABBAXMhCQwBC0EBIQkgAkEwa0H//wNxQQpJIAJB3/8DcUHBAGtB//8DcUEaSXIgAkEkRiACQd8ARnJyIAJB/wBLcg0AIAEhAwJAAkAgAkEnaw4DAwEDAAsCQCACQd0Aaw4EAwEBAwALIAJBIkYgAkH9AEZyDQELQQAhCQsgASEDC0GYCigCACEFDAELCyACDwsgCAuvBAEHfyABQSJGIAFBJ0ZyRQRAEDIPC0GYCigCACEDIAEQJiAAIANBAmpBmAooAgBBARADIAIEQEHUCSgCAEEEQQYgAkEBRhs2AhwLQZgKQZgKKAIAQQJqNgIAQQAQJSEAQZgKKAIAIQQCQAJAIABB9wBHDQAgBC8BAkHpAEcNACAELwEEQfQARw0AIAQvAQZB6ABGDQELQZgKIARBAms2AgAPC0GYCiAEQQhqNgIAAkBBARAlQfsARwRADAELQewJKAIAIQNB1AkoAgAhBUGYCigCACIGIQBBACECA0AgAyEBQZgKIABBAmo2AgBBARAlIQBBmAooAgAhBwJAAkACQCAAQSJHBEAgAEEnRw0BQScQJgwCC0EiECYMAQsgABA1IQNBmAooAgAhAAwBC0GYCigCAEECaiEAQZgKIAA2AgBBARAlIQMLIANBOkcEQAwCC0GYCkGYCigCAEECajYCAEEBECUiA0EiRiADQSdGckUEQAwCC0GYCigCACEIIAMQJkHsCSABQRRqIgM2AgBBmAooAgAhCSABQQA2AhAgASAINgIIIAEgADYCBCABIAc2AgAgASAJQQJqIgA2AgwCQCACRQRAIAUgATYCIAwBCyACIAE2AhALQZgKIAA2AgACQEEBECUiAEEsRwRAIABB/QBGDQEMAwtBmApBmAooAgBBAmoiADYCACABIQIMAQsLIAUgBjYCECAFQZgKKAIAQQJqNgIMDwtBmAogBDYCAAstAQF/AkAgAC8BAEEuRw0AIABBAmsvAQBBLkcNACAAQQRrLwEAQS5GIQELIAELNQEBfwJAIABBoIsESQ0AIAAvAQAgAUcNACAAQaCLBEYEQEEBDwsgAEECay8BABAtIQILIAILKQEBfyAAQaABRiAAQQlrIgJBF01BAEEBIAJ0IAFxG3JFBEBBAA8LQQELC8cBAQBBgggLvwF4AHAAbwByAHQAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AbABhAHMAcwB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcw==",typeof Buffer<"u"?Buffer.from(e,"base64"):Uint8Array.from(atob(e),t=>t.charCodeAt(0));var e},zy=WebAssembly.compile(FU()).then(WebAssembly.instantiate).then(({exports:e})=>{Ee=e})});import{existsSync as HU,readFileSync as QU}from"fs";import Sx from"path";import{fileURLToPath as UU}from"url";function JU(){return"0.5.3"}function Ex(){return Ky===null&&(Ky=JU()),Ky}var Ky,zU,Y5,Cx=_(()=>{"use strict";Ky=null,zU="@rpamis/comet",Y5=`https://registry.npmjs.org/${zU}/latest`});import{promises as KU}from"node:fs";import GU from"node:path";function op(e){return GU.join(e,".comet","current-change.json")}function YU(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function _x(e){return e===null||typeof e=="string"}function XU(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(!YU(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&&!_x(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ip,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ip)throw new Error(`current change selection schema must be ${ip}`);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(!_x(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 xr(e){let t;try{let n=op(e),{bytes:i}=await Io(n,Ix,{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",...XU(t)}}async function Gy(e){await KU.rm(op(e),{force:!0})}async function hs(e,t,r){let n=await xr(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==r?!1:(await Gy(e),!0)}var ip,Ix,ZU,co=_(()=>{"use strict";bn();Di();ip="comet.selection.v2",Ix=Number.MAX_SAFE_INTEGER;ZU=Qt("readCometCurrentSelection",e=>xr(e))});import{promises as Px}from"node:fs";import{AsyncLocalStorage as e2}from"node:async_hooks";import or from"node:path";function fr(e,t,r="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!Tx.test(t))throw new Error(`Invalid change name: ${t}`);return`${r==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function ap(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===Tn&&n.workflow===t&&n.change===r,o=n.format==="compat"&&Object.keys(n).length===4,a=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)&&!Zy.includes(n.application)||(t==="native"?n.application==="native":n.application==="classic-full"||n.application==="classic-hotfix"||n.application==="classic-tweak"));if(!i||!o&&!a)throw new Error(`Invalid change runtime owner for ${t}/${r}`);return n}async function Gn(e,t,r,n){let i;try{({bytes:i}=await qe(e,t,Number.MAX_SAFE_INTEGER,{label:"change runtime owner"}))}catch(a){if(a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error(`Invalid change runtime owner JSON for ${r}/${n}`)}return ap(o,r,n)}function Ox(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function $x(e,t){return fr(e,t),`change-owner-records/${e}/${t}.json`}async function sp(e,t,r){let n;try{n=await qe(e,$x(t,r),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(o){if(o.code==="ENOENT")return null;throw o}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:ap(i,t,r),identity:Ox(n.stat)}}async function jx(e,t,r){let n=await Zf(e,"change owner bindings"),i=async s=>{try{let{stat:c}=await n.stat(fr(t,r,s));return Ox(c)}catch(c){if(c.code==="ENOENT")return null;throw c}},o=await i("active"),a=await i("history");return await n.finish({allowDirectoryContentChanges:!0}),{active:o,history:a}}async function Dx(e,t,r=!1){let n=await jx(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 sp(e,t.workflow,t.change);if(i?.identity&&i.identity===(n.active??n.history))return;let o=$x(t.workflow,t.change);await Vt(e,or.posix.dirname(o),{label:"canonical change runtime owners"});let a=fr(t.workflow,t.change,n.active?"active":"history");try{await rC(or.join(e,a),or.join(e,o),{containedRoot:e})}catch(s){if(!["ENOTSUP","EOPNOTSUPP"].includes(s.code??""))throw s}}async function r2(e,t,r){let n;try{n=await sp(e,t,r)}catch(o){if(o instanceof Ut&&o.reason==="changed")return null;throw o}if(!n?.identity)return null;let i=await jx(e,t,r);return i.active===n.identity&&i.history===null||i.history===n.identity&&i.active===null?n:null}async function cp(e){let t=Pn.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??t2(e)}async function lp(e,t,r=!1){let n=Pn.getStore();if(n?.active&&e.every(o=>n.roots.has(o)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let o=await Pn.run(i,()=>An(()=>r?sc(t):t())),a=Bx();for(let s of a.keys())[...i.projects].some(c=>s.startsWith(c+"\0"))&&a.delete(s);for(let[s,c]of i.owners)a.set(s,c);return o}finally{i.active=!1}}async function Yy(e,t,r){let n=await r2(e,t,r);return n?n.owner:lp([e],async()=>{let i=await Gn(e,fr(t,r),t,r),o=await Gn(e,fr(t,r,"history"),t,r);if(i&&o)throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);return i??o})}async function ki(e,t,r,n={}){if(fr(t,r),!n.readOnly)return Pn.run(null,()=>An(async()=>Yy(await si(e),t,r)));let[i,o]=await cp(e),a=or.parse(i).root,c=(await oe(a,or.relative(a,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await Yy(i,t,r):null,l=o?await Yy(o,t,r):null;if(c&&l&&JSON.stringify(Object.entries(c).sort())!==JSON.stringify(Object.entries(l).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${r}`);return c??l}async function xx(e,t,r,n={}){let i=await ki(e,t,r,n),o=i?.format==="sdk"?i:null,a=Pn.getStore();return n.readOnly&&a?.active&&a.owners.set(Wx(e,t,r),o),o}async function je(e,t,r,n={}){if(!n.readOnly||Pn.getStore()?.active)return xx(e,t,r,n);let i=Bx(),o=Wx(e,t,r);if(i.has(o))return i.get(o);let a=xx(e,t,r,n).catch(s=>{throw i.get(o)===a&&i.delete(o),s});return i.set(o,a),a}async function Lx(e,t,r,n=!1){fr(t,"validate");let i=r.readOnly?await cp(e):[await si(e)],o=async()=>{let a={active:new Set,history:new Set};for(let s of i)for(let c of["active","history"]){let l=or.parse(s).root,u=or.posix.dirname(fr(t,"validate",c)),f=await oe(l,or.relative(l,or.join(s,u)).replaceAll("\\","/"),{label:`${t} ${c} change runtime owners`,expected:"directory"});if(!f.exists)continue;let d=await Px.readdir(f.target,{withFileTypes:!0});for(let p of d){if(p.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(p.name))continue;if(t==="classic"&&c==="active"){let m=/^([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(p.isFile()&&m.test(p.name)||p.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(p.name))continue}if(!p.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${p.name}`);let h=p.name.slice(0,-5);if(!p.isFile()||!Tx.test(h))throw new Error(`Invalid ${t} change runtime owner entry: ${p.name}`);a[c].add(h)}}return a};return n?o():lp(i,o)}async function i2(e,t,r){return r.readOnly?n2(e,t,r):Lx(e,t,r)}async function Xy(e,t,r={}){let n=r.readOnly?await cp(e):[await si(e)];return lp(n,async()=>{r.readOnly&&Pn.getStore()?.runtimeRoots.set(e,n),Pn.getStore()?.projects.add(JSON.stringify([e,t]));let i=await i2(e,t,{readOnly:r.readOnly});if(r.partition==="history")return[...i.history].filter(u=>!i.active.has(u)).sort((u,f)=>u.localeCompare(f,"en"));let a=[...r.partition==="active"?i.active:new Set([...i.active,...i.history])],s=new Array(a.length),c=0;await Promise.all(Array.from({length:Math.min(r.readOnly?8:1,a.length)},async()=>{for(;;){let u=c++;if(u>=a.length)return;let f=a[u];try{let d=await je(e,t,f,r);if(!d&&!await ki(e,t,f,r))throw new Error(`${t} change runtime owner disappeared: ${f}`);s[u]={status:"fulfilled",value:d?f:null}}catch(d){s[u]={status:"rejected",reason:d}}}}));let l=[];for(let u of s){if(u.status==="rejected")throw u.reason;u.value&&l.push(u.value)}return l.sort((u,f)=>u.localeCompare(f,"en"))},r.readOnly===!0)}async function Vx(e,t,r={}){let n=r.readOnly?await cp(e):[await si(e)];return lp(n,async()=>{r.readOnly&&Pn.getStore()?.runtimeRoots.set(e,n),Pn.getStore()?.projects.add(JSON.stringify([e,t]));let i=await Xy(e,t,{...r,partition:"active"}),o=await Xy(e,t,{...r,partition:"history"});return{active:i,history:o}},r.readOnly===!0)}function xl(e,t){return JSON.stringify(Object.entries(e).sort())===JSON.stringify(Object.entries(t).sort())}async function ek(e,t,r){return mN(),Pn.run(null,()=>An(async()=>{let n=await ci(e);return fr(t.workflow,t.change),r(n)}))}async function o2(e,t,r){let n=ap(t,t.workflow,t.change);if(n.format!=="sdk"||n.workflow!=="native"||n.application!=="native")throw new Error("Only builtin Native owners can enter or leave history");await ek(e,n,i=>Mx(i,n,r))}async function a2(e,t){let r=or.posix.dirname(t).split("/");for(let n=r.length;n>=0;n-=1){let i=or.join(e,...r.slice(0,n)),o;try{o=await Px.open(i,"r"),await o.sync()}catch(a){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(a.code??""))throw a}finally{await o?.close()}}}async function Mx(e,t,r,n=!1){let i=t,o=r==="history"?"active":"history",a=fr(t.workflow,t.change,o),s=fr(t.workflow,t.change,r),c=await Gn(e,a,t.workflow,t.change),l=await Gn(e,s,t.workflow,t.change);if(!c&&!l||c&&!xl(c,i)||l&&!xl(l,i))throw new Error(`Change runtime owner identity changed for ${t.workflow}/${t.change}`);l||(await Vt(e,or.posix.dirname(s),{label:"change runtime owner directory"}),await Lt(or.join(e,s),`${JSON.stringify(i)}
|
|
205
|
+
`,{containedRoot:e,exclusive:!0,requireAtomicPublication:!0})),await a2(e,s),c&&await Xo(or.join(e,a),{containedRoot:e,beforeRemove:async()=>{let u=await Gn(e,a,t.workflow,t.change),f=await Gn(e,s,t.workflow,t.change);if(!u||!f||!xl(u,i)||!xl(f,i))throw new Error("Change runtime owner changed during partition move")}}),n||await sp(e,t.workflow,t.change),await Dx(e,t,n)}async function tk(e,t){await o2(e,t,"history")}async function qx(e,t,r){return ek(e,{workflow:t,change:r},async n=>{let i=await Gn(n,fr(t,r),t,r),o=await Gn(n,fr(t,r,"history"),t,r);if(i&&o&&!xl(i,o))throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);let a=i??o;if(i&&!o&&(i.format!=="sdk"||i.application!=="native"))return i;if(!a||a.format!=="sdk"||a.workflow!=="native"||a.application!=="native")throw new Error("Only builtin Native owners can be recovered from history");return await Mx(n,a,"active",!0),a})}async function Fx(e,t,r={}){let n=fr(t.workflow,t.change),i=ap(t,t.workflow,t.change);return ek(e,i,async o=>{if(await Gn(o,fr(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 Vt(o,or.posix.dirname(n),{label:"change runtime owner directory"});try{await Lt(or.join(o,...n.split("/")),`${JSON.stringify(i)}
|
|
206
|
+
`,{containedRoot:o,exclusive:!0,requireAtomicPublication:!0})}catch(s){if(s.code!=="EEXIST")throw s;let c=await Gn(o,n,t.workflow,t.change);if(JSON.stringify(c)!==JSON.stringify(i))throw new Error(`Change ${t.workflow}/${t.change} is already bound to another Runtime`,{cause:s})}return(r.canonical||await sp(o,t.workflow,t.change))&&await Dx(o,i),i})}function lo(e,t,r={}){return Fx(e,t,r)}function rk(e,t){return Fx(e,t)}var Tn,Zy,t2,Tx,Pn,Bx,Wx,n2,pr=_(()=>{"use strict";Xr();bn();Jn();Di();ct();Xr();Tn="comet.change-owner.v1",Zy=["native","classic-full","classic-hotfix","classic-tweak"],t2=Qt("changeOwnerRuntimeRoots",e=>Ih(e)),Tx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;Pn=new e2,Bx=ai("verifiedOwnerBatchResults",()=>new Map),Wx=(e,t,r)=>`${JSON.stringify([e,t])}\0${r}`;n2=Qt("changeOwnerPartitions",Lx)});function ak(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function Yx(e){ua=e}function gs(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 Ce(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(ar.caret,"$1"),r=r.replace(i,a),n},getRegex:()=>new RegExp(r,t)};return n}function Yn(e,t){if(t){if(ar.escapeTest.test(e))return e.replace(ar.escapeReplace,Ux)}else if(ar.escapeTestNoEncode.test(e))return e.replace(ar.escapeReplaceNoEncode,Ux);return e}function Jx(e){try{e=encodeURI(e).replace(ar.percentDecode,"%")}catch{return null}return e}function zx(e,t){let r=e.replace(ar.findPipe,(o,a,s)=>{let c=!1,l=a;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),n=r.split(ar.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(ar.slashPipe,"|");return n}function uo(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let o=e.charAt(n-i-1);if(o===t&&!r)i++;else if(o!==t&&r)i++;else break}return e.slice(0,n-i)}function Kx(e){let t=e.split(`
|
|
207
|
+
`),r=t.length-1;for(;r>=0&&ar.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
208
|
+
`)}function Z2(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 eJ(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let o=4-r%4;n+=" ".repeat(o),r+=o}else n+=i,r++;return n}function Gx(e,t,r,n,i){let o=t.href,a=t.title||null,s=e[1].replace(i.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";n.state.inLink=!0;let l=n.state.linkEmitted,u=n.state.inRawBlock;n.state.linkEmitted=!1;let f=n.inlineTokens(s),d=n.state.linkEmitted;if(n.state.linkEmitted=l,n.state.inLink=!1,!c){if(d){n.state.inRawBlock=u;return}n.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:o,title:a,text:s,tokens:f}}function tJ(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
|
|
209
|
+
`).map(o=>{let a=o.match(r.other.beginningSpace);if(a===null)return o;let[s]=a;return s.length>=i.length?o.slice(i.length):o}).join(`
|
|
210
|
+
`)}function Ke(e,t){return la.parse(e,t)}function nJ(...e){return la.use(...e),Ke.defaults=la.defaults,Yx(Ke.defaults),Ke}var ua,ca,s2,ar,c2,l2,u2,Ol,d2,sk,Xx,Zx,f2,ck,p2,lk,m2,h2,mp,uk,g2,eP,v2,w2,y2,dk,Hx,k2,A2,b2,N2,tP,R2,Ai,vs,$l,S2,E2,rP,C2,_2,I2,nP,x2,P2,T2,O2,iP,$2,j2,D2,B2,W2,L2,V2,M2,q2,F2,H2,Q2,U2,J2,dp,z2,oP,aP,K2,Qx,fk,G2,nk,Y2,up,Pl,X2,Ux,fp,mr,pp,pk,On,Tl,rJ,la,mZ,hZ,sP,gZ,vZ,wZ,mk=_(()=>{"use strict";ua=ak();ca={exec:()=>null};s2=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),ar={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:gs(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:gs(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:gs(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:gs(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:gs(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:gs(e=>new RegExp(`^ {0,${e}}>`))},c2=/^(?:[ \t]*(?:\n|$))+/,l2=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,u2=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ol=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,d2=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,sk=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Xx=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Zx=Ce(Xx).replace(/bull/g,sk).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(),f2=Ce(Xx).replace(/bull/g,sk).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(),ck=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,p2=/^[^\n]+/,lk=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,m2=Ce(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",lk).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),h2=Ce(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,sk).getRegex(),mp="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",uk=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,g2=Ce("^ {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",uk).replace("tag",mp).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),eP=e=>Ce(ck).replace("hr",Ol).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",mp).getRegex(),v2=eP(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),w2=eP(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),y2=Ce(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",w2).getRegex(),dk={blockquote:y2,code:l2,def:m2,fences:u2,heading:d2,hr:Ol,html:g2,lheading:Zx,list:h2,newline:c2,paragraph:v2,table:ca,text:p2},Hx=Ce("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ol).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",mp).getRegex(),k2={...dk,lheading:f2,table:Hx,paragraph:Ce(ck).replace("hr",Ol).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Hx).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",mp).getRegex()},A2={...dk,html:Ce(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",uk).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:ca,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ce(ck).replace("hr",Ol).replace("heading",` *#{1,6} *[^
|
|
211
|
+
]`).replace("lheading",Zx).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},b2=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,N2=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,tP=/^( {2,}|\\)\n(?!\s*$)/,R2=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ai=/[\p{P}\p{S}]/u,vs=/[\s\p{P}\p{S}]/u,$l=/[^\s\p{P}\p{S}]/u,S2=Ce(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,vs).getRegex(),E2=/[\p{Pi}\p{Ps}"']/u,rP=/(?!~)[\p{P}\p{S}]/u,C2=/(?!~)[\s\p{P}\p{S}]/u,_2=/(?:[^\s\p{P}\p{S}]|~)/u,I2=Ce(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",s2?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),nP=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,x2=Ce(nP,"u").replace(/punct/g,Ai).getRegex(),P2=Ce(nP,"u").replace(/punct/g,rP).getRegex(),T2=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,O2=Ce(T2,"u").replace(/openQuote/g,E2).replace(/punct/g,Ai).getRegex(),iP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",$2=Ce(iP,"gu").replace(/notPunctSpace/g,$l).replace(/punctSpace/g,vs).replace(/punct/g,Ai).getRegex(),j2=Ce(iP,"gu").replace(/notPunctSpace/g,_2).replace(/punctSpace/g,C2).replace(/punct/g,rP).getRegex(),D2="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",B2=Ce(D2,"gu").replace(/notPunctSpace/g,$l).replace(/punctSpace/g,vs).replace(/punct/g,Ai).getRegex(),W2=Ce("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,$l).replace(/punctSpace/g,vs).replace(/punct/g,Ai).getRegex(),L2="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",V2=Ce(L2,"gu").replace(/notPunctSpace/g,$l).replace(/punctSpace/g,vs).replace(/punct/g,Ai).getRegex(),M2=Ce(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ai).getRegex(),q2="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",F2=Ce(q2,"gu").replace(/notPunctSpace/g,$l).replace(/punctSpace/g,vs).replace(/punct/g,Ai).getRegex(),H2=Ce(/\\(punct)/,"gu").replace(/punct/g,Ai).getRegex(),Q2=Ce(/^<(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(),U2=Ce(uk).replace("(?:-->|$)","-->").getRegex(),J2=Ce("^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",U2).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),dp=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,z2=Ce(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",dp).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),oP=Ce(/^!?\[(label)\]\[(ref)\]/).replace("label",dp).replace("ref",lk).getRegex(),aP=Ce(/^!?\[(ref)\](?:\[\])?/).replace("ref",lk).getRegex(),K2=Ce("reflink|nolink(?!\\()","g").replace("reflink",oP).replace("nolink",aP).getRegex(),Qx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,fk={_backpedal:ca,anyPunctuation:H2,autolink:Q2,blockSkip:I2,br:tP,code:N2,del:ca,delLDelim:ca,delRDelim:ca,emStrongLDelim:x2,emStrongRDelimAst:$2,emStrongRDelimUnd:W2,escape:b2,link:z2,nolink:aP,punctuation:S2,reflink:oP,reflinkSearch:K2,tag:J2,text:R2,url:ca},G2={...fk,emStrongLDelim:O2,emStrongRDelimAst:B2,emStrongRDelimUnd:V2,link:Ce(/^!?\[(label)\]\((.*?)\)/).replace("label",dp).getRegex(),reflink:Ce(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",dp).getRegex()},nk={...fk,emStrongRDelimAst:j2,emStrongLDelim:P2,delLDelim:M2,delRDelim:F2,url:Ce(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Qx).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:Ce(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Qx).getRegex()},Y2={...nk,br:Ce(tP).replace("{2,}","*").getRegex(),text:Ce(nk.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},up={normal:dk,gfm:k2,pedantic:A2},Pl={normal:fk,gfm:nk,breaks:Y2,pedantic:G2},X2={"&":"&","<":"<",">":">",'"':""","'":"'"},Ux=e=>X2[e];fp=class{options;rules;lexer;constructor(e){this.options=e||ua}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]:Kx(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=tJ(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=uo(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:uo(t[0],`
|
|
212
|
+
`),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:uo(t[0],`
|
|
213
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=uo(t[0],`
|
|
214
|
+
`).split(`
|
|
215
|
+
`),n="",i="",o=[];for(;r.length>0;){let a=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),a=!0;else if(!a)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
|
|
216
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
217
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
218
|
+
${l}`:l,i=i?`${i}
|
|
219
|
+
${u}`:u;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=f,r.length===0)break;let d=o.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let p=d,h=r.join(`
|
|
220
|
+
`),m=p.raw+`
|
|
221
|
+
`+h.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(m);o[o.length-1]=g,n=`${n}
|
|
222
|
+
${h}`,i=i.substring(0,i.length-p.text.length)+g.text;break}else if(d?.type==="list"){let p=d,h=p.raw+`
|
|
223
|
+
`+r.join(`
|
|
224
|
+
`),m=this.list(h);o[o.length-1]=m,n=n.substring(0,n.length-d.raw.length)+m.raw,i=i.substring(0,i.length-p.raw.length)+m.raw,r=h.substring(o.at(-1).raw.length).split(`
|
|
225
|
+
`);continue}}return{type:"blockquote",raw:n,tokens:o,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 o=this.rules.other.listItemRegex(r),a=!1;for(;e;){let c=!1,l="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let f=eJ(t[2].split(`
|
|
226
|
+
`,1)[0],t[1].length),d=e.split(`
|
|
227
|
+
`,1)[0],p=!f.trim(),h=0;if(this.options.pedantic?(h=2,u=f.trimStart()):p?h=t[1].length+1:(h=f.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=f.slice(h),h+=t[1].length),p&&this.rules.other.blankLine.test(d)&&(l+=d+`
|
|
228
|
+
`,e=e.substring(d.length+1),c=!0),!c){let m=this.rules.other.nextBulletRegex(h),g=this.rules.other.hrRegex(h),v=this.rules.other.fencesBeginRegex(h),w=this.rules.other.headingBeginRegex(h),A=this.rules.other.htmlBeginRegex(h),N=this.rules.other.blockquoteBeginRegex(h);for(;e;){let b=e.split(`
|
|
229
|
+
`,1)[0],E;if(d=b,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),E=d):E=d.replace(this.rules.other.tabCharGlobal," "),v.test(d)||w.test(d)||A.test(d)||N.test(d)||m.test(d)||g.test(d))break;if(E.search(this.rules.other.nonSpaceChar)>=h||!d.trim())u+=`
|
|
230
|
+
`+E.slice(h);else{if(p||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||v.test(f)||w.test(f)||g.test(f))break;u+=`
|
|
231
|
+
`+d}p=!d.trim(),l+=b+`
|
|
232
|
+
`,e=e.substring(b.length+1),f=E.slice(h)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(a=!0)),i.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=l}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c of i.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!i.loose){let l=c.tokens.filter(f=>f.type==="space"),u=l.length>0&&l.some(f=>this.rules.other.anyLine.test(f.raw));i.loose=u}for(let c of i.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let f={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=f.checked,i.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=f.raw+c.tokens[0].raw,c.tokens[0].text=f.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(f)):c.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):c.tokens.unshift(f)}}else c.task&&(c.task=!1)}if(i.loose)for(let c of i.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=Kx(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:uo(t[0],`
|
|
233
|
+
`),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=zx(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
234
|
+
`):[],o={type:"table",raw:uo(t[0],`
|
|
235
|
+
`),header:[],align:[],rows:[]};if(r.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?o.align.push("right"):this.rules.other.tableAlignCenter.test(a)?o.align.push("center"):this.rules.other.tableAlignLeft.test(a)?o.align.push("left"):o.align.push(null);for(let a=0;a<r.length;a++)o.header.push({text:r[a],tokens:this.lexer.inline(r[a]),header:!0,align:o.align[a]});for(let a of i)o.rows.push(zx(a,o.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:uo(t[0],`
|
|
236
|
+
`),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)===`
|
|
237
|
+
`?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 o=uo(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=Z2(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(n);o&&(n=o[1],i=o[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)),Gx(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 o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return Gx(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,o,a,s=i,c=0,l=n[0][0],u=r===l,f=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+i);(n=f.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o)continue;if(a=[...o].length,n[3]||n[4]){s+=a;continue}else if(n[5]||n[6]){if(i%3&&!((i+a)%3)){c+=a;continue}if(u)break}if(s-=a,s>0)continue;a=Math.min(a,a+s+c);let d=[...n[0]][0].length,p=e.slice(0,i+n.index+d+a);if(Math.min(i,a)%2){let m=p.slice(1,-1);return{type:"em",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}let h=p.slice(2,-2);return{type:"strong",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}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,o,a,s=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(n=c.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o||(a=[...o].length,a!==i))continue;if(n[3]||n[4]){s+=a;continue}if(s-=a,s>0)continue;a=Math.min(a,a+s);let l=[...n[0]][0].length,u=e.slice(0,i+n.index+l+a),f=u.slice(i,-i);return{type:"del",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}}}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}}}},mr=class ik{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ua,this.options.tokenizer=this.options.tokenizer||new fp,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:ar,block:up.normal,inline:Pl.normal};this.options.pedantic?(r.block=up.pedantic,r.inline=Pl.pedantic):this.options.gfm&&(r.block=up.gfm,this.options.breaks?r.inline=Pl.breaks:r.inline=Pl.gfm),this.tokenizer.rules=r}static get rules(){return{block:up,inline:Pl}}static lex(t,r){return new ik(r).lex(t)}static lexInline(t,r){return new ik(r).inlineTokens(t)}lex(t){t=t.replace(ar.carriageReturn,`
|
|
238
|
+
`),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(ar.tabCharGlobal," ").replace(ar.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(s=>(o=s.call({lexer:this},t,r))?(t=t.substring(o.raw.length),r.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let s=r.at(-1);o.raw.length===1&&s!==void 0?s.raw+=`
|
|
239
|
+
`:r.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
240
|
+
`)?"":`
|
|
241
|
+
`)+o.raw,s.text+=`
|
|
242
|
+
`+o.text,this.inlineQueue.at(-1).src=s.text):r.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
243
|
+
`)?"":`
|
|
244
|
+
`)+o.raw,s.text+=`
|
|
245
|
+
`+o.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},r.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),r.push(o);continue}let a=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(a=t.substring(0,s+1))}if(this.state.top&&(o=this.tokenizer.paragraph(a))){let s=r.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
246
|
+
`)?"":`
|
|
247
|
+
`)+o.raw,s.text+=`
|
|
248
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(o),n=a.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
249
|
+
`)?"":`
|
|
250
|
+
`)+o.raw,s.text+=`
|
|
251
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(o);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],o=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(o+1,-1)))&&!(o>1&&this.linkInText(i.slice(1,o-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let f=l.slice(1,u-1);if(this.linkInText(f))return"["+f.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};n=n.replace(s,c)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o="",a=1/0;for(;t;){if(t.length<a)a=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(o=""),i=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,n,o)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,n,o)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),f;this.options.extensions.startInline.forEach(d=>{f=d.call({lexer:this},u),typeof f=="number"&&f>=0&&(l=Math.min(l,f))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(o=s.raw.slice(-1)),i=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);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)}},pp=class{options;parser;constructor(e){this.options=e||ua}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(ar.notSpaceStart)?.[0],i=e.replace(ar.endingNewline,"")+`
|
|
252
|
+
`;return n?'<pre><code class="language-'+Yn(n)+'">'+(r?i:Yn(i,!0))+`</code></pre>
|
|
253
|
+
`:"<pre><code>"+(r?i:Yn(i,!0))+`</code></pre>
|
|
254
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
255
|
+
${this.parser.parse(e)}</blockquote>
|
|
256
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
257
|
+
`}hr(e){return`<hr>
|
|
258
|
+
`}list(e){let t=e.ordered,r=e.start,n="";for(let a=0;a<e.items.length;a++){let s=e.items[a];n+=this.listitem(s)}let i=t?"ol":"ul",o=t&&r!==1?' start="'+r+'"':"";return"<"+i+o+`>
|
|
259
|
+
`+n+"</"+i+`>
|
|
260
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
261
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
262
|
+
`}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 o=e.rows[i];r="";for(let a=0;a<o.length;a++)r+=this.tablecell(o[a]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
|
|
263
|
+
<thead>
|
|
264
|
+
`+t+`</thead>
|
|
265
|
+
`+n+`</table>
|
|
266
|
+
`}tablerow({text:e}){return`<tr>
|
|
267
|
+
${e}</tr>
|
|
268
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
269
|
+
`}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>${Yn(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=Jx(e);if(i===null)return n;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+Yn(t)+'"'),o+=">"+n+"</a>",o}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=Jx(e);if(i===null)return Yn(r);e=i;let o=`<img src="${e}" alt="${Yn(r)}"`;return t&&(o+=` title="${Yn(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Yn(e.text)}},pk=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}},On=class ok{options;renderer;textRenderer;constructor(t){this.options=t||ua,this.options.renderer=this.options.renderer||new pp,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new pk}static parse(t,r){return new ok(r).parse(t)}static parseInline(t,r){return new ok(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 a=i,s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(a.type)){r+=s||"";continue}}let o=i;switch(o.type){case"space":{r+=this.renderer.space(o);break}case"hr":{r+=this.renderer.hr(o);break}case"heading":{r+=this.renderer.heading(o);break}case"code":{r+=this.renderer.code(o);break}case"table":{r+=this.renderer.table(o);break}case"blockquote":{r+=this.renderer.blockquote(o);break}case"list":{r+=this.renderer.list(o);break}case"checkbox":{r+=this.renderer.checkbox(o);break}case"html":{r+=this.renderer.html(o);break}case"def":{r+=this.renderer.def(o);break}case"paragraph":{r+=this.renderer.paragraph(o);break}case"text":{r+=this.renderer.text(o);break}default:{let a='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){n+=s||"";continue}}let a=o;switch(a.type){case"escape":{n+=r.text(a);break}case"html":{n+=r.html(a);break}case"link":{n+=r.link(a);break}case"image":{n+=r.image(a);break}case"checkbox":{n+=r.checkbox(a);break}case"strong":{n+=r.strong(a);break}case"em":{n+=r.em(a);break}case"codespan":{n+=r.codespan(a);break}case"br":{n+=r.br(a);break}case"del":{n+=r.del(a);break}case"text":{n+=r.text(a);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},Tl=class{options;block;constructor(e){this.options=e||ua}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?mr.lex:mr.lexInline}provideParser(e=this.block){return e?On.parse:On.parseInline}},rJ=class{defaults=ak();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=On;Renderer=pp;TextRenderer=pk;Lexer=mr;Tokenizer=fp;Hooks=Tl;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 o of i.header)r=r.concat(this.walkTokens(o.tokens,t));for(let o of i.rows)for(let a of o)r=r.concat(this.walkTokens(a.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(o=>{let a=i[o].flat(1/0);r=r.concat(this.walkTokens(a,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 o=t.renderers[i.name];o?t.renderers[i.name]=function(...a){let s=i.renderer.apply(this,a);return s===!1&&(s=o.apply(this,a)),s}: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 o=t[i.level];o?o.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 pp(this.defaults);for(let o in r.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let a=o,s=r.renderer[a],c=i[a];i[a]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new fp(this.defaults);for(let o in r.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let a=o,s=r.tokenizer[a],c=i[a];i[a]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new Tl;for(let o in r.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,s=r.hooks[a],c=i[a];Tl.passThroughHooks.has(o)?i[a]=l=>{if(this.defaults.async&&Tl.passThroughHooksRespectAsync.has(o))return(async()=>{let f=await s.call(i,l);return c.call(i,f)})();let u=s.call(i,l);return c.call(i,u)}:i[a]=(...l)=>{if(this.defaults.async)return(async()=>{let f=await s.apply(i,l);return f===!1&&(f=await c.apply(i,l)),f})();let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,o=r.walkTokens;n.walkTokens=function(a){let s=[];return s.push(o.call(this,a)),i&&(s=s.concat(i.call(this,a))),s}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return mr.lex(e,t??this.defaults)}parser(e,t){return On.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return o(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 o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(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 a=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer(e):e?mr.lex:mr.lexInline)(a,i),c=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(c,i.walkTokens));let l=await(i.hooks?await i.hooks.provideParser(e):e?On.parse:On.parseInline)(c,i);return i.hooks?await i.hooks.postprocess(l):l})().catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let a=(i.hooks?i.hooks.provideLexer(e):e?mr.lex:mr.lexInline)(t,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let s=(i.hooks?i.hooks.provideParser(e):e?On.parse:On.parseInline)(a,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(a){return o(a)}}}onError(e,t){return r=>{if(r.message+=`
|
|
270
|
+
Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+Yn(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},la=new rJ;Ke.options=Ke.setOptions=function(e){return la.setOptions(e),Ke.defaults=la.defaults,Yx(Ke.defaults),Ke};Ke.getDefaults=ak;Ke.defaults=ua;Ke.use=nJ;Ke.walkTokens=function(e,t){return la.walkTokens(e,t)};Ke.parseInline=la.parseInline;Ke.Parser=On;Ke.parser=On.parse;Ke.Renderer=pp;Ke.TextRenderer=pk;Ke.Lexer=mr;Ke.lexer=mr.lex;Ke.Tokenizer=fp;Ke.Hooks=Tl;Ke.parse=Ke;mZ=Ke.options,hZ=Ke.setOptions,sP=Ke.walkTokens,gZ=Ke.parseInline,vZ=On.parse,wZ=mr.lex});import{promises as cP}from"node:fs";import ws from"node:path";import{createHash as iJ}from"node:crypto";function F(e){throw new k("INVALID_WORKFLOW",`${e};请修正适配契约或恢复已固定的依赖后继续`)}async function fo(e,t={}){let r={},n=async i=>{let o=await cP.readdir(ws.join(e,i),{withFileTypes:!0});for(let a of o.sort((s,c)=>s.name.localeCompare(c.name,"en"))){let s=i?`${i}/${a.name}`:a.name;if(a.isSymbolicLink()&&F(`依赖不允许符号链接:${s}`),a.isDirectory())await n(s);else if(a.isFile()){let c=await qe(e,s,16777216,{label:`应用依赖 ${s}`});r[s]=c.bytes.toString("base64")}else F(`依赖包含非常规文件:${s}`)}};return await n(""),!t.allowEmpty&&Object.keys(r).length===0&&F("依赖目录为空"),r}function po(e){return $(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,iJ("sha256").update(Buffer.from(r,"base64")).digest("hex")])))}function oJ(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Buffer.from(r,"base64").toString("utf8")]))}function aJ(e,t){for(let[l,u]of[[e,"输入"],[t,"输出"]])(!l||typeof l!="object"||Array.isArray(l))&&F(`${u} 必须提供可检查的 JSON Schema`),l.$async===!0&&F(`${u} 不支持异步 Schema,请注册实际 SDK 验证器`);let r=JSON.stringify([e,t]),n=jl.get(r);if(n)return n;let[i,o]=JSON.parse(r),a=new lP.Ajv({strict:!0,allErrors:!0}),s=a.compile(i),c={ajv:a,input:s,output:JSON.stringify(i)===JSON.stringify(o)?s:a.compile(o)};return jl.size>=64&&jl.delete(jl.keys().next().value),jl.set(r,c),c}async function sJ(e){let t=await cP.realpath(e),r=await fo(t),n=oJ(r);n["SKILL.md"]?.trim()||F(`Skill 缺少真实 SKILL.md:${e}`);for(let[i,o]of Object.entries(n)){if(!i.endsWith(".md"))continue;let a=[];sP(mr.lex(o),s=>{(s.type==="link"||s.type==="image")&&a.push(s.href)});for(let s of a){if(/^(?:[a-z][a-z\d+.-]*:|#|\/\/)/iu.test(s))continue;let c;try{c=decodeURIComponent(s.split(/[?#]/u)[0])}catch{F(`Skill 引用路径编码无效:${i} -> ${s}`)}if(!c)continue;let l=ws.posix.normalize(ws.posix.join(ws.posix.dirname(i),c));(l===".."||l.startsWith("../")||ws.posix.isAbsolute(c))&&F(`Skill 引用越过依赖目录:${i} -> ${s}`),!Object.hasOwn(n,l)&&!Object.keys(n).some(u=>u.startsWith(`${l}/`))&&F(`Skill 引用资源缺失:${i} -> ${s}`)}}return{root:t,files:n,contentHash:po(r)}}async function hk(e,t){(!e||typeof e.id!="string"||!e.id.trim()||typeof e.root!="string")&&F("Skill 依赖缺少身份或目录");let r=await sJ(ws.resolve(t,e.root));e.contentHash!==r.contentHash&&F(`Skill 内容发生漂移:${e.id}`);let n=e.adapter;(!n||!["guidance","action","check","subworkflow"].includes(n.kind)||!["read","write","external"].includes(n.sideEffect)||!["none","user"].includes(n.interaction)||!["self-report","machine-check","independent-review"].includes(n.completion)||!["stop","repair","retry"].includes(n.failure)||!["manual","reconcile"].includes(n.recovery)||typeof n.controlsApproval!="boolean")&&F(`Skill 适配契约不完整:${e.id}`),(!Array.isArray(n.scope)||!n.scope.length||n.scope.some(s=>typeof s!="string"||!s.trim())||!Array.isArray(n.requiredCapabilities)||n.requiredCapabilities.some(s=>typeof s!="string"||!s.trim()))&&F(`Skill 缺少范围或宿主能力:${e.id}`),n.kind==="guidance"&&(n.sideEffect!=="read"||n.controlsApproval||n.interaction!=="none")&&F(`有副作用或审批逻辑的 Skill 不能作为普通指导:${e.id}`),n.sideEffect==="external"&&n.recovery!=="reconcile"&&F(`外部操作缺少未知结果核对契约:${e.id}`);let i=n.review;(!i||i.status!=="accepted"||!i.reviewedBy?.trim()||i.contentHash!==r.contentHash||!Array.isArray(i.capabilities)||!i.capabilities.length||!Array.isArray(i.effects)||!i.effects.length)&&F(`Skill 必需能力尚未完成内容适配审查:${e.id}`);for(let s of[...i.capabilities,...i.effects])(!s||!s.excerpt?.trim()||!r.files[s.file]?.includes(s.excerpt))&&F(`Skill 审查证据与真实文件不匹配:${e.id}`);i.capabilities.some(s=>typeof s.id!="string"||!s.id.trim())&&F(`Skill 能力证据缺少身份:${e.id}`);let o=aJ(n.inputSchema,n.outputSchema),a=(s,c)=>l=>{s(l)||F(`${e.id} ${c} 不匹配:${o.ajv.errorsText(s.errors)}`)};return{...r,id:e.id,adapter:n,validateInput:a(o.input,"输入"),validateOutput:a(o.output,"输出")}}var lP,jl,ys=_(()=>{"use strict";lP=kr(Fd(),1);mk();et();ct();jl=new Map});import $n from"node:path";import{realpathSync as cJ,existsSync as lJ}from"node:fs";function gk(e){let t=structuredClone(e),r=n=>{if(!(!n||typeof n!="object"||Object.isFrozen(n))){for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(t),t}function pn(e){return["running","unknown"].includes(e.status)||e.status==="cancelled"&&e.type!=="invoke_skill"&&!!e.claim&&!e.cancellation&&!e.executionStop}function hp(e,t){let r=(n,i)=>{let o=$n.relative($n.resolve(n),$n.resolve(i));return!o||!$n.isAbsolute(o)&&o!==".."&&!o.startsWith(".."+$n.sep)};return r(e,t)||r(t,e)}function gp(e,t,r){return e.manifest.bindings.filter(n=>n.workflowId===t.workflow.id&&n.stepId===r.stepId&&n.usage==="action").flatMap(n=>{let i=e.manifest.skills.find(a=>a.id===n.skillId);if(!i||i.adapter.sideEffect==="read")return[];if(i.adapter.sideEffect!=="write")return i.adapter.scope.map(a=>({ref:a,workspace:!1,write:i.adapter.sideEffect==="write"}));let o=e.projectRoot??process.cwd();if(n.workspaceFrom){o=r.input;for(let a of n.workspaceFrom.split("."))o=o&&typeof o=="object"?o[a]:void 0}if(typeof o!="string"||!$n.isAbsolute(o))throw new k("COMMAND_REJECTED","Skill 缺少实际写入工作区");return i.adapter.scope.map(a=>{let s=$n.resolve(o,a),c=s;for(;!lJ(c)&&c!==$n.dirname(c);)c=$n.dirname(c);return{ref:$n.resolve(cJ(c),$n.relative(c,s)),workspace:!!n.workspaceFrom,write:!0}})})}function ks(e,t,r,n=[]){let i=(a,s)=>gp(e,a,s),o=i(t,r);if(o.length){for(let a of[t,...n.filter(s=>s.runId!==t.runId)])for(let s of a.actions)if((a.runId!==t.runId||s.id!==r.id)&&(pn(s)||a.runId===t.runId&&s.status==="pending")&&i(a,s).some(c=>o.some(l=>{if(a.runId===t.runId&&c.write&&l.write&&c.workspace!==l.workspace)throw new k("COMMAND_REJECTED","并行写入不能混用声明工作区和默认范围;请为两项工作指定实际工作区");return!c.write||!l.write?l.ref===c.ref:hp(c.ref,l.ref)}))){let c=new k(a.runId===t.runId?"COMMAND_REJECTED":"SCOPE_HELD",`Skill 写入范围存在并行冲突,仍由 Run ${a.runId} 的 ${s.stepId} 占用;请停止原执行或提交真实结果`);throw Object.assign(c,{blockedRunIds:[a.runId]}),c}}}function uP(e,t,r){let n=e.manifest.bindings.filter(a=>a.workflowId===r.workflow.id&&a.stepId===t.stepId&&a.usage==="action"),i=n[0],o=i?e.skills.get(i.skillId):void 0;if(n.length!==1||!i||!o||t.type!=="invoke_skill"||t.ref!==i.skillId)throw new k("EXECUTOR_UNSUPPORTED","Action 未绑定到唯一的真实 Skill");return{binding:i,skill:o}}function As(e,t,r){let{binding:n,skill:i}=uP(e,t,r);if(i.validateInput(t.input),i.adapter.sideEffect!=="read"){let o=n.authorizationFrom?r.actionContexts[t.id]?.results[n.authorizationFrom]:void 0,a=r.waits.find(s=>s.stepId===n.authorizationFrom&&s.sequence===o?.sequence);if(!o||a?.status!=="resolved"||!a.decision||!(n.authorizationChoices??["approved"]).includes(a.decision.choice)||a.decision.proposalHash!==a.proposalHash||$(o.value)!==$({choice:a.decision.choice,proposal:a.proposal}))throw new k("STALE_PROPOSAL","此工作缺少父流程的当前批准记录")}return{binding:n,skill:i}}function dP(e,t){let r=async(n,i,o)=>{if(!o)throw new k("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=As(e,n,o);if(ks(e,o,n),s.adapter.requiredCapabilities.some(c=>!t.capabilities.includes(c)))throw new k("CAPABILITY_REQUIRED","宿主缺少 Skill 必需能力");if(s.adapter.sideEffect==="external"&&!t.reconcile)throw new k("RECONCILIATION_REQUIRED","外部操作没有结果核对适配器,不能执行");if(!await t.authorize({action:n,run:o,binding:a,skill:s,context:i}))throw new k("COMMAND_REJECTED","宿主授权不覆盖此 Skill、范围或副作用")};return{id:t.id,capabilities:t.capabilities,preflight:r,supports:n=>n.type==="invoke_skill"&&e.manifest.bindings.some(i=>i.stepId===n.stepId&&i.skillId===n.ref&&i.usage==="action"),async execute(n,i,o){if(!o)throw new k("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=uP(e,n,o);return await t.invokeSkill({action:n,run:o,binding:a,skill:s,context:i})}}}var vp=_(()=>{"use strict";et()});import{randomUUID as fP}from"node:crypto";import{promises as uJ}from"node:fs";import da from"node:path";function wk(e){let t=e.rootDir,r=p=>{throw new k("STORE_INDEX_CORRUPT",p)},n=async p=>{let h=da.parse(t).root;if(!(await oe(h,da.relative(h,t).replaceAll("\\","/"),{label:"应用 Store",expected:"directory"})).exists)return null;let m=`${vk}/${p}.json`;if(!(await oe(t,m,{label:"应用存储索引",expected:"file"})).exists)return null;try{let g=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await qe(t,m,Number.MAX_SAFE_INTEGER,{label:"应用存储索引"})).bytes));if(p==="inventory"){let{checksum:v,...w}=g;return v!==$(w)&&r("独立成员清单校验值不一致"),w}return g}catch{return r(`应用存储索引 ${p} 无法读取;请保留现场并显式检查`)}},i=async(p,h)=>{await Vt(t,vk,{label:"应用存储索引"}),await Lt(da.join(t,vk,`${p}.json`),JSON.stringify(["index","inventory"].includes(p)?{...h,checksum:$(h)}:h)+`
|
|
271
|
+
`,{containedRoot:t,requireAtomicPublication:!0})},o=async()=>JSON.stringify(await Promise.all(["",".runtime-store-v2",".runtime-store-history"].map(async p=>{let h=await oe(p?t:da.dirname(t),p||da.basename(t),{label:"应用存储分区",expected:"directory"});if(!h.exists)return null;let m=await uJ.lstat(h.target);return[m.dev,m.ino,m.mtimeMs,m.ctimeMs]})));async function a(){let p=await n("index");if(!p)return null;let{checksum:h,...m}=p;return h!==$(m)&&r("应用存储索引校验值不一致"),m&&(m.schema!==wp||typeof m.epoch!="string"||!["building","ready"].includes(m.state)||!Array.isArray(m.holders)||m.holders.some(g=>typeof g!="string")||new Set(m.holders).size!==m.holders.length||!Number.isSafeInteger(m.memberCount)||m.memberCount<0||m.pending!==null&&(!m.pending||typeof m.pending.runId!="string"||typeof m.pending.registering!="boolean"))&&r("应用存储索引格式损坏"),m}async function s(p){let h=await n("inventory");return(!h||h.epoch!==p.epoch||!Array.isArray(h.members)||h.members.some(m=>typeof m!="string")||new Set(h.members).size!==h.members.length||h.aborted!==void 0&&(!Array.isArray(h.aborted)||h.aborted.some(m=>typeof m!="string"||h.members.includes(m))||new Set(h.aborted).size!==h.aborted.length)||h.members.length!==p.memberCount||$(h)!==p.inventoryHash)&&r("应用存储成员清单与 epoch/hash 不一致,不能忽略已登记 Run"),h}async function c(p,h){let m=await By({rootDir:t}),g=[],v=[];for(let w of m){(w.error||!w.runId)&&r(`Run 无法发现:${w.storageKey} (${w.error?.code??"missing identity"})`);let A=w.runId;await e.settle?.(A);let N=await e.read(A);!N&&h?.aborted?.includes(A)&&!h.members.includes(A)||(N||r(`已发现的 Run 正文缺失:${A}`),g.push(A),await e.holds(N)&&v.push(A))}return h?.members.some(w=>!g.includes(w))&&r("已登记 Run 缺失,不能通过重建索引丢弃占用;请恢复原记录"),p.holders=v.sort(),{epoch:p.epoch,members:g.sort(),...h?.aborted?{aborted:h.aborted.filter(w=>!g.includes(w))}:{}}}async function l(){let p=da.parse(t).root;await Vt(p,da.relative(p,t).replaceAll("\\","/"),{label:"应用 Store"});let h=await a();if(h?.state==="ready")return h;h||(await n("inventory")&&r("成员清单存在但索引缺失,请显式检查,不能静默初始化"),h={schema:wp,epoch:fP(),state:"building",inventoryHash:null,memberCount:0,holders:[],pending:null,stamps:null},await i("index",h));let m=await n("inventory"),g=await n("repair");g&&g.inventory.epoch===h.epoch&&$(g.inventory)===h.inventoryHash&&m&&$(m)===g.previousHash&&(m=g.inventory),m&&(m.epoch!==h.epoch||!Array.isArray(m.members)||m.members.some(w=>typeof w!="string")||new Set(m.members).size!==m.members.length||h.inventoryHash!==null&&($(m)!==h.inventoryHash||m.members.length!==h.memberCount))&&r("初始化中的成员清单不匹配");let v=await c(h,m??void 0);return!m&&h.inventoryHash!==null&&$(v)!==h.inventoryHash&&r("初始化期间成员清单发生变化,不能重写并丢弃原成员"),h.inventoryHash=$(v),h.memberCount=v.members.length,await i("index",h),await i("inventory",v),h.state="ready",h.stamps=await o(),await i("index",h),h}async function u(p){if(!p.pending)return;let{runId:h,registering:m}=p.pending;await e.settle?.(h);let g=await e.read(h);if(!g&&!m&&r(`未完成写入的 Run 缺失:${h}`),!g&&m){let v=await s(p),w=await n("registration");(v.members.includes(h)||w?.epoch===p.epoch&&w.previousHash===p.inventoryHash&&w.inventory.members.includes(h))&&r(`注册已提交或已观测到提交,但 Run 已缺失:${h}`)}if(m){let v=await s(p),w=!1;g&&!v.members.includes(h)?(v.members.push(h),v.members.sort(),v.aborted&&(v.aborted=v.aborted.filter(A=>A!==h)),w=!0):!g&&!v.aborted?.includes(h)&&(v.aborted=[...v.aborted??[],h].sort(),w=!0),w&&(await i("registration",{epoch:p.epoch,previousHash:p.inventoryHash,inventory:v}),await i("inventory",v),p.inventoryHash=$(v),p.memberCount=v.members.length)}p.holders=p.holders.filter(v=>v!==h),g&&await e.holds(g)&&p.holders.push(h),p.holders.sort(),p.pending=null,p.stamps=await o(),await i("index",p)}async function f(p){if(!p.pending?.registering)return;let h=await n("registration");if(h?.epoch===p.epoch&&h.previousHash===p.inventoryHash){let m=await n("inventory");m&&$(m)===$(h.inventory)&&(p.inventoryHash=$(m),p.memberCount=m.members.length)}}async function d(){let p=await l();return await f(p),p.pending&&await u(p),p.stamps!==await o()&&r("Store 分区身份已变化,必须显式 audit;不能继续使用占用投影"),p}return{async isAbortedRegistration(p){let h=await a();if(!h||h.state!=="ready"||h.pending)return!1;let m=await s(h);return!m.members.includes(p)&&!!m.aborted?.includes(p)&&await e.read(p)===null},async holders(){let p=await d(),h=[];for(let m of p.holders){await e.settle?.(m);let g=await e.read(m);g||r(`占用 Run 缺失:${m}`),await e.holds(g)&&h.push(g)}return h},async begin(p,h){let m=await d();h&&(await s(m)).members.includes(p)&&r(`已登记 Run 不能作为新记录重建:${p}`),m.pending={runId:p,registering:h},await i("index",m)},async finish(){let p=await a();(!p||p.state!=="ready")&&r("应用存储索引未就绪"),await f(p),await u(p)},async inspect(){try{let p=await a();return!p&&await n("inventory")&&r("成员清单存在但索引缺失"),p}catch(p){let h=await n("inventory");if(!h||typeof h.epoch!="string")throw p;return{schema:wp,epoch:h.epoch,state:"corrupt",error:{code:"STORE_INDEX_CORRUPT",message:p instanceof Error?p.message:String(p)}}}},async repair(p,h){let m;try{m=await a()}catch(w){if(p!=="rebuild")throw w;m=null}if(!m&&p==="rebuild"){let w=await n("inventory");w&&w.epoch===h&&Array.isArray(w.members)&&w.members.every(A=>typeof A=="string")&&new Set(w.members).size===w.members.length&&(m={schema:wp,epoch:w.epoch,state:"building",inventoryHash:$(w),memberCount:w.members.length,holders:[],pending:null,stamps:null})}if(!m||m.epoch!==h)throw new k("STORE_INDEX_EPOCH_CHANGED","索引 epoch 已变化,请重新 inspect");await f(m),m.pending&&await u(m);let g=await s(m),v=await c(m,g);return p==="rebuild"&&(m.epoch=fP(),v.epoch=m.epoch),await i("repair",{previousHash:m.inventoryHash,inventory:v}),m.inventoryHash=$(v),m.memberCount=v.members.length,m.state="building",await i("index",m),await i("inventory",v),m.state="ready",m.stamps=await o(),await i("index",m),m}}}var vk,wp,pP=_(()=>{"use strict";Jn();ct();et();vk=".runtime-store-coordination",wp="comet.application-holder-index.v1"});import dJ from"node:os";import fJ from"node:path";function mP(e,t,r=dJ.homedir()){return fJ.join(t==="project"?e:r,".comet/applications")}var hP=_(()=>{"use strict"});import mn from"node:path";function pJ(e){return/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e)||F("应用身份无效"),e}function gP(e,t){let r=mn.resolve(e,t),n=mn.parse(r).root;return{volume:n,ref:mn.relative(n,r).replaceAll("\\","/")}}async function vP(e,t,r){let n=gP(e,t);return oe(n.volume,n.ref,{expected:r,label:"SDK application installation"})}async function mJ(e,t){let r=`${pJ(t)}/current.json`;if(!(await vP(e,r,"file")).exists)return null;let n=gP(e,r),{bytes:i}=await qe(n.volume,n.ref,1024*1024,{label:"SDK application installation"}),o=JSON.parse(i.toString("utf8"));if((o.schema!=="comet.workflow.application.install.v1"||o.id!==t||!o.version?.trim()||!/^[a-f\d]{64}$/u.test(o.contentHash)||o.packageRef!==`${t}/versions/${o.contentHash}`)&&F("安装记录无效;保留文件并重新预览"),o.entry){let a=mn.dirname(mn.dirname(e)),s=mn.dirname(o.entry.root??"");(!mn.isAbsolute(o.entry.root)||![mn.join(a,".claude/skills"),mn.join(a,".agents/skills")].includes(s)||!/^[a-f\d]{64}$/u.test(o.entry.contentHash)||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(mn.basename(o.entry.root)))&&F("宿主入口安装记录无效;保留文件并核对原安装")}return o}async function yk(e,t){let r=mP(e.projectRoot,e.scope,e.userRoot),n=await mJ(r,t);if(!n)return null;let i=`${n.packageRef}/application.json`;return await vP(r,i,"file"),po(await fo(mn.join(r,n.packageRef)))!==n.contentHash&&F("已安装版本内容发生漂移;恢复原包后继续"),mn.join(r,i)}var wP=_(()=>{"use strict";ct();hP();ys()});var yP=_(()=>{"use strict";vp()});import Ot from"node:path";function bi(e,t){let r=Ot.relative(e,t);return!r||!Ot.isAbsolute(r)&&r!==".."&&!r.startsWith(".."+Ot.sep)}function hJ(e,t,r){if(!t.workspaceFrom)return e.projectRoot;let n=r?.input;for(let i of t.workspaceFrom.split("."))n=n&&typeof n=="object"?n[i]:void 0;if(typeof n!="string"||!Ot.isAbsolute(n))throw new Error("当前 Action 缺少已声明的实际写入工作区");return n}function kP(e){let t=Ot.resolve(e.projectRoot),r=[".git","node_modules",".claude",".agents",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].map(s=>Ot.resolve(t,s)),n={manifest:e.manifest,skills:e.skills,projectRoot:t},i=["AGENTS.md","AGENTS.override.md","CLAUDE.md"].map(s=>Ot.join(t,s)),o=e.manifest.bindings.filter(s=>s.usage==="action"&&e.skills.get(s.skillId)?.adapter.sideEffect==="write"),a=e.manifest.bindings.some(s=>s.usage==="action");return async(s,c)=>{if(c.intent!=="write")return{allowed:!0,reason:"此请求没有可归属的 SDK 应用写入"};try{if(!c.targets.length)throw new Error("SDK 应用写入必须声明实际文件");let l=[];for(let N of c.targets){let b=Ot.resolve(t,N),E=Ot.relative(t,b);if(!E||!bi(t,b))throw new Error("写入目标必须位于当前项目内");if(await oe(t,E.replaceAll("\\","/"),{expected:"file",label:"SDK 应用写入"}),bi(Ot.resolve(e.packageRoot),b)||r.some(V=>bi(V,b))||i.some(V=>!Ot.relative(V,b))||!Ot.relative(Ot.join(t,".comet/current-change.json"),b))throw new Error("固定应用、SDK 状态与宿主配置只能由正式 Runtime 或安装入口维护");l.push(b)}let u=Ot.join(t,".comet/requests");if(l.every(N=>bi(u,N)&&N.endsWith(".json")))return{allowed:!0,reason:"临时协议请求不是推进状态;Runtime 仍核对身份与批准"};let f=[],d=new Set,p=0,h=async N=>{if(d.has(N.runId))throw new Error("子流程归属循环");if((["running","waiting"].includes(N.status)||N.actions.some(E=>E.status==="pending"||pn(E))||N.ready.length>0||N.waits.some(E=>E.status==="pending")||(N.evidenceWaits??[]).some(E=>E.status==="pending"))&&++p>128)throw new Error("活跃子流程超出安全读取范围");d.add(N.runId),f.push(N);for(let E of N.children){let V=N.actions.find(z=>z.id===E.actionId);if(!V||V.type!=="child_workflow")throw new Error("子流程与 SDK Action 归属不一致");if(!V.claim)continue;let j=await e.readChild(E.runId);if(j.runId!==E.runId||j.workflow.id!==E.workflow.id||j.workflow.version!==E.workflow.version||j.lineage.length!==N.lineage.length+1||j.lineage.at(-1)!==N.runId||N.lineage.some((z,X)=>j.lineage[X]!==z))throw new Error("子流程没有当前 SDK Run 的有效归属");await h(j)}};await h(s);let m=["completed","cancelled","failed"].includes(s.status),g=[],v=[];for(let N of f)for(let b of o.filter(E=>E.workflowId===N.workflow.id)){let E=e.skills.get(b.skillId),V=N.actions.filter(j=>j.stepId===b.stepId);for(let j of V){let z=hJ(e,b,j);v.push(...E.adapter.scope.map(X=>Ot.resolve(z,X))),!(m||["cancelled","failed"].includes(N.status)||j.status!=="running")&&(As(n,j,N),ks(n,N,j,f),g.push(...E.adapter.scope.map(X=>Ot.resolve(z,X))))}!b.workspaceFrom&&!V.length&&v.push(...E.adapter.scope.map(j=>Ot.resolve(t,j)))}let w=Ot.join(t,".comet/evidence",e.manifest.id),A=!m&&f.some(N=>N.actions.some(b=>["running","unknown"].includes(b.status)));for(let N of l)if(!(bi(u,N)&&N.endsWith(".json"))&&!(A&&bi(w,N))){if(m){if(v.some(b=>bi(b,N))||bi(Ot.join(t,".comet"),N))throw new Error("已结束 Run 的声明产物保持固定;继续修改应启动新的 Run")}else if((!e.custom||a)&&!g.some(b=>bi(b,N)))throw new Error("当前 SDK Action 没有此写入权限;先确认当前提案并领取允许写入的 Action")}return e.custom?await e.custom(s,c):{allowed:!0,reason:m?"目标不属于已结束应用或控制资源":"写入属于当前已批准且已领取的 SDK Action"}}catch(l){return{allowed:!1,reason:l instanceof Error?l.message:"无法安全核对 SDK 应用写入"}}}}var AP=_(()=>{"use strict";ct();vp()});function Dl(e,t,r){return(!e||typeof e!="object"||Array.isArray(e))&&F(`${r} 必须是 JSON 对象`),Object.keys(e).some(n=>!t.includes(n))&&F(`${r} 含未声明字段`),e}function jn(e,t,r=256){(typeof e!="string"||!e.trim()||e.length>r)&&F(`${t} 必须是长度不超过 ${r} 的非空文本`)}function wJ(e,t){let r=Dl(e,["title","description","steps"],"应用展示信息");if(r.title!==void 0&&jn(r.title,"应用展示名称"),r.description!==void 0&&jn(r.description,"应用展示说明",4e3),r.steps===void 0)return;(!Array.isArray(r.steps)||r.steps.length>bP)&&F("步骤展示信息必须是有界数组");let n=new Set;for(let i of r.steps){let o=Dl(i,["workflowId","stepId","title","phase","description","outputFields"],"步骤展示信息");jn(o.workflowId,"展示流程 ID"),jn(o.stepId,"展示步骤 ID"),jn(o.title,"步骤展示名称"),o.phase!==void 0&&jn(o.phase,"步骤阶段名称"),o.description!==void 0&&jn(o.description,"步骤展示说明",4e3);let a=JSON.stringify([o.workflowId,o.stepId]);if(n.has(a)&&F(`重复步骤展示信息:${o.workflowId}/${o.stepId}`),n.add(a),t){let c=t.filter(l=>l.id===o.workflowId);(!c.length||c.some(l=>!Object.hasOwn(l.steps,o.stepId)))&&F(`展示信息引用不存在的步骤:${o.workflowId}/${o.stepId}`)}if(o.outputFields===void 0)continue;(!Array.isArray(o.outputFields)||o.outputFields.length>32)&&F("步骤展示输出字段必须是有界数组");let s=new Set;for(let c of o.outputFields){let l=Dl(c,["path","label"],"步骤展示输出字段");jn(l.path,"展示输出路径",512),jn(l.label,"展示输出名称"),(!/^[A-Za-z_][A-Za-z_0-9]*(?:\.(?:[A-Za-z_][A-Za-z_0-9]*|0|[1-9][0-9]*))*$/u.test(l.path)||l.path.split(".").some(u=>["__proto__","constructor","prototype"].includes(u)))&&F(`展示输出字段路径无效:${l.path}`),s.has(l.path)&&F(`重复展示输出字段:${l.path}`),s.add(l.path)}}}function kk(e){(typeof e!="string"||e.length>1024||!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\.json$/u.test(e)||["application.json","installation.json"].includes(e))&&F("应用流程定义必须声明固定包内的 JSON 相对路径")}function yJ(e,t){let r=typeof e=="string"?e:Mn(e),n=Dl(JSON.parse(r),["schema","application","workflows","presentation"],"应用流程定义");n.schema!=="comet.workflow.application.definition.v1"&&F("应用流程定义格式不受支持");let i=Dl(n.application,["id","version"],"流程定义应用身份");jn(i.id,"流程定义应用 ID"),jn(i.version,"流程定义应用版本"),t&&(t.id!==i.id||t.version!==i.version)&&F("流程定义与应用固定身份不匹配"),(!Array.isArray(n.workflows)||!n.workflows.length||n.workflows.length>gJ)&&F("应用流程定义必须包含有界的完整流程数组");let o=0,a=0,s=n.workflows.map(l=>((!l||typeof l!="object"||!l.steps||typeof l.steps!="object")&&F("应用流程定义缺少步骤"),o+=Object.keys(l.steps).length,a+=Array.isArray(l.transitions)?l.transitions.length:0,(o>bP||a>vJ)&&F("应用流程定义超过步骤或转移数量限制"),ln(l))),c=new Set;for(let l of s){let u=JSON.stringify([l.id,l.version]);c.has(u)&&F(`重复流程身份:${l.id}@${l.version}`),c.add(u)}for(let l of s)for(let[u,f]of Object.entries(l.steps))f.type==="child_workflow"&&!c.has(JSON.stringify([f.workflow.id,f.workflow.version]))&&F(`子流程定义不存在:${l.id}/${u}`);return n.presentation!==void 0&&wJ(n.presentation,s),{schema:"comet.workflow.application.definition.v1",application:{id:i.id,version:i.version},workflows:s,...n.presentation===void 0?{}:{presentation:n.presentation}}}function NP(e,t){if(t.definition!==void 0)return kk(t.definition),Object.hasOwn(e,t.definition)||F("固定包缺少声明的应用流程定义"),yJ(Buffer.from(e[t.definition],"base64").toString("utf8"),t)}function RP(e,t){let r=n=>n.map(i=>{let o=ln(i);return[o.id,o.version,$(o)]}).sort((i,o)=>JSON.stringify(i).localeCompare(JSON.stringify(o),"en"));$(r(e.workflows))!==$(r(t))&&F("实际工厂的流程与固定流程定义不匹配,请同步确认方案")}function Ak(e,t){let r=new Map(e.workflows.map(i=>[JSON.stringify([i.id,i.version]),$(i)])),n=JSON.stringify([t.workflow.id,t.workflow.version]);return r.get(n)===t.workflow.hash&&t.definitionHashes[n]===t.workflow.hash&&Object.entries(t.definitionHashes).every(([i,o])=>r.get(i)===o)}var gJ,bP,vJ,SP=_(()=>{"use strict";et();lr();ys();gJ=256,bP=4096,vJ=16384});import{createHash as kJ}from"node:crypto";async function CP(e,t){let r={},n={},i=new EP.Ajv({strict:!0,allErrors:!0});for(let o of t){let a=await qe(e,o.ref,16777216,{label:`必需产物 ${o.ref}`}),s=a.bytes.toString("utf8");if(o.nonEmpty&&!s.trim())throw new Error(`必需产物不能为空:${o.ref}`);if(o.requiredText?.some(c=>!s.includes(c)))throw new Error(`实际工件不满足内容要求:${o.ref}`);if(o.requiredHeadings?.length){let c=new Set,l,u="";for(let d of s.split(/\r?\n/u)){let p=/^ {0,3}(`{3,}|~{3,})/u.exec(d);if(p){let m=p[1];l?l.char===m[0]&&m.length>=l.length&&d.slice(p[0].length).trim()===""&&(l=void 0):l={char:m[0],length:m.length},u="";continue}if(l)continue;let h=/^ {0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$/u.exec(d);h?c.add(h[1].trim()):u.trim()&&/^ {0,3}(?:=+|-+)\s*$/u.test(d)&&c.add(u.trim()),u=/^ {0,3}\S/u.test(d)?d:""}let f=o.requiredHeadings.filter(d=>!c.has(d));if(f.length)throw new Error(`必需产物缺少章节:${o.ref},${f.join("、")}`)}if(o.schema!==void 0){let c=o.schema;if(typeof c!="boolean"&&(c===null||Array.isArray(c)||typeof c!="object"||c.$async===!0))throw new Error(`工件需要同步 JSON Schema:${o.ref}`);let l=i.compile(c);if(!l(JSON.parse(s)))throw new Error(`实际工件结构无效:${o.ref},${i.errorsText(l.errors)}`)}r[o.ref]=s,n[o.ref]=kJ("sha256").update(a.bytes).digest("hex")}return{files:r,artifactHashes:n}}var EP,_P=_(()=>{"use strict";EP=kr(Fd(),1);et();ct();ys()});import xP from"node:path";function bk(e,t,r,n){let i=t.bindings.find(a=>a.usage==="action"&&a.workflowId===r.workflow.id&&a.stepId===n.stepId);if(!i?.workspaceFrom)return e;let o=Nk(n.input,i.workspaceFrom);if(typeof o!="string"||!xP.isAbsolute(o))throw new Error("产物检查缺少当前 Action 已声明的实际工作区");return o}function PP(e){(typeof e!="string"||!e||e.length>4096||e.includes("\\")||e.includes(":")||e.includes("\0")||xP.posix.isAbsolute(e)||e.split("/").some(r=>!r||r==="."||r===".."||/[ .]$/u.test(r)))&&F("产物引用必须是项目内安全相对路径"),([".git","node_modules",".agents",".claude",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].some(r=>e.toLowerCase()===r||e.toLowerCase().startsWith(r+"/"))||["agents.md","agents.override.md","claude.md",".comet/current-change.json"].includes(e.toLowerCase()))&&F(`产物引用不能指向控制资源:${e}`)}function IP(e){(typeof e!="string"||!/^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/u.test(e)||e.split(".").some(t=>["__proto__","constructor","prototype"].includes(t)))&&F("产物字段选择器无效")}function Rk(e){(!Array.isArray(e)||e.length>256)&&F("阶段产物契约必须是有界数组");let t=new Set;for(let r of e){(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(o=>!["workflowId","stepId","artifacts","noArtifactsReason","replaces"].includes(o)))&&F("阶段产物契约含未声明字段");let n=r;(typeof n.workflowId!="string"||!n.workflowId.trim()||typeof n.stepId!="string"||!n.stepId.trim()||t.has(yp(n.workflowId,n.stepId))||!Array.isArray(n.artifacts)||n.artifacts.length>64)&&F("阶段产物契约缺少唯一流程、步骤或产物列表"),t.add(yp(n.workflowId,n.stepId)),!n.artifacts.length&&(typeof n.noArtifactsReason!="string"||!n.noArtifactsReason.trim())&&F(`无强制产物的阶段需要说明原因:${yp(n.workflowId,n.stepId)}`),n.artifacts.length&&n.noArtifactsReason!==void 0&&F("必需产物与无产物声明不能同时存在"),n.replaces&&(!Array.isArray(n.replaces)||n.replaces.some(o=>typeof o!="string"||!o.trim())||new Set(n.replaces).size!==n.replaces.length)&&F("替代产物的步骤声明无效");let i=new Set;for(let o of n.artifacts){(!o||typeof o!="object"||Object.keys(o).some(s=>!["ref","refFrom","sha256From","nonEmpty","schema","requiredText","requiredHeadings"].includes(s))||!!o.ref==!!o.refFrom)&&F("必需产物需要唯一的 ref 或 refFrom"),o.ref!==void 0&&PP(o.ref),o.refFrom!==void 0&&IP(o.refFrom),o.sha256From!==void 0&&IP(o.sha256From);let a=o.ref??`output:${o.refFrom}`;i.has(a)&&F("阶段产物引用重复"),i.add(a),o.nonEmpty!==void 0&&typeof o.nonEmpty!="boolean"&&F("nonEmpty 必须是布尔值");for(let s of[o.requiredText,o.requiredHeadings])s!==void 0&&(!Array.isArray(s)||!s.length||s.length>64||s.some(c=>typeof c!="string"||!c.trim()))&&F("产物内容检查必须是非空文本数组")}}}function AJ(e,t){for(let r of t){let n=e.workflows.find(i=>i.id===r.workflowId);n?.steps[r.stepId]||F(`阶段产物契约引用不存在的步骤:${yp(r.workflowId,r.stepId)}`);for(let i of r.replaces??[])n.steps[i]||F(`替代产物的步骤不存在:${i}`);r.artifacts.length&&!["handoff","invoke_skill","call_tool","child_workflow"].includes(n.steps[r.stepId].type)&&F("必需产物必须绑定可回传结果的执行步骤"),n.steps[r.stepId].type==="child_workflow"&&r.artifacts.some(i=>!i.sha256From)&&F("子流程产物需要 sha256From,读取子流程结果中的实际摘要")}}async function TP(e,t,r){let n=t.artifacts.map(o=>{let a=o.ref??Nk(r,o.refFrom);return PP(a),{...o,ref:a,nonEmpty:o.nonEmpty!==!1}}),i=await CP(e,n);return{...i,artifacts:n.map(({ref:o})=>({uri:o,sha256:i.artifactHashes[o]}))}}async function OP(e,t,r){if(r.status!=="succeeded"||!t.artifacts.length)return;let n=await TP(e,t,r.output);for(let i=0;i<n.artifacts.length;i++){let o=n.artifacts[i],a=t.artifacts[i];if((a.sha256From?Nk(r.output,a.sha256From):r.artifacts?.find(c=>c.uri===o.uri)?.sha256)!==o.sha256)throw new Error(`必需产物缺少当前结果的实际摘要或内容已变化:${o.uri}`)}}async function Bl(e,t,r,n,i,o){let a=t.filter(c=>c.workflowId===r.workflow.id),s=new Set(a.find(c=>c.stepId===n)?.replaces??[]);for(let c of a)if(i[c.stepId])for(let l of c.replaces??[])i[c.stepId].sequence>(i[l]?.sequence??-1)&&s.add(l);for(let c of a){let l=i[c.stepId];if(!l||!c.artifacts.length||s.has(c.stepId))continue;let u=r.actions.find(f=>f.stepId===c.stepId&&["succeeded","failed"].includes(f.status)&&r.actionContexts[f.id]?.sequence===l.sequence);if(!u?.outcome||$(u.outcome.output)!==$(l.value))throw new Error(`依赖产物没有对应的原 Action 证据:${c.stepId}`);await OP(o?bk(e,o,r,u):e,c,u.outcome)}}function $P(e,t){let r=t.manifest.artifactContracts;if(r===void 0)return e;Rk(r),AJ(e,r);let n=(o,a)=>r.find(s=>s.workflowId===o.workflow.id&&s.stepId===a),i=async o=>{o.outcome.status==="succeeded"&&await Bl(t.projectRoot,r,o.run,o.action.stepId,o.run.actionContexts[o.action.id]?.results??{},t.manifest);let a=n(o.run,o.action.stepId);a&&await OP(bk(t.projectRoot,t.manifest,o.run,o.action),a,o.outcome)};return{...e,executors:e.executors?.map(o=>({...o,...o.preflight?{async preflight(a,s,c){c&&await Bl(t.projectRoot,r,c,a.stepId,c.actionContexts[a.id]?.results??{},t.manifest),await o.preflight?.(a,s,c)}}:{},async execute(a,s,c){let l=await o.execute(a,s,c),u=c?n(c,a.stepId):void 0;if(!u?.artifacts.length||l.status!=="succeeded")return l;try{let f=await TP(bk(t.projectRoot,t.manifest,c,a),u,l.output);return{...l,artifacts:[...(l.artifacts??[]).filter(d=>!f.artifacts.some(p=>p.uri===d.uri)),...f.artifacts]}}catch{return l}}})),validators:e.validators?.map(o=>({...o,async validate(a){let s=await o.validate(a);if(!s.accepted)return s;try{return await i(a),s}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}})),async validateOutcome(o){try{await i(o);let a=await e.validateOutcome?.(o)??{accepted:!0};return a.accepted&&await i(o),a}catch(a){return{accepted:!1,reason:a instanceof Error?a.message:String(a)}}}}}var Nk,yp,jP=_(()=>{"use strict";et();_P();ys();Nk=(e,t)=>t.split(".").reduce((r,n)=>r&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),yp=(e,t)=>`${e}/${t}`});import{promises as Sk}from"node:fs";import hr from"node:path";import{createRequire as bJ,isBuiltin as NJ}from"node:module";function MP(e){return["completed","cancelled"].includes(e.status)&&!e.actions.some(t=>t.status==="pending"||pn(t))&&e.children.length===0&&!e.ready.length&&!e.waits.some(t=>t.status==="pending")&&!(e.evidenceWaits??[]).some(t=>t.status==="pending")}function bs(e){return(typeof e!="string"||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e))&&F("应用身份必须是小写名称"),e}async function Ek(e,t,r=!1,n=!1){let i=Ze(e),o=()=>{if(Ze(e)!==i)throw new k("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime")},a=async()=>{if(o(),!r){if(await ci(e)!==i)throw new k("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");o()}},s=St({rootDir:hr.join(i,"applications",bs(t)),mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...n?{singleWriter:!0}:{}}),c=(u,f,d)=>{let p=s.prepareCompareAndSwap(u,f,d);return async()=>{if(o(),r)throw new k("READ_ONLY_OPERATION","应用诊断不能推进 Run");await a();let h=await s.settleRun(u);if(["closing","closed","reopening"].includes(h)){let g=await s.read(u);if(!g||g.revision!==f)return!1;h==="closing"&&await s.closeRun(u,g.revision),await s.reopenRun(u,g.revision)}let m=await p();return m&&d.application.base==="standalone"&&MP(d.run)&&await s.closeRun(u,d.revision),m}},l=async(u,f)=>(await a(),await s[f?"readProjection":"read"](u));return{queryScope:s.queryScope,read:u=>l(u,!1),readProjection:u=>l(u,!0),compareAndSwap:async(u,f,d)=>c(u,f,d)(),prepareCompareAndSwap:c,restoreCheckpoint:async(u,f,d)=>{if(o(),r)throw new k("READ_ONLY_OPERATION","应用诊断不能恢复 Run");if(await a(),await s.settleRun(u)==="closed"){let h=await s.read(u);if(!h||h.revision!==f)return!1;await s.reopenRun(u,h.revision)}return s.restoreCheckpoint(u,f,d)}}}async function BP(e){let t=await fo(e.application.packageRoot),r=Ck(JSON.parse(Buffer.from(t["application.json"],"base64").toString("utf8")));if(r.id!==e.application.id||r.version!==e.application.version||r.base!==e.application.base||$({package:po(t),skills:r.skills.map(n=>({id:n.id,contentHash:n.contentHash}))})!==e.application.contentHash)throw new k("SCOPE_HELD",`固定占用应用定义无法验证:${e.application.id} / ${e.runId}`);return r}function WP(e,t,r){return e.actions.filter(n=>n.type==="invoke_skill"&&pn(n)&&t.bindings.some(i=>{let o=t.skills.find(a=>a.id===i.skillId);return i.workflowId===e.workflow.id&&i.stepId===n.stepId&&i.usage==="action"&&o&&o.adapter.sideEffect!=="read"&&o.adapter.scope.length>0})).map(n=>({runId:e.runId,applicationContentHash:r,actionId:n.id,attempt:n.attempt,inputHash:n.inputHash,claimToken:n.claim?rp(n.claim.token):null}))}async function qP(e){let t=nn(e.run,e.runId),r=t.actions.filter(n=>n.type==="invoke_skill"&&pn(n));if(!r.length)return!1;try{let n=await fo(e.application.packageRoot),i=Ck(JSON.parse(Buffer.from(n["application.json"],"base64").toString("utf8")));return $({package:po(n),skills:i.skills.map(o=>({id:o.id,contentHash:o.contentHash}))})!==e.application.contentHash?!0:r.some(o=>i.bindings.some(a=>{let s=i.skills.find(c=>c.id===a.skillId);return a.workflowId===t.workflow.id&&a.stepId===o.stepId&&a.usage==="action"&&s&&s.adapter.sideEffect!=="read"&&s.adapter.scope.length>0}))}catch{return!0}}function LP(e,t,r=!1){let n=hr.join(Ze(e),"applications",bs(t)),i=St({rootDir:n,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...r?{singleWriter:!0}:{}});return wk({rootDir:n,read:o=>i.read(o),settle:o=>i.settleRun(o),holds:qP})}async function kp(e,t,r){return(await RJ(e,t,r))?.run??null}async function RJ(e,t,r){let n=await(await Ek(e,t,!0)).read(r);if(!n)return null;if(n.application.id!==t||n.runId!==n.run.runId||n.revision!==n.run.revision)throw new k("INVALID_RUN","应用归属与 SDK Run 不一致");return n.run=nn(n.run,r),n}function Ck(e){(!e||typeof e!="object"||Array.isArray(e))&&F("应用文件必须是 JSON 对象");let t=e;return t.artifactContracts!==void 0&&Rk(t.artifactContracts),t.schema!=="comet.workflow.application.v1"&&F("应用格式不受支持,请重新生成 SDK 应用;原文件会保留"),t.definition!==void 0&&kk(t.definition),t.rule!==void 0&&(typeof t.rule!="string"||!t.rule.endsWith(".md")||hr.isAbsolute(t.rule)||t.rule.includes("\\")||t.rule.includes(":")||t.rule.split("/").some(r=>!r||r==="."||r===".."))&&F("应用规则 Rule 必须声明固定包内的 Markdown 相对路径"),bs(t.id),Zy.includes(t.id)&&F(`应用身份 ${t.id} 与内置应用冲突,请使用独立名称`),(!t.version?.trim()||!["standalone","native","classic-full","classic-hotfix","classic-tweak"].includes(t.base)||!t.runtimeVersion?.trim()||!t.entrySkill?.trim()||!t.module?.endsWith(".mjs")||!Array.isArray(t.skills)||!Array.isArray(t.bindings))&&F("应用定义缺少版本、基础流程、入口或绑定"),t}async function Ap(e,t,r){let n=await(await Ek(await Sk.realpath(e),t,!0)).readProjection(r);return n?hr.join(n.application.packageRoot,"application.json"):await yk({projectRoot:e,scope:"project"},bs(t))??await yk({projectRoot:e,scope:"user"},bs(t))??hr.join(e,".comet/applications",bs(t),"application.json")}async function Wl(e){let t=await Sk.realpath(e.projectRoot),r=hr.resolve(e.file);hr.basename(r)!=="application.json"&&F("应用入口文件必须命名为 application.json");let n=await Sk.realpath(hr.dirname(r));n===t&&F("应用包须放在独立目录,不能包含项目的运行状态");let i=await fo(n),o=Ck(JSON.parse(Buffer.from(i["application.json"]??"","base64").toString("utf8"))),a=NP(i,o);o.rule&&(!o.rule.endsWith(".md")||!i[o.rule]||!Buffer.from(i[o.rule],"base64").toString("utf8").trim())&&F("应用规则 Rule 必须是固定包内的非空 Markdown 文件");let s=Ex(),c=o.runtimeVersion==="0.5.2"&&s==="0.5.3"&&!!e.runId&&(o.base==="native"||o.base.startsWith("classic-"));o.runtimeVersion!==s&&!c&&F(`应用要求 Runtime ${o.runtimeVersion},当前是 ${s}`),(!i[o.entrySkill]||!i[o.module])&&F("应用入口 Skill 或执行模块缺失");let l=new Map;for(let R of o.skills)l.has(R.id)&&F(`重复 Skill 身份:${R.id}`),l.set(R.id,await hk(R,n));let u={id:o.id,version:o.version,base:o.base,runtimeVersion:o.runtimeVersion,projectRoot:t,packageRoot:n,contentHash:$({package:po(i),skills:[...l.values()].map(R=>({id:R.id,contentHash:R.contentHash}))})},f=async()=>{let R=await fo(n),I=await Promise.all(o.skills.map(L=>hk(L,n)));if($({package:po(R),skills:I.map(L=>({id:L.id,contentHash:L.contentHash}))})!==u.contentHash)throw new k("WORKFLOW_CHANGED","运行中的应用或依赖发生漂移;恢复原内容后继续原 Action")};if(e.expectedIdentity&&$(u)!==$(e.expectedIdentity))throw new k("WORKFLOW_CHANGED","恢复需要原固定应用包、依赖和工作区");let d=o.base!=="standalone",p=await Ek(t,o.id,e.readOnly,d),h=R=>{if($(R.application)!==$(u))throw new k("WORKFLOW_CHANGED","应用定义、执行/验证绑定、Skill 或工作区归属发生变化;请恢复原应用包和依赖后继续原 Run");if(R.revision!==R.run.revision||R.runId!==R.run.runId)throw new k("INVALID_RUN","应用归属与 SDK Run 不一致")},m;if(e.runId){let R=await p.readProjection(e.runId);R&&(h(R),m=(await Oo({...p,readProjection:async()=>R},e.runId)).run)}await zy;for(let[R,I]of Object.entries(i)){if(!R.endsWith(".mjs"))continue;let D=Buffer.from(I,"base64").toString("utf8");for(let L of Jy(D)[0]){if(L.d===-2)continue;let q=L.n;if(q||F(`应用模块不能动态选择未固定的导入:${R}`),NJ(q)||q==="@rpamis/comet/runtime"||q==="@rpamis/comet/applications"||q==="@rpamis/comet/applications/compiler"||q==="@rpamis/comet/applications/native"||q==="@rpamis/comet/applications/classic")continue;q.startsWith(".")||F(`应用模块依赖未固定:${R} -> ${q},请 bundle 后再加载`);let H=hr.posix.normalize(hr.posix.join(hr.posix.dirname(R),q));(!i[H]||H.startsWith("../"))&&F(`应用模块依赖缺失或越过包目录:${R} -> ${q}`),!H.endsWith(".mjs")&&!H.endsWith(".json")&&F(`执行依赖必须是可检查的 .mjs 或 JSON:${R} -> ${q},请先 bundle`)}}let g=DP.get(n);g&&g!==u.contentHash&&F("当前进程已加载不同的应用实现,请在新进程加载新版本"),DP.set(n,u.contentHash);let v=bJ(r)(hr.join(n,o.module));typeof v.createApplication!="function"&&F("应用模块必须导出 createApplication");let w={manifest:structuredClone(o),skills:l,projectRoot:t,packageRoot:n,identity:u,createSkillExecutor:R=>dP({manifest:o,skills:l,projectRoot:t},R)};if(m&&!e.useLatestDefinition){let R;Object.defineProperty(w,"existingRun",{enumerable:!0,get:()=>R??=cr(m)})}let A=await v.createApplication(w);(!A||!Array.isArray(A.workflows)||!A.workflows.length)&&F("应用模块必须提供完整 SDK 工作流"),A=$P(A,{manifest:o,projectRoot:t});let N=A.workflows.map(ln);a&&(c?m&&!Ak(a,m)&&!Ak({...a,workflows:N},m)&&F("旧固定应用 Run 不匹配原定义或当前业务定义"):RP(a,N));let b=new Set;for(let R of o.bindings){let I=`${R.workflowId}/${R.stepId}/${R.usage}${R.usage==="guidance"?`/${R.skillId}`:""}`;R.workspaceFrom!==void 0&&!/^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)*$/u.test(R.workspaceFrom)&&F(`工作区输入路径无效:${I}`),b.has(I)&&F(`重复 Skill 绑定:${I}`),b.add(I);let D=N.find(H=>H.id===R.workflowId),L=D?.steps[R.stepId],q=l.get(R.skillId);if((!L||!q)&&F(`绑定的工作或 Skill 不存在:${I}`),(!R.capability?.trim()||!q.adapter.review.capabilities.some(H=>H.id===R.capability))&&F(`真实 Skill 没有已审查的所需能力:${I}`),R.usage==="guidance"){q.adapter.kind!=="guidance"&&F("只有只读指导 Skill 可附加为 guidance");continue}if(R.usage==="subworkflow"){(q.adapter.kind!=="subworkflow"||L.type!=="child_workflow")&&F("完整流程必须绑定显式 child_workflow");continue}if((R.usage!=="action"||!["action","check"].includes(q.adapter.kind)||L.type!=="invoke_skill"||L.ref!==R.skillId)&&F(`Skill 工作类型或引用不匹配:${I}`),q.adapter.controlsApproval&&F("接管审批的 Skill 必须适配为隔离的子流程"),(L.outputSchema===void 0||$(L.outputSchema)!==$(q.adapter.outputSchema))&&F(`Skill 输出与工作流契约不匹配:${I}`),q.adapter.completion!=="self-report"&&!(q.adapter.completion==="machine-check"&&o.artifactContracts?.some(H=>H.workflowId===R.workflowId&&H.stepId===R.stepId&&H.artifacts.length))&&(!L.validator||!A.validators?.some(H=>H.id===L.validator?.id&&H.version===L.validator.version))&&F(`机器检查或独立评审需要真实验证器:${I}`),q.adapter.requiredCapabilities.some(H=>!L.requiredCapabilities?.includes(H))&&F(`Skill 必需宿主能力未传到 Action:${I}`),q.adapter.sideEffect!=="read"){let H=R.authorizationFrom?D.steps[R.authorizationFrom]:void 0,ne=R.authorizationChoices??["approved"];(H?.type!=="ask_user"||!Array.isArray(ne)||!ne.length||ne.some(Y=>typeof Y!="string"||!H.choices.includes(Y)))&&F(`有副作用的 Skill 缺少有效父流程审批:${I}`)}q.adapter.sideEffect==="external"&&L.retry!=="reconcile"&&F(`外部 Skill 必须先核对再重试:${I}`)}for(let R of N){let I=(q,H,ne)=>{q&&!H?.some(Y=>Y.id===q.id&&Y.version===q.version)&&F(`${ne} 未注册固定实现:${q.id}@${q.version}`)};I(R.transitionHandler,A.transitionHandlers,"转移处理器"),I(R.stateValidator,A.stateValidators,"状态验证器");for(let q of Object.values(R.commands??{}))I(q.validator,A.commandValidators,"命令验证器");for(let[q,H]of Object.entries(R.steps))H.type==="await_evidence"?I(H.validator,A.evidenceValidators,"证据验证器"):I(H.validator,A.validators,"工作验证器"),H.type==="invoke_skill"&&!o.bindings.some(ne=>ne.workflowId===R.id&&ne.stepId===q&&ne.usage==="action")&&F(`Skill Action 缺少适配绑定:${R.id}/${q}`);let D=o.bindings.filter(q=>q.workflowId===R.id&&q.usage==="action"&&l.get(q.skillId).adapter.sideEffect!=="read"),L=(q,H,ne=new Set)=>q===H?!0:ne.has(q)?!1:(ne.add(q),R.transitions.some(Y=>Y.from===q&&L(Y.to,H,ne)));for(let q=0;q<D.length;q++)for(let H of D.slice(q+1)){let ne=D[q];l.get(ne.skillId).adapter.sideEffect==="write"&&l.get(H.skillId).adapter.sideEffect==="write"&&!!ne.workspaceFrom!=!!H.workspaceFrom&&!L(ne.stepId,H.stepId)&&!L(H.stepId,ne.stepId)&&F(`并行写入不能混用声明工作区和默认范围:${ne.stepId} / ${H.stepId}`),!ne.workspaceFrom&&!H.workspaceFrom&&l.get(ne.skillId).adapter.scope.some(Y=>l.get(H.skillId).adapter.scope.some(ue=>l.get(ne.skillId).adapter.sideEffect==="write"&&l.get(H.skillId).adapter.sideEffect==="write"?hp(hr.resolve(t,Y),hr.resolve(t,ue)):ue===Y))&&!L(ne.stepId,H.stepId)&&!L(H.stepId,ne.stepId)&&F(`并行 Skill 的写入范围冲突:${ne.stepId} / ${H.stepId},请声明隔离或执行顺序`)}}let E=()=>{if(e.readOnly)throw new k("READ_ONLY_OPERATION","应用诊断不能恢复或推进 Run")},V=Ze(t),j=async R=>{if(Ze(t)!==V)throw new k("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");return await ci(t),R()},z=hr.join(V,"applications",o.id),X=St({rootDir:z,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...d?{singleWriter:!0}:{}}),de=(R,I)=>I.type==="invoke_skill"&&o.bindings.some(D=>{let L=l.get(D.skillId);return D.workflowId===R.workflow.id&&D.stepId===I.stepId&&D.usage==="action"&&L&&L.adapter.sideEffect!=="read"&&L.adapter.scope.length>0}),se=wk({rootDir:z,read:R=>X.read(R),settle:R=>X.settleRun(R),holds:R=>R.application.contentHash!==u.contentHash?qP(R):nn(R.run,R.runId).actions.some(I=>pn(I)&&de(R.run,I))}),De=R=>JSON.stringify(R?.actions.filter(I=>de(R,I)&&pn(I)).map(I=>[I.id,I.status,I.claim?.token,I.inputHash]).sort()??[]),Z=R=>WP(R,o,u.contentHash),Xe=async R=>{let I=await LP(t,R,R===o.id&&d).holders(),D=[];for(let L of I){let q=L.application.id===u.id&&L.application.contentHash===u.contentHash?o:await BP(L);D.push(...WP(nn(L.run,L.runId),q,L.application.contentHash))}return D},Ht=(R=!1)=>kx(V,o.id,Xe,R),B=async(R,I,D=!1)=>{if(!o.bindings.some(Y=>{if(Y.workflowId!==R.workflow.id||Y.stepId!==I.stepId||Y.usage!=="action")return!1;let ue=l.get(Y.skillId);return ue&&ue.adapter.sideEffect!=="read"&&ue.adapter.scope.length>0}))return[];let q=gp({manifest:o,projectRoot:t},R,I);for(let Y of await Ht(D)){if(Y===o.id||D&&!await bx(V,Y))continue;let ue=await LP(t,Y).holders();for(let le of ue){let y=nn(le.run,le.runId);if(le.application.id!==Y||le.application.projectRoot!==t)throw new k("SCOPE_HELD",`应用 ${Y} 的固定占用身份无法验证:${y.runId}`);let S=await BP(le);for(let T of y.actions.filter(pn))if(gp({manifest:S,projectRoot:t},y,T).some(P=>q.some(Q=>P.write&&Q.write?hp(P.ref,Q.ref):P.ref===Q.ref))){let P=new k("SCOPE_HELD",`写入范围仍由应用 ${Y} 的 Run ${y.runId} / Action ${T.id} 占用;请停止原执行或提交真实结果`);throw Object.assign(P,{blockedRunIds:[y.runId],blockedApplicationIds:[Y]}),P}}}let H=await se.holders(),ne=[];for(let Y of H){if(Y.runId===R.runId)continue;let ue=nn(Y.run,Y.runId);if(Y.application.contentHash!==u.contentHash)throw new k("SCOPE_HELD",`其他固定版本仍占用应用工作区:${ue.runId}`);ne.push(ue)}return ne},ee={queryScope:p.queryScope,async readProjection(R){await f();let I=await p.readProjection(R);return I?(h(I),I.run):null},async read(R){await f();let I=await p.read(R);return I?(h(I),I.run):null},async restoreCheckpoint(R,I,D){return D=structuredClone(D),E(),await f(),j(async()=>{await f();let q=await p.read(R);if(q&&h(q),D.runId!==R||D.actions.some(Y=>Y.status==="running"))throw new k("INVALID_RUN","应用恢复必须使用同一 Run 的 portable checkpoint,活跃领取须先转为 unknown");let H=o.base==="native"?"native":o.base.startsWith("classic-")?"classic":null;if(H){let Y=await ki(t,H,R);if(!Y||Y.format!=="sdk"||Y.application!==u.id||Y.runId!==R)throw new k("INVALID_RUN","恢复 Run 前须验证相同的固定应用和 change 归属")}let ne={runId:R,revision:D.revision,application:u,run:D};h(ne),await Ax(V,o.id,R,Z(D)),await Ht(!0);for(let Y of D.actions.filter(ue=>pn(ue)&&ue.type==="invoke_skill"))ks({manifest:o,skills:l,projectRoot:t},D,Y,await B(D,Y,!0));await Qy(V,o.id,Z(D),!0);try{return await se.begin(R,!q),await p.restoreCheckpoint(R,I,ne)}finally{await se.finish(),await Uy(V,o.id,Xe,!0)}})},async compareAndSwap(R,I,D){E(),await f(),D=structuredClone(D);let L=p.prepareCompareAndSwap(R,I,{runId:R,revision:D.revision,application:u,run:D}),q=await p.read(R),H=(await se.inspect())?.state!=="ready"||!q||De(q.run)!==De(D)||MP(D),ne=async()=>{await f();let Y=await p.read(R);if(Y&&h(Y),Y||await Ht(),(Y?.revision??null)!==I)return!1;for(let ue of D.actions)if(ue.status==="running"&&!Y?.run.actions.some(le=>le.id===ue.id&&le.status==="running"&&le.claim?.token===ue.claim?.token)&&(ks({manifest:o,skills:l,projectRoot:t},D,ue,await B(D,ue)),o.artifactContracts&&await Bl(t,o.artifactContracts,D,ue.stepId,D.actionContexts[ue.id]?.results??{},o),ue.type==="invoke_skill")){As({manifest:o,skills:l},ue,D);let le=A.executors?.find(y=>y.id===ue.claim?.executorId);if(!le)throw new k("EXECUTOR_UNAVAILABLE","Skill 必须由应用已配置的执行端口领取");if(le.supports(gk(ue))!==!0||!le.preflight)throw new k("EXECUTOR_UNSUPPORTED","Skill 执行端口缺少对应的领取预检");if(ue.requiredCapabilities.some(y=>!le.capabilities.includes(y)))throw new k("CAPABILITY_REQUIRED","已配置执行端口缺少 Skill 所需能力")}if(o.artifactContracts)for(let ue of D.waits)ue.status==="resolved"&&ue.decision?.choice==="approved"&&Y?.run.waits.some(le=>le.id===ue.id&&le.status==="pending")&&await Bl(t,o.artifactContracts,D,ue.stepId,ue.results,o);if((Y?.revision??null)!==I||!H&&De(Y?.run)!==De(D))return!1;if(H){let ue=new Set(Y?Z(Y.run).map($):[]),le=Z(D).filter(y=>!ue.has($(y)));le.length&&(await Ht(),await Qy(V,o.id,le))}try{return H&&await se.begin(R,!Y),await L()}finally{H&&(await se.finish(),await Uy(V,o.id,Xe))}};return H?j(ne):ne()}},pe=A.wrapStore?A.wrapStore(ee,u,{readOnly:e.readOnly}):ee;if(e.runId&&!m&&!e.readOnly&&A.wrapStore){let I=await pe.read(e.runId)?await p.read(e.runId):null;if(I)return h(I),Wl(e)}let kt={...A,...o.base==="standalone"?{inspectHook:kP({projectRoot:t,packageRoot:n,manifest:o,skills:l,custom:A.inspectHook,readChild:async R=>(await Pt({...A,store:pe}).inspectProjection(R)).run})}:{},async validateOutcome(R){if(R.action.type==="invoke_skill")try{As({manifest:o,skills:l},R.action,R.run)}catch(I){return{accepted:!1,reason:I instanceof Error?I.message:"Skill 结果不满足应用契约"}}return A.validateOutcome?.(R)??{accepted:!0}}},C=Pt({...kt,store:pe});return c&&await C.inspect(e.runId),{manifest:o,definition:a,identity:u,implementation:kt,skills:l,store:pe}}var DP,Ll=_(()=>{"use strict";xo();Xr();Nx();Rx();et();Cx();co();pr();ys();vp();pP();wP();yP();AP();SP();jP();DP=new Map});function SJ(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Et(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(SJ(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",n=0;for(let i of e){let o=Buffer.byteLength(i,"utf8");if(n+o>t)break;r+=i,n+=o}return{text:r,truncated:!0}}var Ni=_(()=>{"use strict"});function fa(e,t,r,n=""){let i=Object.keys(e),o=t.filter(s=>!Object.hasOwn(e,s)),a=i.filter(s=>!t.includes(s));if(o.length||a.length)throw new Vl({code:"invalid-fields",path:n,context:r,missingFields:o,unknownFields:a,expectedFields:[...t]})}var Vl,bp=_(()=>{"use strict";Vl=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function Ns(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}var FP,Ml,_k,HP,QP,UP,ql=_(()=>{"use strict";FP=["passed","failed","not-run"],Ml=["pass","fail","blocked"],_k=["passed","failed","blocked"],HP=["aligned","conflict","blocked"],QP=["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"],UP=["final-result"]});function Ik(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function Np(e,t,r="acceptance_review"){if(!Array.isArray(e))throw new Error(`Native Builder ${r} must be an array`);let n=[],i=l=>{try{return l()}catch(u){n.push(u instanceof Error?u.message:String(u))}},o=t&&new Set(t.map(({id:l})=>l)),a=[],s=[],c=e.flatMap((l,u)=>{let f=`Native Builder ${r}[${u}]`;if(!l||typeof l!="object"||Array.isArray(l))return n.push(`${f} must be an object`),[];let d=l;i(()=>fa(d,["id","status","evidence","note"],f,`/${r}/${u}`));let p=i(()=>Ik(d.id,`${f}.id`));p&&(a.includes(p)&&n.push(`${f}.id contains duplicate ID: ${p}`),a.push(p),o&&!o.has(p)&&s.push({index:u,id:p}));let h=p&&o?.has(p)?f+" ("+p+")":f,m=i(()=>Ns(d.status,QP,`${f}.status`)),g;Array.isArray(d.evidence)?g=d.evidence.map((w,A)=>i(()=>Ik(w,`${f}.evidence[${A}]`))).filter(w=>w!==void 0):n.push(`${h}.evidence must be an array of concrete strings of at most 4000 characters; received ${typeof d.evidence}`);let v=i(()=>Ik(d.note,`${h}.note`));return p&&m&&g&&v?[{id:p,status:m,evidence:g,note:v}]:[]});if(t&&!n.length)return Fl(t,c),c;if(t){for(let{index:u,id:f}of s)n.push(`Native Builder ${r}[${u}].id contains unknown ID: ${f}`);let l=t.filter(({id:u})=>!a.includes(u)).map(({id:u})=>u);l.length&&n.push(`Native Builder ${r} missing: ${l.join(", ")}`)}if(n.length)throw new Error(n.join(`
|
|
272
|
+
`));return c}function Fl(e,t){if(!t)throw new mo(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),n=t.map(({id:c})=>c),i=new Set(n);if(i.size!==n.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let o=n.filter(c=>!r.has(c));if(o.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${o.join(", ")}`);let a=e.filter(({id:c})=>!i.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(a.length||s.length)throw new mo(a,s)}var mo,Rp=_(()=>{"use strict";bp();ql();mo=class extends Error{constructor(r,n){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${n.length?`; not ready: ${n.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=n}missingIds;incompleteIds}});function _J(e){return e.toLowerCase().startsWith(".env")}function JP(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>_J(n))?"environment-file":r.some(n=>CJ.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>EJ.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var EJ,CJ,zP=_(()=>{"use strict";EJ=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),CJ=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});var Hl=_(()=>{"use strict";$a()});import{createHash as IJ}from"node:crypto";import{promises as Mt}from"node:fs";import Pr from"node:path";import{TextDecoder as GP}from"node:util";function Sp(e,t){let r=Pr.relative(e,t);return r===""||!Pr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pr.sep}`)}function XP(e){let t=Pr.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let o=i.codePointAt(0)??0;return o<=31||o===127})||Pr.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),n=JP(e);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function ZP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function xJ(e,t){return ft({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ho(e,t){let r={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ft(r,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function KP(e){let t=await Mt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Mt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function eT(e,t){let r=Pr.resolve(e),n=Pr.resolve(t);if(!Sp(r,n))throw new Error("Native artifact path is outside its root");let i=[await KP(r)],o=r;for(let a of Pr.relative(r,n).split(Pr.sep).filter(Boolean)){o=Pr.join(o,a);let s=await KP(o);if(!Sp(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${o}`);i.push(s)}return i}async function Ep(e){for(let t of e){let r=await Mt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xJ(t,r)||await Mt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Ve(e){let t=XP(e.ref),r=e.maxBytes===null?null:ZP(e.maxBytes??YP),n=Pr.resolve(e.root,...t.split("/")),i=await eT(e.root,Pr.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Mt.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&o.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let a=await Mt.realpath(n);if(!Sp(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Mt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Mt.lstat(n),Mt.realpath(n)]);if(await Ep(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!ho(o,c)||!ho(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let A=r===null?p.length:r+1-d,N=await s.read(p,0,Math.min(p.length,A),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([s.stat(),Mt.lstat(n),Mt.realpath(n)]);if(await Ep(i),!m.isFile()||m.isSymbolicLink()||g!==a||!ho(c,h)||!ho(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(f,d),w;try{w=new GP("utf-8",{fatal:!0}).decode(v)}catch(A){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:A})}return{ref:t,size:d,hash:e.includeHash===!1?null:IJ("sha256").update(v).digest("hex"),text:w}}finally{await s.close()}}async function tT(e){let t=XP(e.ref),r=ZP(e.maxBytes),n=Pr.resolve(e.root,...t.split("/")),i=await eT(e.root,Pr.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Mt.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);let a=await Mt.realpath(n);if(!Sp(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Mt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Mt.lstat(n),Mt.realpath(n)]);if(await Ep(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!ho(o,c)||!ho(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=Math.min(c.size,r),d=[],p=0,h=Buffer.allocUnsafe(Math.min(64*1024,r));for(;p<f;){let b=await s.read(h,0,Math.min(h.length,f-p),null);if(b.bytesRead===0)break;p+=b.bytesRead,d.push(Buffer.from(h.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,g,v]=await Promise.all([s.stat(),Mt.lstat(n),Mt.realpath(n)]);if(await Ep(i),!g.isFile()||g.isSymbolicLink()||v!==a||!ho(c,m)||!ho(c,g)||p!==f)throw new Error(`Native artifact changed while reading: ${t}`);let w=c.size>r,A=Buffer.concat(d,p),N;try{N=new GP("utf-8",{fatal:!0}).decode(A,{stream:w})}catch(b){throw new Error(`Native artifact prefix is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:c.size,text:N,truncated:w}}finally{await s.close()}}var YP,hn=_(()=>{"use strict";zP();Hl();YP=Number.MAX_SAFE_INTEGER});import{promises as PJ}from"node:fs";import TJ from"node:path";function _p(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Cp(e,t,r){let n=Object.keys(e).filter(o=>!t.has(o)),i=[...t].filter(o=>!(o in e));if(n.length>0||i.length>0){let o=[...i.length>0?[`missing ${i.join(", ")}`]:[],...n.length>0?[`unexpected ${n.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${o.join("; ")}`)}}function nT(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,n)=>r.localeCompare(n,"en"))}function WJ(e){let t=new Map(e.map(o=>[o.name,o])),r=new Set,n=new Set,i=o=>{if(!n.has(o)){if(r.has(o))throw new Error(`Native children dependency cycle includes ${o}`);r.add(o);for(let a of t.get(o).depends_on)i(a);r.delete(o),n.add(o)}};for(let o of e)i(o.name)}function iT(e,t,r=[]){let n=new Set(t);for(let a of e){let s=a.covers.filter(c=>!n.has(c));if(s.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${s.join(", ")}`)}let i=new Set(e.flatMap(a=>a.covers)),o=r.filter(a=>!i.has(a));if(o.length>0)throw new Error(`Native children do not cover parent acceptance: ${o.join(", ")}`)}function cT(e,t,r){let n={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Pk&&e.acceptance_index){let i=r.requiredAcceptanceIds??[],o=r.allowedAcceptanceIds??t??i,a=Object.keys(e.acceptance_index);n.missing=i.filter(l=>!(l in e.acceptance_index)),n.extra=a.filter(l=>!o.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=s.get(l),f=e.acceptance_index[l];u&&f&&(f.source!==u.source||f.text!==u.text)&&n.mismatched.push(l)}let c=new Set(a);for(let l of e.children)n.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return n.uncovered=i.filter(l=>!oT(e.children,l)),aT(n)?n:null}if(e.schema===pa&&t){let i=new Set(t);for(let o of e.children)n.unknownCovers.push(...o.covers.filter(a=>!i.has(a)));return n.uncovered=(r.requiredAcceptanceIds??[]).filter(o=>!oT(e.children,o)),aT(n)?n:null}return null}function oT(e,t){return e.some(r=>r.covers.includes(t))}function aT(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ri(e){return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[],allowedAcceptanceIds:e.acceptance.map(({id:t})=>t)}}function LJ(e){let t=_p(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[n,i]of Object.entries(t)){let o=_p(i,`Native children acceptance_index.${n}`);if(Cp(o,new Set(["source","text"]),`Native children acceptance_index.${n}`),typeof o.source!="string"||o.source.length===0)throw new Error(`Native children acceptance_index.${n}.source must be a non-empty string`);if(typeof o.text!="string"||o.text.length===0)throw new Error(`Native children acceptance_index.${n}.text must be a non-empty string`);r[n]={source:o.source,text:o.text}}return r}function VJ(e,t,r){let n=r.requiredAcceptanceIds??[],i=r.allowedAcceptanceIds??t??n,o=Object.keys(e),a=n.filter(c=>!(c in e)),s=o.filter(c=>!i.includes(c));if(a.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${s.join(", ")||"none"}`)}function Ip(e,t,r={}){let n=(0,sT.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${n.errors[0].message}`);let i=_p(n.toJS({mapAsMap:!1}),"Native children contract"),o=i.schema;if(o!==pa&&o!==ma)throw Cp(i,rT,"Native children contract"),new Error(`Native children schema must be ${pa} or ${ma}`);let a=o===pa?"v1":"acceptance_index"in i?"indexed-v2":Array.isArray(i.children)&&i.children.every(d=>!d||typeof d!="object"||!("summary"in d))&&i.children.some(d=>d&&typeof d=="object"&&"covers"in d)?"referenced-v2":"summary-v2";if(a==="referenced-v2"&&!r.acceptanceCatalog)throw new Error("Native referenced children require the current acceptance catalog");let s=a.replace("-"," ");if(Cp(i,a==="indexed-v2"?$J:rT,"Native children contract"),!Array.isArray(i.children)||i.children.length===0)throw new Error("Native children must be a non-empty array");let c=i.children.map((d,p)=>{let h=_p(d,`Native child ${p}`);if(Cp(h,a==="indexed-v2"||a==="referenced-v2"?BJ:a==="summary-v2"?DJ:jJ,`Native ${s} child fields (child ${p})`),typeof h.name!="string"||!OJ.test(h.name))throw new Error(`Native child ${p} name is invalid`);let m=a==="summary-v2";if(m){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:m?h.summary:null,depends_on:nT(h.depends_on,`Native child ${h.name} depends_on`),covers:a==="indexed-v2"||a==="referenced-v2"||a==="v1"?nT(h.covers,`Native child ${h.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let p=d.depends_on.filter(h=>!u.has(h));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}WJ(c);let f=r.policy==="advisory";if(o===Pk){if(a==="indexed-v2"||a==="referenced-v2"){let d=a==="indexed-v2"?LJ(i.acceptance_index):{},p=[...new Set([...Object.keys(d),...r.requiredAcceptanceIds??[],...c.flatMap(v=>v.covers)])],h=new Map(r.acceptanceCatalog?.map(v=>[v.id,v])),m=Object.fromEntries(p.map(v=>{let w=h.get(v)??d[v];if(!w)throw new Error(`Native acceptance catalog is missing ${v}`);return[v,{source:w.source,text:w.text}]}));f||VJ(m,t,r);let g=Object.keys(m);return f||iT(c,g,r.requiredAcceptanceIds??[]),{schema:ma,acceptance_index:m,children:c}}return{schema:ma,children:c}}return t&&!f&&iT(c,t),{schema:pa,children:c}}async function Si(e){let t=TJ.join(e.changeDir,xk);try{await PJ.lstat(t)}catch(a){if(a.code==="ENOENT")return null;throw a}let r=await Ve({root:e.changeDir,ref:xk,includeHash:!1}),n=e.policy==="advisory",i=n?{...e.validation,policy:"advisory"}:e.validation??{},o=Ip(r.text,e.acceptanceIds,i);return{contract:o,size:r.size,drift:n?cT(o,e.acceptanceIds,e.validation??{}):null}}function Fe(e,t,r){let n=e?.contractRef??e?.contractHash;if(t&&typeof n=="string"){let i=t.state;if(r?.stepId==="supervisor.prepare"&&r.executionOrigin&&n===i.children_contract_hash){let s=t.actionContexts[r.id].results["shape.prepare"],c=s&&t.actions.find(l=>l.stepId==="shape.prepare"&&l.status==="succeeded"&&t.actionContexts[l.id].sequence===s.sequence);if(c&&c.id===i.children_contract_ref)return c.id}if(n===i.children_contract_ref)return n;let o=t.outputs["supervisor.prepare"];if(o?.value?.contractHash===n){let s=t.actions.find(u=>u.stepId==="supervisor.prepare"&&u.status==="succeeded"&&t.actionContexts[u.id].sequence===o.sequence),c=s&&t.actionContexts[s.id].results["shape.prepare"],l=c&&t.actions.find(u=>u.stepId==="shape.prepare"&&u.status==="succeeded"&&t.actionContexts[u.id].sequence===c.sequence);if(l&&l.id===i.children_contract_ref)return l.id}}return typeof n=="string"?n:void 0}var sT,xk,pa,ma,Pk,OJ,rT,$J,jJ,DJ,BJ,Tr=_(()=>{"use strict";sT=kr(dn(),1);hn();xk="children.yaml",pa="comet.native.children.v1",ma="comet.native.children.v2",Pk=ma,OJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rT=new Set(["schema","children"]),$J=new Set(["schema","acceptance_index","children"]),jJ=new Set(["name","depends_on","covers"]),DJ=new Set(["name","summary","depends_on"]),BJ=new Set(["name","depends_on","covers"])});function ha(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}function uT(e,t){let r=(0,xp.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}function go(e,t){let r=e.lastIndexOf(lT);if(e.startsWith(Ql)&&r>=0&&e.endsWith(`
|
|
273
|
+
`)){let n=e.slice(r+lT.length,-1);try{let i=JSON.parse(n);if(JSON.stringify(i)===n){let o=e.slice(0,r+1),a=uT(o,t);if(a&&typeof a=="object"&&!Array.isArray(a)&&!Object.hasOwn(a,yi)&&Ql+(0,xp.stringify)(a)===o)return{...a,[yi]:i}}}catch{}}return uT(e,t)}var xp,Ql,lT,Ul=_(()=>{"use strict";xp=kr(dn(),1);et();Ql=`# comet-execution: managed-run
|
|
274
|
+
`;lT=`
|
|
275
|
+
${yi}: `});function Tk(e){let t=e.input;if(!t||typeof t!="object"||typeof t.candidateId!="string"||!t.candidateId||typeof t.identityProvider!="string"||!t.identityProvider||typeof t.builderExecutionRef!="string"||!t.builderExecutionRef||t.verifierExecutionRef!==null&&typeof t.verifierExecutionRef!="string"||!Number.isSafeInteger(t.iteration)||t.iteration<1||!Number.isSafeInteger(t.goalCycle)||t.goalCycle<1||typeof t.registeredAt!="string"||Number.isNaN(Date.parse(t.registeredAt))||e.type!=="handoff"||e.ref!=="native-verifier"||e.stepId!=="native-verifier"||t.verifierExecutionRef!==null&&t.verifierExecutionRef===t.builderExecutionRef||e.claim&&(e.claim.executorId!==t.identityProvider||e.claim.token===t.builderExecutionRef||t.verifierExecutionRef!==null&&e.claim.token!==t.verifierExecutionRef))throw new Error("Native Verifier action binding is invalid");return t}function dT(e,t){let r=Tk(t);return t.runId===e.name&&r.candidateId===e.builder_handoff?.candidate_id&&r.identityProvider===e.builder_handoff.identity_provider&&r.builderExecutionRef===e.builder_handoff.builder_execution_ref&&r.iteration===e.loop.iteration&&r.goalCycle===e.loop.goal_cycle&&t.attempt===e.loop.attempt}var Pp=_(()=>{"use strict";To();lr()});import{randomUUID as MJ}from"crypto";import{promises as gr}from"fs";import Dn from"path";function Tp(e,t){let r=Dn.relative(e,t);return r===""||!Dn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dn.sep}`)}function qJ(e,t){return ft({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Op(e,t){return ft({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function FJ(e,t){return Op(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function fT(e){let t=await gr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await gr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Rs(e){for(let t of e){let r=await gr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!qJ(t,r)||await gr.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function HJ(e,t,r){let[n,i]=await Promise.all([gr.lstat(e),gr.realpath(e),r?Rs(r):Promise.resolve()]);if(!n.isFile()||n.isSymbolicLink()||!Op(n,t)||r&&!Tp(r[0].realPath,i))throw new Error("Native atomic write temporary file changed after close");return n}async function QJ(e,t){let r=Dn.resolve(e),n=Dn.resolve(t);if(!Tp(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let i=[await fT(r)],o=Dn.relative(r,n).split(Dn.sep).filter(Boolean),a=r;for(let s of o){await Rs(i),a=Dn.join(a,s);try{await gr.mkdir(a)}catch(l){if(l.code!=="EEXIST")throw l}let c=await fT(a);if(!Tp(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${a}`);i.push(c)}return await Rs(i),i}async function Jl(e){let t;try{t=await gr.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 UJ(e,t,r={}){let n=Dn.dirname(e),i=r.containedRoot?await QJ(r.containedRoot,n):null;i||await gr.mkdir(n,{recursive:!0});let o=Dn.join(n,`.${Dn.basename(e)}.${MJ()}.tmp`),a,s,c;try{if(await r.beforeTemporaryOpen?.(),a=await gr.open(o,"wx"),s=await a.stat(),i){let[l,u]=await Promise.all([gr.lstat(o),gr.realpath(o)]);if(await Rs(i),!l.isFile()||l.isSymbolicLink()||!Op(s,l)||!Tp(i[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await a.writeFile(t,"utf8"):await a.writeFile(t),await a.sync(),c=await a.stat(),!Op(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await a.close(),a=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await HJ(o,c,i),await r.beforeCommit?.(),i){await Rs(i);let l=await gr.lstat(o);if(!l.isFile()||l.isSymbolicLink()||!c||!FJ(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await Za(o,e),await zc(o)):await Ko(o,e),await Jl(n)}catch(l){if(await a?.close(),!i)await gr.rm(o,{force:!0});else try{await Rs(i),await gr.rm(o,{force:!0})}catch{}throw l}}async function Ge(e,t,r={}){await UJ(e,t,r)}async function Ei(e,t,r={}){await Ge(e,JSON.stringify(t,null,2)+`
|
|
276
|
+
`,r)}var $t=_(()=>{"use strict";zd();Hl()});function zl(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ss,$p=_(()=>{"use strict";Ss="comet.native.v4"});var Bk={};Nh(Bk,{NativePortableStateVersionConflictError:()=>Kl,appendNativePortableHistory:()=>Hr,compareAndSwapNativePortableState:()=>gT,createNativePortableState:()=>_s,parseNativePortableState:()=>M,parseNativeReportedChecks:()=>Xn,readNativePortableState:()=>wn,writeNativePortableState:()=>Dk});import{promises as JJ}from"node:fs";function ZJ(e,t){let r=qt(e,"Native approved children plan");if(!Array.isArray(r.children))throw new Error("Native approved children plan requires children");let n=r.children.map(i=>{let o={...qt(i,"Native approved child")};return r.schema==="comet.native.children.v2"&&!r.acceptance_index&&typeof o.summary=="string"?delete o.covers:delete o.summary,o});return Ip(JSON.stringify({...r,children:n}),t.map(i=>i.id),{acceptanceCatalog:t})}function qt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vr(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function ut(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function $k(e,t){return e===null?null:ut(e,t)}function mT(e,t){let r=ut(e,t);if(!YJ.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Es(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function lt(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function ez(e,t){return e===null?null:lt(e,t,Number.MIN_SAFE_INTEGER)}function Ct(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function gn(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((n,i)=>r(n,i))}function Bp(e,t){return gn(e,t,(r,n)=>ut(r,`${t}[${n}]`))}function ga(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Cs(e,t){let r=ut(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Dp(e,t,r=!1){let n=ut(e,t);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return n}function vn(e,t){let r=qt(e,t);return vr(r,new Set(["text","truncated"]),t),{text:ut(r.text,`${t}.text`,{empty:!0}),truncated:Es(r.truncated,`${t}.truncated`)}}function tz(e,t){let r=`Native spec_changes[${t}]`,n=qt(e,r);vr(n,new Set(["capability","operation","source","delta_source","base_hash"]),r);let i=ut(n.capability,`${r}.capability`);if(!KJ.test(i))throw new Error(`${r}.capability is invalid`);let o=Ct(n.operation,["create","modify","remove"],`${r}.operation`),a=n.source===null?null:Dp(n.source,`${r}.source`),s=n.delta_source===void 0?void 0:Dp(n.delta_source,`${r}.delta_source`),c=n.base_hash===void 0?void 0:n.base_hash===null?null:mT(n.base_hash,`${r}.base_hash`);if(o==="remove"&&a!==null)throw new Error(`${r} remove requires source null`);if(o!=="remove"&&a===null)throw new Error(`${r} ${o} requires a source`);if(s!==void 0&&o==="remove")throw new Error(`${r} remove cannot contain delta_source`);return{capability:i,operation:o,source:a,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function rz(e){let t="Native workspace",r=qt(e,t);vr(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let n=Ct(r.isolation,["current","branch","worktree"],`${t}.isolation`),i=$k(r.change_branch,`${t}.change_branch`),o=$k(r.target_branch,`${t}.target_branch`),a=r.finish===null?null:Ct(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(n==="current"&&a!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(o===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||o===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:o,finish:a}}function nz(e){let t="Native loop",r=qt(e,t);vr(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let n=Bp(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);ga(n,`${t}.previous_unresolved_ids`);let i=r.stop_reason===void 0?void 0:Ct(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Ct(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:lt(r.goal_cycle,`${t}.goal_cycle`,1),iteration:lt(r.iteration,`${t}.iteration`),attempt:lt(r.attempt,`${t}.attempt`),retry_epoch:lt(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:lt(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:lt(r.no_progress_count,`${t}.no_progress_count`),...i===void 0?{}:{stop_reason:i},execution_failure_count:lt(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:n,next_action:$k(r.next_action,`${t}.next_action`)}}function iz(e,t){let r=`Native acceptance[${t}]`,n=qt(e,r);vr(n,new Set(["id","source","text","result","reason"]),r);let i=ut(n.id,`${r}.id`);if(!GJ.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Dp(n.source,`${r}.source`),text:ut(n.text,`${r}.text`),result:Ct(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:vn(n.reason,`${r}.reason`)}}function jk(e,t){let r=`Native builder_handoff.checks[${t}]`,n=qt(e,r);return vr(n,new Set(["name","result","note"]),r),{name:vn(n.name,`${r}.name`),result:Ct(n.result,FP,`${r}.result`),note:n.note===null?null:vn(n.note,`${r}.note`)}}function Xn(e){return gn(e,"Native reported checks",(t,r)=>{let n=qt(t,`Native reported checks[${r}]`);return jk({name:Et(ut(n.name,"Reported check name")),result:n.result,note:n.note==null?null:Et(ut(n.note,"Reported check note"))},r)})}function oz(e){let t="Native builder_handoff",r=qt(e,t);vr(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at","raw_input_ref"]),t);let n=Bp(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);ga(n,`${t}.addressed_acceptance_ids`);let i=r.review===null||r.review===void 0?null:qt(r.review,`${t}.review`);return i&&vr(i,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ut(r.candidate_id,`${t}.candidate_id`),identity_provider:ut(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ut(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:lt(r.iteration,`${t}.iteration`,1),summary:vn(r.summary,`${t}.summary`),addressed_acceptance_ids:n,...r.acceptance_review===void 0?{}:{acceptance_review:Np(r.acceptance_review)},checks:gn(r.checks,`${t}.checks`,jk),checks_truncated:Es(r.checks_truncated,`${t}.checks_truncated`),known_limits:gn(r.known_limits,`${t}.known_limits`,(o,a)=>vn(o,`${t}.known_limits[${a}]`)),known_limits_truncated:Es(r.known_limits_truncated,`${t}.known_limits_truncated`),review:i?{status:Ct(i.status,["passed"],`${t}.review.status`),summary:vn(i.summary,`${t}.review.summary`),reviewer_execution_ref:ut(i.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Cs(r.submitted_at,`${t}.submitted_at`),...r.raw_input_ref!==void 0?{raw_input_ref:ut(r.raw_input_ref,`${t}.raw_input_ref`)}:{}}}function az(e,t){let r=`Native blockers[${t}]`,n=qt(e,r);vr(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=Bp(n.acceptance_ids,`${r}.acceptance_ids`);return ga(i,`${r}.acceptance_ids`),{owner:Ct(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:vn(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:Ct(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function sz(e,t){let r=`Native verification.checks[${t}]`,n=qt(e,r);return vr(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ut(n.id,`${r}.id`),name:vn(n.name,`${r}.name`),argv_display:gn(n.argv_display,`${r}.argv_display`,(i,o)=>vn(i,`${r}.argv_display[${o}]`)),argv_truncated:Es(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Dp(n.cwd_ref,`${r}.cwd_ref`,!0),status:Ct(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:ez(n.exit_code,`${r}.exit_code`),duration_ms:lt(n.duration_ms,`${r}.duration_ms`)}}function cz(e){let t="Native verification",r=qt(e,t);vr(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","reported_checks","summary","risks","risks_truncated","completed_at"]),t);let n=gn(r.checks,`${t}.checks`,sz);ga(n.map(o=>o.id),`${t}.checks IDs`);let i=ut(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ut(r.candidate_id,`${t}.candidate_id`),identity_provider:i,verifier_execution_ref:ut(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:lt(r.iteration,`${t}.iteration`,1),attempt:lt(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":Ct(r.assurance,["host-attested","self-reviewed","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Ct(r.verdict,Ml,`${t}.verdict`),checks:n,...r.reported_checks===void 0?{}:{reported_checks:gn(r.reported_checks,`${t}.reported_checks`,jk)},summary:vn(r.summary,`${t}.summary`),risks:gn(r.risks,`${t}.risks`,(o,a)=>vn(o,`${t}.risks[${a}]`)),risks_truncated:Es(r.risks_truncated,`${t}.risks_truncated`),completed_at:Cs(r.completed_at,`${t}.completed_at`)}}function hT(e,t){let r=`Native history[${t}]`,n=qt(e,r);vr(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=Bp(n.unresolved_ids,`${r}.unresolved_ids`);return ga(i,`${r}.unresolved_ids`),{goal_cycle:lt(n.goal_cycle,`${r}.goal_cycle`,1),iteration:lt(n.iteration,`${r}.iteration`),attempt:lt(n.attempt,`${r}.attempt`),outcome:Ct(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:vn(n.summary,`${r}.summary`),completed_at:Cs(n.completed_at,`${r}.completed_at`)}}function lz(e){let t="Native history_overflow.outcome_counts",r=qt(e,t),n=["pass","fail","blocked","execution-error","recovery"];return vr(r,new Set(n),t),{pass:lt(r.pass,`${t}.pass`),fail:lt(r.fail,`${t}.fail`),blocked:lt(r.blocked,`${t}.blocked`),"execution-error":lt(r["execution-error"],`${t}.execution-error`),recovery:lt(r.recovery,`${t}.recovery`)}}function uz(e){let t="Native history_overflow",r=qt(e,t);vr(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let n=lt(r.dropped_entries,`${t}.dropped_entries`),i=r.first_dropped_at===null?null:Cs(r.first_dropped_at,`${t}.first_dropped_at`),o=r.last_dropped_at===null?null:Cs(r.last_dropped_at,`${t}.last_dropped_at`);if(n===0&&(i!==null||o!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||o===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let a=lz(r.outcome_counts);if(Object.values(a).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:o,outcome_counts:a}}function dz(e){if(e.verifier_action){if(Tk(e.verifier_action),e.verifier_action.runId!==e.name)throw new Error("Native Verifier action belongs to another change");if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"&&["pending","running","unknown"].includes(e.verifier_action.status)&&!dT(e,e.verifier_action))throw new Error("Native Verifier action is stale for the current candidate or attempt")}let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&Fl(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let n of r.acceptance_ids)if(!t.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");let r=["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance);if(e.verification.assurance!=="self-reviewed"&&r!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="self-reviewed"&&e.verification.verifier_execution_ref!==e.builder_handoff.builder_execution_ref)throw new Error("Native self-reviewed verification must use the Builder session");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.assurance!=="self-reviewed"&&e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let n=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,i=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function fz(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(n=>n.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function M(e){let t=qt(e,"Native portable state");if(vr(t,XJ,"Native portable state"),t.schema!==Ss)throw new Error(`Native portable state schema must be ${Ss}`);let r=ut(t.name,"Native state name");if(!zJ.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=gn(t.spec_changes,"Native spec_changes",tz);ga(n.map(s=>s.capability),"Native spec change capabilities");let i=gn(t.acceptance,"Native acceptance",iz);ga(i.map(s=>s.id),"Native acceptance IDs");let o=gn(t.history,"Native history",hT);if(o.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let a={schema:Ss,name:r,language:Ct(t.language,["en","zh-CN"],"Native state language"),phase:Ct(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Ct(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:lt(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:mT(t.shape_confirmation_hash,"Native Shape confirmation hash")},...(t.children_contract_ref??t.children_contract_hash)===void 0?{}:{children_contract_ref:ut(t.children_contract_ref??t.children_contract_hash,"Native children approval reference")},...t.children_contract_ref!==void 0&&t.children_contract_hash!==void 0?{children_contract_hash:ut(t.children_contract_hash,"Legacy children approval reference")}:{},...t.children_contract===void 0?{}:{children_contract:ZJ(t.children_contract,i)},...t.coordination_mode===void 0?{}:{coordination_mode:Ct(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:n,workspace:rz(t.workspace),loop:nz(t.loop),acceptance:i,builder_handoff:t.builder_handoff===null?null:oz(t.builder_handoff),...t.verifier_action===void 0?{}:{verifier_action:jN(t.verifier_action)},blockers:gn(t.blockers,"Native blockers",az),verification:t.verification===null?null:cz(t.verification),history:o,history_overflow:uz(t.history_overflow),verification_result:Ct(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Ct(t.verification_report,["verification.md"],"Native verification_report"),archived:Es(t.archived,"Native archived"),created_at:Cs(t.created_at,"Native created_at")};return dz(a),fz(a),a}function _s(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return M({schema:Ss,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:zl(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Hr(e,t){let r=M(e),n=hT(t,r.history.length),i=[...r.history,n],o={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;i.length>50;){let a=i.shift();o.dropped_entries+=1,o.first_dropped_at??=a.completed_at,o.last_dropped_at=a.completed_at,o.outcome_counts[a.outcome]+=1}return M({...r,history:i,history_overflow:o})}async function wn(e){let t=await JJ.readFile(e,"utf8");return M(go(t,"Native portable state"))}async function Dk(e,t,r={}){let n=M(t);await Ge(e,(0,pT.stringify)(n),r)}async function pz(e,t){let r=jp.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),o=r.then(()=>i);jp.set(e,o),await r;try{return await t()}finally{n(),jp.get(e)===o&&jp.delete(e)}}async function gT(e){return pz(e.file,async()=>{let t=lt(e.expectedStateVersion,"Native expected state version",1),r=M(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let n=await wn(e.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==t)throw new Kl(t,n.state_version);return await Dk(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let i=await wn(e.file);if(i.state_version!==t)throw new Kl(t,i.state_version)}}),r})}var pT,zJ,KJ,GJ,YJ,XJ,Kl,jp,xe=_(()=>{"use strict";Ni();Rp();Tr();ql();pT=kr(dn(),1);To();Ul();Pp();$t();$p();zJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GJ=/^A[1-9][0-9]*$/u,YJ=/^[a-f0-9]{64}$/u,XJ=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","shape_semantic_snapshot","children_contract_ref","children_contract_hash","children_contract","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","verifier_action","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at","run_checkpoint","archive_receipt","application_checkpoint"]);Kl=class extends Error{constructor(r,n){super(`Native state version conflict: expected ${r}, got ${n}`);this.expectedStateVersion=r;this.actualStateVersion=n;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};jp=new Map});import vT from"node:path";async function Wp(e){let t=[],r=new Set,n=e.ownerObservation===void 0?await je(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,i=St({singleWriter:!0,rootDir:vT.join(Ze(e.projectRoot),"sdk-runs/native")}),o=new Set;async function a(s){if(!o.has(s.runId)){o.add(s.runId);for(let c of s.actions)["pending","running","unknown"].includes(c.status)&&(r.add(s.runId),t.push({runId:s.runId,actionId:c.id,stepId:c.stepId,attempt:c.attempt,inputHash:c.inputHash,reason:"原业务任务仍待完成或由 Agent 核对结果"}));for(let c of s.children){let l=n&&n.application!=="native"?await kp(e.projectRoot,n.application,c.runId):await i.read(c.runId);if(l)["cancelled","completed"].includes(l.status)?await a(l):r.add(c.runId);else{let u=s.actions.find(d=>d.id===c.actionId);u?.type==="child_workflow"&&u.status==="cancelled"&&u.attempt===1&&!u.claim&&!u.outcome&&u.receipts.length===0&&u.reconciliations.length===0||r.add(c.runId)}}}}return await a(e.run),{quiescent:t.length===0&&r.size===0,outstandingActions:t,outstandingRuns:[...r]}}async function Gl(e){if(e.run.status!=="cancelled")return null;let{quiescent:t,outstandingActions:r,outstandingRuns:n}=await Wp(e),i=e.ownerObservation===void 0?await je(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,o=t?await xr(e.projectRoot):null,a=!!(o?.status==="selected"&&o.selection.change===e.run.runId&&(i?.application==="native"?o.selection.workflow==="native":i&&o.selection.workflow==="application"&&o.selection.applicationId===i.application)),s=null;return a&&(s={reason:"业务调度已取消,当前选择尚未释放;请核对工作区事务并重试清理。",inspectionCommand:"comet native doctor --json",repairCommand:"comet native doctor --repair --json",finishCommand:`comet native doctor ${e.run.runId} --repair --json`}),{status:t&&!a?"cancelled":"cancelling",reason:e.run.reason??null,quiescent:t,cleanupRequired:a,cleanup:s,outstandingActions:r,outstandingRuns:n}}async function Yl(e){return(await Gl(e))?.status==="cancelled"}async function Wk(e,t){let r=await je(e,"native",t,{readOnly:!0});if(!r)return!1;let n=r.application==="native"?await St({singleWriter:!0,rootDir:vT.join(Ze(e),"sdk-runs/native")}).read(r.runId):await kp(e,r.application,r.runId);if(!n||n.status!=="cancelled")return!1;let i=await Pt({workflows:[],store:{read:async()=>n,compareAndSwap:async()=>!1}}).inspect(r.runId);if(i.workflow.id!=="comet-native"||!["1","2","3","4"].includes(i.workflow.version)||i.runId!==t||M(i.state).name!==t||i.input?.name!==t||typeof i.input.artifactRootRef!="string")throw new Error("Native cancellation Run does not match its change ownership");return Yl({projectRoot:e,run:i})}var Is=_(()=>{"use strict";Xr();et();Ll();pr();co();xe()});import mz from"node:path";async function Lk(e){let t=await Vx(e,"native",{readOnly:!0}),r=St({singleWriter:!0,rootDir:mz.join(Ze(e),"sdk-runs","native")}),n=await An(()=>sc(()=>Oa(t.history,4,i=>r.readPartitionMetadata(i))));for(let[i,o]of t.history.entries())if(n[i]!=="closed")throw new Error(`Native history partition for ${o} is ${n[i]}; run comet native doctor ${o} --migrate-history --json to inspect and finish migration`);return await Oa(t.active,4,async i=>{if((await je(e,"native",i,{readOnly:!0}))?.application!=="native")return;let a=await r.readPartitionMetadata(i);if(a==="closing"||a==="reopening")throw new Error(`Native Run ${i} has an unfinished ${a} transaction; run comet native doctor ${i} --migrate-history --json`)}),t}var Vk=_(()=>{"use strict";ct();bn();et();pr();Xr();Hu()});function Mk(e){return e.charCodeAt(0)===65279?e.slice(1):e}var qk=_(()=>{"use strict"});async function wT(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=[],o=setTimeout(()=>a({text:null}),Math.ceil(e)),a=f=>{r||(r=!0,clearTimeout(o),process.stdin.removeListener("data",s),process.stdin.removeListener("end",c),process.stdin.removeListener("close",l),process.stdin.removeListener("error",u),process.stdin.pause(),t(f))},s=f=>{let d=Buffer.isBuffer(f)?f:Buffer.from(f),p=1048576-n;if(p<=0){a({text:null});return}let h=d.subarray(0,p);i.push(h),n+=h.length,d.length>h.length&&a({text:null})},c=()=>a({text:Buffer.concat(i,n).toString("utf8")}),l=()=>{process.stdin.readableEnded||a({text:null})},u=()=>a({text:null});process.stdin.on("data",s),process.stdin.once("end",c),process.stdin.once("close",l),process.stdin.once("error",u),o.unref(),process.stdin.resume()})}var yT=_(()=>{"use strict"});import kT from"node:path";import{fileURLToPath as hz}from"node:url";function xs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Lp(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function wz(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 yz(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!kT.isAbsolute(r.trim())))return r.trim()}}function kz(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 Az(e){for(let t of["hook_event_name","hookEventName","event_name","eventName"]){let r=e[t];if(typeof r=="string"&&r.trim())return Lp(r)}}function bz(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function Nz(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 Rz(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return Nz(e[t]);return e}function Mp(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 o=i[1]?.trim();o&&o!=="/dev/null"&&t.push(o)}return t}function wa(e){return[...new Set(e.flatMap(t=>{let r=t.trim();if(!r)return[];if(/^file:/iu.test(r))try{return[hz(r)]}catch{return[r]}return/^[A-Za-z]:/u.test(r)?[r]:/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(r)?[]:[r]}))]}function va(e,t){if(typeof t=="string"){let r=t.trim();r&&e.push(r);return}if(Array.isArray(t)){for(let r of t)va(e,r);return}if(xs(t)){for(let r of Fk)va(e,t[r]);for(let r of AT)va(e,t[r]);for(let r of bT)va(e,t[r])}}function Sz(e,t){let r=[],n=[t,e].filter(xs);for(let i of n){for(let o of Fk)va(r,i[o]);for(let o of AT)va(r,i[o]);for(let o of bT)va(r,i[o]);for(let o of NT){let a=i[o];typeof a=="string"&&r.push(...Mp(a))}}return typeof t=="string"&&r.push(...Mp(t)),r}function Vp(e){if(typeof e=="string"&&e.startsWith("*** Begin Patch")&&/^[- +].+/mu.test(e))return Mp(e).map(i=>({path:i,patch:e}));if(!xs(e))return[];for(let i of NT)if(typeof e[i]=="string")return Vp(e[i]);let t=Fk.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(!xs(i))return[];let o=i.old_string??i.oldString,a=i.new_string??i.newString;if(typeof o!="string"||!o||typeof a!="string")return[];n.push({oldText:o,newText:a,replaceAll:i.replace_all===!0})}return n.length?[{path:t,replacements:n}]:[]}function Xl(e,t){if(t?.trim()){let p=wa([t]);return{intent:p.length>0?"write":"non-write",targets:p,toolName:null}}if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(Mk(e))}catch{let p=Mp(e);if(p.length>0){let h=wa(p);return{intent:h.length>0?"write":"non-write",targets:h,toolName:"apply_patch",...Vp(e).length?{writes:Vp(e)}:{}}}return{intent:"unknown",targets:[],toolName:null}}if(!xs(r))return{intent:"unknown",targets:[],toolName:null};let n=wz(r),i=Rz(r),o=n&&Lp(n)==="applypatch"&&xs(i)&&typeof i.command=="string"?{...i,patch:i.command}:i,a=Sz(r,o),s=wa(a),c=Vp(o),l=yz(r),u=l?kT.resolve(l):void 0,f=l!==u?l:void 0,d=kz(r);if(Az(r)==="beforeagentstart"){let p=bz(r);return{intent:"context",targets:[],toolName:null,...p?{task:p}:{},...u?{cwd:u}:{},...f?{rawCwd:f}:{},...d?{sessionId:d}:{}}}return a.length>0&&s.length===0?{intent:"non-write",targets:s,toolName:n,...u?{cwd:u}:{},...f?{rawCwd:f}:{},...d?{sessionId:d}:{}}:n&&gz.has(Lp(n))?{intent:s.length>0?"write":"unknown",targets:s,toolName:n,...c.length?{writes:c}:{},...u?{cwd:u}:{},...f?{rawCwd:f}:{},...d?{sessionId:d}:{}}:n&&vz.has(Lp(n))?{intent:"non-write",targets:[],toolName:n,...u?{cwd:u}:{},...f?{rawCwd:f}:{},...d?{sessionId:d}:{}}:n?{intent:"unknown",targets:s,toolName:n,...u?{cwd:u}:{},...f?{rawCwd:f}:{},...d?{sessionId:d}:{}}:{intent:s.length>0?"write":"unknown",targets:s,toolName:null,...u?{cwd:u}:{},...f?{rawCwd:f}:{},...d?{sessionId:d}:{}}}async function RT(e={}){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Xl("",t);let r=await(e.readStdin??wT)();r.text===null&&(process.stderr.write(`[COMET-HOOK] stdin timeout: the host did not provide hook input within the expected window
|
|
277
|
+
`),process.exit(1));try{return Xl(r.text,t)}catch{return Xl("",t)}}var gz,vz,Fk,AT,bT,NT,Hk=_(()=>{"use strict";qk();yT();gz=new Set(["applypatch","create","createfile","deletefile","edit","editfile","multiedit","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),vz=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Fk=["file_path","filePath","path","target_file","targetFile"],AT=["file_paths","filePaths","paths","files","targets"],bT=["operations","edits"],NT=["patch","diff","patchText","patch_text","changes"]});import{createHash as Ez}from"crypto";function Qk(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Cz(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function qp(e,t={}){return(await eu(e,t)).document}async function ST(e){try{return(await qe(e,Zl,Sl,{label:Zl})).bytes}catch(t){if(Cz(t))return null;throw t}}function ET(e){return e?{exists:!0,sha256:Ez("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Fp(e){return ET(await ST(e))}async function eu(e,t={}){let r=await ST(e);return{source:r?.toString("utf8")??null,document:r?fs(r.toString("utf8"),t):null,identity:ET(r)}}async function Uk(e){return(await qp(e))?.config??null}var Zl,Ps=_(()=>{"use strict";vi();ct();Zl=".comet/config.yaml"});import{promises as Ts}from"fs";import Or from"path";function Hp(e,t){let r=Or.relative(e,t);return r===""||r!==".."&&!r.startsWith(`..${Or.sep}`)&&!Or.isAbsolute(r)}function CT(e,t){return Or.isAbsolute(t)?t:`${e}${Or.sep}${t}`}async function Jk(e){let t=CT(process.cwd(),e),r=s=>s.split(process.platform==="win32"?/[\\/]+/u:/\/+/u),n=Or.parse(t).root,i=await Ts.realpath(n),o=r(t.slice(n.length)),a=0;for(;o.length>0;){let s=o.shift();if(!s||s===".")continue;if(s===".."){i=Or.dirname(i);continue}let c=Or.join(i,s),l;try{l=await Ts.lstat(c)}catch(u){if(u.code!=="ENOENT")throw u;if(o.includes("..")){i=c;continue}return Or.join(c,...o)}if(l.isSymbolicLink()){if(o.includes(".."))throw new Error("Hook 目标经过链接后返回父级;请使用规范物理路径");if(++a>40)throw new Error("Hook 目标链接解析超过 40 层,无法安全确定归属");let u=await Ts.readlink(c);if(Or.isAbsolute(u)){let f=Or.parse(u).root;i=await Ts.realpath(f),o=[...r(u.slice(f.length)),...o]}else o=[...r(u),...o];continue}if(o.length>0&&!l.isDirectory())throw new Error("Hook 目标的中间路径不是目录;请使用规范物理路径");i=await Ts.realpath(c)}return i}async function _T(e,t){let r=Or.resolve(e),n=Or.resolve(t);if(Hp(r,n))return!0;let[i,o]=await Promise.all([Jk(r),Jk(t)]);return i!==null&&o!==null&&Hp(i,o)}async function IT(e,t){let r=Or.resolve(e),n=await Ts.realpath(r),i=[],o=[];for(let a of wa(t)){let s=CT(r,a),c=await Jk(s);((c?Hp(n,c):Hp(r,s))?i:o).push(a)}return{projectTargets:i,externalTargets:o}}var xT=_(()=>{"use strict";Hk()});import jt from"path";function Iz(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}function xz(e,t){let r=jt.isAbsolute(t)?jt.resolve(t):jt.resolve(e,t),n=jt.relative(jt.resolve(e),r);return n===""||jt.isAbsolute(n)||n===".."||n.startsWith(`..${jt.sep}`)?null:n.replaceAll("\\","/")}function PT(e){return process.platform==="win32"?e.toLowerCase():e}async function Qp(e,t,r=[]){let n=jt.isAbsolute(t)?jt.resolve(t):jt.resolve(e,t),i=jt.resolve(e);if(!Iz(i,n))return null;let o=xz(e,t);if(!o)return null;let s=(await _z(e)).allow_paths.find(f=>{let d=PT(o),p=PT(f);return d===p||d.startsWith(`${p}/`)});if(!s)return null;let c=await IT(e,[t]),l=jt.isAbsolute(t)?t:`${i}${jt.sep}${t}`;if(c.projectTargets.length!==1)return null;let u=[jt.join(i,".git"),jt.join(i,".comet"),...r];for(let f of u)if(await _T(jt.resolve(f),l))return null;return`${o} (configured Hook allow path: ${s})`}var _z,zk=_(()=>{"use strict";bn();Ps();xT();_z=Qt("hookWritePolicy",async e=>(await Uk(e))?.hook??{allow_paths:[]})});var Os,ya,Up,Zn,$s=_(()=>{"use strict";Os=class extends Error{constructor(r,n,i){super(`Native change ${r} revision conflict: expected ${n}, actual ${i}`);this.change=r;this.expectedRevision=n;this.actualRevision=i;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},ya=class extends Error{constructor(r,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Up=class extends Error{constructor(r,n,i,o){super(`Canonical spec conflict for ${r}: expected ${n??"(missing)"}, actual ${i??"(missing)"}`);this.capability=r;this.expectedHash=n;this.actualHash=i;this.canonicalPath=o;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Zn=class extends Error{constructor(r,n,i){super(r,i);this.preparation=n;this.name="NativeWorkspacePreparationError"}preparation}});import{AsyncLocalStorage as jT}from"node:async_hooks";import{performance as $T}from"node:perf_hooks";function Vz(e=0){Bz+=1,Wz+=e;for(let t of Lz.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}function tu(e){let t=$T.now();try{return e()}finally{Vz($T.now()-t)}}var Bz,Wz,Lz,mte,Jp=_(()=>{"use strict";Bz=0,Wz=0,Lz=new jT,mte=new jT});var DT=_(()=>{"use strict"});var vte,Kk=_(()=>{"use strict";vte=["$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("; ")});var Ete,Gk=_(()=>{"use strict";DT();Jp();Kk();Ete=8*1024*1024});var BT=_(()=>{"use strict"});import{execFileSync as Hz}from"child_process";import WT from"fs";import vo from"path";import{AsyncLocalStorage as Xk}from"node:async_hooks";function VT(e){return ru.getStore()?e():ru.run(new Map,e)}function Uz(e){let t=ru.getStore();for(let r of e)t?.set(wo(r.root),e);return e}function nu(e,t){return tu(()=>Hz("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function he(e,t){return wo(e)===wo(t)}function wo(e){let t=vo.resolve(e);try{let r=WT.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ye(e){let t=Qz.getStore()?.get(wo(e));if(t)return{...t};try{let r=LT.getStore()?.get(wo(e)),n=ru.getStore()?.get(r??wo(e));if(n){let c=Yk(r??e,n);if(c)return c;if(n.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=MT(e),o=Yk(e,i);if(o&&WT.existsSync(vo.join(e,".git")))return o;let a=vo.resolve(nu(e,["rev-parse","--show-toplevel"])),s=Yk(a,i);if(!s)throw new Error("Current worktree is missing from Git worktree list");return s}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function zp(e){try{let t=ru.getStore()?.get(LT.getStore()?.get(wo(e))??wo(e));return t?t.map(r=>({...r})):MT(e)}catch{return[]}}function MT(e){let t=Jz(nu(e,["worktree","list","--porcelain","-z"]));return Uz(t),t.map(r=>({...r}))}function Jz(e){let t=e.split("\0"),r=[],n=null;for(let i of t)i.startsWith("worktree ")?(n&&r.push(n),n={root:vo.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}function $r(e){return zp(e).map(t=>t.root)}function Yk(e,t){let r=t.find(o=>he(vo.resolve(o.root),vo.resolve(e)));if(!r)return null;let n=vo.resolve(t[0].root),i=vo.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!he(n,i),currentWorktreeRoot:i,primaryWorktreeRoot:n,currentBranch:r.branch}}function iu(e,t){try{return nu(e,["check-ref-format","--branch",t]),nu(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function ge(e,t){try{let r=nu(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var ru,LT,Qz,_t=_(()=>{"use strict";Jp();Gk();BT();Kk();ru=new Xk,LT=new Xk,Qz=new Xk});function FT(e,t){return Zk[e][t]}function JT(e,t){return HT[e][t]??QT[e][t]}function eA(e){return UT.get(e.trim().toLocaleLowerCase("en-US"))??null}function Gz(e){return Kp[e].section}function ou(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact===!1&&r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(n=>{if(n!=="scope")return`# ${FT(e,n)}
|
|
278
|
+
`;let i=[`# ${FT(e,n)}
|
|
279
|
+
`];return i.push(`## ${Gz(e)}
|
|
280
|
+
`),i.push(jr(e,`<!-- Add only needed level-three categories (Created, Modified, Deleted, Not created), with paths and responsibilities. Omit unused categories. -->
|
|
281
|
+
`,`<!-- 按实际改动添加三级标题(新建、修改、删除、明确不建),写明路径与职责;无内容的类别可省略。 -->
|
|
282
|
+
`)),i.join(`
|
|
283
|
+
`)}).join(`
|
|
284
|
+
`)}function jr(e,t,r){return e==="zh-CN"?r:t}var Zk,HT,QT,UT,qT,zz,Kz,Kp,js=_(()=>{"use strict";Zk={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},HT={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},QT={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},UT=new Map,qT=new Map,zz=new Set,Kz=new Map,Kp={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(Zk)){for(let[t,r]of Object.entries(Zk[e]))UT.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(HT[e]))qT.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(QT[e]))qT.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(Kp)){zz.add(Kp[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(Kp[e].subsections))Kz.set(r.toLocaleLowerCase("en-US"),t)}});var Fte,tA=_(()=>{"use strict";Jn();Ps();ct();Fte=Number.MAX_SAFE_INTEGER});async function rA(e,t){if(!t)return;let r=await Fp(e);if(!Qk(r,t))throw new Error("Project config changed before commit; rerun the operation")}var nA=_(()=>{"use strict";Jn();vi();Ps();ct();tA()});import{promises as Ds}from"fs";import Je from"path";import Zz from"os";async function iA(e){try{return await Ds.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tK(e){try{let t=await Ds.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function au(e,t){let r=Je.relative(e,t);return r===""||!Je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Je.sep}`)}async function su(e){let t=[],r=e;for(;!await iA(r);){let i=Je.dirname(r);if(i===r)break;t.push(Je.basename(r)),r=i}let n=await Ds.realpath(r);return Je.resolve(n,...t.reverse())}async function oA(e){try{return(await Ds.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function aA(e){let t=Je.resolve(e);try{(await Ds.stat(t)).isDirectory()||(t=Je.dirname(t))}catch(i){if(i.code!=="ENOENT")throw i}let r=t,n=Je.resolve(Zz.homedir());for(;;){if(!(t===n&&r!==n)){let a=Je.join(t,...Gp.split("/")),s=t===r||await tK(a);if(await iA(a)&&s)return t}if(await iA(Je.join(t,".git")))return t;let o=Je.dirname(t);if(o===t)return r;t=o}}function sA(e){return ds(e)}async function rK(e,t){let r=sA(t),n=Je.resolve(e,...r.split("/")),i=await Ds.realpath(e),o=await su(n);if(!au(i,o))throw new Error("native.artifact_root resolves outside the project root");return n}async function ke(e,t,r={}){let n=sA(t),i=await rK(e,n),o=Je.join(i,"comet");if(await oA(o))throw new Error("The configured Native comet root must not be a symbolic link");let[a,s]=await Promise.all([su(i),su(o)]);if(!au(a,s))throw new Error("The configured Native comet root resolves outside its artifact root");let c=Je.resolve(e),l=Ze(c),u=Je.join(l,"native");if(await oA(u))throw new Error("The Native Runtime root must not be a symbolic link");return await Bn(l,u),{projectRoot:c,configFile:Je.join(e,...Gp.split("/")),artifactRoot:i,artifactRootRef:n,nativeRoot:o,specsDir:Je.join(o,"specs"),changesDir:Je.join(o,"changes"),archiveDir:Je.join(o,"archive"),workspaceRuntimeRoot:l,runtimeDir:u,changesRuntimeDir:Je.join(u,"changes"),transactionsDir:Je.join(u,"transactions")}}function nK(e){if(!eK.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Yp(e,t){nK(t);let r=Je.join(e.changesRuntimeDir,t);if(!Gt(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function cu(e,t){return Yp(e,t)}function Xp(e,t){let r=Je.resolve(t);if(Gt(e.runtimeDir,r))return e.runtimeDir;if(Gt(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function Gt(e,t){return au(Je.resolve(e),Je.resolve(t))}async function Bn(e,t){let r=Je.resolve(e),n=Je.resolve(t);if(!au(r,n))throw new Error(`Path is outside the Native root: ${t}`);if(await oA(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[i,o]=await Promise.all([su(r),su(n)]);if(!au(i,o))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Gp,eK,Ye=_(()=>{"use strict";Xr();vi();Gp=".comet/config.yaml",eK=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import iK from"path";async function Be(e){let t=(await qp(e))?.config??null;return t?.native?t:null}async function Zp(e){let t=await Be(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function em(e,t,r={}){let n=await eu(e,{allowPartialProject:!0}),i=_l(n.document?.value??{},t),o=iK.join(e,...Gp.split("/"));await Ge(o,Cl(i,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await rA(e,n.identity)}})}var lu,It=_(()=>{"use strict";vi();Ps();nA();$t();Ye();lu=Xf});function Bs(e){return e.replaceAll(`\r
|
|
285
|
+
`,`
|
|
286
|
+
`).replaceAll("\r",`
|
|
287
|
+
`)}function XT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new gt(`${t} must be an object`);return e}function ZT(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new gt(`${r} has unknown field(s): ${n.join(", ")}`)}function eO(e,t){if(typeof e!="string"||e.trim().length===0)throw new gt(`${t} must be a non-empty string`);return e.trim()}function KT(e,t){if(e!==void 0){if(typeof e!="string")throw new gt(`${t} must be text`);return Bs(e).replace(/^\n+|\n+$/gu,"")}}function GT(e,t){let r=eO(e,t);if(!YT.test(r))throw new gt(`${t} is not a valid stable requirement ID`);return r}function aK(e,t){let r=eO(e,t);if(!oK.test(r))throw new gt(`${t} is not a valid capability ID`);return r}function sK(e,t){let r=`Native delta operations[${t}]`,n=XT(e,r);ZT(n,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let i=GT(n.id,`${r}.id`),o=n.operation;if(!["add","modify","remove","rename"].includes(String(o)))throw new gt(`${r}.operation is invalid`);let a=o,s=n.to_id===void 0?void 0:GT(n.to_id,`${r}.to_id`),c=KT(n.title,`${r}.title`),l=KT(n.body,`${r}.body`);if(a==="add"){if(s!==void 0||!l?.trim())throw new gt(`${r} add requires body and forbids to_id`)}else if(a==="modify"){if(s!==void 0||!l?.trim())throw new gt(`${r} modify requires body and forbids to_id`)}else if(a==="remove"){if(s!==void 0||c!==void 0||l!==void 0)throw new gt(`${r} remove forbids to_id, title, and body`)}else if(s===void 0||s===i||l==="")throw new gt(`${r} rename requires a different to_id`);return{id:i,operation:a,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l}}}function cK(e){let t=XT(e,"Native delta");if(ZT(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==cA)throw new gt(`Native delta schema must be ${cA}`);let r=aK(t.capability,"Native delta capability");if(!Array.isArray(t.operations))throw new gt("Native delta operations must be an array");let n=t.operations.map(sK),i=new Set;for(let[o,a]of n.entries()){let s=[a.id,...a.to_id===void 0?[]:[a.to_id]];for(let c of s){if(i.has(c))throw new gt(`Native delta operations contain duplicate or overlapping requirement ID ${c} at ${o}`);i.add(c)}}return{schema:cA,capability:r,base_version:Number.isSafeInteger(t.base_version)&&Number(t.base_version)>0?Number(t.base_version):1,operations:n}}function lK(e){let t=(0,uA.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new gt(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Dr(e){return cK(typeof e=="string"?lK(e):e)}function uK(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function dK(e){let t=[],r=null;for(let[n,i]of e.entries()){let o=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(i.trimEnd());if(o){r?o[1][0]===r.marker&&o[1].length>=r.length&&o[2].trim().length===0&&(r=null):r={marker:o[1][0],length:o[1].length};continue}if(r)continue;let a=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(i);if(!a)continue;let s=a[3];if(!YT.test(s))throw new gt(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:n,level:a[2].length,id:s,title:a[4]?.trim()??""})}return t}function tm(e){let t=Bs(e),r=t.split(`
|
|
288
|
+
`),n=dK(r),i=[],o=new Set;for(let l of n){if(o.has(l.id))throw new gt(`Native total Spec contains duplicate requirement ID ${l.id}`);o.add(l.id);let u=r.length;for(let f=l.line+1;f<r.length;f+=1){if(n.some(p=>p.line===f)){u=f;break}let d=uK(r[f]);if(d!==null&&d<=l.level){u=f;break}}i.push({start:l.line,end:u,marker:l})}let a=new Map;for(let l of i){let u=`${r.slice(l.start,l.end).join(`
|
|
289
|
+
`)}${l.end<r.length?`
|
|
290
|
+
`:""}`,f=r.slice(l.start+1,l.end).join(`
|
|
291
|
+
`).replace(/^\n/u,"").replace(/\n+$/u,"");a.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:f,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of i)s.push(r.slice(c,l.start).join(`
|
|
292
|
+
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
293
|
+
`)),{text:t,lines:r,requirements:a,legacyText:s.join(`
|
|
294
|
+
`)}}function rm(e,t,r,n){let i=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,o=Bs(n).replace(/\n+$/u,"");return[i,"",...o.split(`
|
|
295
|
+
`),"",""].join(`
|
|
296
|
+
`)}function lA(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function nm(e,t){if(e.operation==="rename"){if(!t)throw new gt(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function fK(e,t,r){let n=tm(e),i=[...n.lines],o=n.requirements.get(t.id);if(!o)throw new gt(`Requirement target disappeared: ${t.id}`);return i.splice(o.startLine,o.endLine-o.startLine,...r.split(`
|
|
297
|
+
`)),i.join(`
|
|
298
|
+
`)}function pK(e,t){let r=Bs(e),n=r.length===0||r.endsWith(`
|
|
299
|
+
|
|
300
|
+
`)?"":`
|
|
301
|
+
`,i=`${r}${n}`;return`${i.endsWith(`
|
|
302
|
+
`)||i.length===0?i:`${i}
|
|
303
|
+
`}${t}`}function mK(e,t){if(e.operation==="add"||e.operation==="modify"){let o=t.requirements.get(e.id);if(!o)return!1;let a=nm(e,e.operation==="modify"?o:void 0);return o.raw===rm(a.level,a.id,a.title,a.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),n=t.requirements.get(e.id);if(!r||n)return!1;let i=nm(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===rm(i.level,i.id,i.title,i.body)}function tO(e){let t=Bs(e.baselineMarkdown),r=[],n=[];for(let o of e.delta.operations){let a=tm(t),s=a.requirements.get(o.id);if(e.allowAlreadyApplied&&mK(o,a)){n.push({id:o.id,operation:o.operation,status:"already-applied",targetIds:lA(o)});continue}if(o.operation==="add"){if(s)throw new uu([o.id],`Native delta add conflicts with existing requirement ${o.id}`);let c=nm(o,void 0);t=pK(t,rm(c.level,c.id,c.title,c.body))}else{if(!s)throw new uu([o.id],`Native delta ${o.operation} target does not exist: ${o.id}`);let c=nm(o,s);if(o.operation==="rename"&&tm(t).requirements.has(o.to_id))throw new uu([o.id,o.to_id],`Native delta rename destination already exists: ${o.to_id}`);if(o.operation==="remove"){let l=[...tm(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
|
|
304
|
+
`)}else t=fK(t,s,rm(c.level,c.id,c.title,c.body))}r.push(...lA(o)),n.push({id:o.id,operation:o.operation,status:"changed",targetIds:lA(o)})}return{markdown:Bs(t),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:n}}function rO(e){return tO({baselineMarkdown:e.baselineMarkdown,delta:Dr(e.delta),allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}function du(e){return tO({baselineMarkdown:e.currentMarkdown,delta:Dr(e.delta),allowAlreadyApplied:!0,rebased:!1})}var uA,cA,Ws,oK,YT,gt,uu,ka=_(()=>{"use strict";uA=kr(dn(),1),cA="comet.native.delta.v1",Ws="delta.yaml",oK=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YT=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,gt=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},uu=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var ei,Ci,_i,im=_(()=>{"use strict";ei="comet.native.v3",Ci="comet.native.v2",_i="comet.native.v1"});import hK from"node:path";function pu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function aO(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Vs(e){if(!oO.test(e))throw new Error(`Invalid Native change name: ${e}`)}function om(e){if(!oO.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function sO(e,t){if(e.length===0||hK.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function NK(e,t){let r=pu(e,`spec_changes[${t}]`);if(aO(r,wK,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(om(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let n=r.source,i=r.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof n=="string"&&sO(n,`Spec source for ${r.capability}`),r.operation==="create"){if(!n)throw new Error(`Create spec ${r.capability} requires source`);if(i!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!n)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof i!="string"||!fA.test(i))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof i!="string"||!fA.test(i))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof n=="string"?{source:n}:{},base_hash:i}}function RK(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function pA(e,t){if(aO(e,t,ko),typeof e.name!="string")throw new Error("Native change name is required");if(Vs(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!yK.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!kK.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(NK),n=r.map(i=>i.capability).filter((i,o,a)=>a.indexOf(i)!==o);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!AK.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&sO(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!RK(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function am(e){let t=pu(e,ko);if(t.schema!==_i)throw new Error(`Expected ${_i}`);return{schema:_i,...pA(t,gK)}}function fu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function dA(e,t,r){if(e===null)return null;let n=typeof e=="string"?bK.exec(e):null;if(!n||n[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function SK(e){if(e==null)return null;if(typeof e!="string"||!fA.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function EK(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function sm(e){let t=pu(e,ko);if(t.schema!==Ci)throw new Error(`Expected ${Ci}`);if(fu(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ci} minimum_runtime_version must be 2`);return{schema:Ci,minimum_runtime_version:2,revision:fu(t.revision,"Native v2 revision"),...pA(t,iO)}}function cm(e){let t=pu(e,ko);if(t.schema!==ei){if(t.schema===_i||t.schema===Ci){let a=t.schema===_i?am(t):sm(t);throw new Ls(a.name,a.schema)}throw new Ii(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=fu(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ii(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=fu(t.revision,"Native revision"),i=pA(t,vK),o=SK(t.approved_contract_hash);if(i.approval===null&&o!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ei,minimum_runtime_version:3,revision:n,verification_protocol:EK(t.verification_protocol),...i,approved_contract_hash:o,implementation_scope:dA(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:dA(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:dA(t.partial_allowance,"Native partial_allowance","allowances")}}function mA(e){let t=pu(e,ko);if(t.schema===_i){let i=am(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${ei}`}}if(t.schema===Ci){let i=sm(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${ei}`}}if(t.schema!==ei){let i=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:i,state:null,message:new Ii(typeof t.schema=="string"?t.schema:"(missing)",i).message}}let r=fu(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Ii(t.schema,r).message};let n=cm(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}var nO,gK,iO,vK,wK,yK,kK,AK,ko,fA,oO,bK,Ls,Ii,mu=_(()=>{"use strict";im();nO=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],gK=new Set(nO),iO=new Set([...nO,"minimum_runtime_version","revision"]),vK=new Set([...iO,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),wK=new Set(["capability","operation","source","base_hash"]),yK=new Set(["shape","build","verify","archive"]),kK=new Set(["implicit","confirmed"]),AK=new Set(["pending","pass","fail"]),ko="comet-state.yaml",fA=/^[a-f0-9]{64}$/u,oO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bK=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ls=class extends Error{constructor(r,n){super(`Native change ${r} uses ${n}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ii=class extends Error{constructor(r,n){super(r!==ei||n===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import{createHash as CK}from"crypto";function Wn(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function _K(e,t){t.has(e)&&Wn("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||Wn("sparse arrays are not supported");return(r.length!==e.length||r.some((n,i)=>n!==String(i)))&&Wn("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Wn("symbol properties are not supported"),`[${e.map(n=>hA(n,t)).join(",")}]`}finally{t.delete(e)}}function IK(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Wn("only plain objects are supported"),t.has(e)&&Wn("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Wn("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(a=>{let s=n[a];return(!s||!("value"in s))&&Wn("accessor properties are not supported"),`${JSON.stringify(a)}:${hA(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hA(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Wn("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?_K(e,t):IK(e,t);case"bigint":case"function":case"symbol":case"undefined":return Wn(`${typeof e} values are not supported`)}return Wn("unsupported value type")}function xK(e){return hA(e,new Set)}function lm(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return CK("sha256").update(`${e}
|
|
305
|
+
${xK(t)}`).digest("hex")}var gA=_(()=>{"use strict"});function uO(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function cO(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let n=r[1][0];return t===null?{marker:n,length:r[1].length}:n===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function lO(e){return e.includes("-->")||e.includes("--!>")}function*um(e){let t=null,r=!1,n=null,i=new Set(["code","pre","script","style","svg","template"]),o=e.replace(/\r\n?/gu,`
|
|
306
|
+
`),a=0,s=0;for(;a<=o.length;){let c=o.indexOf(`
|
|
307
|
+
`,a),l=c===-1?o.slice(a):o.slice(a,c);if(yield{line:l,body:t===null&&!r&&n===null,index:s},s+=1,t!==null)t=cO(l,t);else if(r)lO(l)&&(r=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=cO(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!lO(d))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&i.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(n=p[1])}}}if(c===-1)break;a=c+1}}function hu(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function wA(e,t,r,n=[],i="content-hash"){let o=hu(r),a=t.replaceAll("\\","/").trim(),s=n.map(hu);if(o.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:i==="content-hash"?`acceptance-${lm(PK,{kind:e,source:a,context:s,text:o})}`:"",kind:e,source:a,context:s,text:o}}function yA(e,t,r="content-hash"){let n=new Set;for(let i of e){let o=r==="content-hash"?i.id:JSON.stringify([i.kind,i.source,i.context,i.text]);if(n.has(o))throw new Error(`${t} contains duplicate acceptance criteria`);n.add(o)}return e}function TK(e){let t=null,r=null,n=0,i=0;for(let{line:o,body:a,index:s}of um(e)){i=s+1;let c=a?uO(o):null;c?.level===1&&(eA(c.text)==="acceptanceExamples"?(n+=1,n===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??i}}function dO(e,t="brief.md",r=vA.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=TK(e);if(i===null)return[];let o=null;for(let{line:l,body:u,index:f}of um(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[1].length;o=o===null?p:Math.min(o,p)}let a=[],s=null,c=()=>{if(s!==null){if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);a.push(s)}};for(let{line:l,body:u,index:f}of um(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===o?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),yA(a.map(l=>wA("brief-example",t,l.join(`
|
|
308
|
+
`),[],n)),"Brief",n)}function fO(e,t="brief.md",r=vA.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=new mr().blockTokens(e.replace(/\r\n?/gu,`
|
|
309
|
+
`)),o=i.flatMap((c,l)=>c.type==="heading"&&eA(c.text)==="acceptanceExamples"?[{index:l,depth:c.depth}]:[]);if(o.length===0)return[];if(o.length!==1)throw new Error("Brief must contain exactly one Acceptance examples section");let a=o[0],s=[];for(let c of i.slice(a.index+1)){if(c.type==="heading"&&c.depth<=a.depth)break;if(c.type==="list")for(let l of c.items){if(s.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let u=l.raw.replace(/^ {0,3}(?:[-*+]|\d{1,9}[.)])[ \t]*/u,"");s.push(wA("brief-example",t,u,[],n))}}return yA(s,"Brief",n)}function pO(e,t="spec.md",r=vA.maxCriteria,n="content-hash",i={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let o=[],a=[],s=null,c=()=>{if(s===null)return;if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(i.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");o.push({...wA("spec-scenario",t,[s.title,...s.body].join(`
|
|
310
|
+
`),s.context,n),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of um(e)){let f=u?uO(l):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(c();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let p=hu(d[1]);if(p.length===0)throw new Error("Scenario title must not be empty");s={level:f.level,title:p,body:[],context:a.map(h=>h.text)}}else if(f){for(s!==null&&f.level<=s.level?c():s!==null&&s.body.push(l);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else s!==null&&u&&s.body.push(l)}return c(),yA(o,"Specification",n)}var PK,bre,vA,mO=_(()=>{"use strict";mk();js();gA();PK="comet.native.acceptance.v1",bre=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),vA=Object.freeze({maxCriteria:1024})});import hO from"node:path";function gO(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||hO.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||hO.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function OK(e,t){return e.localeCompare(t,"en")}function vO(e){let t=gO(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((s,c)=>OK(s.capability,c.capability));if(new Set(r.map(s=>s.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=(e.legacyBriefBoundaries?dO:fO)(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:s,text:c})=>({source:s,text:c})),o=i.length;for(let s of r){let c=gO(s.source,`Native spec source for ${s.capability}`);for(let l of pO(s.markdown,c,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let u=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(u)||u<0||u>=o)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${c}`);continue}i.push({source:c,text:l.text})}}let a=new Set;for(let s of i){s.text=hu(s.text);let c=s.text;if(a.has(c))throw new Error(`Native acceptance contains a duplicate criterion: ${s.text}`);a.add(c)}if(i.length===0)throw new Error(`Native change must define at least one acceptance criterion. In ${t}, write each criterion as a top-level Markdown list item under Acceptance examples, for example: "- Input hello prints Words: 1." Keep requested tables; a table alone does not create formal acceptance items. Alternatively use complete Scenario: blocks in the target Specs. Add the explicit criteria without changing their meaning, then retry the same Shape step; do not recreate the change.`);return i.map((s,c)=>({id:`A${c+1}`,source:s.source,text:s.text}))}var dm=_(()=>{"use strict";mO()});function LK(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function VK(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function yO(e){let t=LK(e,"Native portable migration transaction"),r=Object.keys(t).filter(n=>!$K.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==wO)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!DK.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!jK.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!WK.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!BK.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:wO,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:VK(t.createdAt,"Native portable migration transaction createdAt")}}var wO,$K,jK,DK,BK,WK,kO=_(()=>{"use strict";mu();dm();xe();Ni();$p();im();wO="comet.native.portable-migration.v1",$K=new Set(["schema","id","change","fromSchema","status","createdAt"]),jK=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DK=/^[a-z0-9][a-z0-9-]{7,127}$/u,BK=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),WK=new Set([_i,Ci,ei])});import AA from"node:path";function RO(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function SO(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function kA(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function AO(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function zK(e,t){let r=`Native portable Archive spec_changes[${t}]`,n=RO(e,r);if(SO(n,JK,r),typeof n.capability!="string"||!NO.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation,o=n.delta_source;if(o!==void 0&&(typeof o!="string"||o.length===0||o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||o.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let a=kA(n.base_hash,`${r}.base_hash`),s=AO(n.delta_content,`${r}.delta_content`),c=AO(n.source_content,`${r}.source_content`),l=kA(n.expected_target_hash,`${r}.expected_target_hash`),u=kA(n.result_hash,`${r}.result_hash`),f=o!==void 0;if(f&&(s==null||c===void 0||c===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f&&Dr(s).capability!==n.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(i==="remove"){if(n.source!==null||n.content!==null||o!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null,...a===void 0?{}:{base_hash:a},...l===void 0?{}:{expected_target_hash:l}}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);return{capability:n.capability,operation:i,source:n.source,content:n.content,...o===void 0?{}:{delta_source:o},...a===void 0?{}:{base_hash:a},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function KK(e){let t=RO(e,"Native portable Archive transaction");if(SO(t,UK,"Native portable Archive transaction"),t.schema!==fm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!FK.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!NO.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!HK.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!QK.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(zK);if(new Set(r.map(({capability:i})=>i)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let n=new Date(t.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:fm,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function pm(e){let t=MK.exec(e);if(t)return{kind:"archive",change:t[1]};let r=qK.exec(e);return r?{kind:"migration",change:r[1]}:null}function mm(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,n=pm(r);if(!n||n.kind!==t.kind||n.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return AA.join(e.transactionsDir,r)}async function bA(e,t){let r=pm(t);if(!r)return null;let n=await Ve({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),o=AA.join(e.transactionsDir,t);if(r.kind==="archive"){let s=KK(i);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:o,journal:s}}let a=yO(i);if(a.change!==r.change)throw new Error(`Native portable transaction filename does not match ${a.change}`);return{kind:"migration",change:r.change,file:o,journal:a}}async function xi(e,t){let r=mm(e,t);try{return await bA(e,AA.basename(r))}catch(n){if(n.code==="ENOENT")return null;throw n}}function EO(e){return e.kind==="archive"||e.journal.status!=="committed"}var fm,bO,MK,qK,FK,HK,QK,UK,JK,NO,gu=_(()=>{"use strict";hn();ka();kO();fm="comet.native.archive-transaction.v4",bO="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",MK=new RegExp(`^portable-archive-(${bO})\\.json$`,"u"),qK=new RegExp(`^portable-migration-(${bO})\\.json$`,"u"),FK=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,HK=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QK=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),UK=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),JK=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),NO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as GK}from"node:crypto";import{constants as hm,promises as Dt}from"node:fs";import mt from"node:path";function yn(e,t){let r=mt.relative(e,t);return r===""||!mt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${mt.sep}`)}function YK(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function NA(e,t){return ft({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function XK(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function gm(e,t){return ft({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ms(e,t){let r=await Dt.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Dt.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function RA(e,t,r){let n=mt.resolve(e),i=mt.resolve(t);if(!yn(n,i))throw new Error(`${r} is outside its managed root`);let o=[await Ms(n,r)],a=n;for(let s of mt.relative(n,i).split(mt.sep).filter(Boolean)){await Qr(o,r),a=mt.join(a,s);let c=await Ms(a,r);if(!yn(o[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${a}`);o.push(c)}return await Qr(o,r),o}async function Qr(e,t){for(let r of e){let n=await Dt.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!NA(r,n)||await Dt.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function ZK(e,t,r){let n=[],i=0,o=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let a=t===null?o.length:t+1-i,{bytesRead:s}=await e.read(o,0,Math.min(o.length,a),null);if(s===0)break;if(i+=s,t!==null&&i>t)throw new Error(`${r} exceeds ${t} bytes`);n.push(Buffer.from(o.subarray(0,s)))}return Buffer.concat(n,i)}async function CO(e){let t=e.maxBytes===null?null:YK(e.maxBytes),r=mt.resolve(e.file),n=await RA(e.root,mt.dirname(r),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(u=>Ms(mt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Qr(n,e.label);let o=await Dt.lstat(r);if(!o.isFile()||o.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&o.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let a=XK(o),s=await Dt.realpath(r);if(!yn(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(u=>yn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?hm.O_RDONLY:hm.O_RDONLY|hm.O_NOFOLLOW|hm.O_NONBLOCK,l=await Dt.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([Dt.lstat(r),Dt.realpath(r)]);if(await Qr(n,e.label),await Qr(i,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!gm(a,u)||!gm(a,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await ZK(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([l.stat(),Dt.lstat(r),Dt.realpath(r)]);if(await Qr(n,e.label),await Qr(i,e.label),!m.isFile()||m.isSymbolicLink()||g!==s||!gm(a,h)||!gm(a,m))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:GK("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function _O(e){let t=mt.resolve(e.root),r=mt.resolve(e.directory);if(!yn(t,r))throw new Error(`${e.label} is outside its managed root`);let n=[await Ms(t,e.label)],i=t;for(let o of mt.relative(t,r).split(mt.sep).filter(Boolean)){await Qr(n,e.label),i=mt.join(i,o);try{await Dt.mkdir(i)}catch(s){if(s.code!=="EEXIST")throw s}let a=await Ms(i,e.label);if(!yn(n[0].realPath,a.realPath))throw new Error(`${e.label} resolves outside its managed root: ${i}`);n.push(a)}await Qr(n,e.label)}async function IO(e){let t=mt.resolve(e.root),r=mt.resolve(e.source),n=mt.resolve(e.target);if(r===n||!yn(t,r)||!yn(t,n)||yn(r,n)||yn(n,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await _O({root:t,directory:mt.dirname(n),label:`${e.label} target parent`});let i=await RA(t,mt.dirname(r),e.label),o=await RA(t,mt.dirname(n),e.label),a=await Ms(r,e.label);if(!yn(i[0].realPath,a.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await Dt.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Qr(i,e.label),Qr(o,e.label)]);let s=await Dt.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!NA(a,s)||await Dt.realpath(r)!==a.realPath)throw new Error(`${e.label} source changed before move`);await Dt.rename(r,n),await Promise.all([Qr(i,e.label),Qr(o,e.label)]);let c=await Dt.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!NA(a,c)||!yn(i[0].realPath,await Dt.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await Dt.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}var SA=_(()=>{"use strict";$t();Hl()});import{lstatSync as tG,promises as Gre}from"fs";import kn from"path";import{TextDecoder as rG}from"util";function wm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ym(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function TO(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function EA(e,t){if(typeof e!="string"||e.length===0||kn.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function vm(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function xO(e,t){if(EA(e,t),e.includes("\\")||e!==kn.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function cG(e,t){let r=wm(e,`transaction operations[${t}]`);if(ym(r,iG,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);EA(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&EA(r[n],`transaction operation ${r.id} ${n}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function lG(e){let t=wm(e,"Native Archive transaction journal");if(ym(t,oG,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!PO.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!TO(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(vm(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=wm(s,`Archive transaction operations[${c}]`);if(ym(l,aG,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);xO(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&xO(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&vm(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(vm(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);vm(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${t.id}`,o=r.filter(s=>s.type==="move");if(o.length!==1||o[0].id!=="archive-change"||o[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(o[0].target)||r.at(-1)!==o[0])throw new Error("Native Archive transaction must end with its exact change move");let a=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||a.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(a.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function uG(e){let t=wm(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return lG(t);if(ym(t,nG,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!PO.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!kn.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!kn.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!TO(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(cG),n=r.map(i=>i.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function OO(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);let r=kn.join(e.transactionsDir,t),n=kn.join(e.runtimeDir,"transaction-history",t),i=o=>{try{return tG(o),!0}catch(a){if(a.code==="ENOENT")return!1;throw a}};if(!i(n))return r;if(i(r))throw new Error(`Conflicting active and historical Native transaction: ${t}`);return n}async function $O(e,t){let r=await CA(e,t);if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${t} is unfinished`);let n=OO(e,t),i=kn.join(e.runtimeDir,"transaction-history",t);n!==i&&(await IO({root:e.runtimeDir,source:n,target:i,label:"Native completed transaction"}),await Jl(kn.dirname(i)),await Jl(e.transactionsDir),await Jl(e.runtimeDir))}function dG(e,t){let r=OO(e,t);return{directory:r,journal:kn.join(r,"transaction.json"),events:kn.join(r,"events.jsonl"),staged:kn.join(r,"staged"),backups:kn.join(r,"backups")}}async function fG(e,t){let r=dG(e,t);return await Promise.all(Object.values(r).map(n=>Bn(e.runtimeDir,n))),r}async function CA(e,t,r={}){let n=await fG(e,t),i=await CO({root:e.runtimeDir,file:n.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),o=JSON.parse(sG.decode(i.bytes)),a=uG(o);if(a.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return a}var nG,iG,oG,aG,PO,sG,jO=_(()=>{"use strict";$t();Ye();SA();nG=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),iG=new Set(["id","type","source","target","staged","backup"]),oG=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),aG=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),PO=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),sG=new rG("utf-8",{fatal:!0})});import{promises as pG}from"fs";async function mG(e,t,r){let n;try{n=await pG.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let o=await CA(e,i.name);if(o.id!==t&&o.status!=="committed"&&o.status!=="rolled-back")return!0;(o.status==="committed"||o.status==="rolled-back")&&await $O(e,o.id)}catch{return!0}for(let i of n)if(pm(i.name))try{let o=await bA(e,i.name);if(!o||r?.kind===o.kind&&r.change===o.change)continue;if(EO(o))return!0}catch{return!0}return!1}async function He(e,t,r){if(await Zp(e.projectRoot),await mG(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return t()}var Bt=_(()=>{"use strict";It();gu();jO()});var DO=_(()=>{"use strict"});var km=_(()=>{"use strict"});var Am=_(()=>{"use strict"});var BO=_(()=>{"use strict"});var _A=_(()=>{"use strict";Am()});var WO=_(()=>{"use strict";Am();_A()});var kG,LO=_(()=>{"use strict";kG=kr(dn(),1);Jn();vi();ct()});var Nne,VO=_(()=>{"use strict";Jn();ct();Nne=Number.MAX_SAFE_INTEGER});var MO=_(()=>{"use strict";Am();Jn();BO();WO();vi();LO();ct();Ps();nA();VO();zk();co();tA();_A()});var qO=_(()=>{"use strict";MO();$a()});var wie,FO=_(()=>{"use strict";qO();wie=Number.MAX_SAFE_INTEGER});var HO=_(()=>{"use strict";FO();km()});var Pie,QO=_(()=>{"use strict";km();HO();$t();Hl();Pie={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER}});var UO=_(()=>{"use strict";km();Bt();Ye();QO()});import{createHash as bG}from"node:crypto";import{promises as JO}from"node:fs";import Aa from"node:path";function XO(e,t){let r=Aa.relative(e,t);return Aa.isAbsolute(r)||r===".."||r.startsWith(`..${Aa.sep}`)?null:r.replaceAll("\\","/")||"."}function ZO(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function xA(e,t){if(e.length===0||ZO(e)||e.includes("\\")||Aa.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Aa.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function KO(e,t){return bG("sha256").update(`${e}
|
|
311
|
+
${t}`).digest("hex")}async function GO(e,t,r){let n=await JO.realpath(e),i=await JO.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let o=YO==="win32"?Aa.normalize(n).toLowerCase():n;return{physical:KO(t,`${o}
|
|
312
|
+
${i.dev}
|
|
313
|
+
${i.ino}
|
|
314
|
+
${i.birthtimeMs}`),path:KO(r,o)}}async function RG(e){let t=XO(e.projectRoot,e.nativeRoot);if(!t)throw new Error("Native root is outside the project root");xA(t,"Native workspace root ref");let[r,n]=await Promise.all([GO(e.projectRoot,"comet.native.workspace-project-root.v2","comet.native.workspace-project-root-path.v2"),GO(e.nativeRoot,"comet.native.workspace-native-root.v2","comet.native.workspace-native-root-path.v2")]);return{nativeRootRef:t,projectRootId:r.physical,nativeRootId:n.physical,projectRootPathId:r.path,nativeRootPathId:n.path}}function SG(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function IA(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ZO(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function EG(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(IA(e.changeBranch,"Native workspace change branch"),IA(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function CG(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${n.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!zO.test(t.baseCommit)||typeof t.targetCommit!="string"||!zO.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");IA(t.targetBranch,"Native workspace Git target branch")}function PA(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!vu.test(String(t.projectRootId))||!vu.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");SG(t.capturedAt),xA(t.nativeRootRef,"Native workspace root ref");let i=t.projectRootPathId!==void 0,o=t.nativeRootPathId!==void 0;if(i!==o)throw new Error("Native workspace path identities must be provided together");if(i&&!vu.test(String(t.projectRootPathId))||o&&!vu.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!vu.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&CG(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(EG(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function _G(e,t){return Aa.join(cu(e,t),"workspace.json")}function IG(e,t){let r=_G(e,t),n=Xp(e,r),i=XO(n,r);if(!i||i===".")throw new Error("Native workspace file escaped its root");return{root:n,ref:xA(i,"Native workspace file ref")}}async function xG(e,t){try{let r=IG(e,t),n=await Ve({root:r.root,ref:r.ref,maxBytes:NG});return JSON.parse(n.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function e0(e,t){let r=await xG(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(PA(r),r)}async function t0(e){PA(e.identity);let t=await RG(e.paths),r=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),YO==="win32"&&r.length>0&&r.every(o=>o==="project-root-legacy-identity"||o==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):r.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:r}}async function r0(e){if(PA(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await t0(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ye(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function n0(e,t){let r=await e0(e,t);if(r===null)return null;let n=await r0({paths:e,identity:r});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return r}var vu,zO,NG,YO,i0=_(()=>{"use strict";_t();$t();hn();Bt();Ye();vu=/^[a-f0-9]{64}$/u,zO=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,NG=Number.MAX_SAFE_INTEGER,YO=process.platform});import{promises as TG}from"fs";import qs from"path";function Fs(e,t){Vs(t);let r=qs.join(e.changesDir,t);if(!Gt(e.changesDir,r))throw new Error("Native change path escaped");return r}async function OG(e,t){let r=cu(e,t),n=qs.join(r,"schema-migration.json");await Bn(Gt(e.runtimeDir,n)?e.runtimeDir:e.nativeRoot,n);try{return await TG.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function $G(e,t=qs.dirname(e)){let r=qs.relative(t,e).split(qs.sep).join("/"),n=await Ve({root:t,ref:r,maxBytes:null,includeHash:!1}),i=(0,TA.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${i.errors[0].message}`);return i.toJS()}async function jG(e,t){let r=qs.join(Fs(e,t),ko);await Bn(e.nativeRoot,r);let n=mA(await $G(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await OG(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:n}async function wu(e,t){let r=await jG(e,t);if(r.status==="migration-required")throw new Ls(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Ii(r.schema,r.minimumRuntimeVersion);return await n0(e,t),r.state}var TA,boe,Hs=_(()=>{"use strict";$s();$s();Vk();bn();TA=kr(dn(),1);_t();et();pr();Ll();Is();Hu();hn();$t();js();It();Bt();xe();Ye();SA();DO();UO();i0();im();mu();mu();boe=ou("en")});import{execFileSync as DG}from"node:child_process";function o0(e,t,r=WG){try{return tu(()=>DG("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:BG,killSignal:"SIGKILL",maxBuffer:r,windowsHide:!0}))}catch(n){let i=typeof n.stderr=="string"?n.stderr.trim():Buffer.isBuffer(n.stderr)?n.stderr.toString("utf8").trim():"";throw new OA(e,t,i)}}function ce(e,t){return o0(e,t).trim()}function ba(e){return ce(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function $A(e,t){ce(e,["check-ref-format","--branch",t])}function a0(e){return LG(o0(e,["status","--porcelain=v1","-z","--untracked-files=all"]))}function LG(e){return[...new Set(VG(e).flatMap(t=>t.paths.map(r=>r.replaceAll("\\","/"))))].sort()}function VG(e){if(!e)return[];let t=e.split("\0").filter(Boolean),r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(i.length<4)throw new Error("Git status returned an invalid porcelain record");let o=[i.slice(3)];if(i[0]==="R"||i[0]==="C"||i[1]==="R"||i[1]==="C"){let a=t[n+1];if(!a)throw new Error("Git status returned an incomplete rename record");o.push(a),n+=1}r.push({status:i.slice(0,2),paths:o})}return r}var BG,WG,OA,Ur=_(()=>{"use strict";Jp();Gk();BG=3e4,WG=8*1024*1024,OA=class extends Error{constructor(r,n,i){super(`git ${n.join(" ")} failed${i?`: ${i}`:""}`);this.cwd=r;this.args=n;this.stderr=i;this.name="GitCommandError"}cwd;args;stderr}});var s0=_(()=>{"use strict"});import MG from"node:path";function c0(e,t){let r=t.actions.map(o=>o.stepId==="repair.implementation"&&o.status==="succeeded").lastIndexOf(!0),n=t.actions[r];if(r<0||n?.outcome?.output?.driftKind!=="report-drift"||t.actions.slice(r+1).some(o=>o.stepId==="verify.report"&&o.status==="succeeded"))return null;let i=t.input.artifactRootRef;return typeof i!="string"?null:{ref:MG.posix.join(i.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),instruction:e.language==="zh-CN"?"读取用户修改的原验证报告,核对其补充并作为待验证输入;不得将旧报告当作新候选已通过的证据。":"Read the user-edited verification report and assess its notes as inputs; do not treat the old report as proof that the new candidate passed."}}function yu(e,t){let r=e.builder_handoff?.candidate_id??null,n=new Map;for(let o of t.actions){if(!["verify.checks","verify.requested-checks"].includes(o.stepId)||!o.outcome)continue;let a=o.outcome.output;if(a?.candidateId===r)for(let s of a.checks??[])n.set(s.id,{id:s.id,status:s.status,actionId:o.id,logRef:s.logRef,inputScope:s.inputScope?.kind??"project"})}let i=[...t.actions].reverse().find(o=>o.stepId==="verify.verifier"&&o.status==="succeeded");return{schema:"comet.native.repair-context.v1",previousCandidateId:r,unresolvedAcceptanceIds:e.loop.previous_unresolved_ids,previousVerifierActionId:i?.id??null,previousChecks:[...n.values()],...c0(e,t)?{userEditedReport:c0(e,t)}:{},candidateHandling:"review-existing-work-first",instruction:e.language==="zh-CN"?"先核对并保留用户当前修改。若现有工作已满足已确认需求,原样提交后继候选,无需为推进流程重新写入;确有遗漏时只修复遗漏。旧检查由 Runtime 判断复用,新候选仍需独立验收全部验收项。":"Inspect and preserve the user’s current changes first. If the existing work satisfies the approved requirements, submit it unchanged as the successor candidate; do not rewrite files merely to advance. Repair only actual gaps. Runtime decides check reuse and the successor still requires independent verification of every acceptance criterion."}}var jA=_(()=>{"use strict";s0()});function DA(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function BA(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){DA(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:wr,executionRef:DA(t.executionRef,"Native execution ref"),[l0]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:DA(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[u0]:!0})}})}function WA(e){return typeof e=="object"&&e!==null&&e[u0]===!0}function d0(e){return typeof e=="object"&&e!==null&&e[l0]===!0}var l0,u0,wr,Na=_(()=>{"use strict";l0=Symbol("comet.native.trusted-execution-identity"),u0=Symbol("comet.native.trusted-verifier-envelope"),wr="skill-coordinated"});function bm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function f0(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Nm(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Rm(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,n)=>{let i=bm(r,`Native Verifier acceptance ${n}`);fa(i,["id","result","reason"],`Native Verifier acceptance ${n}`,`${t}/${n}`);let o=Nm(i.id,`Native Verifier acceptance ${n} ID`),a=Ns(i.result,_k,`Native Verifier acceptance ${o} result`);return{id:o,result:a,reason:Nm(i.reason,`Native Verifier acceptance ${o} reason`)}})}function qG(e,t){let r=bm(e,"Native Verifier final result");fa(r,["iteration","attempt","verdict","acceptance","risks","summary",...Object.hasOwn(r,"requestReview")?["requestReview"]:[]],"Native Verifier final result",t);let n=Ns(r.verdict,Ml,"Native Verifier verdict");if(!Array.isArray(r.risks)||!r.risks.every(o=>typeof o=="string"))throw new Error("Native Verifier risks must be text entries");let i;if(r.requestReview!==void 0){let o=bm(r.requestReview,"Native requestReview");fa(o,["result","reason"],"Native requestReview",`${t}/requestReview`),i={result:Ns(o.result,HP,"Native requestReview result"),reason:Nm(o.reason,"Native requestReview reason")}}return{...i?{requestReview:i}:{},iteration:f0(r.iteration,"Native Verifier iteration"),attempt:f0(r.attempt,"Native Verifier attempt"),verdict:n,acceptance:Rm(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Nm(r.summary,"Native Verifier summary")}}function p0(e,t=""){let r=bm(e,"Native Verifier response");if(r.kind==="final-result")return fa(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:qG(r.result,`${t}/result`)};throw new Error(`Native Verifier response kind must be one of: ${UP.join(", ")}`)}function m0(e){if(!WA(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(r.requireIndependentSession!==!1&&t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let n=p0(t.payload),i=n.result.iteration,o=n.result.attempt;if(i!==r.iteration||o!==r.attempt)throw new Error(`Native Verifier result is stale for the current iteration or attempt: expected iteration=${r.iteration}, attempt=${r.attempt}; received iteration=${i}, attempt=${o}. Inspect the current action and use its outputTemplate before submitting a new outcomeId`);let a=Sm(n.result,r);return{...n,result:{...n.result,acceptance:a}}}function Sm(e,t){Rm(e.acceptance);let r=[...t.acceptanceIds],n=new Set(t.knownAcceptanceIds??r),i=new Set(t.previouslyPassedAcceptanceIds??[]),o=r.filter(m=>!n.has(m)),a=[...i].filter(m=>!n.has(m));if(o.length>0||a.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:m})=>m),l=c.filter((m,g)=>c.indexOf(m)!==g),u=c.filter(m=>!n.has(m)),f=r.filter(m=>!c.includes(m)),d=e.acceptance.filter(({id:m,result:g})=>s.has(m)||!n.has(m)?!1:!i.has(m)||g!=="passed").map(({id:m,result:g})=>`${m}=${g}`);if(l.length>0||u.length>0||f.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${f.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let p=e.acceptance.filter(({id:m})=>s.has(m));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let h=p.map(({result:m})=>m);if(e.verdict==="pass"&&h.some(m=>m!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!h.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!h.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return p}var ku=_(()=>{"use strict";ql();bp();Na()});function Au(e,t){if(!FG.test(e))throw new Error(`${t} must be a Git commit`)}function Ao(e,t){let r=e.children.find(n=>n.name===t);return r.covers.length>0?r.covers.map(n=>({id:n,source:e.acceptance_index?.[n]?.source??"brief.md",text:e.acceptance_index?.[n]?.text??n})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}var FG,Em,Pi=_(()=>{"use strict";ql();jA();ku();FG=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Em="comet.native.supervisor.v2"});import{promises as HG}from"node:fs";import bu from"node:path";function h0(e,t){return bu.join(Yp(e,t),"supervisor")}function g0(e,t){return bu.join(h0(e,t),"state.json")}function QG(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Em)throw new Error(`Native Supervisor state schema must be ${Em}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[i,o]of Object.entries(t.integration))if(i!=="checkExecution"&&(typeof o!="string"||o.length===0))throw new Error(`Native Supervisor integration field ${i} is invalid`);if(Au(t.integration.targetCommit,"Native Supervisor target commit"),Au(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let i=t.finalVerification.layers;if(!["complete","incomplete"].includes(i.childVerification)||!["complete","incomplete"].includes(i.parentIntegration)||!Array.isArray(i.parentChecks)||!i.parentChecks.every(o=>typeof o=="string")||!Array.isArray(i.notRerun)||!i.notRerun.every(o=>typeof o=="string")||!Array.isArray(i.incomplete)||!i.incomplete.every(o=>typeof o=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let i of t.history)if(!i||typeof i!="object"||typeof i.kind!="string"||typeof i.summary!="string"||typeof i.at!="string"||i.child!==null&&typeof i.child!="string"||i.runId!==null&&typeof i.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,n=new Set;for(let i of t.children){if(!i||typeof i!="object"||typeof i.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(i.name))throw new Error(`Native Supervisor child ${i.name} is duplicated`);if(r.add(i.name),!Array.isArray(i.dependsOn)||!i.dependsOn.every(o=>typeof o=="string"))throw new Error(`Native Supervisor child ${i.name} dependencies are invalid`);if(typeof i.summary!="string"&&i.summary!==null)throw new Error(`Native Supervisor child ${i.name} summary is invalid`);if(i.builderFailureCount!==void 0&&(!Number.isSafeInteger(i.builderFailureCount)||i.builderFailureCount<0))throw new Error(`Native Supervisor child ${i.name} Builder failure count is invalid`);if(i.projectRoot!==void 0&&i.projectRoot!==null&&(typeof i.projectRoot!="string"||i.projectRoot.length===0))throw new Error(`Native Supervisor child ${i.name} projectRoot is invalid`);for(let[o,a]of[["base",i.baseCommit],["candidate",i.candidateCommit],["verified",i.verifiedCommit],["integration",i.integrationCommit]])a!==null&&Au(a,`Native Supervisor child ${i.name} ${o} commit`);if(!Array.isArray(i.checks)||!Array.isArray(i.verification?.checks??[]))throw new Error(`Native Supervisor child ${i.name} evidence is invalid`);if(i.task!==null){if(!i.task||typeof i.task!="object")throw new Error(`Native Supervisor child ${i.name} task is invalid`);if(!["builder","verifier"].includes(i.task.role)||i.task.child!==i.name||typeof i.task.projectRoot!="string"||i.task.projectRoot.length===0||typeof i.task.runId!="string"||i.task.runId.length===0)throw new Error(`Native Supervisor child ${i.name} task identity is invalid`);if(Au(i.task.baseCommit,`Native Supervisor child ${i.name} task base commit`),n.has(i.task.runId))throw new Error(`Native Supervisor task runId ${i.task.runId} is duplicated`);if(n.add(i.task.runId),i.task.role==="verifier"&&i.task.baseCommit!==i.candidateCommit)throw new Error(`Native Supervisor child ${i.name} verifier base commit is invalid`);if(i.task.projectRoot!==i.projectRoot)throw new Error(`Native Supervisor child ${i.name} task projectRoot is invalid`);if(i.task.role==="builder"&&i.status!=="active"||i.task.role==="verifier"&&!["active","needs-reverify"].includes(i.status))throw new Error(`Native Supervisor child ${i.name} task status is invalid`)}}}async function bo(e,t,r={}){try{let n=await HG.readFile(g0(e,t),"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&Array.isArray(i.children))for(let a of i.children)a.contractRef===void 0&&typeof a.contractHash=="string"&&(a.contractRef=a.contractHash),a.task&&a.task.contractRef===void 0&&typeof a.task.contractHash=="string"&&(a.task.contractRef=a.task.contractHash);if(i&&typeof i=="object"){let a=i;if(a.integration&&delete a.integration.checkExecution,Array.isArray(a.children))for(let s of a.children)s.task&&(delete s.task.checkExecution,delete s.task.checksReason)}if(QG(i),i.children.some(a=>!a.acceptanceScope||a.task&&!a.task.acceptance))try{let a=e;if(!a.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(xe(),Bk)),c=await s(bu.join(a.changesDir,t,"comet-state.yaml")),l=await Si({changeDir:bu.join(a.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Ri(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of i.children)l.contract.children.some(({name:f})=>f===u.name)&&(u.acceptanceScope=Ao(l.contract,u.name),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractRef=u.contractRef,u.task.verificationBoundary="child-scope-parent-reverifies-all"))}catch(a){if(!r.diagnostics)throw a}let o=e;if(o.changesDir)try{let{readNativePortableState:a}=await Promise.resolve().then(()=>(xe(),Bk)),s=await a(bu.join(o.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(i.integration.targetBranch=s.workspace.change_branch)}catch(a){if(a.code!=="ENOENT")throw a}return i}catch(n){if(n.code==="ENOENT")return null;throw n}}var No=_(()=>{"use strict";$t();Tr();Ye();Pi()});import Cm from"node:path";function LA(...e){if(e.length===0)return Cm.resolve();if(Cm.win32.isAbsolute(e[0])){let t=Cm.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Cm.resolve(...e)}var v0=_(()=>{"use strict"});import{randomUUID as UG}from"node:crypto";import{promises as Nu,lstatSync as VA,readFileSync as JG,realpathSync as zG}from"node:fs";import ti from"node:path";function w0(e){try{if(ce(e,["ls-files","--",Qs]))return!1;let t=ti.join(e,Qs),r=VA(t);if(!r.isFile()||r.isSymbolicLink())return!1;let n=Ze(e),i=MA(e);for(let s of[n,ti.dirname(i)]){let c=VA(s);if(c.isSymbolicLink()||!c.isDirectory())return!1}let o=VA(i);if(!o.isFile()||o.isSymbolicLink()||zG(i)!==ti.resolve(i))return!1;let a=JSON.parse(JG(i,"utf8"));return a.created===!0||typeof a.hash=="string"}catch{return!1}}async function y0(e){let t=ti.join(e,Qs);try{await Nu.access(t)}catch(i){if(i.code==="ENOENT")return;throw i}let r=await si(e),n=MA(e);await Nu.mkdir(ti.dirname(n),{recursive:!0}),await Ei(n,{created:!0},{containedRoot:r})}function Ro(e,t=[]){return a0(e).every(r=>t.some(n=>r===n||r.startsWith(`${n}/`))||r===Qs&&w0(e))}async function k0(e){if(!w0(e))return;let t=await si(e),r="native/preserved-configs/"+UG()+".yaml",n=ti.join(t,r);await Nu.mkdir(ti.dirname(n),{recursive:!0}),await Nu.copyFile(ti.join(e,Qs),n),await Ei(MA(e),{created:!0,preservedRef:r},{containedRoot:t}),await Nu.unlink(ti.join(e,Qs))}var Qs,MA,Ru=_(()=>{"use strict";Xr();Ur();$t();Qs=".comet/config.yaml",MA=e=>ti.join(Ze(e),"native","workspace-config.json")});import{promises as Su}from"node:fs";import Br from"node:path";function R0(e,t){let r=Br.relative(e,t);return r===""||!Br.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Br.sep}`)}function A0(e){let t={...e.native};return delete t.max_parallel_children,JSON.stringify(t)}async function _m(e,t){let r=await Be(e);if(r&&t){if(A0(r)!==A0(t))throw new Error(`Native worktree configuration differs from the source project: ${Br.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await em(e,t),await y0(e),!0):!1}async function b0(e,t){let r=["/.comet/runtime"];if(t&&R0(e,t)){let l=Br.relative(e,t).replaceAll("\\","/");r.push(`/${l.replace(/\/+$/u,"")}/`)}let n=ce(e,["rev-parse","--git-common-dir"]),i=Br.resolve(e,n),o=Br.join(i,"info","exclude"),a="";try{a=await Su.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}let s=r.filter(l=>!a.split(/\r?\n/u).includes(l));if(s.length===0)return!1;await Su.mkdir(Br.dirname(o),{recursive:!0});let c=a.length===0||a.endsWith(`
|
|
315
|
+
`)?"":`
|
|
316
|
+
`;return await Su.appendFile(o,`${c}${s.join(`
|
|
317
|
+
`)}
|
|
318
|
+
`,"utf8"),!0}function KG(e,t,r){let n=Br.resolve(e,r??Br.join(".worktrees",t)),i=Br.resolve(e,ce(e,["rev-parse","--git-common-dir"]));if(R0(i,n))throw new Error("Native worktree path cannot be inside the Git common directory");if($r(e).some(o=>he(o,n)))throw new Error(`Native worktree path is already registered: ${n}`);return n}async function GG(e){try{throw await Su.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function N0(e){try{return await Su.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qA(e){let t=Br.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let h=ye(t);if(h.isGitWorktree&&h.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:h.currentBranch,targetBranch:h.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:h.currentBranch,targetBranch:h.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=ye(t);if(!r.isGitWorktree||r.currentBranch===null||r.primaryWorktreeRoot===null||r.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;$A(t,n);let i=r.currentBranch===n,o=e.targetBranch??(i?void 0:r.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if($A(t,o),!iu(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);let a=await b0(r.primaryWorktreeRoot);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!i){if(!ba(t))throw new Error("Native branch isolation requires a clean current working directory");if(iu(t,n))throw new Error(`Native change branch already exists: ${n}`);ce(t,["switch","-c",n,o]),h=!0}let m;try{m=await _m(t,e.sourceConfig)}catch(g){throw new Zn(`Native branch preparation is incomplete: ${g.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:m}}}if(i){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?Br.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!he(h,r.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${r.currentWorktreeRoot}`);let m;try{m=await _m(t,e.sourceConfig)}catch(g){throw new Zn(`Native worktree preparation is incomplete: ${g.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:m}}}let s=zp(r.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await N0(c.root)){let h=e.worktreePath?Br.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!he(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await _m(c.root,e.sourceConfig)}catch(g){throw new Zn(`Native worktree preparation is incomplete: ${g.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:m}}}c&&!await N0(c.root)&&(ce(r.primaryWorktreeRoot,["worktree","prune"]),s=zp(r.primaryWorktreeRoot));let l=iu(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=KG(r.primaryWorktreeRoot,e.name,e.worktreePath);await GG(u);let f=await b0(r.primaryWorktreeRoot,u),p={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a||f,configInitialized:!1};try{ce(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),p.createdBranch=!l,p.createdWorktree=!0,p.configInitialized=await _m(u,e.sourceConfig)}catch(h){throw new Zn(`Native worktree preparation is incomplete: ${h.message}`,p,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:p}}var S0=_(()=>{"use strict";$s();$s();Ur();_t();It();Ru()});import Ra from"node:path";function vt(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function wt(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native Supervisor parent name: ${t}`);return LA(e,".worktrees",`${t}-integration`)}function Wt(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return LA(e,".worktrees",`${t}-${r}`)}async function Im(e){let t=Ra.join(".worktrees",`${e.parent}-integration`);return qA({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:vt(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function xm(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return qA({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Ra.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function HA(e,t){try{return ce(e,["show-ref","--verify","--quiet",`refs/heads/${t}`]),!0}catch{return!1}}function ZG(e,t){let r=Ra.relative(Ra.resolve(e),Ra.resolve(t));return r===""||!Ra.isAbsolute(r)&&!r.startsWith(`..${Ra.sep}`)}function FA(e){if(ye(e.targetRoot).currentBranch!==e.targetBranch||ge(e.targetRoot,e.targetBranch)!==e.targetCommit)throw new Error("Native Supervisor target branch changed during cleanup")}function Cu(e){FA(e);let t=$r(e.projectRoot);for(let r of e.candidates){if(t.some(n=>he(n,r.root))){if(ZG(r.root,process.cwd()))throw new Error(`Native Supervisor cannot clean the current worktree: ${r.root}`);if(ye(r.root).currentBranch!==r.branch||!Ro(r.root))throw new Error(`Native Supervisor cleanup found a changed worktree: ${r.root}`)}if(HA(e.projectRoot,r.branch))try{ce(e.projectRoot,["merge-base","--is-ancestor",r.branch,e.targetCommit])}catch{throw new Error(`Native Supervisor cleanup found an unintegrated branch: ${r.branch}`)}}}function Us(e){let t=$r(e.projectRoot);return e.candidates.every(r=>!t.some(n=>he(n,r.root))&&!HA(e.projectRoot,r.branch))}async function QA(e){if(!Us(e)){Cu(e);for(let t of e.candidates)FA(e),$r(e.projectRoot).some(r=>he(r,t.root))&&(await k0(t.root),ce(e.projectRoot,["worktree","remove",t.root]));for(let t of e.candidates)FA(e),HA(e.projectRoot,t.branch)&&ce(e.targetRoot,["branch","-d",t.branch]);if(!Us(e))throw new Error("Native Supervisor cleanup did not remove every temporary worktree")}}async function E0(e,t){let r=await bo(e,t.name,{diagnostics:!0});if(!r)return null;let n=ye(e.projectRoot).primaryWorktreeRoot??e.projectRoot,i=wt(n,t.name),o=vt(t.name);if(r.parent!==t.name||!he(r.integration.worktree,i)||r.integration.branch!==o||!t.workspace.change_branch)throw new Error("Native Supervisor cleanup lacks its original parent workspace");let a=r.children.map(s=>{let c=s.projectRoot??s.task?.projectRoot??s.verification?.execution?.projectRoot,l=Wt(n,t.name,s.name);if(!c||!he(c,l)||!["integrated","archived"].includes(s.status))throw new Error("Native Supervisor cleanup requires its original integrated Child workspace: "+s.name);return{root:c,branch:"comet/supervisor/"+t.name+"/"+s.name}});return a.push({root:i,branch:o}),{projectRoot:e.projectRoot,targetRoot:e.projectRoot,targetBranch:t.workspace.change_branch,targetCommit:r.integration.headCommit,candidates:a}}var Wr=_(()=>{"use strict";_t();v0();Ur();Pi();No();Ru();S0()});var _u=_(()=>{"use strict";_t();Ur();It();Bt();Pi();No();Wr()});var x0=_(()=>{"use strict";Pi();No();Wr();_u()});var nY,Js=_(()=>{"use strict";nY=kr(dn(),1);_t();Ur();Tr();It();Ye();xe();x0();Tr()});import{promises as oY}from"node:fs";import P0 from"node:path";function dt(e,t){if(!So.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=P0.join(e.changesDir,t);if(!Gt(e.changesDir,r))throw new Error("Native change path escaped");return r}function Jr(e,t){return P0.join(dt(e,t),T0)}async function zs(e,t){try{let r=await oY.readFile(Jr(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Iu(e,t){if(!t)return;let r=ye(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Lr(e,t){return wn(Jr(e,t))}var So,T0,Yt=_(()=>{"use strict";To();Pp();_t();Ur();xe();Ye();So=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,T0="comet-state.yaml"});var O0=_(()=>{"use strict";Js();Yt()});var $0=_(()=>{"use strict"});function UA(e){return{valid:e.length===0,findings:e}}function j0(e,t){return UA(e.trim()?[]:[{code:"spec-document-empty",message:"Native target Spec is empty: "+t,path:t}])}function aY(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let n of e.split(/\r?\n/u)){if(sY(n,r)!==null||r.marker!==null)continue;let i=n.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(i)||i.includes("|")&&i.split("|").some(a=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(a)))return!0;let o=i.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let a=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(a)||/[./_-]/u.test(a))return!0}}return!1}function sY(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let n=r[1]??"",i=n[0];return t.marker===null?(t.marker=i,t.length=n.length,"opened"):i===t.marker&&n.length>=t.length&&e.trim()===n?(t.marker=null,t.length=0,"closed"):null}async function D0(e,t,r={}){let n;try{n=(await Ve({root:e,ref:t,maxBytes:r.maxBytes??null,includeHash:!1})).text}catch(o){return UA([{code:"brief-missing",message:o.message,path:t}])}let i=[];return n.trim()||i.push({code:"brief-empty",message:"Native brief is empty: "+t,path:t}),aY(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),UA(i)}var Ks,JA=_(()=>{"use strict";hn();Hs();$0();Ye();Ks=class extends Error{constructor(r,n,i){super(r);this.findings=n;this.change=i;this.name="NativeDocumentConstraintError"}findings;change}});function B0(e){return e.replace(cY,"$1 [REDACTED]").replace(lY,"[REDACTED PRIVATE KEY]").replace(uY,"$1[REDACTED]@").replace(dY,"[REDACTED TOKEN]").replace(fY,'$1"[REDACTED]"').replace(pY,"$1$2$1$3$4[REDACTED]$4").replace(mY,"$1$2[REDACTED]")}var cY,lY,uY,dY,fY,pY,mY,W0=_(()=>{"use strict";cY=/\b(Bearer|Basic)\s+[^\s"']+/giu,lY=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,uY=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,dY=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,fY=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,pY=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,mY=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{randomUUID as hY}from"node:crypto";function Vr(e){return Et(B0(e))}function zr(e){return e.state_version+1}function vY(e,t,r){let n=[...e];if(new Set(n).size!==n.length)throw new Error(`${r} contains duplicate IDs`);let i=new Set(t.map(({id:a})=>a)),o=n.filter(a=>!i.has(a));if(o.length>0)throw new Error(`${r} contains unknown IDs: ${o.join(", ")}`);return n}function L0(e){return e.map(t=>({...t,result:"pending",reason:null}))}function V0(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function wY(e){return(e??[]).map(t=>({name:Vr(t.name),result:t.result,note:t.note?Vr(t.note):null}))}function Gs(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:Vr(e.summary),completed_at:e.completedAt}}function zA(e){let t=M(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:n})=>n);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return M({...t,phase:"build",status:"active",state_version:zr(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function KA(e){let t=M(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:n})=>n);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return M({...t,status:"await-user",state_version:zr(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function GA(e){let t=M(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!d0(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let n=vY(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),i=[],o,a;if(r.acceptanceReview!==void 0)try{a=Np(r.acceptanceReview,t.acceptance,"acceptanceReview")}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}else if(e.requireAcceptanceReview!==!1)try{Fl(t.acceptance,void 0)}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}for(let[l,u]of(r.checks??[]).entries())(!u||typeof u.name!="string")&&i.push("Native Builder checks["+l+"].name must be a string"),(!u||!["passed","failed","not-run"].includes(String(u.result)))&&i.push("Native Builder checks["+l+"].result must be passed, failed, or not-run; received "+JSON.stringify(u?.result)),u?.note!=null&&typeof u.note!="string"&&i.push("Native Builder checks["+l+"].note must be a string or null");if(i.length===1&&o instanceof mo)throw o;if(i.length)throw new Error(i.join(`
|
|
319
|
+
`)+`
|
|
320
|
+
Correct the reported business fields and submit a new outcomeId using the original claim.`);let s=L0(t.acceptance),c=(r.now??new Date).toISOString();return M({...t,phase:"verify",state_version:zr(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:s,builder_handoff:{candidate_id:r.candidateId??hY(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:Vr(r.summary),addressed_acceptance_ids:n,acceptance_review:a,checks:wY(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(l=>Vr(l)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:Vr(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:c},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function ri(e){let t=M(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return M({...t,state_version:zr(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function yY(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.verifierExecutionRef===e.state.builder_handoff?.builder_execution_ref?"self-reviewed":e.envelope.identityProvider===wr?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:[],summary:Vr(e.response.result.summary),risks:e.response.result.risks.map(t=>Vr(t)),risks_truncated:!1,completed_at:e.completedAt}}function YA(e){let t=M(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=V0(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let n=m0({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,requireIndependentSession:e.requireIndependentSession,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:d})=>d),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:d})=>d==="passed").map(({id:d})=>d),requiredChecksPassed:(e.reportedChecks??[]).every(({result:d})=>d==="passed")}});if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let i=(e.now??new Date).toISOString(),o=new Map(n.result.acceptance.map(d=>[d.id,d])),a=t.acceptance.map(d=>{let p=o.get(d.id);return p?{...d,result:p.result,reason:Vr(p.reason)}:d}),s=a.filter(({result:d})=>d==="failed"||d==="blocked").map(({id:d})=>d),c=yY({state:t,envelope:e.envelope,response:n,completedAt:i});if(e.reportedChecks&&(c.reported_checks=e.reportedChecks),n.result.verdict==="pass"){let d=Hr({...t,acceptance:a,verification:c},Gs({state:t,outcome:"pass",summary:n.result.summary,completedAt:i})),p=t.builder_handoff.identity_provider===wr;return{response:n,state:M({...d,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:zr(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:Vr(e.requireIndependentSession===!1?"Verification passed; user acceptance is required before Archive.":"The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(n.result.verdict==="blocked"){let d=Hr({...t,acceptance:a,verification:c},Gs({state:t,outcome:"blocked",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:M({...d,status:"await-user",state_version:zr(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:Vr(n.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=l>=e.maxVerifyFailures,f=Hr({...t,acceptance:a,verification:c},Gs({state:t,outcome:"fail",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:M({...f,phase:u?"verify":"build",status:u?"await-user":"active",state_version:zr(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:Vr("Native verification reached the configured failed iteration limit."),acceptance_ids:s,resolution_action:"await-user"}]:[],loop:{...t.loop,stage:u?"await-user":"repairing",iteration:u?t.loop.iteration:t.loop.iteration+1,attempt:u?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:0,stop_reason:u?"budget":void 0,execution_failure_count:0,previous_unresolved_ids:s,next_action:u?"await-user":"repair-failed-acceptance"}})}}function XA(e){let t=M(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==wr||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return M({...t,phase:"archive",status:"active",state_version:zr(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function ZA(e,t){let r=M(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let n=Hr(r,Gs({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return M({...n,status:"active",state_version:zr(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(i=>i.result==="failed"||i.result==="blocked"?{...i,result:"pending",reason:null}:i),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function eb(e){let t=M(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),n=t.loop.execution_failure_count+1,i=n>=gY,o=Hr(t,Gs({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return M({...o,status:i?"blocked":"active",state_version:zr(t),blockers:i?[{owner:"runtime",reason:Vr(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:i?"blocked":"verify-ready",execution_failure_count:n,next_action:i?"retry-verifier":"dispatch-new-verifier"}})}function tb(e){let t=M(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:s})=>s==="retry-verifier"),n=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:s})=>s==="confirm-verifier-unavailable"),i=t.status==="await-user"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass";if(t.phase!=="verify"||!r&&!n&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let o=V0(t),a=t.acceptance.some(({result:s})=>s==="passed");return M({...t,status:"active",state_version:zr(t),...n||i?{verification_result:"pending",verification_report:null,verification:null,...i?{acceptance:t.acceptance.map(s=>({...s,result:"pending",reason:null}))}:{}}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...n?{previous_unresolved_ids:a?o:[]}:{},next_action:"dispatch-new-verifier"}})}function Ys(e){let t=M(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,n=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,i=r!==void 0&&n>=r.maxVerifyFailures,o=(e.now??new Date).toISOString(),a=Hr(t,Gs({state:t,outcome:"recovery",summary:e.reason,completedAt:o})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?L0(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return i?M({...a,phase:"verify",status:"await-user",state_version:zr(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:Vr(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:n,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):M({...a,phase:"build",status:"active",state_version:zr(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:n,stop_reason:void 0,next_action:"submit-builder-candidate"}})}var gY,Sa=_(()=>{"use strict";Rp();xe();Ni();Na();ku();W0();gY=3});import M0 from"node:path";async function rb(e){let{paths:t,state:r}=e;if(r.phase!=="shape"||r.status!=="active")return;let n=M0.join(t.changesDir,r.name);for(let i of e.specChanges){if(i.operation!=="modify"||!i.delta_source||!i.source)continue;let o=await Ve({root:t.specsDir,ref:i.capability+"/spec.md",maxBytes:null,includeHash:!1}),a=await Ve({root:n,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=Dr(a.text);if(s.capability!==i.capability)throw new Error("Native Delta capability does not match its target");let c=rO({baselineMarkdown:o.text,delta:s,allowAlreadyApplied:!0}),l=await Ve({root:n,ref:i.source,maxBytes:null,includeHash:!1});if(l.text!==c.markdown){if(l.text!==o.text)throw new Error("Native target has independent edits: "+i.source+". Reconcile the target and Delta before preparing Shape.");await Ge(M0.join(n,...i.source.split("/")),c.markdown,{containedRoot:t.nativeRoot})}}}var nb=_(()=>{"use strict";$t();hn();ka()});import{promises as kY}from"node:fs";function q0(e){if(!e.builder_handoff||!e.verification)throw new Error("Native verification result requires a candidate and accepted evidence");return lm("comet.native.verification-result.v1",{candidateId:e.builder_handoff.candidate_id,acceptance:e.acceptance,verification:e.verification})}function Kr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
321
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ln(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function AY(e){return e.archived?jr(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?jr(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?jr(e.language,"Verification passed; ready to archive","验收通过,可归档"):jr(e.language,"Verification passed","验收通过")}function bY(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?jr(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?AY(e):e.verification_result==="blocked"?jr(t,"Blocked","已阻塞"):e.verification_result==="fail"?jr(t,"Failed","未通过"):jr(t,"Pending","待处理")}function NY(e){if(e.verification?.assurance==="semantic-verification-unavailable")return jr(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return jr(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return jr(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===wr?wr:"host-attested"),r=t===wr&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","self-reviewed":"Acceptance reviewed in the implementation session","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","self-reviewed":"已在实现会话中完成验收","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function xu(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,n=d=>JT(r,d),i=(d,p)=>jr(r,d,p),o=e.acceptance.map(d=>`| ${Ln(d.id)} | ${Ln(d.result)} | ${Ln(d.source)} | ${Ln(d.text)} | ${Ln(Kr(d.reason))} |`).join(`
|
|
322
|
+
`),a=e.verification.reported_checks?[`| ${i("Agent-reported check","Agent 报告的检查")} | ${i("Result","结果")} | ${i("Execution and evidence","执行与证据")} |`,"| --- | --- | --- |",...e.verification.reported_checks.map(d=>`| ${Ln(Kr(d.name))} | ${d.result} | ${Ln(Kr(d.note))} |`)].join(`
|
|
323
|
+
`):e.verification.checks.length===0?`_${i("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${i("Check","检查")} | ${i("Command","命令")} | ${i("Working directory","工作目录")} | ${i("Status","状态")} | ${i("Exit","退出码")} | ${i("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let p=d.argv_display.map(Kr).join(" ");return`| ${Ln(Kr(d.name))} | ${Ln(p||"—")} | ${Ln(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
324
|
+
`),s=e.builder_handoff?[`### ${i("Builder-reported evidence","Builder 报告的证据")}`,"",i("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(d=>`- ${Kr(d.name)}: ${d.result} — ${Kr(d.note)}`),...e.builder_handoff.checks_truncated?[i("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${i("Known limitation","已知限制")}: ${Kr(d)}`),...e.builder_handoff.known_limits_truncated?[i("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
|
|
325
|
+
`):"",c=e.blockers.length===0?`_${i("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Kr(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
326
|
+
`),l=e.verification.risks.length===0?`_${i("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Kr(d)}`).join(`
|
|
327
|
+
`),u=e.history.length===0?`_${i("No previous iterations.","没有之前的迭代。")}_`:[`| ${i("Goal cycle","目标周期")} | ${i("Iteration","迭代")} | ${i("Attempt","尝试")} | ${i("Outcome","结果")} | ${i("Unresolved","未解决项")} | ${i("Summary","摘要")} | ${i("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Ln(Kr(d.summary))} | ${d.completed_at} |`)].join(`
|
|
328
|
+
`),f=t?.finalVerification.layers?`
|
|
329
|
+
## ${i("Supervisor evidence layers","Supervisor 分层证据")}
|
|
330
|
+
|
|
331
|
+
- ${i("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
|
|
332
|
+
- ${i("Parent integration","父级集成")}: ${t.finalVerification.layers.parentIntegration}
|
|
333
|
+
- ${i("Parent checks","父级检查")}: ${t.finalVerification.layers.parentChecks.join(", ")||"—"}
|
|
334
|
+
- ${i("Not rerun","未重跑")}: ${t.finalVerification.layers.notRerun.join(", ")||"—"}
|
|
335
|
+
- ${i("Incomplete","未完成")}: ${t.finalVerification.layers.incomplete.join(", ")||"—"}
|
|
336
|
+
`:"";return`---
|
|
337
|
+
generated_from_state_version: ${e.state_version}
|
|
338
|
+
---
|
|
339
|
+
|
|
340
|
+
# ${n("verification")}
|
|
341
|
+
|
|
342
|
+
## ${n("currentResult")}
|
|
343
|
+
|
|
344
|
+
- ${i("Result","结果")}: **${bY(e)}**
|
|
345
|
+
- ${i("Verification status","验证情况")}: **${NY(e)}**
|
|
346
|
+
- ${i("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
347
|
+
- ${i("Iteration","迭代")}: ${e.verification.iteration}
|
|
348
|
+
- ${i("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
349
|
+
- ${i("Completed","完成时间")}: ${e.verification.completed_at}
|
|
350
|
+
- ${i("Summary","摘要")}: ${Kr(e.verification.summary)}
|
|
351
|
+
|
|
352
|
+
## ${n("acceptance")}
|
|
353
|
+
|
|
354
|
+
| ${i("ID","编号")} | ${i("Result","结果")} | ${i("Source","来源")} | ${i("Criterion","验收项")} | ${i("Reason","原因")} |
|
|
355
|
+
| --- | --- | --- | --- | --- |
|
|
356
|
+
${o}
|
|
357
|
+
|
|
358
|
+
## ${n("checks")}
|
|
359
|
+
|
|
360
|
+
${a}
|
|
361
|
+
|
|
362
|
+
${s}
|
|
363
|
+
|
|
364
|
+
## ${n("blockers")}
|
|
365
|
+
|
|
366
|
+
${c}
|
|
367
|
+
|
|
368
|
+
## ${n("risks")}
|
|
369
|
+
|
|
370
|
+
${l}
|
|
371
|
+
|
|
372
|
+
## ${n("previousIterations")}
|
|
373
|
+
|
|
374
|
+
${u}
|
|
375
|
+
|
|
376
|
+
${f}
|
|
377
|
+
|
|
378
|
+
${e.history_overflow.dropped_entries>0?`${i("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
|
|
379
|
+
|
|
380
|
+
`:""}## ${n("conclusion")}
|
|
381
|
+
|
|
382
|
+
${Kr(e.verification.summary)}
|
|
383
|
+
`}function RY(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Pu(e){let t;try{t=await kY.readFile(e.file,"utf8")}catch(n){if(n.code==="ENOENT")return"missing";throw n}let r=RY(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Pm(e){await Ge(e.file,xu(e.state,e.supervisor),{beforeCommit:e.beforeCommit})}var Xs=_(()=>{"use strict";xe();js();$t();gA();Na()});import{randomUUID as SY}from"node:crypto";import{promises as EY}from"node:fs";import ib from"node:path";function ob(e){return"native/preserved-verification/"+encodeURIComponent(e)}function Tm(e,t){if(!e.builder_handoff||!e.verification)throw new Error("Native report requires its accepted Verifier result");return{candidateId:e.builder_handoff.candidate_id,reportRef:ib.posix.join(t.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt}}async function Tu(e){let{state:t,paths:r,file:n}=e,i=ib.relative(r.projectRoot,n).replaceAll("\\","/"),o=await qe(r.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Native verification view"}).catch(c=>{if(c.code==="ENOENT")return null;throw c}),a=xu(t);if(o?.bytes.equals(Buffer.from(a)))return{};let s;if(o){await ci(r.projectRoot);let c=ob(e.runId);await Vt(r.workspaceRuntimeRoot,c,{label:"Native preserved report"}),s=c+"/"+SY()+".md",await EY.writeFile(ib.join(r.workspaceRuntimeRoot,...s.split("/")),o.bytes,{flag:"wx"})}return await Ge(n,a,{containedRoot:r.projectRoot}),s?{preservedReportRef:s}:{}}var Ea=_(()=>{"use strict";ct();Xr();$t();Ye();xe();Xs()});import{promises as Om}from"node:fs";import $m from"node:path";function F0(e,t){let r=e.map(({code:n,message:i,path:o})=>`- ${n}${o?` (${o})`:""}: ${i}`).join(`
|
|
384
|
+
`);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
|
|
385
|
+
`)}async function jm(e){let t=dt(e.paths,e.state.name),r=e.state.document_constraints_version,n=r===2||r===3,i=r===3,o=[...(await D0(t,e.state.brief,{strict:!0,compact:n,structure:i,maxBytes:null})).findings],a=e.specChanges??e.state.spec_changes,s=a.filter(({operation:d})=>d!=="remove"),c=e.state.spec_changes.filter(({operation:d})=>d!=="remove"),l=new Set(s.map(({capability:d})=>d)),u=e.state.phase==="shape",f=new Set(a.filter(({operation:d})=>d==="remove").map(({capability:d})=>d));if(e.specChanges!==void 0&&!(u&&s.length>0))for(let d of c)l.has(d.capability)||u&&f.has(d.capability)||o.push({code:"spec-document-missing",message:u?`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file, stage the replacement target Spec under specs/<capability>/spec.md, or record the intended capability deletion as a formal remove entry.`:`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${d.capability}/spec.md`});for(let d of s){let p=`specs/${d.capability}/spec.md`;if(d.source!==p){o.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${p}.`,path:d.source??p});continue}try{let h=(await Ve({root:t,ref:p,maxBytes:null,includeHash:!1})).text;o.push(...j0(h,p).findings)}catch(h){o.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${h.message}. Restore the complete file at ${p}.`,path:p})}}return{valid:o.length===0,findings:o}}async function ab(e){let t=await jm(e);if(!t.valid)throw new Ks(F0(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}async function Dm(e){let t=dt(e.paths,e.state.name),r=$m.join(t,"specs"),n=new Map(e.state.spec_changes.filter(({operation:a})=>a==="remove").map(a=>[a.capability,a])),i;try{i=await Om.readdir(r,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")i=[];else throw a}let o=[];for(let a of i.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(a.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${a.name}`);if(!a.isDirectory())continue;if(!So.test(a.name))throw new Error(`Invalid Native capability: ${a.name}`);if(n.has(a.name))throw new Error(`Capability ${a.name} cannot be proposed and removed together`);let s=`specs/${a.name}/spec.md`,c=$m.join(t,...s.split("/")),l=await Om.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=$m.join(e.paths.specsDir,a.name,"spec.md"),f="create";try{let m=await Om.lstat(u);if(!m.isFile()||m.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${a.name}`);f="modify"}catch(m){if(m.code!=="ENOENT")throw m}let d=`specs/${a.name}/${Ws}`,p=$m.join(t,...d.split("/")),h={};try{let m=await Om.lstat(p);if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${d}`);let g=await Ve({root:t,ref:d,maxBytes:null,includeHash:!1}),v=Dr(g.text);if(v.capability!==a.name)throw new Error(`Native delta capability ${v.capability} does not match directory ${a.name}`);h={delta_source:d}}catch(m){if(m.code!=="ENOENT")throw m}o.push({capability:a.name,operation:f,source:s,...h})}return o.push(...n.values()),o.sort((a,s)=>a.capability.localeCompare(s.capability,"en"))}async function Bm(e){let t=dt(e.paths,e.state.name),r=async o=>{let a=e.artifactTexts?.get(o);return a!==void 0?a:(await Ve({root:t,ref:o,maxBytes:null,includeHash:!1})).text},n=await r("brief.md"),i=[];for(let o of e.specChanges)o.source!==null&&i.push({capability:o.capability,source:o.source,markdown:await r(o.source)});return{acceptance:vO({briefMarkdown:n,specs:i,legacyBriefBoundaries:e.legacyBriefBoundaries,resolveBriefReferences:e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1})}}var TY,Eo=_(()=>{"use strict";pr();js();JA();$t();hn();Hs();Js();It();ka();Sa();Bt();Ye();dm();xe();Yt();Ni();nb();No();Ea();TY=ou("en",{compact:!0})});var Q0=_(()=>{"use strict";_t();Js();It();Sa();Bt();Eo();xe();Yt();Ni();_u();Pi();No();Wr()});var Wm=_(()=>{"use strict";xe();Ni();Yt()});var U0=_(()=>{"use strict";_u();No();Sa();Bt();Eo();Yt();Na();Xs();Ea();Pp();ku()});var z0=_(()=>{"use strict";Sa();Bt();Eo();Yt();Wm();_u();No();Ea()});var K0=_(()=>{"use strict";$t();hn();Js();ka();Bt();dm();Eo();Yt();Wm()});var sb=_(()=>{"use strict";O0();Eo();Q0();Yt();Wm();U0();z0();K0()});function cb(e,t,r){if(e.phase!=="verify")return[];let n=[];return e.status==="await-user"&&(t.stepId==="verify.stop"&&["await-user","resolve-verifier-blocker"].includes(e.loop.next_action??"")?(e.loop.next_action==="resolve-verifier-blocker"&&n.push({action:"resolve-verifier-blocker",choice:"retry"}),n.push({action:"revise-implementation",choice:"repair"})):t.stepId==="verify.confirm"&&e.loop.next_action==="confirm-skill-coordinated-pass"&&(n.push({action:"accept-result",choice:"approved"},{action:"revise-implementation",choice:"rejected"}),t.choices.includes("reverify")&&n.push({action:"retry-verifier",choice:"reverify"}))),t.stepId==="verify.retry"&&e.status==="blocked"&&e.loop.next_action==="retry-verifier"&&n.push({action:"retry-verifier",choice:"retry"}),n.filter(({choice:i})=>t.choices.includes(i))}var G0=_(()=>{"use strict"});import OY from"node:path";async function $Y(e){let t=await xr(e.projectRoot);if(t.status==="missing")return null;if(t.selection.workflow!=="native"){if(t.selection.workflow!=="application")return null;let r=await je(e.projectRoot,"native",t.selection.change,{readOnly:!0});if(!r||r.application!==t.selection.applicationId)return null}return Vs(t.selection.change),t.selection}async function jY(e,t){let r=await je(e.projectRoot,"native",t);if(r){let n=r.application==="native"?null:await Wl({projectRoot:e.projectRoot,runId:t,file:await Ap(e.projectRoot,r.application,t)}),o=await(n?Pt({...n.implementation,store:n.store}):Pt({workflows:[],store:St({singleWriter:!0,rootDir:OY.join(e.workspaceRuntimeRoot,"sdk-runs/native")})})).inspect(t);if(o.workflow.id!=="comet-native"||M(o.state).name!==t)throw new Error(`Native SDK Run ${t} does not match its change selection`)}else await zs(e,t)?await Lr(e,t):await wu(e,t)}async function Y0(e){let t=await $Y(e);return t?(await jY(e,t.change),t.change):null}var _ue,lb=_(()=>{"use strict";co();pr();Hs();It();Bt();xe();sb();et();Ll();_ue=Number.MAX_SAFE_INTEGER});import{createHash as DY,randomUUID as BY}from"node:crypto";import{promises as yt}from"node:fs";import Gr from"node:path";function ub(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function ec(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=Gr.join(e.archiveDir,t);if(!Gt(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function ni(e){try{return await yt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $u(e,t){let r=await xi(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Ou(e,t){await yt.mkdir(e.transactionsDir,{recursive:!0}),await Ei(mm(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function fb(e,t){let r=Gr.join(e.specsDir,t),n=Gr.join(r,"spec.md");if(!Gt(e.specsDir,n))throw new Error("Native canonical spec path escaped");let i;try{i=await yt.lstat(e.specsDir)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let o;try{o=await yt.lstat(r)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[a,s]=await Promise.all([yt.realpath(e.specsDir),yt.realpath(r)]);if(!Gt(a,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let c;try{c=await yt.lstat(n)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!Gt(s,await yt.realpath(n)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{return{text:(await Ve({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1})).text,exists:!0}}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}}async function WY(e){let t=Gr.join(e.paths.specsDir,e.change.capability),r=Gr.join(t,"spec.md");if(!Gt(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let s;try{s=await yt.lstat(e.paths.specsDir)}catch(f){if(f.code==="ENOENT")return;throw f}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let c;try{c=await yt.lstat(t)}catch(f){if(f.code==="ENOENT")return;throw f}if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[l,u]=await Promise.all([yt.realpath(e.paths.specsDir),yt.realpath(t)]);if(!Gt(l,u))throw new Error("Native canonical capability path escaped");try{let f=await yt.lstat(r);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await yt.unlink(r)}catch(f){if(f.code!=="ENOENT")throw f}await yt.rmdir(t).catch(f=>{if(f.code!=="ENOENT"&&f.code!=="ENOTEMPTY")throw f});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let n=await fb(e.paths,e.change.capability),i=e.change.delta_content?du({currentMarkdown:n.text,delta:Dr(e.change.delta_content)}).markdown:e.change.content,o=n.exists&&n.text===i;if(e.change.operation==="create"&&n.exists&&!o)throw new Error(`Canonical Native spec conflicts with the pending create: ${e.change.capability}`);let a=Gr.join(dt(e.paths,e.state.name),e.change.source);await Ge(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),!o&&(await yt.mkdir(t,{recursive:!0}),await Ge(r,i,{containedRoot:e.paths.nativeRoot}))}function pb(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function LY(e,t){let r=dt(e,t.name),n=[];for(let i of t.spec_changes){if(i.source===null){n.push({...i,content:null});continue}let o=await Ve({root:r,ref:i.source,maxBytes:null,includeHash:!1});if(i.delta_source){let a=await Ve({root:r,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=Dr(a.text);if(s.capability!==i.capability)throw new Error(`Native delta capability ${s.capability} does not match ${i.capability}`);let c=await fb(e,i.capability),l=du({currentMarkdown:c.text,delta:s});n.push({...i,content:l.markdown,delta_content:a.text,source_content:o.text});continue}n.push({...i,content:o.text})}return n}function mb(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(pb(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function VY(e){let t=[],r=[];for(let n of e.state.spec_changes)try{let i=dt(e.paths,e.state.name);n.source&&await Ve({root:i,ref:n.source,maxBytes:null,includeHash:!1});let o;if(n.delta_source){let a=await Ve({root:i,ref:n.delta_source,maxBytes:null,includeHash:!1}),s=Dr(a.text);if(s.capability!==n.capability)throw new Error("Native delta capability does not match its target");let c=await fb(e.paths,n.capability);o=[...du({currentMarkdown:c.text,delta:s}).operationResults]}r.push({capability:n.capability,operation:n.operation,source:n.source,...n.delta_source?{delta_source:n.delta_source,delta_operations:o}:{}})}catch(i){t.push(i.message)}return{blockers:t,requiresReverification:!1,specPreview:r}}async function hb(e){let t=e.state??await Lr(e.paths,e.name);if(t.name!==e.name)throw new Error("Native Archive state belongs to another change");let r=[];if(e.state===void 0)try{let s=await E0(e.paths,t);s&&!Us(s)&&Cu(s)}catch(s){r.push(s.message)}let n=!1,i;if(t.document_constraints_version===1){let s=await jm({paths:e.paths,state:t});r.push(...s.findings.map(({message:c})=>c))}try{pb(t)}catch(s){r.push(s.message)}let o=await $u(e.paths,e.name);if(o===null){let s=ec(e.paths,ub(t));await ni(s)&&r.push(`Native Archive target already exists: ${s}`);let c=await VY({paths:e.paths,state:t});r.push(...c.blockers),n=c.requiresReverification,i=c.specPreview}else i=o.spec_changes.map(s=>({capability:s.capability,operation:s.operation,source:s.source,...s.delta_source===void 0?{}:{delta_source:s.delta_source},...s.delta_content?{delta_operations:Dr(s.delta_content).operations.map(c=>({id:c.id,operation:c.operation,status:"changed",targetIds:c.operation==="rename"?[c.id,c.to_id]:[c.id]}))}:{}}));let a=e.derivedReport?"aligned":t.verification===null?"missing":await Pu({file:Gr.join(dt(e.paths,t.name),"verification.md"),stateVersion:e.verificationReportStateVersion??t.state_version});return a!=="aligned"&&r.push(`verification.md is ${a}`),{ready:r.length===0,blockers:r,requiresReverification:n,specPreview:i,capabilityPeers:[],archiveDir:ec(e.paths,ub(t)),stateVersion:t.state_version}}async function X0(e){let{paths:t,state:r}=e;return He(t,async()=>{pb(r);let n=await $u(t,r.name);if(n)mb(n,r);else{let i=await hb({paths:t,name:r.name,state:r,verificationReportStateVersion:e.verificationReportStateVersion,derivedReport:e.derivedReport});if(!i.ready)throw new Error(`Native SDK Archive preflight is blocked: ${i.blockers.join("; ")}`);n={schema:fm,id:BY(),change:r.name,start_state_version:r.state_version,archive_ref:ub(r),status:"prepared",next_spec_index:0,spec_changes:await LY(t,r),created_at:new Date().toISOString()},await Ou(t,n)}if(n.status==="prepared"){for(let i=n.next_spec_index;i<n.spec_changes.length;i+=1)await WY({paths:t,state:r,change:n.spec_changes[i]}),n={...n,next_spec_index:i+1},await Ou(t,n);n={...n,status:"specs-applied"},await Ou(t,n)}return n},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function gb(e){let t=await $u(e.paths,e.state.name);if(!t||t.status!=="specs-applied")throw new Error("Native SDK Archive Specs have not been applied");if(mb(t,e.state),t.next_spec_index!==t.spec_changes.length)throw new Error("Native SDK Archive Spec transaction is incomplete");return{transactionId:t.id,archiveRef:t.archive_ref,stateVersion:t.start_state_version,specCount:t.spec_changes.length}}async function MY(e,t,r){let n=Gr.join(ec(e,t),"comet-state.yaml"),i;try{i=await yt.readFile(n,"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}if(!ha(i))return;let o=(0,db.parseDocument)(i,{uniqueKeys:!0});if(o.errors.length>0)throw new Error("Native SDK Archive state is invalid");o.set(Z0,r),await Ge(n,o.toString(),{containedRoot:e.nativeRoot})}async function qY(e,t){let r=Gr.join(ec(e,t),"comet-state.yaml"),n=await Ve({root:e.nativeRoot,ref:Gr.relative(e.nativeRoot,r).replaceAll("\\","/"),maxBytes:null});if(!ha(n.text))throw new Error("Native SDK Archive portable receipt has no managed Run");let i=(0,db.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error("Native SDK Archive state is invalid");return i.toJS()[Z0]}function e$(e,t){if(!t.trim())throw new Error("Native SDK Archive Run ID is missing");let r=DY("sha256").update(t).digest("hex");return Gr.join(e.runtimeDir,"sdk-archive-receipts",`${r}.json`)}async function t$(e){let{paths:t,state:r,runId:n}=e;return He(t,async()=>{if(r.phase!=="archive"||r.status!=="done"||!r.archived||r.loop.stage!=="done")throw new Error("Native SDK Archive finalization requires committed done state");let i=await $u(t,r.name);if(!i){let l=await ju({paths:t,state:r,runId:n,archiveRef:e.archiveRef});if(l.transactionId!==e.transactionId)throw new Error("Native Archive recovery belongs to another transaction");return l}if(mb(i,r),i.id!==e.transactionId||i.archive_ref!==e.archiveRef||i.next_spec_index!==i.spec_changes.length||i.spec_changes.length!==r.spec_changes.length||i.spec_changes.some((l,u)=>l.capability!==r.spec_changes[u]?.capability||l.operation!==r.spec_changes[u]?.operation||l.source!==r.spec_changes[u]?.source)||!["specs-applied","report-aligned","moved"].includes(i.status))throw new Error("Native SDK Archive recovery does not match its completed Spec operations");let o=dt(t,r.name),a=ec(t,i.archive_ref);if(i.status==="specs-applied"){if(!await ni(o)||await ni(a))throw new Error("Native Archive layout contradicts its transaction");let l=Gr.join(o,"verification.md");if(!await ni(l))try{e.derivedReport?await e.derivedReport.write(l):await Pm({file:l,state:r})}catch(u){if(!e.derivedReport?.optionalView)throw u}i={...i,status:"report-aligned"},await Ou(t,i)}if(i.status==="report-aligned"){let l=await ni(o),u=await ni(a);if(l===u)throw new Error("Native Archive layout contradicts its transaction");l&&(await yt.mkdir(t.archiveDir,{recursive:!0}),await Ko(o,a)),i={...i,status:"moved"},await Ou(t,i)}if(i.status!=="moved"||await ni(o)||!await ni(a))throw new Error("Native SDK Archive has not moved the change");let s={runId:n,change:r.name,archiveRef:i.archive_ref,transactionId:i.id,stateVersion:r.state_version,specs:i.spec_changes.map(l=>({capability:l.capability,operation:l.operation}))};await MY(t,i.archive_ref,s);let c=e$(t,n);return await yt.mkdir(Gr.dirname(c),{recursive:!0}),await Ei(c,s,{containedRoot:t.runtimeDir}),await yt.rm(mm(t,{kind:"archive",change:r.name}),{force:!0}),s},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function ju(e){let{paths:t,state:r,runId:n}=e,i;try{i=JSON.parse(await yt.readFile(e$(t,n),"utf8"))}catch(o){if(o.code!=="ENOENT"||!e.archiveRef)throw o;i=await qY(t,e.archiveRef)}if(!i||i.runId!==n||i.change!==r.name||i.stateVersion!==r.state_version||e.archiveRef!==void 0&&i.archiveRef!==e.archiveRef||typeof i.transactionId!="string"||!Array.isArray(i.specs)||i.specs.length!==r.spec_changes.length||i.specs.some((o,a)=>o?.capability!==r.spec_changes[a]?.capability||o.operation!==void 0&&o.operation!==r.spec_changes[a]?.operation)||await $u(t,r.name)||await ni(dt(t,r.name)))throw new Error("Native SDK Archive completion record does not match its Run or transaction");if(!await ni(ec(t,i.archiveRef)))throw new Error("Native SDK Archive destination is missing");return i}async function r$(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o,actionId:a,state:s}=e,c=await ke(t,o.input.artifactRootRef);return He(c,async()=>{let l=await r.read(n);if(l?.revision!==i)return!1;if(l.actions.find(f=>f.id===a)?.status==="unknown"&&await xi(c,{kind:"archive",change:s.name}))throw new Error("Native Archive has a transaction; recover its actual progress with archive --recover");return r.compareAndSwap(n,i,o)},{allowedPortableTransaction:{kind:"archive",change:s.name}})}var db,Z0,Lm=_(()=>{"use strict";Wr();Yt();lb();db=kr(dn(),1);zd();Ul();$t();hn();ka();Bt();Ye();Eo();Yt();xe();gu();Xs();Z0="archive_receipt"});import Vm from"node:path";import{isDeepStrictEqual as FY}from"node:util";async function HY(e,t,r){let n=M(e.state),i=e.input,o=e.waits.some(u=>u.stepId==="verify.confirm"&&u.status==="resolved"&&u.decision?.choice==="approved");if(n.phase!=="archive"||n.status!=="active"||n.loop.stage!=="archive-ready"||!n.builder_handoff||!n.verification||n.verification_result!=="pass"||i.name!==n.name||typeof i.artifactRootRef!="string"||t.stepId!=="archive.prepare"||t.ref!=="native-archive-preflight"||!o)throw new Error("Native Archive preflight lacks a confirmed SDK result");let a=await Be(r);if(!a||a.native.artifact_root!==i.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let s=await ke(r,i.artifactRootRef,{readOnly:!0}),c=Vm.join(s.changesDir,n.name,"verification.md"),l=Vm.relative(r,c).replaceAll("\\","/");return{state:n,paths:s,reportFile:c,reportRef:l,reportStateVersion:n.state_version-1}}async function QY(e,t,r){let n=await HY(e,t,r),i=await hb({paths:n.paths,name:n.state.name,state:n.state,requireCurrentAcceptance:!1,verificationReportStateVersion:n.reportStateVersion,derivedReport:!0}),o=Vm.relative(r,i.archiveDir).replaceAll("\\","/");if(o.startsWith("../")||Vm.isAbsolute(o))throw new Error("Native Archive destination is outside the project");return{candidateId:n.state.builder_handoff.candidate_id,stateVersion:n.state.state_version,reportRef:n.reportRef,reportStateVersion:n.reportStateVersion,archiveDirRef:o,ready:i.ready,blockers:i.blockers,requiresReverification:i.requiresReverification,capabilityPeers:i.capabilityPeers,specPreview:i.specPreview}}async function n$(e,t,r){return QY(e,t,r)}function i$(e,t,r){return JSON.stringify([r,e.runId,e.revision,t.id,t.attempt,t.claim?.token])}async function wb(e,t,r,n=!1){let i=M(e.state),o=e.input,a=e.outputs["archive.prepare"]?.value;if(i.phase!=="archive"||i.status!=="active"||!i.builder_handoff||o.name!==i.name||typeof o.artifactRootRef!="string"||t.stepId!=="archive.execute"||t.ref!=="native-archive"||!a||a.ready!==!0||a.candidateId!==i.builder_handoff.candidate_id||a.stateVersion!==i.state_version)throw new Error("Native SDK Archive apply lacks a successful preflight for its current step");let s=await Be(r);if(!s||s.native.artifact_root!==o.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let c=await ke(r,o.artifactRootRef,{readOnly:!0});if(n){let l=await xi(c,{kind:"archive",change:i.name});if(l?.kind!=="archive"||l.journal.spec_changes.length!==i.spec_changes.length||l.journal.spec_changes.some((u,f)=>u.capability!==i.spec_changes[f]?.capability||u.operation!==i.spec_changes[f]?.operation))throw new Error("Native Archive recovery belongs to different Spec operations");await gb({paths:c,state:i})}return{state:i,paths:c,verificationReportStateVersion:a.reportStateVersion,derivedReport:!0}}function UY(e){if(e.status==="unknown")return e.rejectedOutcomes?.find(({outcome:t})=>{let r=t.output;return t.actionId===e.id&&t.attempt===e.attempt&&t.inputHash===e.inputHash&&t.claimToken===e.claim?.token&&t.outcomeId===`${e.id}:${e.attempt}:executor-result`&&t.status==="failed"&&t.event===void 0&&r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.ready===!1&&r.reason==="candidate-drift"&&typeof r.message=="string"&&r.message.trim().length>0&&Object.keys(r).length===3})?.outcome.output}async function o$(e,t,r){let n=M(e.state),i=e.input,o=e.outputs["archive.execute"]?.value;if(n.phase!=="archive"||n.status!=="done"||!n.archived||i.name!==n.name||typeof i.artifactRootRef!="string"||t.stepId!=="archive.finalize"||t.ref!=="native-archive-finalize"||!o||o.stateVersion!==n.state_version-1||typeof o.transactionId!="string"||typeof o.archiveRef!="string")throw new Error("Native SDK Archive finalization lacks its completed Spec transaction");let a=await ke(r,i.artifactRootRef,{readOnly:!0});return{state:n,paths:a,applied:o}}async function JY(e,t,r,n=!1){return o$(e,t,r)}function zY(e,t){return{optionalView:!0,preservedReportsRef:ob(e.runId),write:r=>Tu({state:t.state,paths:t.paths,runId:e.runId,file:r})}}var vb,yb,Mm,kb,qm,Ab,Fm,a$=_(()=>{"use strict";Is();Ea();et();It();Ye();Lm();xe();gu();vb=new Map;yb={id:"comet-native-archive-preflight",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive-preflight",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive preflight requires a bound SDK Run");let n=await n$(r,e,t.projectRoot);return vb.set(i$(r,e,t.projectRoot),n),{status:n.ready?"succeeded":"failed",output:n}}},Mm={id:"comet-native-archive-preflight-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==yb.id)return{accepted:!1,reason:"Native Archive preflight was not run by the Runtime"};let i=r.output;if(r.status==="failed"&&i?.ready===!1&&r.event===void 0)return{accepted:!0};try{let o=i$(e,t,n.projectRoot),a=vb.get(o);vb.delete(o);let s=a??await n$(e,t,n.projectRoot);return $(r.output)!==$(s)||r.status==="succeeded"!==s.ready||r.event!==void 0?{accepted:!1,reason:"Native Archive preflight changed after execution"}:{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}};kb={id:"comet-native-archive-apply",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive requires a bound SDK Run");let n=await wb(r,e,t.projectRoot),i=await X0(n);return{status:"succeeded",output:{transactionId:i.id,archiveRef:i.archive_ref,stateVersion:i.start_state_version,specCount:i.spec_changes.length}}}};qm={id:"comet-native-archive-apply-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==kb.id||r.event!==void 0)return{accepted:!1,reason:"Native Archive Specs were not applied by the Runtime"};try{if(r.status==="failed"){let c=UY(t);if(!c||!FY(r.output,c))return{accepted:!1,reason:"Native Archive lacks a matching rejected prewrite failure"};let{state:l,paths:u}=await wb(e,t,n.projectRoot);return await xi(u,{kind:"archive",change:l.name})?{accepted:!1,reason:"Native Archive has a transaction; recover its actual progress"}:{accepted:!0}}let i=t.status==="unknown",{state:o,paths:a}=await wb(e,t,n.projectRoot,i);if(r.status!=="succeeded")return{accepted:!1,reason:"Unexpected Native Archive apply event"};let s={...await gb({paths:a,state:o})};return $(r.output)===$(s)?{accepted:!0}:{accepted:!1,reason:"Native Archive Spec application changed before commit"}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};Ab={id:"comet-native-archive-finalize",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive-finalize",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive finalization requires a bound SDK Run");let n=await o$(r,e,t.projectRoot),{state:i,paths:o,applied:a}=n,s=await t$({paths:o,state:i,runId:r.runId,transactionId:a.transactionId,archiveRef:a.archiveRef,derivedReport:zY(r,n)});if(s.transactionId!==a.transactionId||s.archiveRef!==a.archiveRef)throw new Error("Native SDK Archive receipt does not match applied Specs");return{status:"succeeded",output:s}}},Fm={id:"comet-native-archive-finalize-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Ab.id||r.event!==void 0)return{accepted:!1,reason:"Native Archive was not finalized by the Runtime"};try{let{state:i,paths:o,applied:a}=await JY(e,t,n.projectRoot,r.status==="succeeded");if(r.status!=="succeeded")return{accepted:!1,reason:"Native Archive finalization did not succeed"};let s=await ju({paths:o,state:i,runId:e.runId,archiveRef:a.archiveRef,history:t.status==="unknown",allowMissingReport:!0});return s.transactionId!==a.transactionId||s.archiveRef!==a.archiveRef||$(r.output)!==$(s)?{accepted:!1,reason:"Native Archive receipt changed before commit"}:{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function Hm(e,t){return t?.workflow.hash===$(ln(e))}var bb=_(()=>{"use strict";et()});import{promises as KY}from"node:fs";import s$ from"node:path";async function Qm(e,t){let r=M(e.state),n=e.input,i=await Be(t);if(r.phase!=="shape"||r.archived||n.name!==r.name||typeof n.artifactRootRef!="string"||i?.native.artifact_root!==n.artifactRootRef)throw new Error("Native SDK capability association is not bound to the current Shape");let o=await ke(t,n.artifactRootRef),a=s$.join(o.changesDir,r.name,"capability-association.yaml"),s=s$.relative(t,a),c=await oe(t,s,{label:"Native capability association",expected:"file"});return{paths:o,file:a,inspected:c}}var c$,Um,Jm,l$=_(()=>{"use strict";ct();It();Bt();Ye();xe();c$={id:"comet-native-disassociate",capabilities:[],supports(e){return e.stepId==="shape.disassociate"&&e.ref==="native-disassociate"},async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native SDK project context is required");let n=e.input.activation,i=M(r.state);if(n?.expectedStateVersion!==i.state_version)throw new Error("Native SDK capability revocation references a stale Shape");let o=await Qm(r,t.projectRoot);return await He(o.paths,async()=>{let a=await Qm(r,t.projectRoot);a.inspected.exists&&await KY.rm(a.file)}),{status:"succeeded",output:{removed:!0}}}},Um={id:"comet-native-disassociate-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state);if(t!=="disassociate-capability"||i.phase!=="shape"||!["active","await-user"].includes(i.status)||i.archived||r===null||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!=="expectedStateVersion"||r.expectedStateVersion!==i.state_version||!n?.projectRoot)return{accepted:!1,reason:"Native capability revocation is stale or outside Shape"};try{return(await Qm(e,n.projectRoot)).inspected.exists?{accepted:!0}:{accepted:!1,reason:"Native capability association does not exist"}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},Jm={id:"comet-native-disassociate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status!=="succeeded"||t.stepId!=="shape.disassociate"||!n?.projectRoot||r.output?.removed!==!0)return{accepted:!1,reason:"Native capability revocation has no successful receipt"};try{return(await Qm(e,n.projectRoot)).inspected.exists?{accepted:!1,reason:"Native capability association still exists"}:{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});import zm from"node:path";async function Nb(e,t,r){om(r);let n=M(e.state),i=e.input,o=await Be(t);if(n.archived||n.status==="done"||i.name!==n.name||typeof i.artifactRootRef!="string"||o?.native.artifact_root!==i.artifactRootRef)throw new Error("Native SDK capability removal requires an active change");let a=await ke(t,i.artifactRootRef);if(!(await oe(t,zm.relative(t,zm.join(a.specsDir,r,"spec.md")),{label:"Canonical Native spec",expected:"file"})).exists)throw new Error(`Canonical Native spec does not exist: ${r}`);if((await oe(t,zm.relative(t,zm.join(a.changesDir,n.name,"specs",r)),{label:"Native proposed spec",expected:"directory"})).exists)throw new Error(`Capability ${r} cannot be proposed and removed together`);return n}var Km,u$,Gm,d$=_(()=>{"use strict";ct();mu();It();Ye();xe();Km={id:"comet-native-remove-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state);if(t!=="remove-capability"||!["active","await-user","blocked"].includes(i.status)||r===null||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!=="capability,expectedStateVersion"||typeof r.capability!="string"||r.expectedStateVersion!==i.state_version||!n?.projectRoot)return{accepted:!1,reason:"Native capability removal is stale or invalid"};try{return await Nb(e,n.projectRoot,r.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},u$={id:"comet-native-remove",capabilities:[],supports(e){return e.stepId==="shape.remove"&&e.ref==="native-remove"},async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native SDK project context is required");let n=e.input.activation,i=M(r.state);if(typeof n?.capability!="string"||n.expectedStateVersion!==i.state_version)throw new Error("Native capability removal references a stale change");return await Nb(r,t.projectRoot,n.capability),{status:"succeeded",output:{capability:n.capability}}}},Gm={id:"comet-native-remove-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=t.input.activation;if(r.status!=="succeeded"||t.stepId!=="shape.remove"||!n?.projectRoot||typeof i?.capability!="string"||r.output?.capability!==i.capability)return{accepted:!1,reason:"Native capability removal has no matching receipt"};try{return await Nb(e,n.projectRoot,i.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}}});function tc(e,t){let r=t.stepId==="supervisor.child.verifier",n=t.input.activation,i=e.actions.findIndex(o=>o.id===t.id);for(let o=i-1;o>=0;o-=1){let a=e.actions[o];if(a.stepId==="shape.revalidate"||a.stepId==="shape.prepare")break;if(!(a.status!=="succeeded"||a.outcome?.output?.requireIndependentReview!==!0)){if(r){let c=a.input.activation;if(a.stepId==="supervisor.child.builder"&&c?.child===n?.child)return!0}else if(["build.builder","supervisor.parent.builder"].includes(a.stepId))return!0}}return!1}var Ym=_(()=>{"use strict"});function Rb(e,t){let r=M(e.state),n=new Map;for(let i of e.actions){if(i.status!=="succeeded")continue;let o=i.outcome?.output;if(i.stepId==="supervisor.prepare"){let a=wt(t,r.name),s=vt(r.name);if(typeof o?.integrationWorktree!="string"||!he(o.integrationWorktree,a)||o.integrationBranch!==s)throw new Error("Native 需求修订的集成工作区归属不一致");n.set(s,{kind:"integration",child:null,worktree:a,branch:s,head:""})}if(i.stepId==="supervisor.child.prepare"){if(typeof o?.child!="string")throw new Error("Native 需求修订缺少 Child 归属");let a=o.child,s=Wt(t,r.name,a),c=`comet/supervisor/${r.name}/${a}`;if(typeof o.worktree!="string"||!he(o.worktree,s)||o.branch!==c)throw new Error("Native 需求修订的 Child 工作区归属不一致");n.set(c,{kind:"child",child:a,worktree:s,branch:c,head:""})}}return[...n.values()].map(i=>{let o=ye(i.worktree),a=ge(i.worktree,i.branch);if(o.currentBranch!==i.branch||!o.primaryWorktreeRoot||!he(o.primaryWorktreeRoot,t)||!a)throw new Error("Native 需求修订的 Git 工作区身份已变化");return{...i,head:a}})}function Ca(e,t,r){let o=[...e.actions].reverse().find(a=>a.stepId==="shape.revise"&&a.status==="succeeded")?.outcome?.output?.workspaces?.find(a=>typeof a.worktree=="string"&&he(a.worktree,t)&&a.branch===r);if(!o)return null;if(ge(t,r)!==o.head)throw new Error("Native 修订后保留的工作区提交已变化,请核对原现场");return o}var Sb=_(()=>{"use strict";_t();xe();Wr()});function Eb(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return Object.keys(t).sort().join(",")!=="archiveActionId,expectedStateVersion,proposalHash,reason"||typeof t.reason!="string"||!t.reason.trim()||typeof t.expectedStateVersion!="number"||typeof t.proposalHash!="string"||typeof t.archiveActionId!="string"?null:t}async function f$(e,t,r){let n=e.actions.find(i=>i.id===t.archiveActionId);if(!n||n.status!=="cancelled"||!["archive.prepare","archive.execute"].includes(n.stepId))throw new Error("Native implementation revision has no original pending Archive action");return{drift:!0,requirementsChanged:!1,driftKind:"implementation-changed",archiveStep:n.stepId,reason:t.reason.trim()}}function GY(e){return e.waits.find(t=>{if(t.status!=="pending"||t.stepId!=="build.resume")return!1;let r=t.proposal?.activation?.failedBuilderActionId;return e.actions.some(n=>n.id===r&&n.stepId==="build.builder"&&n.status==="failed")})}function YY(e,t,r){if(e.actions.some(o=>["running","unknown"].includes(o.status)))return!1;if(["verify","archive"].includes(t.phase))return r===void 0;if(t.phase!=="build")return!1;if(t.children_contract_ref)return r===void 0;let n=XY(e);if(n)return r===n;let i=GY(e);return i!==void 0&&i.proposalHash===r}function XY(e){let t=M(e.state);if(t.phase!=="build"||t.children_contract_ref||!["running","waiting"].includes(e.status)||e.actions.some(a=>["running","unknown"].includes(a.status)))return null;let r=e.actions.filter(a=>a.status==="pending");if(r.length!==1||r[0].stepId!=="build.builder")return null;let{id:n,attempt:i,inputHash:o}=r[0];return $({actionId:n,attempt:i,inputHash:o})}var Xm,Cb,Zm,eh,p$,th,m$=_(()=>{"use strict";et();xe();Sb();Xm={id:"comet-native-implementation-revision-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state),o=Eb(r),a=e.actions.filter(l=>l.status==="pending"),s=a[0],c=[...e.waits].reverse().find(l=>l.stepId==="verify.confirm"&&l.status==="resolved"&&l.decision?.choice==="approved");return t!=="revise-implementation"||!o||!n?.projectRoot||i.phase!=="archive"||i.status!=="active"||i.archived||i.state_version!==o.expectedStateVersion||!c||c.proposalHash!==o.proposalHash||a.length!==1||s.id!==o.archiveActionId||!["archive.prepare","archive.execute"].includes(s.stepId)||e.actions.some(l=>["running","unknown"].includes(l.status))||e.actions.some(l=>l.stepId==="archive.execute"&&l.status==="succeeded")||e.waits.some(l=>l.status==="pending")||e.evidenceWaits?.some(l=>l.status==="pending")||e.ready.length>0?{accepted:!1,reason:"Native implementation revision is stale or Archive is already in progress"}:{accepted:!0}}};Cb={id:"comet-native-revise-implementation",capabilities:[],supports:e=>e.stepId==="repair.implementation"&&e.ref==="native-revise-implementation",async execute(e,t,r){let n=Eb(e.input.activation);if(!r||!n||!t?.projectRoot)throw new Error("Native implementation revision lacks its input");return{status:"succeeded",output:await f$(r,n,t.projectRoot)}}},Zm={id:"comet-native-implementation-revision-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=Eb(t.input.activation);if(!i||!n?.projectRoot||r.status!=="succeeded"||t.claim?.executorId!==Cb.id)return{accepted:!1,reason:"Native implementation revision has no matching read-only result"};let o=await f$(e,i,n.projectRoot);return{accepted:$(r.output)===$(o),reason:"Native candidate changed during revision"}}};eh={id:"comet-native-revise-command",version:"1",async validate({run:e,name:t,input:r}){let n=M(e.state);return t!=="revise-requirements"||n.archived||!["active","await-user","blocked"].includes(n.status)||e.status==="completed"||r===null||typeof r!="object"||Array.isArray(r)||!["expectedStateVersion,reason","expectedStateVersion,proposalHash,reason"].includes(Object.keys(r).sort().join(","))||!YY(e,n,r.proposalHash)||r.expectedStateVersion!==n.state_version||typeof r.reason!="string"||!r.reason.trim()||e.actions.some(i=>i.stepId==="archive.execute"&&["succeeded","running","unknown"].includes(i.status))?{accepted:!1,reason:"Native requirements revision is stale or cannot interrupt Archive application"}:{accepted:!0}}},p$={id:"comet-native-revise-requirements",capabilities:[],supports(e){return e.stepId==="shape.revise"&&e.ref==="native-revise-requirements"},async execute(e,t,r){if(!r)throw new Error("Native SDK Run is required");let n=e.input.activation,i=M(r.state);if(typeof n?.reason!="string"||!n.reason.trim()||n.expectedStateVersion!==i.state_version)throw new Error("Native requirements revision references a stale change");if(i.children_contract_ref&&!t?.projectRoot)throw new Error("Native Supervisor 需求修订缺少实际项目");let o=i.children_contract_ref?Rb(r,t.projectRoot):void 0;return{status:"succeeded",output:{reason:n.reason.trim(),...o?{workspaces:o}:{}}}}},th={id:"comet-native-revise-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){let i=t.input.activation,o=M(e.state),a=!0;try{o.children_contract_ref&&(a=!!n?.projectRoot&&$(r.output?.workspaces??null)===$(Rb(e,n.projectRoot)))}catch{a=!1}return{accepted:r.status==="succeeded"&&t.stepId==="shape.revise"&&typeof i?.reason=="string"&&r.output?.reason===i.reason.trim()&&a,reason:"Native requirements revision has no matching receipt"}}}});function Xt(e){for(let t=e.actions.length-1;t>=0;t--){let r=e.actions[t];if((r.id===e.state.children_contract_ref||r.stepId==="shape.revalidate")&&r.status==="succeeded")return e.actions.slice(t+1)}return e.actions}function _b(e){if(!Number.isSafeInteger(e.maxParallel)||e.maxParallel<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let t=new Set(e.contract.children.map(o=>o.name)),r=new Set(e.integrated),n=new Set(e.active);if(r.size!==e.integrated.length||n.size!==e.active.length)throw new Error("Native Supervisor child facts contain duplicate names");for(let o of[...r,...n]){if(!t.has(o))throw new Error(`Native Supervisor fact names unknown child ${o}`);if(r.has(o)&&n.has(o))throw new Error(`Native Supervisor child ${o} cannot be both integrated and active`)}let i=Math.max(0,e.maxParallel-n.size);return e.contract.children.filter(o=>!r.has(o.name)&&!n.has(o.name)&&o.depends_on.every(a=>r.has(a))).slice(0,i).map(o=>o.name)}var _a=_(()=>{"use strict"});async function rc(e,t){let r=M(e.state),n=e.input;if(!["build","verify","archive"].includes(r.phase)||r.name!==n.name||!r.children_contract_ref||typeof n.artifactRootRef!="string")throw new Error("Native SDK Supervisor preparation lacks a confirmed child plan");let i=await Be(t);if(!i||i.native.artifact_root!==n.artifactRootRef)throw new Error("Native SDK Supervisor project configuration changed");let o=e.outputs["shape.revalidate"]?.value??e.outputs["shape.prepare"]?.value,a=r.children_contract??o?.children?.contract;if(!a)throw new Error("Native SDK Supervisor lacks its original approved children plan; explicitly revise requirements to confirm it");let s=r.workspace.change_branch??r.workspace.target_branch;if(!s)throw new Error("Native SDK Supervisor requires a bound Git target branch");return{state:r,config:i,contract:a,targetBranch:s}}async function Yr(e,t){let r=await rc(e,t),n=ge(t,r.targetBranch);if(!n)throw new Error("Native SDK Supervisor target branch has no commit");return{...r,targetCommit:n}}function ZY(e){let t=e.input.activation;if(!t||typeof t.child!="string"||typeof Fe(t)!="string"||typeof t.integrationBranch!="string"||typeof t.integrationWorktree!="string"||typeof t.targetCommit!="string")throw new Error("Native SDK Supervisor child preparation lacks its activation");return{...t,contractRef:Fe(t)}}async function Ib(e,t,r){let n=await Yr(e,r),i=ZY(t);if(!n.contract.children.some(({name:a})=>a===i.child)||Fe(i,e)!==n.state.children_contract_ref||i.integrationBranch!==vt(n.state.name)||!he(i.integrationWorktree,wt(r,n.state.name))||ge(r,i.integrationBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor child preparation no longer matches its parent plan");if(ye(i.integrationWorktree).currentBranch!==i.integrationBranch)throw new Error("Native SDK Supervisor integration worktree changed before child preparation");return{...n,input:i}}var xb,rh,Pb,nh,Ia=_(()=>{"use strict";Tr();_t();It();xe();Sb();Wr();xb={id:"native-supervisor-prepare",capabilities:[],supports(e){return e.stepId==="supervisor.prepare"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor preparation requires a bound Run and project");let n=await Yr(r,t.projectRoot);Ca(r,wt(t.projectRoot,n.state.name),vt(n.state.name))},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor preparation requires a bound Run and project");let n=await Yr(r,t.projectRoot),i=Ca(r,wt(t.projectRoot,n.state.name),vt(n.state.name)),o=await Im({projectRoot:t.projectRoot,parent:n.state.name,targetBranch:n.targetBranch,sourceConfig:n.config});return{status:"succeeded",output:{contractRef:n.state.children_contract_ref,integrationBranch:o.binding.changeBranch,integrationWorktree:o.projectRoot,targetBranch:n.targetBranch,targetCommit:n.targetCommit,integrationCommit:i?.head??n.targetCommit,maxParallelChildren:n.state.coordination_mode==="single-session"?1:n.config.native.max_parallel_children??lu}}}},rh={id:"native-supervisor-prepare-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||!xb.supports(t))return{accepted:!1,reason:"Native SDK Supervisor preparation lacks its project"};try{let i=await Yr(e,n.projectRoot),o=r.output,a=wt(n.projectRoot,i.state.name),s=vt(i.state.name),c=Ca(e,a,s);if(!o||Fe(o,e,t)!==i.state.children_contract_ref||o.integrationBranch!==s||typeof o.integrationWorktree!="string"||!he(o.integrationWorktree,a)||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||(o.integrationCommit??o.targetCommit)!==(c?.head??i.targetCommit))throw new Error("Native SDK Supervisor preparation result does not match its plan");if(ye(a).currentBranch!==s)throw new Error("Native SDK Supervisor integration worktree has a different branch");if(ge(a,s)!==(c?.head??i.targetCommit))throw new Error("Native SDK Supervisor integration worktree head changed");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},Pb={id:"native-supervisor-child-prepare",capabilities:[],supports(e){return e.stepId==="supervisor.child.prepare"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor child preparation requires a bound Run and project");let n=await Ib(r,e,t.projectRoot);Ca(r,Wt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`)},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor child preparation requires a bound Run and project");let n=await Ib(r,e,t.projectRoot);Ca(r,Wt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`);let i=await xm({projectRoot:t.projectRoot,parent:n.state.name,child:n.input.child,targetBranch:n.input.integrationBranch,sourceConfig:n.config});return{status:"succeeded",output:{child:n.input.child,contractRef:n.input.contractRef,worktree:i.projectRoot,branch:i.binding.changeBranch,baseCommit:n.input.targetCommit}}}},nh={id:"native-supervisor-child-prepare-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||!Pb.supports(t))return{accepted:!1,reason:"Native SDK Supervisor child preparation lacks its project"};try{let i=await Ib(e,t,n.projectRoot),o=r.output,a=Wt(n.projectRoot,i.state.name,i.input.child),s=`comet/supervisor/${i.state.name}/${i.input.child}`;if(!o||o.child!==i.input.child||Fe(o,e)!==Fe(i.input,e)||typeof o.worktree!="string"||!he(o.worktree,a)||o.branch!==s||o.baseCommit!==i.input.targetCommit)throw new Error("Native SDK Supervisor child preparation result does not match its plan");let c=ye(a),l=Ca(e,a,s);if(c.currentBranch!==s||ge(a,s)!==o.baseCommit&&!l)throw new Error("Native SDK Supervisor child worktree changed before Builder dispatch");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});import{promises as g$}from"node:fs";import Mr from"node:path";function nc(e){let t=e?.activation;if(!t||typeof t.child!="string"||typeof t.candidateCommit!="string"||typeof t.integrationCommit!="string"||typeof t.checksActionId!="string"&&typeof t.mergeActionId!="string"||typeof Fe(t)!="string")throw new Error("Native Supervisor child archive lacks its activation");return{...t,contractRef:Fe(t)}}function Tb(e,t,r,n){for(let i of[...Xt(e)].reverse()){if(i.stepId!==t||i.status!=="succeeded"||!i.outcome||i.input?.activation?.child!==r)continue;let a=i.outcome.output;if(!(!a||!n(a)))return{action:i,output:a}}return null}async function v$(e,t,r,n=!1){let i=await Yr(e,r),o=i.state,a=nc(t.input);if(o.phase!=="build"||o.status!=="active"||!o.children_contract_ref||Fe(a,e)!==o.children_contract_ref||!i.contract.children.some(({name:Z})=>Z===a.child)||!xa.test(a.candidateCommit)||!xa.test(a.integrationCommit))throw new Error("Native Supervisor child archive does not match the confirmed plan");let s=a.checksActionId?e.actions.find(Z=>Z.id===a.checksActionId):void 0,c=s?.outcome?.output;if(s&&(s.stepId!=="supervisor.child.integration-checks"||s.status!=="succeeded"||c?.candidateId!==a.integrationCommit||typeof c.completedAt!="string"))throw new Error("Native legacy archive lacks its original accepted integration result");let l=a.mergeActionId??s?.input?.activation?.mergeActionId,u=e.actions.find(Z=>Z.id===l),f=u?.outcome?.output,d=a.repairActionId??s?.input?.activation?.repairActionId,p=d?e.actions.find(Z=>Z.id===d):void 0,h=p?.outcome?.output;if(u?.stepId!=="supervisor.child.integrate"||u.status!=="succeeded"||f?.child!==a.child||(p?p.stepId!=="supervisor.child.integration-repair"||p.status!=="succeeded"||p.input.activation?.mergeActionId!==u.id||p.input.activation.child!==a.child||p.input.activation.candidateCommit!==a.candidateCommit||Fe(p.input.activation,e)!==o.children_contract_ref||h?.integrationCommit!==a.integrationCommit:f.integrationCommit!==a.integrationCommit))throw new Error("Native Supervisor child archive lacks its accepted integration task");let m=c?.completedAt??ce((e.outputs["supervisor.prepare"]?.value).integrationWorktree,["show","-s","--format=%cI",a.integrationCommit]).trim(),g=Tb(e,"supervisor.child.verifier",a.child,Z=>{let Xe=Z.evidence;return Z.verdict==="pass"&&Z.candidateCommit===a.candidateCommit&&typeof Xe?.summary=="string"&&!!Xe.summary.trim()});if(!g||!g.action.claim?.sessionId)throw new Error("Native Supervisor child archive lacks its passing Verifier");let v=g.output.evidence,w=Tb(e,"supervisor.child.builder",a.child,Z=>Z.candidateCommit===a.candidateCommit),A=["1","2","3"].includes(g.action.executionOrigin?.workflow.version??""),N=A?Tb(e,"supervisor.child.checks",a.child,Z=>Z.candidateId===a.candidateCommit):null;if(A&&!N)throw new Error("Legacy Child archive lacks its original accepted checks");let b=N?.output,E=e.outputs["supervisor.prepare"]?.value;if(typeof E?.integrationWorktree!="string"||typeof E.integrationBranch!="string")throw new Error("Native Supervisor child archive lacks its integration workspace");let V=Wt(r,o.name,a.child),j=`comet/supervisor/${o.name}/${a.child}`;if(ye(V).currentBranch!==j)throw new Error("Native Supervisor child worktree moved before the child archive");if(ye(E.integrationWorktree).currentBranch!==E.integrationBranch)throw new Error("Native Supervisor integration worktree moved before the child archive");let z=ce(V,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(Z=>Z&&Z!==".comet/config.yaml").map(Z=>Z.replaceAll("\\","/"));if(!n&&(!Ro(V,z)||!Ro(E.integrationWorktree)))throw new Error("Native Supervisor child archive requires clean worktrees");let X=new Map;if(Array.isArray(v.acceptance))for(let Z of v.acceptance)typeof Z?.id!="string"||typeof Z?.result!="string"||X.set(Z.id,typeof Z.reason=="string"?Z.reason:"");let de=Ao(i.contract,a.child);for(let{id:Z}of de)if(!X.has(Z))throw new Error(`Native Supervisor child archive evidence does not cover acceptance ${Z}`);let se=(b?.checks??[]).map(Z=>{if(typeof Z.id!="string"||typeof Z.name!="string"||!Array.isArray(Z.argvDisplay)||typeof Z.cwdRef!="string"||Z.status!=="passed"||!Number.isSafeInteger(Z.durationMs))throw new Error("Native Supervisor child archive requires passed Child checks");return{id:Z.id,name:Z.name,argvDisplay:Z.argvDisplay,cwdRef:Z.cwdRef,status:Z.status,exitCode:typeof Z.exitCode=="number"?Z.exitCode:null,durationMs:Z.durationMs}}),De=Array.isArray(v.risks)?v.risks.filter(Z=>typeof Z=="string"):[];return{parent:o.name,maxParallelChildren:i.state.coordination_mode==="single-session"?1:i.config.native.max_parallel_children??lu,child:a.child,language:o.language,targetBranch:i.targetBranch,worktree:V,branch:j,candidateCommit:a.candidateCommit,integrationBranch:E.integrationBranch,integrationWorktree:E.integrationWorktree,integrationCommit:a.integrationCommit,builderSessionId:w?.action.claim?.sessionId??null,builderSummary:typeof w?.output.summary=="string"?w.output.summary:null,verifierSessionId:g.action.claim.sessionId,verifierSummary:v.summary,verifierRisks:De,verifierAcceptance:X,childChecks:se,...A?{}:{reportedChecks:Xn(v.checks??[])},childChecksCompletedAt:b?.completedAt??m,integrationChecksCompletedAt:m,scopedAcceptance:de}}async function t9(e,t,r,n){let i=await Yr(e,r),o=await ke(r,i.config.native.artifact_root),a=Mr.join(o.changesDir,n.parent),s=await Ve({root:a,ref:i.state.brief,includeHash:!1}),c=await Promise.all(i.state.spec_changes.flatMap(d=>d.source?[Ve({root:a,ref:d.source,includeHash:!1})]:[])),l=n.language==="zh-CN"?"子任务归档":"Archived Child",u=n.scopedAcceptance.map(d=>`- ${d.id}: ${d.text}`).join(`
|
|
386
|
+
`),f=[s,...c].map(d=>`- ${d.ref}`).join(`
|
|
387
|
+
`);return{"brief.md":`# ${n.child}
|
|
388
|
+
|
|
389
|
+
${l}: ${n.parent}
|
|
390
|
+
|
|
391
|
+
${n.language==="zh-CN"?"本归档仅覆盖以下已确认验收项。Spec 是 Parent 已确认内容的快照,不表示独立 Child Spec 变更或新增验收。":"This archive covers only the confirmed acceptance below. The Spec is a snapshot of the confirmed Parent, not an independent Child Spec change or additional acceptance."}
|
|
392
|
+
|
|
393
|
+
${u}
|
|
394
|
+
|
|
395
|
+
[Parent Spec](spec.md) · [${n.language==="zh-CN"?"来源与原始简报":"Sources and original brief"}](archive-source.md) · [${n.language==="zh-CN"?"验收记录":"Verification"}](verification.md)
|
|
396
|
+
`,"spec.md":c.length===0?`# Parent Spec
|
|
397
|
+
|
|
398
|
+
No Spec change was declared by the confirmed Parent.
|
|
399
|
+
`:c.length===1?c[0].text:c.map(d=>`# ${d.ref}
|
|
400
|
+
|
|
401
|
+
${d.text}`).join(`
|
|
402
|
+
|
|
403
|
+
`),"archive-source.md":`# ${n.language==="zh-CN"?"归档材料来源":"Archive material sources"}
|
|
404
|
+
|
|
405
|
+
- Parent Run: ${e.runId}
|
|
406
|
+
- Archive Action: ${t.id}
|
|
407
|
+
- Contract: ${Fe(nc(t.input),e)}
|
|
408
|
+
- Candidate: ${n.candidateCommit}
|
|
409
|
+
- Verifier: ${n.verifierSessionId}
|
|
410
|
+
- Integration Action: ${nc(t.input).mergeActionId??nc(t.input).checksActionId}
|
|
411
|
+
|
|
412
|
+
${f}
|
|
413
|
+
|
|
414
|
+
## ${n.language==="zh-CN"?"Parent 原始简报":"Original Parent brief"}
|
|
415
|
+
|
|
416
|
+
${s.text}`}}async function r9(e,t,r){let n=[];for(let i of Object.keys(t))await Ve({root:e,ref:i}).catch(a=>{if(a.code==="ENOENT")return null;throw a})||n.push(i);if(!r)for(let i of n)await Ge(Mr.join(e,i),t[i],{containedRoot:e});return n}function n9(e){let t=e.scopedAcceptance.filter(({id:n})=>e9.test(n)).map(({id:n,source:i,text:o})=>{let a=e.verifierAcceptance.get(n);return{id:n,source:i,text:o,result:"passed",reason:a?Et(a):null}}),r=_s({name:e.child,language:e.language,workspace:{isolation:"worktree",change_branch:e.branch,target_branch:e.targetBranch,finish:"merge"}});return M({...r,created_at:e.childChecksCompletedAt,phase:"archive",status:"done",archived:!0,loop:{...r.loop,iteration:1,attempt:1,stage:"done",next_action:null},acceptance:t,builder_handoff:{candidate_id:e.candidateCommit,identity_provider:wr,builder_execution_ref:e.builderSessionId??e.verifierSessionId,iteration:1,summary:Et(e.builderSummary??e.verifierSummary),addressed_acceptance_ids:t.map(({id:n})=>n),checks:e.childChecks.map(n=>({name:Et(n.name),result:"passed",note:null})),checks_truncated:!1,known_limits:[],known_limits_truncated:!1,review:null,submitted_at:e.childChecksCompletedAt},verification:{candidate_id:e.candidateCommit,identity_provider:wr,verifier_execution_ref:e.verifierSessionId,iteration:1,attempt:1,assurance:e.builderSessionId===e.verifierSessionId?"self-reviewed":"skill-coordinated",verdict:"pass",...e.reportedChecks?{reported_checks:e.reportedChecks}:{},checks:e.childChecks.map(n=>({id:n.id,name:Et(n.name),argv_display:n.argvDisplay.map(i=>Et(i)),argv_truncated:!1,cwd_ref:n.cwdRef,status:"passed",exit_code:n.exitCode,duration_ms:n.durationMs})),summary:Et(e.verifierSummary),risks:e.verifierRisks.map(n=>Et(n)),risks_truncated:!1,completed_at:e.integrationChecksCompletedAt},verification_result:"pass",verification_report:"verification.md",history:[]})}async function w$(e,t){let r=await Be(e.worktree);if(!r)throw new Error("Native Supervisor child worktree has no project config");let n=await ke(e.worktree,r.native.artifact_root),i=Mr.join(n.archiveDir,t),o=Mr.resolve(i),a=Mr.resolve(n.archiveDir);if(!o.toLowerCase().startsWith(`${a.toLowerCase()}${Mr.sep}`)&&o.toLowerCase()!==a.toLowerCase())throw new Error("Native Supervisor child archive path escaped the archive root");return{target:o,relative:Mr.relative(e.worktree,o).replaceAll("\\","/"),changesDir:n.changesDir,nativeRoot:n.nativeRoot}}function $b(e){let t=e.integrationChecksCompletedAt.slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(t))throw new Error("Native Supervisor child archive lacks a valid archive date");return`${t}-${e.child}`}function ih(e,t,r){let n=ce(e,["show","--name-only","--format=",t]).split(`
|
|
417
|
+
`).map(i=>i.trim()).filter(Boolean);if(n.length===0||n.some(i=>!i.startsWith(`${r}/`)))throw new Error(`Native Supervisor child archive commit ${t} touches paths outside ${r}`)}async function i9(e,t,r,n){let i=e.actions.findIndex(s=>s.id===t.id),o=i<0?void 0:e.actions.slice(0,i).reverse().find(s=>s.stepId==="supervisor.child.archive"&&s.status==="succeeded"&&s.input?.activation?.child===r.child),a=o?.outcome?.output;if(!o||o.claim?.executorId!==oh.id||a?.child!==r.child||a.archiveRef!==$b(r)||a.candidateCommit!==nc(o.input).candidateCommit||a?.baseCommit!==nc(o.input).integrationCommit||typeof a.archiveCommit!="string"||!xa.test(a.archiveCommit))throw new Error("Native Supervisor child archive lacks its accepted predecessor receipt");ih(r.worktree,a.archiveCommit,n.relative);for(let[s,c]of[[r.worktree,r.candidateCommit],[r.integrationWorktree,r.integrationCommit]])ce(s,["merge-base","--is-ancestor",a.archiveCommit,c])}async function h$(e){try{return await g$.access(e),!0}catch{return!1}}var Ob,xa,e9,oh,ah,y$=_(()=>{"use strict";Tr();Ob=kr(dn(),1);_t();Ur();$t();hn();It();Ye();xe();Ni();Na();_a();Ia();Pi();Wr();Xs();Ru();xa=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,e9=/^A[1-9][0-9]*$/u;oh={id:"native-supervisor-child-archive",capabilities:[],supports(e){return e.stepId==="supervisor.child.archive"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native Supervisor child archive requires a bound Run and project");let n=await v$(r,e,t.projectRoot);if(ge(n.worktree,n.branch)!==n.candidateCommit)throw new Error("Native Supervisor child worktree moved before the child archive");if(ge(n.integrationWorktree,n.integrationBranch)!==n.integrationCommit)throw new Error("Native Supervisor integration head moved before the child archive");let i=$b(n),o=await w$(n,i),a=null;if(await h$(o.target)&&(a=await wn(Mr.join(o.target,"comet-state.yaml")).catch(()=>null),!a||a.name!==n.child||!a.archived||a.workspace.change_branch!==n.branch))throw new Error("Native Supervisor child archive directory holds another change");let s;if(a?.verification?.candidate_id===n.candidateCommit&&a.verification.verifier_execution_ref===n.verifierSessionId&&a.verification.completed_at===n.integrationChecksCompletedAt){let u=ge(n.worktree,n.branch);if(!u||!xa.test(u))throw new Error("Native Supervisor child worktree has no archive commit");ih(n.worktree,u,o.relative),s=u}else{if(await h$(Mr.join(o.changesDir,n.child)))throw new Error(`Native Supervisor child ${n.child} still has an active change directory; archive it through the normal flow first`);let u=n9(n),f=await t9(r,e,t.projectRoot,n);if(a&&await i9(r,e,n,o),await g$.mkdir(o.target,{recursive:!0}),a){let g={...f,"comet-state.yaml":(0,Ob.stringify)(u),"verification.md":xu(u)};for(let[v,w]of Object.entries(g))await Ge(Mr.join(o.target,v),w,{containedRoot:o.nativeRoot})}else await r9(o.target,f,!1),await Ge(Mr.join(o.target,"comet-state.yaml"),(0,Ob.stringify)(u),{containedRoot:o.nativeRoot}),await Pm({file:Mr.join(o.target,"verification.md"),state:u});if(await Pu({file:Mr.join(o.target,"verification.md"),stateVersion:u.state_version})!=="aligned")throw new Error("Native Supervisor child archive report is not aligned");ce(n.worktree,["add","--force","--",`${o.relative}/comet-state.yaml`,`${o.relative}/verification.md`,`${o.relative}/brief.md`,`${o.relative}/spec.md`,`${o.relative}/archive-source.md`]);let p=ce(n.worktree,["diff","--cached","--name-only","--",o.relative]).split(`
|
|
418
|
+
`).filter(Boolean);if(p.length===0)throw new Error("Native Supervisor child archive produced no committable content");let h=p.filter(g=>!g.startsWith(`${o.relative}/`));if(h.length>0)throw new Error(`Native Supervisor child archive staging left unrelated paths: ${h.join(", ")}`);ce(n.worktree,["commit","-m",`chore(native): archive ${n.child}`]);let m=ge(n.worktree,n.branch);if(!m||!xa.test(m))throw new Error("Native Supervisor child archive commit is missing");ih(n.worktree,m,o.relative),s=m}let c=ge(n.integrationWorktree,n.integrationBranch);if(!c||!xa.test(c))throw new Error("Native Supervisor integration branch has no head");let l=c;try{ce(n.integrationWorktree,["merge-base","--is-ancestor",s,c])}catch{ce(n.integrationWorktree,["merge","--no-ff","--no-edit",n.branch]);let u=ge(n.integrationWorktree,n.integrationBranch);if(!u||!xa.test(u))throw new Error("Native Supervisor child archive merge produced no head");l=u;let f=ce(n.integrationWorktree,["rev-list","--parents","-n","1",l]).split(" ");if(f.length!==3||f[1]!==c||f[2]!==s)throw new Error("Native Supervisor child archive merge is not the expected commit")}if(ge(n.worktree,n.branch)!==s)throw new Error("Native Supervisor child branch moved after the archive commit");return{status:"succeeded",output:{child:n.child,archiveRef:i,candidateCommit:n.candidateCommit,archiveCommit:s,baseCommit:n.integrationCommit,integrationCommit:l,maxParallelChildren:n.maxParallelChildren}}}},ah={id:"native-supervisor-child-archive-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==oh.id||r.status!=="succeeded")return{accepted:!1,reason:"Native Supervisor child archive was not executed by Runtime"};try{let i=await v$(e,t,n.projectRoot),o=r.output,a=$b(i);if(!o||o.child!==i.child||o.archiveRef!==a||o.candidateCommit!==i.candidateCommit||o.baseCommit!==i.integrationCommit||typeof o.archiveCommit!="string"||typeof o.integrationCommit!="string")throw new Error("Native Supervisor child archive outcome does not match its binding");let s=await w$(i,a),c=await wn(Mr.join(s.target,"comet-state.yaml"));if(c.name!==i.child||!c.archived||c.status!=="done"||c.verification?.verdict!=="pass"||c.workspace.change_branch!==i.branch)throw new Error("Native Supervisor child archive state does not match the child");if(ih(i.worktree,o.archiveCommit,s.relative),ge(i.worktree,i.branch)!==o.archiveCommit)throw new Error("Native Supervisor child branch is not at its archive commit");let l=ce(i.integrationWorktree,["rev-list","--parents","-n","1",o.integrationCommit]).split(" ");if(!l.includes(o.archiveCommit)||!l.includes(i.integrationCommit))throw new Error("Native Supervisor integration did not receive the child archive commit");if(ge(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native Supervisor integration head moved after the child archive");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});var k$,sh,ch,A$=_(()=>{"use strict";_t();Ur();Tr();xe();Ym();Ia();Pi();Wr();ku();k$=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sh={id:"native-supervisor-builder-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.child.builder"||t.type!=="handoff")return{accepted:!1,reason:"Native SDK Supervisor Builder result lacks its project"};try{let i=M(e.state),o=await rc(e,n.projectRoot),a=t.input.activation,s=r.output;if(s?.requireIndependentReview!==void 0&&typeof s.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");if(i.phase!=="build"||!t.claim?.sessionId||!a||typeof a.child!="string"||!o.contract.children.some(({name:l})=>l===a.child)||Fe(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!he(a.worktree,Wt(n.projectRoot,i.name,a.child))||a.branch!==`comet/supervisor/${i.name}/${a.child}`||typeof a.baseCommit!="string"||!k$.test(a.baseCommit)||!s||typeof s.candidateCommit!="string"||!k$.test(s.candidateCommit))throw new Error("Native SDK Supervisor Builder result lacks a claimed child candidate");if(ye(a.worktree).currentBranch!==a.branch||ge(a.worktree,a.branch)!==s.candidateCommit)throw new Error("Native SDK Supervisor Builder candidate does not match its worktree");return Xn(s.checks??[]),ce(a.worktree,["merge-base","--is-ancestor",a.baseCommit,s.candidateCommit]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},ch={id:"native-supervisor-verifier-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.child.verifier"||t.type!=="handoff")return{accepted:!1,reason:"Native SDK Supervisor Verifier lacks its project"};try{let i=M(e.state),o=await rc(e,n.projectRoot),a=t.input.activation,s=r.output,c=s?.evidence;if(i.phase!=="build"||!t.claim?.sessionId||!a||typeof a.child!="string"||!o.contract.children.some(({name:f})=>f===a.child)||Fe(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!he(a.worktree,Wt(n.projectRoot,i.name,a.child))||typeof a.candidateCommit!="string"||typeof a.builderSessionId!="string"||tc(e,t)&&t.claim.sessionId===a.builderSessionId||!s||s.candidateCommit!==a.candidateCommit||!["pass","fail","blocked"].includes(String(s.verdict))||!c||typeof c.summary!="string"||!c.summary.trim()||!Array.isArray(c.checks))throw new Error("Native SDK Supervisor Verifier lacks a bound result or required independent session");let l=Xn(c.checks),u=Rm(c.acceptance);return Sm({verdict:s.verdict,acceptance:u},{acceptanceIds:Ao(o.contract,a.child).map(({id:f})=>f),requiredChecksPassed:l.every(f=>f.result==="passed")}),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function jb(e,t){let n=[...e.actions].reverse().find(i=>i.stepId===t&&i.status==="succeeded")?.outcome?.output;return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function b$(e,t,r){let n=jb(e,"supervisor.prepare"),i=wt(t,r.name),o=vt(r.name);if(!n||Fe(n,e)!==r.children_contract_ref||typeof n.integrationWorktree!="string"||!he(n.integrationWorktree,i)||n.integrationBranch!==o)throw new Error("Native SDK Supervisor cleanup lacks its integration workspace");let a=new Map;for(let s of Xt(e)){if(s.stepId!=="supervisor.child.prepare"||s.status!=="succeeded")continue;let c=s.outcome?.output;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Native SDK Supervisor cleanup has an invalid Child receipt");let l=c;if(typeof l.child!="string"||typeof l.worktree!="string"||Fe(l,e)!==r.children_contract_ref||!he(l.worktree,Wt(t,r.name,l.child))||l.branch!==`comet/supervisor/${r.name}/${l.child}`)throw new Error("Native SDK Supervisor cleanup has a mismatched Child receipt");a.set(l.child,{root:l.worktree,branch:l.branch})}if(a.size===0)throw new Error("Native SDK Supervisor cleanup has no prepared Children");return[...a.values(),{root:i,branch:o}]}function N$(e,t,r){let n=M(e.state),i=jb(e,"supervisor.parent.deliver");if(t.stepId!=="supervisor.cleanup"||n.status!=="done"||!n.archived||!n.children_contract_ref||!jb(e,"archive.finalize")||!i||typeof i.targetRoot!="string"||typeof i.targetBranch!="string"||typeof i.targetCommit!="string"||i.targetCommit!==i.integrationCommit||!$r(r).some(o=>he(o,i.targetRoot))||ye(i.targetRoot).currentBranch!==i.targetBranch||ge(i.targetRoot,i.targetBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor cleanup lacks the verified delivery");return{projectRoot:r,targetRoot:i.targetRoot,targetBranch:i.targetBranch,targetCommit:i.targetCommit,candidates:b$(e,r,n)}}function R$(e,t,r,n){Cu({projectRoot:t,targetRoot:wt(t,n.name),targetBranch:vt(n.name),targetCommit:r,candidates:b$(e,t,n)})}function o9(e){return{targetBranch:e.targetBranch,targetCommit:e.targetCommit}}var Db,lh,Bb=_(()=>{"use strict";Tr();_t();xe();_a();Wr();Db={id:"native-supervisor-cleanup",capabilities:[],supports(e){return e.stepId==="supervisor.cleanup"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor cleanup requires a bound Run and project");let n=N$(r,e,t.projectRoot);return await QA(n),{status:"succeeded",output:o9(n)}}},lh={id:"native-supervisor-cleanup-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Db.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor cleanup was not executed by Runtime"};try{let i=N$(e,t,n.projectRoot),o=r.output;if(!o||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||!Us(i))throw new Error("Native SDK Supervisor cleanup outcome does not match the worktrees");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function ic(e,t=e.outcome){let r=e.input.activation,i=t?.output?.candidateCommit??r?.integrationCommit;if(e.stepId!=="supervisor.parent.builder"||typeof r?.integrationCommit!="string"||!S$.test(r.integrationCommit)||typeof i!="string"||!S$.test(i))throw new Error("Native Supervisor parent candidate has no valid Git commit");return i}var S$,Wb=_(()=>{"use strict";S$=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});import E$ from"node:path";async function C$(e,t,r){let n=await Yr(e,r),i=M(e.state),o=t.input.activation,a=e.outputs["supervisor.prepare"]?.value,s=[...e.actions].reverse().find(v=>v.stepId==="supervisor.parent.builder"&&v.status==="succeeded"),c=s?ic(s):null,l=e.waits.some(v=>v.stepId==="verify.confirm"&&v.status==="resolved"&&v.decision?.choice==="approved"),u=e.workflow.version==="4"||e.actions.some(v=>v.stepId==="verify.revalidate"&&v.status==="succeeded"),f=vt(i.name),d=wt(r,i.name);if(i.phase!=="archive"||i.verification_result!=="pass"||!i.verification||!i.builder_handoff||!l||!u||!o||Fe(o,e)!==i.children_contract_ref||o.candidateId!==i.builder_handoff.candidate_id||o.integrationBranch!==f||typeof o.integrationWorktree!="string"||!he(o.integrationWorktree,d)||typeof o.integrationCommit!="string"||c!==o.integrationCommit||a?.targetBranch!==n.targetBranch||typeof a.targetCommit!="string"||ye(d).currentBranch!==f||ge(d,f)!==o.integrationCommit)throw new Error("Native SDK Supervisor delivery lacks the approved integration candidate");let p=$r(r).find(v=>ye(v).currentBranch===n.targetBranch);if(!p)throw new Error("Native SDK Supervisor target branch worktree is unavailable");let h=ge(p,n.targetBranch),g=[...Xt(e)].reverse().find(v=>v.stepId==="supervisor.child.integrate"&&v.status==="succeeded")?.outcome?.output?.targetCommit??a.targetCommit;if(h!==g&&h!==o.integrationCommit)throw new Error("Native SDK Supervisor target branch changed after Shape confirmation");return ce(d,["merge-base","--is-ancestor",a.targetCommit,o.integrationCommit]),R$(e,r,o.integrationCommit,i),{state:i,input:o,targetRoot:p,targetBranch:n.targetBranch,targetCommit:h,integrationBranch:f,integrationCommit:o.integrationCommit}}function a9(e){return{contractRef:e.state.children_contract_ref,integrationCommit:e.integrationCommit,targetBranch:e.targetBranch,targetRoot:e.targetRoot,targetCommit:e.integrationCommit}}function s9(e,t){try{let r=e.targetRoot;ce(r,["diff","--cached","--quiet",e.integrationCommit]),ce(r,["diff","--quiet"]);let n=ce(r,["diff","--name-only","--no-renames","-z",e.targetCommit,e.integrationCommit]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/"));return ce(r,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/")).some(o=>n.includes(o))?!1:Ro(r,[...t,...n])}catch{return!1}}async function c9(e,t,r,n){let i=await ke(n,t.input.artifactRootRef),o=he(e.targetRoot,n)?E$.relative(e.targetRoot,E$.join(i.changesDir,e.state.name)).replaceAll("\\","/"):null,a=[...o?[o]:[],".comet/current-change.json",".comet/runtime"];if(!Ro(e.targetRoot,a)&&!(e.targetCommit!==e.integrationCommit&&r.reconciliations.some(s=>s.attempt===r.attempt-1)&&s9(e,a)))throw new Error("Native SDK Supervisor target worktree has unrelated changes")}var Lb,uh,_$=_(()=>{"use strict";Bb();Tr();_t();Ur();Ye();xe();Wb();_a();Ia();Wr();Ru();Lb={id:"native-supervisor-parent-deliver",capabilities:[],supports(e){return e.stepId==="supervisor.parent.deliver"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor delivery requires a bound Run and project");let n=await C$(r,e,t.projectRoot);if(await c9(n,r,e,t.projectRoot),n.targetCommit!==n.integrationCommit&&ce(n.targetRoot,["merge","--ff-only",n.integrationBranch]),ge(n.targetRoot,n.targetBranch)!==n.integrationCommit)throw new Error("Native SDK Supervisor target did not receive the verified integration");return{status:"succeeded",output:a9(n)}}},uh={id:"native-supervisor-parent-deliver-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Lb.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor delivery was not executed by Runtime"};try{let i=await C$(e,t,n.projectRoot),o=r.output;if(!o||Fe(o,e)!==i.state.children_contract_ref||o.integrationCommit!==i.integrationCommit||o.targetBranch!==i.targetBranch||typeof o.targetRoot!="string"||!he(o.targetRoot,i.targetRoot)||o.targetCommit!==i.integrationCommit||ge(i.targetRoot,i.targetBranch)!==i.integrationCommit)throw new Error("Native SDK Supervisor delivery outcome does not match the target");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});async function x$(e,t,r){let n=await Yr(e,r),i=M(e.state),o=t.input.activation;if(i.phase!=="build"||!o||typeof o.child!="string"||!n.contract.children.some(({name:h})=>h===o.child)||Fe(o,e)!==i.children_contract_ref||typeof o.worktree!="string"||!he(o.worktree,Wt(r,i.name,o.child))||o.branch!==`comet/supervisor/${i.name}/${o.child}`||typeof o.candidateCommit!="string"||ge(o.worktree,o.branch)!==o.candidateCommit||typeof o.verifierActionId!="string"||typeof o.verifierSessionId!="string")throw new Error("Native SDK Supervisor integration lacks its verified Child candidate");let a=e.actions.find(h=>h.id===o.verifierActionId),s=a?.outcome?.output;if(a?.stepId!=="supervisor.child.verifier"||a.status!=="succeeded"||a.claim?.sessionId!==o.verifierSessionId||s?.verdict!=="pass"||s.candidateCommit!==o.candidateCommit)throw new Error("Native SDK Supervisor integration lacks a bound passing Verifier");let c=vt(i.name),l=wt(r,i.name);if(ye(l).currentBranch!==c)throw new Error("Native SDK Supervisor integration worktree changed");let u=e.actions.findIndex(h=>h.id===t.id),f=Xt(e).filter(h=>e.actions.indexOf(h)<u).reverse().find(h=>["supervisor.child.integrate","supervisor.child.integration-repair"].includes(h.stepId)&&h.status==="succeeded"),d=e.outputs["supervisor.prepare"]?.value,p=f?f.outcome?.output?.integrationCommit:d?.integrationCommit??d?.targetCommit;if(typeof p!="string")throw new Error("Native SDK Supervisor integration lacks its checked base commit");return{state:i,plan:n,input:o,integrationBranch:c,integrationWorktree:l,expectedBaseCommit:p}}function P$(e,t,r){let n=t;for(let i of e.actions){if(i.stepId!=="supervisor.child.archive"||i.status!=="succeeded"||!i.outcome)continue;let o=i.outcome.output;o&&typeof o.baseCommit=="string"&&typeof o.integrationCommit=="string"&&o.baseCommit===n&&(n=o.integrationCommit)}return n===r}async function I$(e,t,r){let n=await x$(e,t,r);if(e.actions.some(a=>a.id!==t.id&&a.stepId==="supervisor.child.integrate"&&["running","unknown"].includes(a.status)))throw new Error("Another Native SDK Supervisor integration Action is unresolved");if(!ba(n.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree must be clean before merge");let i=ge(n.integrationWorktree,n.integrationBranch);if(!i||i!==n.expectedBaseCommit&&!P$(e,n.expectedBaseCommit,i))throw new Error("Native SDK Supervisor integration branch changed after the prior check");let o=e.outputs["supervisor.prepare"]?.value;if(typeof o?.targetCommit!="string")throw new Error("Native SDK Supervisor integration lacks its original target binding");return ce(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,i]),ce(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,n.plan.targetCommit]),{...n,baseCommit:i}}var dh,Vb,fh,T$=_(()=>{"use strict";_t();Ur();Tr();xe();xe();_a();Ia();Wr();dh={id:"native-supervisor-integration-repair-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};try{if(!n?.projectRoot||!t.claim?.sessionId)throw new Error("Integration repair requires its actual Agent session");let i=await Yr(e,n.projectRoot),o=t.input.activation,a=r.output,s=e.actions.find(A=>A.id===o?.mergeActionId),c=s?.outcome?.output,l=e.actions.find(A=>A.id===o?.failedCheckActionId),u=e.actions.find(A=>A.id===o?.failedExtensionActionId),f=u?.input?.activation?.reviewSource,d=e.actions.find(A=>A.id===o?.repairActionId),p=d?.outcome?.output,h=d?.status==="succeeded"&&d.stepId==="supervisor.child.integration-repair"&&d.input.activation?.mergeActionId===s?.id?p?.integrationCommit:c?.integrationCommit,m=l?.status==="failed"&&l.stepId==="supervisor.child.integration-checks"&&l.input.activation?.mergeActionId===s?.id,g=u?.stepId.startsWith("native.extension.integration.")&&u.outcome&&u.outcome.output.verdict==="fail"&&f?.scope==="integration"&&(f.actionId===s?.id||f.actionId===o?.repairActionId),v=wt(n.projectRoot,i.state.name),w=vt(i.state.name);if(!o||!m&&!g||Fe(o,e)!==i.state.children_contract_ref||typeof o.child!="string"||!i.contract.children.some(A=>A.name===o.child)||s?.stepId!=="supervisor.child.integrate"||s.status!=="succeeded"||c?.child!==o.child||h!==o.integrationCommit||typeof o.integrationWorktree!="string"||!he(o.integrationWorktree,v)||o.integrationBranch!==w||!a||typeof a.summary!="string"||!a.summary.trim()||typeof a.integrationCommit!="string"||typeof o.integrationCommit!="string"||a.integrationCommit===o.integrationCommit||ye(v).currentBranch!==w||ge(v,w)!==a.integrationCommit||!ba(v))throw new Error("Integration repair does not match its original merge, failure and workspace");if(ce(v,["merge-base","--is-ancestor",o.integrationCommit,a.integrationCommit]),Xn(a.checks??[]).some(A=>A.result==="failed"))throw new Error("Resolve failed platform checks before submitting integration repair");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};Vb={id:"native-supervisor-integrate",capabilities:[],supports(e){return e.stepId==="supervisor.child.integrate"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor integration requires a bound Run and project");await I$(r,e,t.projectRoot)},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor integration requires a bound Run and project");let n=await I$(r,e,t.projectRoot),{baseCommit:i}=n;ce(n.integrationWorktree,["merge-base",n.plan.targetCommit,i])===n.plan.targetCommit||ce(n.integrationWorktree,["merge","--no-ff","--no-edit",n.plan.targetCommit]);let a=ge(n.integrationWorktree,n.integrationBranch);if(!a)throw new Error("Native SDK Supervisor target sync produced no commit");ce(n.integrationWorktree,["merge-base",n.input.candidateCommit,a])===n.input.candidateCommit||ce(n.integrationWorktree,["merge","--no-ff","--no-edit",n.input.candidateCommit]);let c=ge(n.integrationWorktree,n.integrationBranch);if(!c)throw new Error("Native SDK Supervisor merge produced no commit");return{status:"succeeded",output:{child:n.input.child,candidateCommit:n.input.candidateCommit,baseCommit:i,targetCommit:n.plan.targetCommit,targetMergeCommit:a,integrationCommit:c,integrationBranch:n.integrationBranch,integrationWorktree:n.integrationWorktree}}}},fh={id:"native-supervisor-integrate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Vb.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor integration was not executed by Runtime"};try{let i=await x$(e,t,n.projectRoot),o=r.output;if(!o||o.child!==i.input.child||o.candidateCommit!==i.input.candidateCommit||o.baseCommit!==i.expectedBaseCommit&&(typeof o.baseCommit!="string"||!P$(e,i.expectedBaseCommit,o.baseCommit))||typeof o.integrationCommit!="string"||o.integrationBranch!==i.integrationBranch||typeof o.integrationWorktree!="string"||!he(o.integrationWorktree,i.integrationWorktree)||ge(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native SDK Supervisor integration outcome does not match the worktree");if(!ba(i.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree changed after execution");let a=e.outputs["supervisor.prepare"]?.value,s=o.targetCommit??a.targetCommit,c=o.targetMergeCommit??o.baseCommit;if(s!==i.plan.targetCommit||typeof c!="string")throw new Error("Native SDK Supervisor target changed during integration");if(c!==o.baseCommit){let l=ce(i.integrationWorktree,["rev-list","--parents","-n","1",c]).split(" ");if(l.length!==3||l[0]!==c||l[1]!==o.baseCommit||l[2]!==s)throw new Error("Native SDK Supervisor target sync is not the expected merge commit")}if(ce(i.integrationWorktree,["merge-base","--is-ancestor",s,c]),o.integrationCommit===c)ce(i.integrationWorktree,["merge-base","--is-ancestor",o.candidateCommit,o.integrationCommit]);else{let l=ce(i.integrationWorktree,["rev-list","--parents","-n","1",o.integrationCommit]).split(" ");if(l.length!==3||l[0]!==o.integrationCommit||l[1]!==c||l[2]!==o.candidateCommit)throw new Error("Native SDK Supervisor integration is not the expected merge commit")}return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function Mb(e,t){let r=M(e.state),n=t.input.activation;if(r.phase!=="build"||r.archived||!r.children_contract_ref||t.stepId!=="supervisor.child.verifier"||t.status!=="failed"||t.outcome?.status!=="failed"||!t.claim||!n||Fe(n,e)!==r.children_contract_ref||typeof n.child!="string"||typeof n.candidateCommit!="string"||typeof n.builderSessionId!="string"||!Xt(e).some(i=>i.id===t.id))throw new Error("Native Child Verifier recovery requires a known failed current execution");return{...n,failedVerifierActionId:t.id}}function O$(e,t){return e.actions.find(r=>["supervisor.child.checks","supervisor.child.integration-checks"].includes(r.stepId)&&r.status==="failed"&&r.outcome?.status==="failed"&&r.executionOrigin&&["1","2","3"].includes(r.executionOrigin.workflow.version)&&e.actionContexts[r.id].sequence===t.results[r.stepId]?.sequence)}var $$=_(()=>{"use strict";et();Tr();xe();_a();Ia()});var M$={};Nh(M$,{assertNativeSdkStartAvailable:()=>Gb,collectNativeSdkShapeProposal:()=>u9,defineNativeWorkflowApplication:()=>oc,nativeSdkApplicationForRun:()=>Kb,registerNativeSdkStartOwner:()=>l9});import L$ from"node:path";function Kb(e,t=oc()){if(e&&(e.workflow.version!=="4"||!Hm(t.workflow,e)))throw new Error("Native Run 尚未完成业务数据适配,请通过原 change 的当前入口继续;原记录与批准保留。");return t}async function Gb(e){let t=await ke(e.projectRoot,e.artifactRootRef,{change:e.name});if((await oe(e.projectRoot,L$.relative(e.projectRoot,Jr(t,e.name)),{label:"Native legacy change state",expected:"file"})).exists)throw new Error(`Native change ${e.name} already has legacy Runtime state`)}async function l9(e){let t=await ke(e.projectRoot,e.artifactRootRef,{change:e.name});await He(t,async()=>{await Gb(e),await lo(e.projectRoot,{schema:Tn,workflow:"native",change:e.name,format:"sdk",application:"native",runId:e.name})})}function V$(e){return e.phase==="shape"&&e.status==="active"&&e.loop.next_action==="prepare-shape-confirmation"?3:e.document_constraints_version??2}async function u9(e){let t=M({...e.state,document_constraints_version:V$(e.state)});if(t.phase!=="shape"||!["active","await-user"].includes(t.status))throw new Error("Native Shape proposal requires an active or pending Shape");let r=L$.join(e.paths.changesDir,t.name),n=await Dm({paths:e.paths,state:t});e.materializeTargets===!0&&t.status==="active"&&t.shape_confirmation_hash===void 0&&n.some(s=>s.delta_source)&&await He(e.paths,()=>rb({paths:e.paths,state:t,specChanges:n}));let i=t.status==="active"&&t.loop.next_action==="prepare-shape-confirmation"&&t.shape_confirmation_hash===void 0;await ab({paths:e.paths,state:i?{...t,spec_changes:n}:t,specChanges:n});let o=e.acceptance===void 0?(await Bm({paths:e.paths,state:t,specChanges:n})).acceptance:e.acceptance.map((s,c)=>{let l=["brief.md",...n.flatMap(f=>f.source?[f.source]:[])];if(!s||typeof s.source!="string"||typeof s.text!="string"||!s.text.trim())throw new Error("Native acceptance requires a readable source reference and nonempty text");let u=ao(s.source,"Native acceptance source");if(!l.includes(u))throw new Error("Native acceptance must reference this change brief or a declared specification");return{id:`A${c+1}`,source:u,text:s.text.trim()}});if(!o.length)throw new Error("Native Shape requires at least one acceptance criterion");let a=await Si({changeDir:r,acceptanceIds:o.map(({id:s})=>s),validation:Ri({...t,acceptance:o})});return{specChanges:n,acceptance:o.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})),children:a?{contract:a.contract}:null}}function qb(e){let t={...e,status:"active",state_version:e.state_version+1,loop:{...e.loop,stage:"shape",next_action:"prepare-shape-confirmation"},acceptance:[]};return delete t.shape_confirmation_hash,delete t.children_contract_ref,delete t.children_contract,delete t.coordination_mode,M(t)}function d9(e,t){let r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:t,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:zl(),loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};return delete r.shape_confirmation_hash,delete r.children_contract_ref,delete r.children_contract,delete r.coordination_mode,delete r.verifier_action,M(r)}function j$(e,t){let n={...Hr(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Et(t),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};return delete n.shape_confirmation_hash,delete n.children_contract_ref,delete n.children_contract,delete n.coordination_mode,delete n.verifier_action,M(n)}function Pa(e){if(e===null||typeof e!="object")throw new Error("Native Shape proposal missing");return e}function D$(e,t,r=!1){let n=e.input.activation,i=t;if(!n||!e.claim?.sessionId||!r&&!i?.integrationChecks)throw new Error("Native SDK Supervisor Verifier lacks its Child activation");return{...n,verifierActionId:e.id,verifierSessionId:e.claim.sessionId,...r?{}:{integrationChecks:i.integrationChecks}}}function f9(e){let t=Xt(e),r=new Set(t.filter(n=>n.stepId==="supervisor.child.integrate").map(n=>n.input.activation?.child));return t.find(n=>n.stepId==="supervisor.child.verifier"&&n.status==="succeeded"&&n.outcome?.output?.verdict==="pass"&&!r.has(n.input.activation?.child))??null}function Fb(e,t,r){let n=t.input.activation,o=Xt(e).find(a=>a.stepId==="supervisor.child.builder"&&a.status==="succeeded"&&a.claim?.sessionId===n?.builderSessionId&&a.outcome?.output?.candidateCommit===n?.candidateCommit)?.input?.activation;if(!o||o.child!==n?.child)throw new Error("Native SDK Supervisor repair lacks the failed Child Builder");return{...o,[r]:t.id}}function ph(e,t){let r=[...Xt(e)].reverse().find(i=>i.stepId==="supervisor.parent.builder"&&i.status==="succeeded"),n=r?.input?.activation;if(!r||!n)throw new Error("Native Supervisor parent repair lacks the prior integration candidate");return{...n,integrationCommit:ic(r),...t}}function B$(e,t,r){let n=r.output,i=t.claim?.sessionId;if(["3","4"].includes(e.workflow.version)&&n?.requireIndependentReview!==void 0&&typeof n.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");let o=M(e.state);if(o.phase!=="build"||!["build.builder","supervisor.parent.builder"].includes(t.stepId)||t.type!=="handoff"||!i||!n||typeof n.summary!="string"||!n.summary.trim()||n.addressedAcceptanceIds!==void 0&&(!Array.isArray(n.addressedAcceptanceIds)||n.addressedAcceptanceIds.some(l=>typeof l!="string"))||!Array.isArray(n.checks)||!Array.isArray(n.knownLimits)||n.knownLimits.some(l=>typeof l!="string"))throw new Error("Native Builder result needs a claimed host session and a complete candidate");let a=n.checks,s=n.review;if(s!=null&&(s.status!=="passed"||typeof s.summary!="string"||typeof s.reviewerExecutionRef!="string"))throw new Error("Native Builder review is invalid");let c=BA().captureExecutionIdentity({identityProvider:wr,executionRef:i});return GA({state:o,requireAcceptanceReview:!["3","4"].includes(e.workflow.version),input:{identity:c,summary:n.summary,addressedAcceptanceIds:n.addressedAcceptanceIds??[],acceptanceReview:n.acceptanceReview===void 0?void 0:n.acceptanceReview,checks:a,knownLimits:n.knownLimits,review:s?{status:"passed",summary:s.summary,reviewerExecutionRef:s.reviewerExecutionRef}:null,candidateId:t.id,now:typeof n.submittedAt=="string"&&!Number.isNaN(Date.parse(n.submittedAt))?new Date(n.submittedAt):new Date}})}function p9(e,t,r){let n=r.output,i=t.claim?.sessionId,o=M(e.state),a=o.builder_handoff;if(o.phase!=="verify"||o.status!=="active"||o.loop.next_action!=="await-verifier-result"||t.stepId!=="verify.verifier"||t.type!=="handoff"||r.status!=="succeeded"||!a||!i||tc(e,t)&&i===a.builder_execution_ref||!n||n.candidateId!==a.candidate_id||n.verifierExecutionRef!==i)throw new Error(`Native Verifier result is not bound to an independent current execution; candidateId must match the current candidate and verifierExecutionRef must equal the claimed sessionId ${i??"(missing)"}; use the current outcomeRequest template`);let c=e.input.maxVerifyFailures??El;if(!Number.isSafeInteger(c)||c<1)throw new Error("Native Verify failure budget is invalid");let l=BA(),u=l.captureExecutionIdentity({identityProvider:wr,executionRef:i}),f=YA({state:o,requireIndependentSession:!1,envelope:l.envelopeVerifierResponse({candidateId:a.candidate_id,identity:u,payload:n.response}),reportedChecks:Xn(n.checks??[]),maxVerifyFailures:c});if(typeof e.input.task=="string"&&f.response.result.verdict==="pass"&&f.response.result.requestReview?.result!=="aligned")throw new Error("Native pass requires requestReview aligned with the original task and authorized changes; report fail or blocked for conflicts or unresolved requirements");return{state:f.state}}function m9(e,t,r){let n=r.output;if(r.status!=="failed"||t.stepId!=="verify.verifier"||t.type!=="handoff"||!t.claim?.sessionId||!n||typeof n.summary!="string"||!n.summary.trim())throw new Error("Native Verifier execution failure needs the original claimed session and summary");let i=M(e.state);return eb({state:i,summary:n.summary})}function oc(e="4"){if(e!=="4")throw new Error("旧 Native 受管检查定义不再支持;普通检查请使用 Agent 平台工具。");return g9()}function W$(e,t){let r=[...e.actions].reverse().find(o=>o.stepId==="shape.prepare"&&o.status==="succeeded"),n=Pa(r.outcome.output),i=zA({state:t,acceptance:t.acceptance.map(({id:o,source:a,text:s})=>({id:o,source:a,text:s}))});return n.children?{state:M({...i,children_contract_ref:r.id,children_contract:n.children.contract}),next:["supervisor.prepare"]}:{state:i,next:["build.builder"]}}function h9(e,t){let r=XA(t);if(!r.children_contract_ref)return{state:r,next:["archive.prepare"]};let n=[...e.actions].reverse().find(o=>o.stepId==="supervisor.parent.builder"&&o.status==="succeeded"),i=n?.input?.activation;if(!n||!i)throw new Error("Native Supervisor delivery lacks its parent integration candidate");return{state:r,next:[{stepId:"supervisor.parent.deliver",input:{...i,integrationCommit:ic(n),candidateId:r.builder_handoff?.candidate_id??null}}]}}function g9(){return{workflow:{id:"comet-native",version:"4",entry:"shape.prepare",commands:{"revise-implementation":{stepId:"repair.implementation",validator:{id:Xm.id,version:Xm.version}},"revise-requirements":{stepId:"shape.revise",validator:{id:eh.id,version:eh.version}},"remove-capability":{stepId:"shape.remove",validator:{id:Km.id,version:Km.version}},"disassociate-capability":{stepId:"shape.disassociate",validator:{id:Um.id,version:Um.version}}},stateSchema:{type:"object",required:["schema","name","phase","status","state_version","loop","acceptance"],properties:{schema:{const:"comet.native.v4"},name:{type:"string"},phase:{enum:["shape","build","verify","archive"]},status:{enum:["active","await-user","blocked","done"]},state_version:{type:"integer",minimum:1},loop:{type:"object"},acceptance:{type:"array"}}},transitionHandler:{id:"comet-native-transition",version:"1"},stateValidator:{id:zb.id,version:zb.version},steps:{"repair.implementation":{type:"call_tool",ref:"native-revise-implementation",validator:{id:Zm.id,version:Zm.version}},"shape.revise":{type:"call_tool",ref:"native-revise-requirements",validator:{id:th.id,version:th.version}},"shape.remove":{type:"call_tool",ref:"native-remove",validator:{id:Gm.id,version:Gm.version}},"shape.disassociate":{type:"call_tool",ref:"native-disassociate",validator:{id:Jm.id,version:Jm.version}},"shape.prepare":{type:"call_tool",ref:"native-shape-prepare",validator:{id:Hb.id,version:Hb.version}},"shape.confirm":{type:"ask_user",proposalFrom:"shape.prepare",choices:["approved","rejected"]},"supervisor.shape.confirm":{type:"ask_user",proposalFrom:"shape.prepare",choices:["multi-session","single-session","rejected"]},"build.builder":{type:"handoff",ref:"native-builder",validator:{id:Qb.id,version:Qb.version}},"build.resume":{type:"ask_user",proposalFrom:"build.builder",choices:["continue"]},"supervisor.prepare":{type:"call_tool",ref:"native-supervisor-prepare",validator:{id:rh.id,version:rh.version}},"supervisor.child.prepare":{type:"call_tool",ref:"native-supervisor-child-prepare",validator:{id:nh.id,version:nh.version}},"supervisor.child.builder":{type:"handoff",ref:"native-supervisor-builder",validator:{id:sh.id,version:sh.version}},"supervisor.child.resume":{type:"ask_user",proposalFrom:"supervisor.child.builder",choices:["continue"]},"supervisor.child.verifier":{type:"handoff",ref:"native-supervisor-verifier",validator:{id:ch.id,version:ch.version}},"supervisor.child.verifier-retry":{type:"ask_user",proposalFrom:"supervisor.child.verifier",choices:["retry","repair"]},"supervisor.child.integrate":{type:"call_tool",ref:"native-supervisor-integrate",validator:{id:fh.id,version:fh.version}},"supervisor.child.integration-repair":{type:"handoff",ref:"native-supervisor-integration-repair",validator:{id:dh.id,version:dh.version}},"supervisor.child.integration-resume":{type:"ask_user",proposalFrom:"supervisor.child.integration-repair",choices:["continue"]},"supervisor.child.archive":{type:"call_tool",ref:"native-supervisor-child-archive",validator:{id:ah.id,version:ah.version}},"supervisor.parent.builder":{type:"handoff",ref:"native-supervisor-parent-builder",validator:{id:Ub.id,version:Ub.version}},"supervisor.parent.resume":{type:"ask_user",proposalFrom:"supervisor.parent.builder",choices:["continue"]},"supervisor.parent.deliver":{type:"call_tool",ref:"native-supervisor-parent-deliver",validator:{id:uh.id,version:uh.version}},"supervisor.cleanup":{type:"call_tool",ref:"native-supervisor-cleanup",validator:{id:lh.id,version:lh.version}},"verify.verifier":{type:"handoff",ref:"native-verifier",validator:{id:Jb.id,version:Jb.version}},"verify.retry":{type:"ask_user",proposalFrom:"verify.verifier",choices:["retry"]},"verify.stop":{type:"ask_user",proposalFrom:"verify.verifier",choices:["retry","repair"]},"verify.confirm":{type:"ask_user",proposalFrom:"verify.verifier",choices:["approved","rejected","reverify"]},"archive.prepare":{type:"call_tool",ref:"native-archive-preflight",retry:"idempotent",validator:{id:Mm.id,version:Mm.version}},"archive.execute":{type:"call_tool",ref:"native-archive",validator:{id:qm.id,version:qm.version}},"archive.finalize":{type:"call_tool",ref:"native-archive-finalize",validator:{id:Fm.id,version:Fm.version}}},transitions:[{from:"repair.implementation",to:"archive.prepare"},{from:"repair.implementation",to:"archive.execute"},{from:"repair.implementation",to:"shape.prepare"},{from:"repair.implementation",to:"build.builder"},{from:"repair.implementation",to:"supervisor.parent.builder"},{from:"shape.revise",to:"shape.prepare"},{from:"shape.remove",to:"shape.prepare"},{from:"shape.disassociate",to:"shape.prepare"},{from:"shape.prepare",to:"shape.confirm"},{from:"shape.prepare",to:"supervisor.shape.confirm"},{from:"shape.confirm",to:"shape.prepare",on:"rejected"},{from:"supervisor.shape.confirm",to:"shape.prepare",on:"rejected"},{from:"supervisor.prepare",to:"supervisor.child.prepare"},{from:"supervisor.child.prepare",to:"supervisor.child.builder"},{from:"supervisor.child.builder",to:"supervisor.child.resume",on:"failed"},{from:"supervisor.child.resume",to:"supervisor.child.builder",on:"continue"},{from:"supervisor.child.verifier",to:"supervisor.child.verifier-retry",on:"failed"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.verifier",on:"retry"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.builder",on:"repair"},{from:"supervisor.child.verifier",to:"supervisor.child.integrate"},{from:"supervisor.child.verifier",to:"supervisor.child.builder"},{from:"supervisor.child.archive",to:"supervisor.child.integrate"},{from:"supervisor.child.archive",to:"supervisor.child.prepare"},{from:"supervisor.child.archive",to:"supervisor.parent.builder"},{from:"supervisor.parent.builder",to:"supervisor.parent.resume",on:"failed"},{from:"supervisor.parent.resume",to:"supervisor.parent.builder",on:"continue"},{from:"build.builder",to:"build.resume",on:"failed"},{from:"build.resume",to:"build.builder",on:"continue"},{from:"verify.verifier",to:"verify.confirm"},{from:"verify.verifier",to:"build.builder"},{from:"verify.verifier",to:"supervisor.parent.builder"},{from:"verify.verifier",to:"verify.verifier",on:"failed"},{from:"verify.verifier",to:"verify.retry",on:"failed"},{from:"verify.retry",to:"verify.verifier",on:"retry"},{from:"verify.verifier",to:"verify.stop"},{from:"verify.stop",to:"verify.verifier",on:"retry"},{from:"verify.stop",to:"build.builder",on:"repair"},{from:"verify.stop",to:"supervisor.parent.builder",on:"repair"},{from:"verify.confirm",to:"archive.prepare",on:"approved"},{from:"verify.confirm",to:"build.builder",on:"rejected"},{from:"verify.confirm",to:"supervisor.parent.builder",on:"rejected"},{from:"supervisor.parent.deliver",to:"archive.prepare"},{from:"archive.prepare",to:"archive.execute"},{from:"archive.prepare",to:"verify.stop",on:"failed"},{from:"archive.execute",to:"verify.stop",on:"failed"},{from:"archive.execute",to:"archive.finalize"},{from:"archive.finalize",to:"supervisor.cleanup"},{from:"verify.confirm",to:"verify.verifier",on:"reverify"},{from:"build.builder",to:"verify.verifier"},{from:"supervisor.parent.builder",to:"verify.verifier"},{from:"supervisor.child.builder",to:"supervisor.child.verifier"},{from:"supervisor.child.integrate",to:"supervisor.child.archive"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.integration-repair",on:"repair"},{from:"supervisor.child.integration-repair",to:"supervisor.child.archive"},{from:"supervisor.child.integration-repair",to:"supervisor.child.integration-resume",on:"failed"},{from:"supervisor.child.integration-resume",to:"supervisor.child.integration-repair",on:"continue"},{from:"shape.confirm",to:"build.builder",on:"approved"},{from:"shape.confirm",to:"supervisor.prepare",on:"approved"},{from:"supervisor.shape.confirm",to:"supervisor.prepare",on:"multi-session"},{from:"supervisor.shape.confirm",to:"supervisor.prepare",on:"single-session"},{from:"verify.confirm",to:"supervisor.parent.deliver",on:"approved"}]},transitionHandler:{id:"comet-native-transition",version:"1",apply({run:t,event:r}){let n=M(t.state);if(r.kind==="action-outcome"&&r.stepId==="repair.implementation"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output;if(!i.drift)return{state:n,next:[i.archiveStep]};if(i.requirementsChanged)return{state:j$(n,i.reason),next:["shape.prepare"]};let o=Ys({state:n,reason:i.reason}),a=[...t.actions].reverse().find(s=>s.stepId==="verify.verifier"&&s.status==="succeeded");if(!a)throw new Error("Native implementation revision has no original Verifier result");return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:ph(t,{failedVerifierActionId:a.id})}]:[{stepId:"build.builder",input:{repairContext:yu(o,t)}}]}}if(r.kind==="action-outcome"&&r.stepId==="shape.revise"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output.reason;return{state:j$(n,i),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.remove"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output.capability,o=[...n.spec_changes.filter(a=>a.capability!==i),{capability:i,operation:"remove",source:null}].sort((a,s)=>a.capability.localeCompare(s.capability,"en"));return{state:d9(n,o),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.disassociate")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:qb(n),next:["shape.prepare"]};if(r.kind==="action-outcome"&&r.stepId==="shape.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Pa(r.outcome.output);return{state:KA({state:{...n,document_constraints_version:V$(n),spec_changes:i.specChanges},acceptance:i.acceptance}),next:i.children&&i.children.contract.children.length>=2?["supervisor.shape.confirm"]:["shape.confirm"]}}if(r.kind==="wait-resolved"&&r.stepId==="shape.confirm")return r.choice==="approved"?W$(t,n):{state:qb(n),next:["shape.prepare"]};if(r.kind==="wait-resolved"&&r.stepId==="supervisor.shape.confirm"){if(r.choice==="rejected")return{state:qb(n),next:["shape.prepare"]};let i=Pa(t.outputs["shape.prepare"]?.value);if(!i.children||i.children.contract.children.length<2)throw new Error("Native Supervisor approval lacks its child plan");let o=r.choice,a=M({...n,coordination_mode:o});return W$(t,a)}if(r.kind==="action-outcome"&&r.stepId==="supervisor.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Pa(t.actions.find(s=>s.id===n.children_contract_ref)?.outcome?.output);if(!i.children||!n.children_contract_ref)throw new Error("Native Supervisor preparation lacks the confirmed child plan");let o=r.outcome.output,a=_b({contract:i.children.contract,integrated:[],active:[],maxParallel:n.coordination_mode==="single-session"?1:o.maxParallelChildren??2});return{state:n,next:a.map(s=>({stepId:"supervisor.child.prepare",input:{child:s,contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,targetCommit:o.integrationCommit??o.targetCommit}}))}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output;return{state:n,next:[{stepId:"supervisor.child.builder",input:i}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.builder"){if(r.outcome.status!=="succeeded"){let s=t.actions.find(l=>l.id===r.outcome.actionId),c=s?.input?.activation;if(!c||!s)throw new Error("Native SDK Supervisor Child Builder failure lacks its Action");return{state:n,next:[{stepId:"supervisor.child.resume",input:{...c,failedBuilderActionId:s.id}}]}}let i=t.actions.find(s=>s.id===r.outcome.actionId);if(!i?.claim?.sessionId)throw new Error("Native SDK Supervisor Builder Action lacks its host session");let o=i.input.activation,a=Pa(t.actions.find(s=>s.id===n.children_contract_ref)?.outcome?.output);if(!o||!a.children||typeof o.child!="string")throw new Error("Native SDK Supervisor Builder lacks its confirmed child plan");return{state:n,next:[{stepId:"supervisor.child.verifier",input:{...o,candidateCommit:r.outcome.output.candidateCommit,builderSessionId:i.claim.sessionId,acceptance:Ao(a.children.contract,o.child),checks:r.outcome.output.checks??[]}}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.resume"){let o=t.waits.find(a=>a.stepId==="supervisor.child.resume"&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash)?.proposal?.activation;if(!o||typeof o.failedBuilderActionId!="string"||!t.actions.some(a=>a.id===o.failedBuilderActionId&&a.stepId==="supervisor.child.builder"&&a.status==="failed"))throw new Error("Native SDK Supervisor Child continuation lacks its failed Action");return{state:n,next:[{stepId:"supervisor.child.builder",input:o}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.verifier-retry"){let i=t.waits.find(c=>c.stepId===r.stepId&&c.decision?.id===r.decisionId&&c.proposalHash===r.proposalHash),o=i?.proposal?.activation,a=i&&O$(t,i);if(a){if(r.choice!=="repair")throw new Error("旧失败提案只允许原 repair 决定");let c=a.input.activation;return{state:n,next:[{stepId:a.stepId==="supervisor.child.integration-checks"?"supervisor.child.integration-repair":"supervisor.child.builder",input:a.stepId==="supervisor.child.integration-checks"?{...c,contractRef:n.children_contract_ref,failedCheckActionId:a.id}:Fb(t,a,"failedCheckActionId")}]}}let s=t.actions.find(c=>c.id===o?.failedVerifierActionId);if(!s||!o||$(Mb(t,s))!==$(o))throw new Error("Native Child Verifier recovery lacks its original failed Action");return{state:n,next:[{stepId:r.choice==="retry"?"supervisor.child.verifier":"supervisor.child.builder",input:r.choice==="retry"?o:Fb(t,s,"failedVerifierActionId")}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.verifier"){if(r.outcome.status!=="succeeded"){let a=t.actions.find(s=>s.id===r.outcome.actionId);if(!a)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.verifier-retry",input:Mb(t,a)}]}}let i=r.outcome.output;if(i.verdict==="fail"||i.verdict==="blocked"){let a=t.actions.find(s=>s.id===r.outcome.actionId);if(!a)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.builder",input:Fb(t,a,"failedVerifierActionId")}]}}if(i.verdict!=="pass")return{state:n,next:[]};if(t.actions.some(a=>["supervisor.child.integrate","supervisor.child.integration-repair"].includes(a.stepId)&&["pending","running","unknown"].includes(a.status)))return{state:n,next:[]};let o=t.actions.find(a=>a.id===r.outcome.actionId);if(!o)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.integrate",input:D$(o,r.outcome.output,t.workflow.version==="4")}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.integrate"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let o=t.actions.find(s=>s.id===r.outcome.actionId)?.input?.activation,a=r.outcome.output;if(!o)throw new Error("Native SDK Supervisor integration lacks its Child activation");return{state:n,next:[{stepId:"supervisor.child.archive",input:{child:o.child,candidateCommit:o.candidateCommit,integrationCommit:a.integrationCommit,mergeActionId:r.outcome.actionId,contractRef:n.children_contract_ref}}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.integration-repair"){let i=t.actions.find(a=>a.id===r.outcome.actionId),o=i.input.activation;return{state:n,next:[{stepId:r.outcome.status==="failed"?"supervisor.child.integration-resume":"supervisor.child.archive",input:r.outcome.status==="failed"?{...o,failedBuilderActionId:i.id}:{...o,integrationCommit:r.outcome.output.integrationCommit,repairActionId:i.id}}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.integration-resume"){let o=t.waits.find(a=>a.stepId===r.stepId&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash).proposal.activation;if(!t.actions.some(a=>a.id===(o.failedRepairActionId??o.failedBuilderActionId)&&a.stepId==="supervisor.child.integration-repair"&&a.status==="failed"))throw new Error("Integration continuation lacks its original failed repair");return{state:n,next:[{stepId:"supervisor.child.integration-repair",input:o}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.archive"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Pa(t.actions.find(d=>d.id===n.children_contract_ref)?.outcome?.output),o=t.outputs["supervisor.prepare"]?.value;if(!i.children||!n.children_contract_ref||!o)throw new Error("Native SDK Supervisor continuation lacks its confirmed plan");let a=new Set(Xt(t).filter(d=>d.stepId==="supervisor.child.archive"&&d.status==="succeeded").map(d=>d.input.activation.child)),s=t.actions.find(d=>d.id===r.outcome.actionId);if(!s)throw new Error("Native SDK Supervisor archive Action missing");a.add(s.input.activation.child);let c=f9(t);if(c)return{state:n,next:[{stepId:"supervisor.child.integrate",input:D$(c,c.outcome?.output,t.workflow.version==="4")}]};let l=new Set(Xt(t).filter(d=>d.stepId==="supervisor.child.prepare").map(d=>d.input.activation.child).filter(d=>!a.has(d))),u=_b({contract:i.children.contract,integrated:[...a],active:[...l],maxParallel:n.coordination_mode==="single-session"?1:r.outcome.output.maxParallelChildren??2}),f=r.outcome.output;return a.size===i.children.contract.children.length?{state:n,next:[{stepId:"supervisor.parent.builder",input:{contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,integrationCommit:f.integrationCommit,acceptance:n.acceptance.map(({id:d,source:p,text:h})=>({id:d,source:p,text:h}))}}]}:{state:n,next:u.map(d=>({stepId:"supervisor.child.prepare",input:{child:d,contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,targetCommit:f.integrationCommit}}))}}if(r.kind==="action-outcome"&&r.stepId==="build.builder"){if(r.outcome.status==="failed")return{state:n,next:[{stepId:"build.resume",input:{failedBuilderActionId:r.outcome.actionId}}]};let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Builder Action is missing from its Run");let o=B$(t,i,r.outcome);return{state:ri(o),next:["verify.verifier"]}}if(r.kind==="wait-resolved"&&r.stepId==="build.resume"){let a=t.waits.find(s=>s.stepId==="build.resume"&&s.decision?.id===r.decisionId&&s.proposalHash===r.proposalHash)?.proposal?.activation?.failedBuilderActionId;if(typeof a!="string"||!t.actions.some(s=>s.id===a&&s.stepId==="build.builder"&&s.status==="failed"))throw new Error("Native SDK Builder continuation lacks its failed Action");return{state:n,next:[{stepId:"build.builder",input:{failedBuilderActionId:a}}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.parent.builder"){if(r.outcome.status==="failed"){let a=t.actions.find(c=>c.id===r.outcome.actionId),s=a?.input?.activation;if(!s||!a)throw new Error("Native SDK Supervisor parent Builder failure lacks its Action");return{state:n,next:[{stepId:"supervisor.parent.resume",input:{...s,failedBuilderActionId:a.id}}]}}let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Supervisor parent Builder Action is missing");let o=B$(t,i,r.outcome);return{state:ri(o),next:["verify.verifier"]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.parent.resume"){let o=t.waits.find(a=>a.stepId==="supervisor.parent.resume"&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash)?.proposal?.activation;if(!o||typeof o.failedBuilderActionId!="string"||!t.actions.some(a=>a.id===o.failedBuilderActionId&&a.stepId==="supervisor.parent.builder"&&a.status==="failed"))throw new Error("Native SDK Supervisor parent continuation lacks its failed Action");return{state:n,next:[{stepId:"supervisor.parent.builder",input:o}]}}if(r.kind==="action-outcome"&&r.stepId==="verify.verifier"){let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Verifier Action is missing from its Run");if(r.outcome.status==="failed"){let a=m9(t,i,r.outcome);return a.status==="blocked"?{state:a,next:["verify.retry"]}:{state:ri(a),next:["verify.verifier"]}}let o=p9(t,i,r.outcome);return{state:o.state,next:o.state.verification_result==="pass"?[{stepId:"verify.confirm",input:{report:Tm(o.state,t.input.artifactRootRef)}}]:o.state.phase==="build"?n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:ph(t,{failedVerifierActionId:i.id})}]:[{stepId:"build.builder",input:{repairContext:yu(o.state,t)}}]:["verify.stop"]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.stop"){let i=t.waits.find(c=>c.stepId===r.stepId&&c.decision?.id===r.decisionId&&c.proposalHash===r.proposalHash);if(!i||!cb(n,i,t).some(({choice:c})=>c===r.choice))throw new Error("Native Verify stop decision does not match the current Run");if(r.choice==="retry")return{state:ri(ZA(n,{reason:i.decision?.reason})),next:[{stepId:"verify.verifier",input:{recoveryWaitId:i.id,...i.decision?.reason===void 0?{}:{reason:i.decision.reason}}}]};let o=Ys({state:n,reason:"The user chose to revise the implementation after Verify stopped."}),a=[...t.actions].reverse().find(c=>c.stepId==="verify.verifier"&&c.status==="succeeded"),s=a?void 0:t.actions.find(c=>c.stepId==="verify.checks"&&c.status==="failed"&&t.actionContexts[c.id].sequence===i.results["verify.checks"]?.sequence);if(!a&&!s)throw new Error("Native Verify stop has no original failed result");return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:ph(t,a?{failedVerifierActionId:a.id}:{failedCheckActionId:s.id})}]:[{stepId:"build.builder",input:{repairContext:yu(o,t)}}]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.retry")return{state:ri(tb(n)),next:["verify.verifier"]};if(r.kind==="wait-resolved"&&r.stepId==="verify.confirm"){let i=t.waits.find(a=>a.stepId===r.stepId&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash);if(!i||!cb(n,i,t).some(({choice:a})=>a===r.choice))throw new Error("Native Verify confirmation does not match an executable current decision");if(r.choice==="reverify"){let a=M({...n,status:"active",state_version:n.state_version+1,verification:null,verification_result:"pending",verification_report:null,acceptance:n.acceptance.map(s=>({...s,result:"pending",reason:null})),loop:{...n.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}});return{state:ri(a),next:["verify.verifier"]}}if(r.choice==="approved")return h9(t,n);let o=Ys({state:n,reason:"The user rejected the Skill-coordinated Verifier pass."});return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:ph(t,{rejectedDecisionId:r.decisionId})}]:[{stepId:"build.builder",input:{repairContext:yu(o,t)}}]}}if(r.kind==="action-outcome"&&["archive.prepare","archive.execute"].includes(r.stepId)&&r.outcome.status==="failed"&&r.outcome.output.reason==="candidate-drift")return{state:M({...n,phase:"verify",status:"await-user",state_version:n.state_version+1,verification:null,verification_result:"pending",verification_report:null,acceptance:n.acceptance.map(o=>({...o,result:"pending",reason:null})),blockers:[{owner:"user",reason:Et("归档候选已变化;由 Agent 核对实际修改,选择修订实现或重新验收。"),acceptance_ids:[],resolution_action:"await-user"}],loop:{...n.loop,stage:"await-user",next_action:"await-user"}}),next:["verify.stop"]};if(r.kind==="action-outcome"&&r.stepId==="supervisor.parent.deliver")return{state:n,next:r.outcome.status==="succeeded"?["archive.prepare"]:[]};if(r.kind==="action-outcome"&&r.stepId==="archive.prepare")return{state:n,next:r.outcome.status==="succeeded"?["archive.execute"]:[]};if(r.kind==="action-outcome"&&r.stepId==="archive.execute")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:M({...n,status:"done",archived:!0,state_version:n.state_version+1,blockers:[],loop:{...n.loop,stage:"done",next_action:null}}),next:["archive.finalize"]};if(r.kind==="action-outcome"&&r.stepId==="archive.finalize")return{state:n,next:r.outcome.status==="succeeded"&&n.children_contract_ref?["supervisor.cleanup"]:[]};if(r.kind==="action-outcome"&&r.stepId==="supervisor.cleanup")return{state:n,next:[]};throw new Error(`Native SDK does not handle ${r.stepId} yet`)}},validators:[Zm,th,Gm,Jm,Hb,Qb,Jb,Mm,qm,Fm,rh,nh,sh,ch,fh,dh,Ub,uh,lh,ah],stateValidators:[zb],commandValidators:[Xm,eh,Km,Um],executors:[Cb,p$,u$,c$,yb,kb,Ab,xb,Pb,Vb,Lb,oh,Db]}}var Hb,Qb,Ub,Jb,zb,Du=_(()=>{"use strict";ct();Tr();Ye();Yt();G0();_t();Ur();et();pr();vi();Tr();Js();It();Sa();Bt();Eo();xe();Ni();$p();Na();a$();bb();l$();d$();Ea();Ym();m$();y$();A$();Bb();_$();T$();Wb();_a();Ia();$$();nb();Pi();Wr();jA();Hb={id:"comet-native-shape-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=e.input;if(!n?.projectRoot||typeof i.name!="string"||typeof i.artifactRootRef!="string"||!["shape.prepare","shape.revalidate"].includes(t.stepId))return{accepted:!1,reason:"Native Shape lacks its project and Action"};try{let o=Pa(r.output);if(M(e.state).name!==i.name||!Array.isArray(o.acceptance)||o.acceptance.length===0||!Array.isArray(o.specChanges))throw new Error("Native Shape requires its change, specifications and acceptance criteria");return{accepted:!0}}catch(o){return{accepted:!1,reason:String(o)}}}},Qb={id:"comet-native-builder-outcome",version:"1",async validate({run:e,outcome:t,context:r}){if(t.status==="failed")return{accepted:!0};let n=e.input;if(!r?.projectRoot||typeof n.name!="string"||typeof n.artifactRootRef!="string")return{accepted:!1,reason:"Native Builder result lacks its project binding"};try{if(M(e.state).name!==n.name)return{accepted:!1,reason:"Native Builder result belongs to another change"};let o=await Be(r.projectRoot);if(!o||o.native.artifact_root!==n.artifactRootRef)return{accepted:!1,reason:"Native artifact root changed after Run creation"};let a=t.output;if(["3","4"].includes(e.workflow.version)&&a?.requireIndependentReview!==void 0&&typeof a.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");{if(a?.response||a?.verificationChecks!==void 0)throw new Error("Run checks with platform tools and submit checks reports, not Runtime check plans.");return{accepted:!0}}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},Ub={id:"native-supervisor-parent-builder-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.parent.builder"||t.type!=="handoff")return{accepted:!1,reason:"Native Supervisor parent Builder lacks its project"};try{let i=await rc(e,n.projectRoot),o=t.input.activation,a=i.state,s=wt(n.projectRoot,a.name),c=vt(a.name),l=ic(t,r),u=new Set(Xt(e).filter(f=>f.stepId==="supervisor.child.archive"&&f.status==="succeeded").map(f=>f.input.activation.child));if(a.phase!=="build"||!o||Fe(o,e)!==a.children_contract_ref||o.integrationBranch!==c||typeof o.integrationWorktree!="string"||!he(o.integrationWorktree,s)||typeof o.integrationCommit!="string"||ye(s).currentBranch!==c||ge(s,c)!==l||u.size!==i.contract.children.length||i.contract.children.some(({name:f})=>!u.has(f)))throw new Error("Native Supervisor parent candidate is not the complete integration");return ce(s,["merge-base","--is-ancestor",o.integrationCommit,l]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},Jb={id:"comet-native-verifier-outcome",version:"1",async validate({run:e,outcome:t,context:r}){let n=e.input;if(!r?.projectRoot||typeof n.artifactRootRef!="string")return{accepted:!1,reason:"Native Verifier result lacks its project binding"};try{if(t.status==="failed")return{accepted:!0};let i=await Be(r.projectRoot);if(!i||i.native.artifact_root!==n.artifactRootRef||(n.maxVerifyFailures??El)!==i.native.max_verify_failures)return{accepted:!1,reason:"Native project configuration changed after Run creation"};if(t.output?.response?.kind==="request-checks")throw new Error("Run additional checks with platform tools and report the final result.");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},zb={id:"comet-native-state",version:"1",validate({state:e}){try{return M(e),{accepted:!0}}catch(t){return{accepted:!1,reason:t instanceof Error?t.message:String(t)}}}}});var q$={};Nh(q$,{upgradeNativeRun:()=>Co});function Co(e,t,r){let n=ln(t),i=$(n);if(e.workflow.hash===i&&e.workflow.version===n.version)return e;if(e.workflow.version==="4"&&e.workflow.hash!==v9)throw new Error("Native 当前 Run 的 definition hash 不匹配;不能作为旧业务数据重新绑定。");if(e.workflow.id!=="comet-native"||!["1","2","3","4"].includes(e.workflow.version))throw new Error("Native Run 不属于可升级的内置协议");let o=M(e.state);if(o.name!==e.runId||e.input?.name!==e.runId)throw new Error("Native Run 与需求名称不一致");let a=Vy(e);a.state=o;let s=d=>Object.hasOwn(n.steps,d),c=[],l={"verify.checks-stop":"verify.stop","supervisor.child.checks-stop":"supervisor.child.verifier-retry","supervisor.child.integration-checks-stop":"supervisor.child.verifier-retry"};for(let d of a.actions)s(d.stepId)||!["pending","running","unknown"].includes(d.status)||(c.push({step:d.stepId,results:a.actionContexts[d.id].results}),d.status="cancelled",d.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let d of a.waits)if(!(d.status!=="pending"||s(d.stepId))){if(l[d.stepId]){d.stepId=l[d.stepId];continue}throw new Error("旧 Native 待决定事项没有当前业务对应项,原提案保持不变。")}for(let d of a.evidenceWaits??[])d.status==="pending"&&!s(d.stepId)&&(c.push({step:d.stepId,results:d.results}),d.status="cancelled");let u=a.ready;a.ready=u.filter(d=>s(d.to)&&(d.from===null||s(d.from)));for(let d of u)(!s(d.to)||d.from!==null&&!s(d.from))&&c.push({step:d.to,results:d.results});if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let d=e.reason.slice(15),p=[...a.actions].reverse().find(h=>h.stepId===d);!s(d)&&p&&c.push({step:d,results:a.actionContexts[p.id].results})}if(o.children_contract_ref&&!a.actions.some(d=>d.id===o.children_contract_ref)){let d=[...a.waits].reverse().find(m=>["shape.confirm","supervisor.shape.confirm"].includes(m.stepId)&&m.status==="resolved"&&["approved","single-session","multi-session"].includes(m.decision?.choice??"")),p=a.actions.find(m=>m.stepId==="shape.prepare"&&m.status==="succeeded"&&a.actionContexts[m.id].sequence===d?.results["shape.prepare"]?.sequence),h=p?.outcome?.output?.children?.contract;if(!p||!h)throw new Error("旧 Supervisor 缺少原已批准的子任务方案");a.state={...o,children_contract_hash:o.children_contract_ref,children_contract_ref:p.id,children_contract:h}}let f=new Set;for(let d of c){if(["completed","cancelled"].includes(e.status))break;if(a.waits.some(v=>v.status==="pending"&&["verify.stop","verify.confirm","verify.retry"].includes(v.stepId))&&!d.step.startsWith("supervisor.child."))continue;let h=["shape.revalidate","build.checks"].includes(d.step)?["shape.confirm","supervisor.shape.confirm"]:d.step==="verify.revalidate"?["verify.confirm"]:[],m=[...a.waits].reverse().find(v=>h.includes(v.stepId)&&v.status==="resolved"&&d.results[v.stepId]?.sequence===v.sequence&&["approved","single-session","multi-session"].includes(v.decision?.choice??"")),g;if(m){let v;if(d.step==="build.checks")v={state:a.state,next:["build.builder"]};else{if(!r)throw new Error("旧批准需要当前业务转移器完成数据转换");v=r.apply({run:a,event:{kind:"wait-resolved",stepId:m.stepId,choice:m.decision.choice,proposalHash:m.proposalHash,decisionId:m.decision.id}})}if(v.next.length!==1)throw new Error("旧批准没有唯一的当前业务续行");a.state=v.state;let w=v.next[0];g={from:m.stepId,to:typeof w=="string"?w:w.stepId,results:{...m.results,[m.stepId]:{sequence:m.sequence,value:{choice:m.decision.choice,proposal:m.proposal}}},...typeof w=="string"?{}:{activation:w.input}}}else{let v=[...a.actions].reverse().find(b=>s(b.stepId)&&b.status==="succeeded"&&["build.builder","supervisor.parent.builder","supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair","verify.verifier"].includes(b.stepId)&&d.results[b.stepId]?.sequence===a.actionContexts[b.id].sequence);if(!v)throw new Error("旧 Native Run 缺少已接受的业务续行来源,原记录保持不变。");if(f.has(v.id))continue;f.add(v.id);let w=a.actionContexts[v.id],A,N;if(["supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair"].includes(v.stepId)){if(!r)throw new Error("旧 Child 需要当前业务转移器完成数据转换");let b=r.apply({run:a,event:{kind:"action-outcome",stepId:v.stepId,outcome:v.outcome}});if(b.next.length!==1)throw new Error("旧 Child 没有唯一的当前业务续行");a.state=b.state;let E=b.next[0];A=typeof E=="string"?E:E.stepId,N=typeof E=="string"?void 0:E.input,N&&typeof N=="object"&&!Array.isArray(N)&&(N={...N,contractRef:M(a.state).children_contract_ref},delete N.contractHash)}else{let b=M(a.state),E=v.stepId==="verify.verifier"&&b.verification_result==="pass";A=E?"verify.confirm":"verify.verifier",!E&&b.phase==="verify"&&b.loop.stage==="verify-ready"&&b.loop.next_action!=="await-verifier-result"&&(a.state=ri(b))}g={from:v.stepId,to:A,results:{...w.results,[v.stepId]:{sequence:w.sequence,value:v.outcome.output}},...N===void 0?{}:{activation:N}}}g.to==="verify.confirm"&&(g.activation={report:Tm(M(a.state),a.input.artifactRootRef)}),a.ready.push(g),a.status="running",delete a.reason}a.workflow={id:n.id,version:n.version,hash:i};for(let d of Object.keys(a.definitionHashes))JSON.parse(d)[0]===n.id&&delete a.definitionHashes[d];return a.definitionHashes[JSON.stringify([n.id,n.version])]=i,a}var v9,mh=_(()=>{"use strict";Sa();Ea();et();xe();v9="26c4e50c65dcb5e1280529642a73b650400e3109ba6fa2efded90e03ad790443"});Hu();Is();Vk();Hk();bn();pr();zk();import{promises as j9}from"fs";import _e from"path";function Pz(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 Tz=new Set([".md",".markdown"]);var Oz=new Set([".md",".markdown",".rst",".txt"]),$z=new Set(["docs","doc","documentation",".github"]),jz=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function TT(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function Dz(e,t){for(let r of t){let n=TT(r).replace(/\/+$/u,"");if(n&&(e===n||e.startsWith(`${n}/`)))return!0}return!1}function OT(e,t=[]){let r=TT(e);if(Pz(r)||!r||r.endsWith("/")||Dz(r,t))return!1;let n=r.split("/"),i=n[n.length-1],o=i.lastIndexOf("."),a=o===-1?"":i.slice(o).toLowerCase();return n.length===1?Tz.has(a)||jz.some(s=>s.test(i)):$z.has(n[0])&&Oz.has(a)}Hs();It();ka();Ye();sb();Yt();Di();bn();Ul();et();Ll();pr();ct();It();Bt();Ye();xe();Yt();Du();mh();import{promises as aj}from"node:fs";import Mu from"node:path";et();pr();$t();js();Hs();It();Bt();Du();Yt();xe();Ye();import I9 from"node:path";Lm();et();Xr();import{AsyncLocalStorage as y9}from"node:async_hooks";qv();import{createHash as k9,randomUUID as Gpe}from"node:crypto";import Q$ from"node:path";Ch();import{promises as hh}from"node:fs";import Yb from"node:path";async function F$(e,t){let r=Eh(e),n=Yb.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let a of["","workspaces",r.workspaceId,"observability"]){i=Yb.join(i,a);let s;try{s=await hh.lstat(i)}catch(c){if(!t||c.code!=="ENOENT")throw c;await hh.mkdir(i,{recursive:a===""}).catch(l=>{if(l.code!=="EEXIST")throw l}),s=await hh.lstat(i)}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let o=Yb.join(n,"performance.sqlite");for(let a of["","-wal","-shm"])try{let s=await hh.lstat(o+a);if(!s.isFile()||s.isSymbolicLink()||s.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(s){if(s.code!=="ENOENT")throw s}return o}import{stripVTControlCharacters as w9}from"node:util";function H$(e,t=process.env){let r=w9(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 A9=864e5,b9=1e4,U$=new y9;function Xb(e){let t=U$.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function Bu(e,t){return H$(e).slice(0,t)}async function J$(e,t){if(!t.length)return;let r=U$.getStore();if(r){let i=o=>process.platform==="win32"?Q$.resolve(o).toLowerCase():Q$.resolve(o);if(i(e)===i(await r.projectRoot())){r.spans.push(...t);return}}let n=Jd(await F$(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
419
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
420
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
421
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
422
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
423
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
424
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
425
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
426
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
427
|
+
BEGIN IMMEDIATE;`);let i=n.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
428
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
429
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
430
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
431
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
432
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
433
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
434
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
435
|
+
WHERE excluded.revision >= trace_spans.revision OR (trace_spans.started_at IS NULL AND excluded.started_at IS NOT NULL)`),o=t.length>1e3?[...t.filter(a=>a.parentSpanId===null),...t.filter(a=>a.parentSpanId!==null).slice(-999)].slice(0,1e3):t;for(let a of o){if(!a.change||!a.runId||!a.traceId||!a.spanId||a.change.length>240||a.runId.length>240||a.traceId.length>512||a.spanId.length>512||(a.parentSpanId?.length??0)>512)continue;let s={...a,name:Bu(a.name,240),summary:a.summary?Bu(a.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(a.attributes??{}).slice(0,20).map(([u,f])=>[Bu(u,80),Array.isArray(f)?f.slice(0,30).map(d=>Bu(d,240)):typeof f=="string"?Bu(f,2e3):f]))};t.length>1e3&&a.parentSpanId===null&&(s.attributes.truncated=!0);let c=JSON.stringify(s);for(;Buffer.byteLength(c,"utf8")>4096;){let u=Object.keys(s.attributes).reverse().find(f=>f!=="truncated");if(u)delete s.attributes[u];else if(s.summary)s.summary=s.summary.slice(0,Math.floor(s.summary.length*.75));else break;c=JSON.stringify(s)}if(Buffer.byteLength(c,"utf8")>4096)continue;let l=k9("sha256").update(JSON.stringify([a.traceId,a.spanId])).digest("hex");i.run(l,a.traceId,a.workflow,a.change,a.runId,a.spanId,a.parentSpanId,a.kind,s.name,a.status,a.startedAt,a.endedAt,a.updatedAt,a.revision,c)}n.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*A9).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(b9),n.exec("COMMIT")}finally{n.close()}}var N9=(e,t)=>`workflow:${e}:${t}`,z$=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},K$=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}))}),G$=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function R9(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:o}=e,a=N9(t,n.runId),s=`run:${n.runId}`,c={workflow:t,change:n.runId,runId:n.runId,traceId:a,updatedAt:o,revision:n.revision},l=["completed","failed","cancelled"].includes(n.status),u=new Map(r?.actions.map(d=>[`${d.id}:${d.attempt}`,d])),f=[{...c,spanId:s,parentSpanId:null,kind:"workflow",name:n.workflow.id,status:n.status==="completed"?"succeeded":n.status,startedAt:i?o:null,endedAt:l&&(i||r!==null&&r.status!==n.status)?o:null,summary:n.reason,attributes:{workflowVersion:n.workflow.version,sequence:n.sequence,parentRunIds:n.lineage,childRunIds:n.children.map(d=>d.runId)}}];for(let d of n.actions){let p=u.get(`${d.id}:${d.attempt}`);if(p&&p.status===d.status&&p.outcome?.outcomeId===d.outcome?.outcomeId&&p.reason===d.reason&&p.outcome?.summary===d.outcome?.summary)continue;let h=["succeeded","failed","cancelled"].includes(d.status);f.push({...c,spanId:`action:${d.id}:${d.attempt}`,parentSpanId:s,kind:"action",name:d.stepId,status:d.status,attempt:d.attempt,startedAt:d.status==="running"&&(p?.status==="pending"||i)?o:null,endedAt:h&&(i||r!==null)?o:null,summary:d.outcome?.summary??d.reason,attributes:{phase:z$(d.stepId,t),actionId:d.id,actionType:d.type,ref:d.ref??null,executor:d.claim?.executorId??null,inputFields:G$(d.input),outputFields:d.outcome?G$(d.outcome.output):[],artifacts:(d.outcome?.artifacts??[]).map(m=>m.uri)}})}for(let d of["wait","evidence"]){let p=d==="wait"?n.waits:n.evidenceWaits??[],h=d==="wait"?r?.waits:r?.evidenceWaits,m=new Map(h?.map(g=>[g.id,g]));for(let g of p){let v=m.get(g.id);v?.status!==g.status&&f.push({...c,spanId:`${d}:${g.id}`,parentSpanId:s,kind:d,name:g.stepId,status:g.status==="pending"?"waiting":g.status==="resolved"?"succeeded":g.status==="cancelled"?"cancelled":"unknown",startedAt:!v&&(r!==null||i)&&g.status==="pending"?o:null,endedAt:g.status!=="pending"&&(i||r!==null)?o:null,attributes:{phase:z$(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return f}function Y$(e,t,r){let n=null;return{...r,...r.restoreCheckpoint?{restoreCheckpoint:(i,o,a)=>r.restoreCheckpoint(i,o,a)}:{},async read(i){let o=await r.read(i);try{n=o?K$(o):null}catch{n=null}return o&&Xb({workflow:t,change:o.runId,runId:o.runId}),o},async compareAndSwap(i,o,a){let s=n?.runId===i&&n.revision===o?n:null,c=await r.compareAndSwap(i,o,a);if(c){Xb({workflow:t,change:i,runId:i});try{await J$(e,R9({workflow:t,previous:s,next:a,initial:o===null,observedAt:new Date().toISOString()}))}catch{}try{n=K$(a)}catch{n=null}}return c}}}Xr();var rj=kr(dn(),1);Ul();import{promises as rN}from"node:fs";import{isDeepStrictEqual as eN}from"node:util";import _o from"node:path";gu();Du();bb();mh();et();pr();co();Xr();Is();Bt();Ye();Lm();Xs();xe();import X$ from"node:path";async function Wu(e){let t=e.run.input;if(typeof t?.artifactRootRef!="string"||!Number.isSafeInteger(e.run.revision)||(await je(e.projectRoot,"native",e.run.runId,{readOnly:!0}))?.application!=="native")return!1;if(await St({singleWriter:!0,rootDir:X$.join(Ze(e.projectRoot),"sdk-runs","native")}).readDisposition(e.run.runId)==="closed")return Zb(e);let i=await ke(e.projectRoot,t.artifactRootRef,{readOnly:!0});return He(i,()=>Zb(e))}async function Zb(e){let{projectRoot:t}=e,r=await je(t,"native",e.run.runId,{readOnly:!0});if(!r||r.application!=="native")return!1;let n=St({singleWriter:!0,rootDir:X$.join(Ze(t),"sdk-runs","native")}),i=await n.read(r.runId);if(!i||i.revision!==e.run.revision||!["cancelled","completed"].includes(i.status))return!1;let o=Kb(null),a=Co(i,o.workflow,o.transitionHandler),s=Co(e.run,o.workflow,o.transitionHandler);if($(a)!==$(s))throw new Error("Native Run content changed at the same revision before history closure");if(!Hm(o.workflow,a))throw new Error("Native history requires a known built-in workflow definition");let c=await Pt({...o,workflows:[o.workflow],transitionHandlers:[o.transitionHandler],store:{read:async()=>a,compareAndSwap:async()=>!1}}).inspect(r.runId),l=M(c.state),u=c.input;if(c.runId!==r.change||c.workflow.id!=="comet-native"||l.name!==r.change||u?.name!==r.change||typeof u.artifactRootRef!="string")throw new Error("Native history Run does not match its change ownership");if(await n.readDisposition(c.runId)==="closed")return await tk(t,r),!0;if(c.ready.length>0||c.waits.some(f=>f.status==="pending")||c.evidenceWaits?.some(f=>f.status==="pending"))return!1;if(c.status==="cancelled"){if((await Gl({projectRoot:t,run:c}))?.status!=="cancelled")return!1}else{if(!l.archived||l.phase!=="archive"||l.status!=="done"||!(await Wp({projectRoot:t,run:c})).quiescent)return!1;let f=await xr(t);if(f.status==="selected"&&f.selection.workflow==="native"&&f.selection.change===c.runId)return!1;let d=c.outputs["archive.execute"]?.value,p=c.outputs["archive.finalize"]?.value;if(!d||typeof d.archiveRef!="string"||typeof d.transactionId!="string"||d.stateVersion!==l.state_version-1||!p)return!1;let h=await ke(t,u.artifactRootRef,{readOnly:!0}),m=await ju({paths:h,state:l,runId:c.runId,archiveRef:d.archiveRef,history:!0,allowMissingReport:["3","4"].includes(c.workflow.version),verificationResultHash:c.workflow.version!=="1"?q0(l):void 0});if(m.transactionId!==d.transactionId||$(p)!==$(m))throw new Error("Native history Archive receipt does not match its committed outcome")}return e.recover&&await n.readDisposition(c.runId)==="reopening"?(await qx(t,"native",c.runId),await n.reopenRun(c.runId,c.revision)?Zb({projectRoot:t,run:c}):!1):!await n.closeRun(c.runId,c.revision)||await n.readDisposition(c.runId)!=="closed"?!1:(await tk(t,r),!0)}pr();co();Bt();Ye();Is();async function Z$(e){if(e.run.status!=="cancelled")return;let t=e.run.input?.artifactRootRef;if(typeof t=="string"){let o=await ke(e.projectRoot,t);if(await xi(o,{kind:"archive",change:e.run.runId}))return}let r=await Gl(e);if(!r?.quiescent)return;if(!r.cleanupRequired){await Wu(e);return}let n=e.run.input;if(typeof n?.artifactRootRef!="string")return;let i=await ke(e.projectRoot,n.artifactRootRef);await He(i,async()=>{let o=await xr(e.projectRoot);if(o.status!=="selected"||o.selection.change!==e.run.runId)return;let a=await je(e.projectRoot,"native",e.run.runId);a&&(a.application==="native"?o.selection.workflow==="native":o.selection.workflow==="application"&&o.selection.applicationId===a.application)&&await hs(e.projectRoot,o.selection.workflow,e.run.runId)}).catch(o=>{throw new Error(`Native cancellation is committed but current selection release remains pending. Inspect the unfinished workspace transaction with comet native doctor --json, then retry comet native doctor ${e.run.runId} --repair. ${o instanceof Error?o.message:String(o)}`,{cause:o})}),await Wu(e)}async function ej(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o}=e;if(o.status!=="cancelled")throw new Error("Native cancellation commit requires a cancelled Run");let a=o.input;if(typeof a?.artifactRootRef!="string")throw new Error("Native cancellation commit requires its artifact root");let s=await ke(t,a.artifactRootRef);return He(s,async()=>{let c=await r.read(n);if(c&&c.status!=="cancelled"){if(await xi(s,{kind:"archive",change:n}))throw new Error(`Native Archive transaction must finish before cancellation; run comet native archive ${n} or recover its original Action with --recover`);if(c.actions.some(l=>l.stepId.startsWith("archive.")&&["running","unknown"].includes(l.status)))throw new Error(`Native Archive execution must finish or recover before cancellation; run comet native archive ${n} --recover`)}return r.compareAndSwap(n,i,o)},{allowedPortableTransaction:{kind:"archive",change:n}})}pr();co();Bt();Ye();async function tj(e){if(e.run.status!=="completed")return;let t=e.run.input;if(typeof t?.artifactRootRef!="string")return;let r=await ke(e.projectRoot,t.artifactRootRef);await He(r,async()=>{let n=await xr(e.projectRoot);if(n.status!=="selected"||n.selection.change!==e.run.runId)return;let i=await je(e.projectRoot,"native",e.run.runId);i&&(i.application==="native"?n.selection.workflow==="native":n.selection.workflow==="application"&&n.selection.applicationId===i.application)&&await hs(e.projectRoot,n.selection.workflow,e.run.runId)}).catch(n=>{throw new Error(`Native SDK Run ${e.run.runId} is archived but current selection release remains pending. Inspect the unfinished workspace transaction with comet native doctor --json, then retry comet native doctor ${e.run.runId} --repair. ${n instanceof Error?n.message:String(n)}`,{cause:n})}),await Wu(e)}hn();_t();et();pr();ct();It();$t();Ye();xe();Yt();Yt();Wr();Ym();et();var tN=class extends Error{constructor(r,n,i=!1,o){let a=o?["runtime","dispatch","--application-file",_o.join(o.packageRoot,"application.json"),"--project-root",r,"--request","<recovery-request.json>","--json"]:null;super(a?`Native SDK Run ${n} needs checkpoint recovery. 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.
|
|
436
|
+
Recovery argv: ${JSON.stringify(a)}
|
|
437
|
+
Recovery request: ${JSON.stringify({operation:"next",runId:n})}`:`Native SDK Run ${n} needs checkpoint recovery; run comet native doctor ${n} --repair${i?"":" --confirmed"} before continuing`);this.projectRoot=r;this.change=n;this.interrupted=i}projectRoot;change;interrupted;code="NATIVE_SDK_RUN_RECOVERY_REQUIRED"};function S9(e){return e.revision===1||["completed","cancelled","failed"].includes(e.status)||e.state.phase==="shape"&&e.waits.some(t=>["shape.confirm","supervisor.shape.confirm"].includes(t.stepId)&&t.status==="resolved"&&t.decision?.choice==="rejected")||e.waits.some(t=>t.status==="pending")||e.evidenceWaits?.some(t=>t.status==="pending")?!0:e.actions.some(t=>["pending","running","unknown"].includes(t.status)&&(t.type==="invoke_skill"||t.type==="handoff"||!!t.claim?.sessionId||!["shape.prepare","shape.revalidate","verify.revalidate","archive.prepare"].includes(t.stepId)))}function E9(e,t){return JSON.stringify(e)===JSON.stringify(t)}function C9(e,t,r){if(e.actions.some(s=>s.stepId==="supervisor.cleanup"&&s.status==="succeeded"))return;let i=e.actions.filter(s=>s.status==="succeeded"&&["supervisor.prepare","supervisor.child.prepare"].includes(s.stepId));if(i.length===0)return;let o=$r(r),a=!t.archived;for(let s of i){let c=s.outcome?.output;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Native SDK Supervisor worktree receipt is invalid");let l=c,u=s.stepId==="supervisor.child.prepare"?l.child:null;if(s.stepId==="supervisor.child.prepare"&&typeof u!="string")throw new Error("Native SDK Supervisor Child worktree receipt is invalid");let f=typeof u=="string"?Wt(r,t.name,u):wt(r,t.name),d=typeof u=="string"?l.worktree:l.integrationWorktree,p=typeof u=="string"?l.branch:l.integrationBranch;if(typeof d!="string"||!he(d,f)||typeof p!="string"||a&&(!o.some(h=>he(h,f))||ye(f).currentBranch!==p))throw new Error(`Native SDK Supervisor worktree unavailable in this checkout: ${f}; transfer or repair the Child and integration worktrees before restoring the Run`)}}async function Lu(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=await oe(e.projectRoot,_o.relative(e.projectRoot,e.archiveDir),{label:"Native SDK Archive directory",expected:"directory"});if(!r.exists)return null;let n=(await rN.readdir(r.target,{withFileTypes:!0})).filter(i=>i.isDirectory()&&!i.isSymbolicLink()&&/^\d{4}-\d{2}-\d{2}-/u.test(i.name)&&i.name.slice(11)===t).map(i=>i.name);if(n.length>1)throw new Error(`Native SDK Archive ${t} is ambiguous`);return n.length===1?_o.join(r.target,n[0],"comet-state.yaml"):null}async function Vu(e){let{text:t}=await tT({root:_o.dirname(e),ref:_o.basename(e),maxBytes:Buffer.byteLength(Ql)+1});return ha(t)}async function nj(e,t){let r=await rN.readFile(e,"utf8");if(!ha(r))return!1;let n=go(r,"Native state file");return np(n[yi],t)!==null}function _9(e,t,r,n){return Ql+(0,rj.stringify)({...M(e),...r===void 0?{}:{archive_receipt:r},...n?{application_checkpoint:n}:{}})+(t?`${yi}: ${JSON.stringify(t)}
|
|
438
|
+
`:"")}function Ta(e,t={},r=!1){let n=Ze(e),i=Y$(e,"native",t.store??St({singleWriter:!0,rootDir:_o.join(n,"sdk-runs","native")}));function o(){if(Ze(e)!==n)throw new Error("Native SDK workspace identity changed; recreate the store in the current workspace")}function a(f,d){return go(d,"Native portable state")}async function s(f){return(await qe(e,_o.relative(e,f),Number.MAX_SAFE_INTEGER,{label:"Native portable state"})).bytes.toString("utf8")}async function c(f,d,p=t.readOnly){let h=await Be(e);if(!h)return null;let m=await ke(e,h.native.artifact_root,{...t,readOnly:p,change:f}),g=Jr(m,f),v=g,w;try{w=await s(v)}catch(de){if(de.code!=="ENOENT")throw de;let se=await Lu(m,f);if(!se)return null;v=se,w=await s(v)}if(!ha(w))return null;let A=go(w,"Native state file"),N=np(A[yi],f,{preserveSourceRevision:!0});if(!N)return null;if($(A.application_checkpoint??null)!==$(t.identity??null))throw new Error("Native portable checkpoint requires its original fixed Application package");let b=M(A),E=N.input;if(!E9(M(N.state),b)||E?.name!==f||E.artifactRootRef!==m.artifactRootRef||N.workflow.id!=="comet-native"||v!==g&&!b.archived)throw new Error(`Native portable Run checkpoint for ${f} does not match its state`);if(!t.identity){let[{nativeSdkApplicationForRun:de},{upgradeNativeRun:se}]=await Promise.all([Promise.resolve().then(()=>(Du(),M$)),Promise.resolve().then(()=>(mh(),q$))]);if(t.rootRunId===f&&N.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let De=de(null);se(N,De.workflow,De.transitionHandler)}!t.allowBranchRebind&&N.status!=="cancelled"&&!(b.archived&&N.status==="completed")&&Iu(e,{isolation:b.workspace.isolation,changeBranch:b.workspace.change_branch,targetBranch:b.workspace.target_branch}),C9(N,b,e);let V=N.revision,j={...N,revision:V};if(d&&$(d)!==$({...j,revision:1}))throw new Error(`Native SDK Run ${f} differs from the interrupted checkpoint import; preserve the local records and restore matching Run history before continuing`);if(p)return j;if((V>1||d)&&!i.restoreCheckpoint)throw new Error(`Native RuntimeStore cannot restore checkpoint revision ${V}; use a store with restoreCheckpoint support or restore the original Run history`);let z=t.identity?.id??"native",X=b.archived&&N.status==="completed"?await je(e,"native",f,{readOnly:!0}):null;return(X?.application!==z||X.runId!==f)&&await lo(e,{schema:Tn,workflow:"native",change:f,format:"sdk",application:z,runId:f}),V===1&&!d?await i.compareAndSwap(f,null,j):await i.restoreCheckpoint(f,d?1:null,j),i.read(f)}async function l(f,d){let p=M(f.state),h=f.input;if(p.name!==f.runId||h?.name!==f.runId||typeof h.artifactRootRef!="string")throw new Error(`Native SDK Run ${f.runId} does not match its portable state`);let m=await Be(e);if(m&&m.native.artifact_root!==h.artifactRootRef)throw new Error("Native artifact root changed after Run creation");if(!d||!S9(f))return f;let g=f,v=p,w=await ke(e,h.artifactRootRef,{change:f.runId}),A=Jr(w,f.runId);try{await rN.access(_o.dirname(A))}catch(j){if(j.code!=="ENOENT")throw j;if(!v.archived)return g;let z=await Lu(w,f.runId);if(!z)throw new Error(`Native SDK Archive ${f.runId} is ambiguous`,{cause:j});A=z}let N=null;try{N=await s(A)}catch(j){if(j.code!=="ENOENT")throw j}let b=N&&g.actions.some(j=>j.stepId==="archive.finalize")?a(A,N).archive_receipt:void 0,E=Wy(Ly(g)),V=_9(v,E,b,t.identity);return N!==V&&await Ge(A,V,{containedRoot:w.nativeRoot}),g}async function u(f,d=!1){let p;if(r)try{p=(await Oo(i,f)).record}catch(m){if(m.code!=="RUN_NOT_FOUND")throw m;p=null}else p=await i.read(f);let h=p?.revision===1&&p.actions.some(m=>m.status!=="pending")?p:void 0;if(!p||h){let m=await c(f,h,!0);if(!m)return p;if(!p||m.revision>p.revision){if(t.readOnly)throw new tN(e,f,!!h,t.identity);o(),await ci(e),p=await c(f,h,!1)}}return p?l(p,d&&!t.readOnly):null}return{queryScope:i.queryScope,read:u,readProjection:f=>Ta(e,{...t,store:i,readOnly:!0},!0).read(f),async compareAndSwap(f,d,p){if(t.readOnly)throw new Error("Native SDK diagnostic store is read-only");o();let h=M(p.state);for(let b of p.actions){if(b.status!=="running"||!["verify.verifier","supervisor.child.verifier"].includes(b.stepId)||!tc(p,b))continue;let V=b.input.activation?.builderSessionId??h.builder_handoff?.builder_execution_ref;if(!V||b.claim?.sessionId!==V)continue;let j=await i.read(f),z=j?.actions.find(X=>X.id===b.id);if(j?.revision===d&&(z?.status!=="running"||!eN(z.claim,b.claim)))throw new k("VERIFIER_SESSION_NOT_INDEPENDENT","Native Verifier requires an independent session; use a different sessionId from the Builder.")}let m=h.workspace;try{Iu(e,{isolation:m.isolation,changeBranch:m.change_branch,targetBranch:m.target_branch})}catch(b){let E=await i.read(f),V=p.actions.some(z=>z.status==="running"&&!E?.actions.some(X=>X.id===z.id&&X.status==="running"&&X.attempt===z.attempt&&eN(X.claim,z.claim))),j=E?.actions.some(z=>["running","unknown"].includes(z.status)&&p.actions.some(X=>X.id===z.id&&X.attempt===z.attempt&&eN(X.claim,z.claim)));if(V||p.status!=="cancelled"&&!j)throw b}let g=()=>i.compareAndSwap(f,d,p),v=[...p.actions].reverse().find(b=>b.stepId==="archive.execute"&&b.status==="failed"),A=(v?await i.read(f):null)?.actions.some(b=>b.id===v?.id&&b.status==="unknown"),N=p.status==="cancelled"?await ej({projectRoot:e,store:i,runId:f,expectedRevision:d,next:p}):A?await r$({projectRoot:e,store:i,runId:f,expectedRevision:d,next:p,actionId:v.id,state:h}):await g();return N&&(await l(p,!0),p.status==="cancelled"&&await Z$({projectRoot:e,run:p}),p.status==="completed"&&await tj({projectRoot:e,run:p})),N}}}async function x9(e){let t=oc(),r=Ta(e.paths.projectRoot);return Pt({store:{async read(o){let a=await r.read(o);if(a&&!await je(e.paths.projectRoot,"native",o))throw new k("RUN_OWNER_MISSING",`SDK Run ${o} 缺少归属记录`);return a},async compareAndSwap(o,a,s){if(a===null){if(o!==e.name)throw new Error("Native SDK Run ID and change name differ");await lo(e.paths.projectRoot,{schema:Tn,workflow:"native",change:e.name,format:"sdk",application:"native",runId:o},{canonical:!0})}return r.compareAndSwap(o,a,s)}},workflows:[t.workflow],transitionHandlers:[t.transitionHandler],validators:t.validators,stateValidators:t.stateValidators,commandValidators:t.commandValidators,validateRecovery:t.validateRecovery,executors:t.executors}).start({runId:e.name,workflow:{id:t.workflow.id,version:t.workflow.version},input:{name:e.name,...e.task===void 0?{}:{task:e.task},artifactRootRef:e.paths.artifactRootRef},initialState:e.initialState})}async function ij(e,t){let r=I9.join(dt(e,t),"comet-state.yaml");if(!await Vu(r))return null;let n=await wn(r),i=_s({name:t,language:n.language,workspace:n.workspace,createdAt:n.created_at,nextAction:"prepare-shape-confirmation"});return JSON.stringify(n)!==JSON.stringify(i)?null:i}async function oj(e,t){let r=await ij(e,t);return r?x9({paths:e,name:t,initialState:r}):null}async function sj(e,t,r){if(r.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let n=cj(),i=Co(r,n.workflow,n.transitionHandler);return await Pt({...n,workflows:[n.workflow],transitionHandlers:[n.transitionHandler],store:{read:async()=>i,compareAndSwap:async()=>!1}}).inspect(t),lo(e,{schema:Tn,workflow:"native",change:t,format:"sdk",application:"native",runId:t},{canonical:!0})}async function P9(e,t){let r=await ki(e.projectRoot,"native",t);return r||He(e,async()=>{let n=await ki(e.projectRoot,"native",t);if(n)return n;let i=Mu.relative(e.projectRoot,Jr(e,t));if(!(await oe(e.projectRoot,i,{label:"Native legacy change state",expected:"file"})).exists){let c=await Lu(e,t);if(!c)return null;let l=Mu.relative(e.projectRoot,c),u=await oe(e.projectRoot,l,{label:"Native archived change state",expected:"file"});if(!u.exists||!await Vu(u.target))return null;if(await nN(e.projectRoot,t))return await(await iN(e.projectRoot,t)).runtime.inspect(t),je(e.projectRoot,"native",t);let f=await Ta(e.projectRoot,{rootRunId:t}).read(t);if(f){let d=await je(e.projectRoot,"native",t);return d||sj(e.projectRoot,t,f)}throw new Error(`Native archived change ${t} has a managed state file but lost its Run checkpoint`)}if(await nN(e.projectRoot,t))return await(await iN(e.projectRoot,t)).runtime.inspect(t),je(e.projectRoot,"native",t);let s=await Ta(e.projectRoot,{rootRunId:t}).read(t);if(s){let c=await je(e.projectRoot,"native",t);return c||sj(e.projectRoot,t,s)}if(await oj(e,t)){let c=await je(e.projectRoot,"native",t);if(!c)throw new Error(`Recovered Native change ${t} has no Run ownership`);return c}return await T9(e,t),rk(e.projectRoot,{schema:Tn,workflow:"native",change:t,format:"compat"})})}async function T9(e,t){let r=Jr(e,t);if(await Vu(r)&&!await nj(r,t))throw new Error(`Native change ${t} has a portable state file but lost its local Run history; inspect it with comet native doctor ${t} before restoring`)}async function nN(e,t){let r=await Be(e);if(!r)return null;let n=await ke(e,r.native.artifact_root,{readOnly:!0}),i=Jr(n,t);try{await aj.access(i)}catch(a){if(a.code!=="ENOENT")throw a;let s=await Lu(n,t);if(!s)return null;i=s}return go(await aj.readFile(i,"utf8"),"Native application checkpoint").application_checkpoint??null}var O9=ai("nativeBuiltinDefinition",()=>oc());function cj(){return O9()}async function iN(e,t,r={}){let n=r.owner??await je(e,"native",t,r),i=n?.application==="native"?null:await nN(e,t),o=n?.application??i?.id??"native";if(o==="native"){let c=Ta(e,{...r,rootRunId:t}),l=await c.read(t),u=cj();if(l){let f=Co(l,u.workflow,u.transitionHandler);f!==l&&(await Pt({...u,workflows:[u.workflow],transitionHandlers:[u.transitionHandler],store:{read:async()=>f,compareAndSwap:async()=>!1}}).inspect(t),l=f)}return{runtime:Pt({...u,executors:r.readOnly?[]:u.executors,store:{...c,async read(f){if(l&&f===t){let p=l;return l=null,Promise.resolve(p)}let d=await c.read(f);return d&&Co(d,u.workflow,u.transitionHandler)}},workflows:[u.workflow],transitionHandlers:[u.transitionHandler]}),executors:u.executors,application:null}}let a=i?.packageRoot?Mu.join(i.packageRoot,"application.json"):await Ap(e,o,t),s=await Wl({file:a,projectRoot:e,runId:t,...i?{expectedIdentity:i}:{},readOnly:r.readOnly});if(s.identity.id!==o||s.identity.base!=="native")throw new Error("Native change owner does not match its fixed Application");return{runtime:Pt({...s.implementation,...r.readOnly?{executors:[]}:{},store:s.store}),executors:s.implementation.executors??[],application:s}}async function oN(e,t,r={}){let n=await je(e,"native",t,r);if(!n)throw new Error(`Native change ${t} is not owned by an SDK Run`);let{runtime:i,application:o}=await iN(e,t,{...r,owner:n}),a=await i.inspect(n.runId);if(a.workflow.id!=="comet-native"||!a.input||typeof a.input!="object"||Array.isArray(a.input)||a.input.name!==t||typeof a.input.artifactRootRef!="string")throw new Error(`Native SDK Run ${t} does not match its change ownership`);let s=M(a.state);if(s.name!==t)throw new Error(`Native SDK Run ${t} has a different state name`);return{run:a,state:s,artifactRootRef:a.input.artifactRootRef,application:o}}async function $9(e,t,r={}){let n=Mu.resolve(e);return await je(n,"native",t,r)?{projectRoot:n,...await oN(n,t,r)}:null}async function lj(e,t,r={}){let n=Mu.resolve(e),i=await ki(n,"native",t,r);if(!i&&!r.readOnly){let o=await Be(n);if(o){let a=await ke(n,o.native.artifact_root,{change:t});i=await P9(a,t)}}return i?n:(await $9(n,t,r))?.projectRoot??n}lb();var sN=Qt("nativeHookProjectConfig",Be),dj=Qt("nativeHookSdkRun",(e,t)=>oN(e,t,{readOnly:!0})),D9=new Set(["brief.md","children.yaml","comet-state.yaml","verification.md","capability-association.yaml"]),fj=new Set(["comet-state.yaml","verification.md","capability-association.yaml"]);function cN(e){let t=e.split("/");return t.length===3&&t[0]==="specs"&&t[1]!==void 0&&So.test(t[1])&&(t[2]==="spec.md"||t[2]===Ws)}function gh(e,t){if(!Ft(e,t))return null;let r=_e.relative(e,t).replaceAll("\\","/"),[n,...i]=r.split("/");if(!n||!So.test(n))return null;if(i.length===0)return{name:n,relative:""};let o=i.join("/");return D9.has(o)?{name:n,relative:o}:cN(o)?{name:n,relative:o}:null}function B9(e,t){return Ft(e.workspaceRuntimeRoot,t)||Ft(_e.join(e.projectRoot,".comet","runtime"),t)||_e.relative(e.projectRoot,t).replaceAll("\\","/")===".comet/current-change.json"}function W9(e,t,r){let n=_e.join(e.projectRoot,".comet","comet");if(Ft(e.nativeRoot,t)||_e.resolve(n)===_e.resolve(e.nativeRoot))return null;let i=gh(_e.join(n,"changes"),t);return i&&r.has(i.name)?i:null}function pj(e){return e==="brief.md"?"data.artifacts.briefPath":e==="children.yaml"?"data.artifacts.childrenPath":e.startsWith("specs/")?"data.artifacts.specsDir":"data.artifacts.changeDir"}function mj(e,t,r){return`Published Native specs are updated through Archive. Read ${_e.join(e,"specs",_e.relative(t,r))}, merge the original edit there, and retry the write against that exact target; do not overwrite existing content.`}function uj(e,t,r,n={}){if(B9(t,r)){let s=Ft(t.workspaceRuntimeRoot,r)?_e.relative(t.workspaceRuntimeRoot,r).replaceAll("\\","/"):_e.relative(t.projectRoot,r).replaceAll("\\","/"),c=s.match(/^(?:\.comet\/runtime\/)?native\/changes\/([^/]+)(?:\/|$)/u)?.[1];return{allowed:!1,reason:`Native Runtime-owned path ${s}. Run ${c?`comet native status ${c} --json`:"comet native status --json"} in ${t.projectRoot}, follow its continuation, and retry; do not edit Runtime files directly.`,workflow:"native",...c?{change:c}:{}}}if(!Ft(e,r))return null;let i=W9(t,r,n.registeredChanges??new Set);if(i){let s=_e.join(t.changesDir,i.name,i.relative);return{allowed:!1,reason:`Native formal artifact target ${_e.relative(e,r).replaceAll("\\","/")} is outside the configured artifact root. Use ${s} in ${t.projectRoot}; read existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:i.name}}let o=gh(t.changesDir,r);if(!o)return null;if(fj.has(o.relative))return{allowed:!1,reason:`Native Runtime-owned artifact ${_e.relative(e,r).replaceAll("\\","/")}. Run comet native status ${o.name} --json in ${t.projectRoot} and follow its continuation; do not infer a mutation or edit the file directly.`,workflow:"native",change:o.name};if(n.allowCanonicalFormal===!1)return null;let a=_e.join(t.changesDir,o.name,o.relative);return{allowed:!1,reason:`Native formal artifact target ${_e.relative(e,r).replaceAll("\\","/")} is not registered. Run comet native new ${o.name} in ${t.projectRoot}. Use the response ${pj(o.relative)} to locate ${a}; read initialized or existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:o.name}}function aN(e){return e.length===0?null:e.length===1?e[0]:{...e[0],reason:e.map(t=>t.reason).join(`
|
|
439
|
+
`)}}function L9(e,t,r,n,i,o){let a=_e.relative(e,i).replaceAll("\\","/"),s=_e.join(t.changesDir,n.name,n.relative);return{allowed:!1,reason:o?`Native formal artifact target ${a} belongs to registered change ${n.name}, not selected change ${r}. Run comet native select ${n.name} in ${t.projectRoot}, then read ${s} and merge the original edit.`:`Native formal artifact target ${a} belongs to unregistered change ${n.name}, not selected change ${r}. Run comet native new ${n.name} --isolation worktree in ${t.projectRoot}. Use the response ${pj(n.relative)} to locate ${s}; read initialized or existing content and merge the original edit.`,workflow:"native",change:r}}function hj(e){let t=`Native change ${e.name} is in ${e.phase}; implementation writes are only allowed in Build.`;return e.phase==="shape"?`${t} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:e.phase==="verify"?`${t} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:e.phase==="archive"?`${t} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${t} Create or select a separate Native change if this write belongs to different work.`}async function V9(e){let{projectRoot:t,paths:r,state:n,request:i}=e,o=dt(r,n.name),a=[],s=[],c=[],l=[],u=[],f=await gj(t),d=!1,p=!1,h=!1;for(let m of i.targets){let g=_e.resolve(t,m);if(!Ft(t,g)){h=!0;continue}let v=_e.relative(t,g).replaceAll("\\","/");if(g===_e.join(o,"walkthrough.html")){l.push(v);continue}if(v===".comet/config.yaml"){p=!0;continue}if(!Ft(r.nativeRoot,g)){if(await Qp(t,g,[_e.join(t,".comet"),r.nativeRoot])){d=!0;continue}if(!f&&vj(r,v)){l.push(v);continue}c.push(v);continue}if(!Ft(o,g)){u.push({allowed:!1,reason:Ft(r.specsDir,g)?mj(o,r.specsDir,g):"Portable Native control state is Runtime-owned",workflow:"native",phase:n.phase,change:n.name});continue}let w=_e.relative(o,g).replaceAll("\\","/");if(w==="brief.md"||w==="children.yaml"||w.startsWith("specs/")&&M9(w)){a.push(w);continue}if(w.startsWith("specs/")){s.push(w);continue}u.push({allowed:!1,reason:`${w||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:n.phase,change:n.name})}return s.length>0&&u.push({allowed:!1,reason:s.map(wj).join(`
|
|
440
|
+
`),workflow:"native",phase:n.phase,change:n.name}),u.length>0?aN(u):a.length>0&&(c.length>0||l.length>0)?{allowed:!1,reason:"Formal Native requirements must be edited in separate actions from implementation or documentation files",workflow:"native",phase:n.phase,change:n.name}:a.length>0?{allowed:!0,reason:"保留当前批准。由 Agent 判断正式材料是否改变已确认需求;超出授权时先取得对应决定。",workflow:"native",phase:n.phase,change:n.name}:c.length>0?n.children_contract_ref?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:n.phase,change:n.name}:n.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:n.phase,change:n.name}:["verify","archive"].includes(n.phase)&&!f?{allowed:!0,reason:"保留当前 Run 和用户编辑。由当前 Agent 判断实际影响、补充受影响检查或显式修订实现;文件编辑不自动撤回批准。",workflow:"native",phase:n.phase,change:n.name}:{allowed:!1,reason:hj(n),workflow:"native",phase:n.phase,change:n.name}:l.length>0?{allowed:!0,reason:"Native neutral document write: documentation edits stay outside the implementation scope and do not return the change to Build",workflow:"native",phase:n.phase,change:n.name}:d?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:n.phase,change:n.name}:{allowed:!0,reason:p?"Native control artifact write":h?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:n.phase,change:n.name}}function Ft(e,t){let r=_e.relative(e,t);return r===""||!r.startsWith("..")&&!_e.isAbsolute(r)}async function gj(e){return(await sN(e))?.native?.document_writes==="revert"}function vj(e,t){return OT(t,[_e.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),".comet"])}function wj(e){let t=e.split("/"),r=t[0]==="specs"&&t[1]&&So.test(t[1])?t[1]:null;return`Native formal Spec artifacts must use ${r?`specs/${r}/spec.md (or specs/${r}/${Ws} for delta metadata)`:`specs/<capability>/spec.md (or specs/<capability>/${Ws} for delta metadata)`}; received ${e}`}function M9(e){return cN(e)}function q9(e,t,r){return r.targets.length>0&&r.targets.every(n=>{let i=_e.resolve(e,n);return Ft(e,i)?_e.relative(e,i).replaceAll("\\","/")===".comet/config.yaml"||Ft(t,i):!0})}async function F9(e){let t=await sN(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let r=await ke(e,t.native.artifact_root,{readOnly:!0}),n=await Lk(e),i=new Set(n.active),o=new Set(n.history),a;try{a=await j9.readdir(r.changesDir,{withFileTypes:!0})}catch(u){if(u.code==="ENOENT")a=[];else throw u}let s=[];for(let u of a.sort((f,d)=>f.name.localeCompare(d.name)))!u.isDirectory()||u.isSymbolicLink()||o.has(u.name)||s.push({name:u.name,sdk:i.delete(u.name)});for(let u of i)s.push({name:u,sdk:!0});let c=await Oa(s,4,async({name:u,sdk:f})=>{try{if(f){if(await Wk(e,u))return{status:"fulfilled",value:null};let{state:p,run:h}=await dj(e,u);return{status:"fulfilled",value:p.archived||await Yl({projectRoot:e,run:h})?null:{kind:"sdk",state:p,cancelling:h.status==="cancelled"}}}if(await zs(r,u)){let p=await Lr(r,u);return{status:"fulfilled",value:p.archived?null:{kind:"portable",state:p}}}let d=await wu(r,u);return{status:"fulfilled",value:d.archived?null:{kind:"legacy",state:d}}}catch(d){return{status:"rejected",reason:d}}}),l=[];for(let u of c){if(u.status==="rejected")throw u.reason;u.value&&l.push(u.value)}return{paths:r,changes:l}}async function H9(e,t){let r=await sN(e);if(!r||!(r.workflows??[r.default_workflow]).includes("native"))return null;let n=await ke(e,r.native.artifact_root,{readOnly:!0});try{if(await je(e,"native",t,{readOnly:!0})){if(await Wk(e,t))return{paths:n,changes:[]};let{state:o,run:a}=await dj(e,t),s=o.archived||await Yl({projectRoot:e,run:a});return{paths:n,changes:s?[]:[{kind:"sdk",state:o,cancelling:a.status==="cancelled"}]}}if(await zs(n,t)){let o=await Lr(n,t);return{paths:n,changes:o.archived?[]:[{kind:"portable",state:o}]}}let i=await wu(n,t);return{paths:n,changes:i.archived?[]:[{kind:"legacy",state:i}]}}catch(i){if(i.code==="ENOENT")return{paths:n,changes:[]};throw i}}var Q9=Qt("nativeActiveContext",e=>F9(e)),yj=Qt("selectedNativeContext",H9);async function U9(e,t){let n=(await yj(e,t))?.changes[0]?.state;return n?{workflow:"native",name:n.name,phase:n.phase}:null}async function kj(){let{intent:e,targets:t,writes:r}=await RT();return{intent:e,targets:t,...r?{writes:r}:{}}}async function Aj(e,t,r){t={...t,targets:wa(t.targets)};let n=r?await yj(e,r):await Q9(e);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0){let m=[];for(let v of t.targets){let w=uj(e,n.paths,_e.resolve(e,v));w&&m.push(w)}let g=aN(m);return g||{allowed:!0,reason:q9(e,n.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"}}let i;if(r){if(i=n.changes.find(m=>m.state.name===r),!i)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(n.changes.length===1)i=n.changes[0];else{let m=await Y0(n.paths);if(i=n.changes.find(g=>g.state.name===m),!i)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let o=i.state,a=new Set(n.changes.map(({state:m})=>m.name)),s=new Map,c=[];for(let m of t.targets){let g=_e.resolve(e,m),v=uj(e,n.paths,g,{allowCanonicalFormal:!1,registeredChanges:a});if(v){c.push({...v,phase:o.phase});continue}let w=gh(n.paths.changesDir,g);if(w&&w.name!==o.name){let b=a.has(w.name);if(!b&&r){let E=s.get(w.name);E||(E=U9(e,w.name).then(Boolean),s.set(w.name,E)),b=await E}c.push(L9(e,n.paths,o.name,w,g,b));continue}if(!Ft(e,g))continue;if(Ft(n.paths.specsDir,g)){let b=i.kind!=="legacy"?dt(n.paths,o.name):Fs(n.paths,o.name);c.push({allowed:!1,reason:mj(b,n.paths.specsDir,g),workflow:"native",phase:o.phase,change:o.name});continue}if(!Ft(n.paths.nativeRoot,g))continue;let A=i.kind!=="legacy"?dt(n.paths,o.name):Fs(n.paths,o.name);if(Ft(A,g)){let b=_e.relative(A,g).replaceAll("\\","/");if(b==="walkthrough.html"||b==="brief.md"||b==="children.yaml"||cN(b))continue;c.push({allowed:!1,reason:b.startsWith("specs/")?wj(b):`${b||"change directory"} is Runtime-owned. Run comet native status ${o.name} --json in ${n.paths.projectRoot} and follow its continuation; do not edit it directly.`,workflow:"native",phase:o.phase,change:o.name});continue}let N=_e.relative(e,g).replaceAll("\\","/");c.push({allowed:!1,reason:`Native-managed path ${N} is not an editable artifact for ${o.name}. Run comet native status ${o.name} --json in ${n.paths.projectRoot} and follow its continuation.`,workflow:"native",phase:o.phase,change:o.name})}let l=aN(c);if(l)return l;if(i.kind==="legacy"&&o.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:o.phase,change:o.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:o.phase,change:o.name};if(i.kind==="sdk"&&i.cancelling)return{allowed:!1,reason:`Native change ${o.name} is cancelling; confirm the original executions stopped and finish cancellation cleanup before writing`,workflow:"native",change:o.name,phase:o.phase};if(i.kind!=="legacy")return V9({projectRoot:e,paths:n.paths,state:i.state,request:t,runtimeFormat:i.kind==="sdk"?"sdk":"compat"});let u=!1,f=!1,d=!1,p=!1,h=await gj(e);for(let m of t.targets){let g=_e.resolve(e,m);if(g===_e.join(Fs(n.paths,o.name),"walkthrough.html")){p=!0;continue}if(!Ft(e,g)){f=!0;continue}let v=_e.relative(e,g).replaceAll("\\","/");if(v===".comet/config.yaml"){u=!0;continue}if(Ft(n.paths.nativeRoot,g)){let w=gh(n.paths.changesDir,g);if(w?.name===o.name){if(fj.has(w.relative))return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${v}`,workflow:"native",phase:o.phase,change:o.name};u=!0;continue}return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${v}`,workflow:"native",phase:o.phase,change:o.name}}if(await Qp(e,g,[_e.join(e,".comet"),n.paths.nativeRoot])){d=!0;continue}if(!h&&vj(n.paths,v)){p=!0;continue}return{allowed:!1,reason:hj(o),workflow:"native",phase:o.phase,change:o.name}}return{allowed:!0,reason:u?"Native control artifact write":f?"Write target is outside the guarded project":d?"Native configured Hook allow path":p?"Native neutral document write: documentation edits stay outside the implementation scope":"No guarded write target was provided",workflow:"native",phase:o.phase,change:o.name}}$s();Di();qk();_t();import qu from"path";import{realpathSync as c4}from"fs";function bj(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:`'${t.replace(/'/gu,`'"'"'`)}'`).join(" ")}function Nj(e,t){let r=m=>m!==null&&typeof m=="object"&&!Array.isArray(m)?m:{},n=r(e),i=r(n.entry),o=r(n.run??i.run??(typeof n.runId=="string"?n:void 0)),a=r(n.state??i.state??n),s=r(n.preparation??n.workspace??i.workspace),c=r(n.continuation??i.continuation??n.nextAction??i.nextAction),l=typeof s.projectRoot=="string"&&s.projectRoot!=="."?s.projectRoot:typeof c.cwd=="string"?c.cwd:typeof n.projectRoot=="string"?n.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,u=a.stateVersion??a.state_version,f=a.status??o.status,{current:d,...p}=c,h=d===void 0?c:{...p,currentRef:n.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof a.phase=="string"?a.phase:null,status:typeof f=="string"?f:null,stateVersion:typeof u=="number"?u:null,workspace:{cwd:l},continuation:Object.keys(c).length?{...h,cwd:l}:null,...Object.keys(o).length?{run:{id:typeof o.id=="string"?o.id:typeof o.runId=="string"?o.runId:null,revision:typeof o.revision=="number"?o.revision:null,status:typeof o.status=="string"?o.status:null}}:{}}}var ii={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Rj(e){return e?e.command?`${ii.next} ${e.command}`:e.ask_user?`${ii.next} ${e.ask_user}`:e.instruction?`${ii.next} ${e.instruction}`:null:null}function Sj(e,t){let r=[e.summary],n=Rj(e.next);return n&&r.push(n),e.user_message&&r.push("",ii.relay,e.user_message),t!==void 0&&r.push("",ii.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
441
|
+
`)}
|
|
442
|
+
`}function Ej(e,t,r){let n=[e.summary],i=Rj(e.next);return i&&n.push(i),e.user_message&&n.push("",ii.relay,e.user_message),n.push("",`${ii.detail} ${t}`),r!==void 0&&n.push("",ii.details,JSON.stringify(r,null,2)),n.join(`
|
|
443
|
+
`)}Ye();It();function Ne(e,t,r){return e==="zh-CN"?r:t}var lN={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Cj(e,t){return typeof e=="string"&&lN[e]?Ne(t,lN[e].en,lN[e].zh):typeof e=="string"?e:""}function uN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function J9(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let n=r.result;if(n!=="passed"&&n!=="failed"&&n!=="blocked"&&n!=="pending")return null;t[n]+=1}return t}function _j(e,t){let r=[];e.failed>0&&r.push(Ne(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(Ne(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(Ne(t,`${e.pending} pending`,`${e.pending} 项待验`));let n=Ne(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${n} (${r.join(", ")})`:n}function Ij(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function dN(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function z9(e,t,r){return e==="done"?Ne(r,"complete","已完成"):e==="await-user"?Ne(r,"waiting for a user decision","等待用户决定"):e==="blocked"?Ne(r,"paused: needs attention","已暂停,需要处理"):t?Ne(r,"waiting for a user decision","等待用户决定"):Ne(r,"ready to continue","可继续推进")}function K9(e,t,r){let n=dN(e),i=[];r&&i.push(r);let o=Ne(n,`Change ${e.change}`,`需求 ${e.change}`),a=Cj(e.phase,n),s=e.mode==="wait"?Ne(n,"waiting for the original task","等待原任务完成"):z9(e.disposition,e.userCommunication.required,n);i.push([o,a||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&i.push(_j(t,n));let c=e.userCommunication,l=xj(e,n);return{summary:i.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function xj(e,t){let r=e.userCommunication;return e.mode&&e.mode!=="execute"?e.mode==="ask"?{ask_user:r.agentInstruction}:{instruction:r.agentInstruction}:e.disposition==="await-user"&&r.required?{ask_user:Ne(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")}:e.commandArgs&&e.commandArgs.length>0?{command:bj(e.commandArgs)}:e.disposition==="done"?{ask_user:Ne(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")}:e.disposition==="blocked"?{ask_user:r.required&&r.message?r.agentInstruction:Ne(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}:{instruction:r.agentInstruction}}function G9(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Y9(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",n=Cj(e.phase,t),i=e.status==="await-user"?Ne(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?Ne(t,"paused","已暂停"):e.status==="done"?Ne(t,"complete","已完成"):Ne(t,"in progress","进行中"),o=uN(e.acceptance)?`${Ne(t,", ",",")}${_j(e.acceptance,t)}`:"";return` ${r} · ${n||String(e.phase??"?")} · ${i}${o}`}function X9(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Z9(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function e4(e){if(e.healthy){let n=e.repaired?Ne("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):Ne("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),i=t4(e.continuation);return i?{summary:n,next:i}:{summary:n}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:Ne("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:Ne("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function t4(e){return Ij(e)?xj(e,dN(e)):void 0}function Pj(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Z9(t))return e4(t);if(G9(t)){let n=X9(t.items);return{summary:[t.total===t.items.length?Ne(n,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):Ne(n,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(o=>Y9(o,n))].join(`
|
|
444
|
+
`)}}let r=t.continuation;if(Ij(r)){let n=dN(r),i=K9(r,r4(t),i4(t,n));return n4(t)==="unconfirmed"?{...i,summary:`${i.summary}${Ne(n,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:i}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let n=t.language==="zh-CN"?"zh-CN":"en",i="pendingRootMove"in t;return{summary:Ne(n,i?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,i?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function r4(e){if(uN(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(uN(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return J9(r.acceptance)}return null}function n4(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function i4(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return Ne(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?Ne(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Tj(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:r.outcome==="revision-conflict"||/^expected revision \d+, got \d+$/iu.test(e.message)?Ne("en","This change was updated by another operation. Read the latest state and continue from its current instructions.","这条需求已被另一个操作更新。请读取最新状态,按当前指引继续。"):e.message,...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:Ne("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:Ne("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:Ne("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:Ne("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:Ne("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:Ne("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:Ne("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:Ne("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var vh=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};bp();JA();Rp();var Oj=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--compact 与 --json 合用;重复字段用 outputView.references 的 JSON Pointer 定位,Request 模板保留完整;没有字节收益时返回原完整协议。去掉此选项获取完整协议。","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],fN=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","After Shape approval, new ordinary SDK tasks use `next <change> --session <actual-session>`. Submit business results using the returned command. Runtime checks and the next task are returned together. Older and Supervisor tasks retain their returned protocol through `comet runtime dispatch --application native`; read continuation.inputOptions when present.","For compat Runtime changes, execute `agent.continuation.commandArgs` in `agent.workspace.cwd` and fill `agent.continuation.inputOptions` templates."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","cancel <change-name> Cancel an unfinished change while keeping its code and workspace.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state.","transfer export|import Move an active Supervisor Child Build to another checkout."],options:Oj,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--runtime compat|sdk] [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--runtime compat|sdk Runtime format for this new change; defaults to sdk.","--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Preserve the original request in the SDK Run for independent alignment review; also search Project Knowledge for a capability association.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The SDK Run or portable state, canonical artifact paths, and workspace preparation result; compat Runtime changes include the next Runner continuation.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
|
|
445
|
+
comet native spec remove <change-name> <capability>
|
|
446
|
+
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Compat-only Markdown reference correction; SDK changes return to Shape for revision."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec snapshot":{usage:"comet native spec snapshot <change-name>",purpose:"Restore the originally approved documents first. Runtime checks their complete legacy fingerprint and saves at most 2 MiB of original evidence in this workspace Runtime. It does not approve changed requirements or change the Run, candidate, Action, claim or check receipts. Evidence is local to this workspace; repeat the verified capture after moving to another device.",output:"The validated original Shape identity and captured sources; no workflow state changes."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Compat-only reference correction. SDK changes use Shape edits or next --revise-requirements from Verify/Archive.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"For compat Runtime changes, the audited state and Build continuation for re-verification. SDK changes receive revise-requirements guidance."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; compat Runtime state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Compatibility guidance for running checks through Agent platform tools.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details SDK: include complete business state and Action/Wait history. Compat: include one fixed-size detail page."],output:"SDK status includes the exact continuation, claim request templates, all pending/running/unknown work, and the latest 12 settled records per history collection. run.history reports omitted records; --details returns complete history without --cursor. Compat status reports business continuation and details use --cursor for fixed-size pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name> [--rebind]",options:["--rebind Explicitly bind the same idle SDK Run to the current Git branch; preserve work and approvals, and reject unresolved executions."],purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --session <actual-session> [--action <id>] [--result <json-file>] [--review current-session|independent] [--accept-on-pass <authorization-summary>] [--details]
|
|
447
|
+
comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
448
|
+
comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
|
|
449
|
+
comet native next <sdk-change> --confirmed --coordination-mode multi-session|single-session --summary <text> --expected-state-version <n> --expected-action confirm-shape
|
|
450
|
+
comet native next <sdk-change> --accept-result|--revise-implementation|--retry-verifier|--continue-builder|--resolve-verifier-blocker --summary <text> --proposal-hash <hash> --expected-state-version <n> --expected-action <action>
|
|
451
|
+
comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Advance SDK-owned Runtime actions and bound user decisions, or recover a compat Runtime Agent boundary and use its skill-coordinated Builder/Verifier JSON bridge.",options:["--session <actual-session> Claim a new ordinary SDK task using its real receiving session.","--action <id> Preserve the current task ID when claiming or reporting.","--result <json-file> Submit actual status/output business fields, run authorized internal steps, and return the next task. Requires --action and --session.","--review current-session|independent Continue ordinary Verify in this session or leave it for a separate actual receiver. Honor explicit user requests for independent review.","--accept-on-pass <authorization-summary> With this Verify result only, record prior explicit user delegation to accept and archive if all criteria pass. Without this option, wait for user acceptance.","--details With --session, include the full SDK projection alongside the current task.","--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request For compat changes, with --accept-result record the explicitly chosen isolated-workspace finish in the same guarded decision. SDK Runs keep Git delivery separate.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Renew a pending Shape proposal or return Verify, Archive, or a quiescent SDK Supervisor Build to Shape. SDK changes also allow revising after an ordinary Builder explicitly failed; use the current continuation proposal hash. Preserve partial work and reconcile running/unknown Actions first. The new Shape still requires explicit approval. Completed SDK Runs require an application-validated blocked Child recovery.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--continue-builder After a failed SDK Builder Action, explicitly continue from its preserved workspace in a new Action.","--resolve-verifier-blocker Resume an SDK or compat blocked Verifier with the retained candidate and valid checks; a completed SDK Supervisor Child resumes with a new Builder. SDK recovery requires the current proposal hash and both expected guards; original outcomes are preserved.","--max-parallel <n> Compat-only Supervisor concurrency override. SDK and Compat use native.max_parallel_children (default 2); configure it in project settings or .comet/config.yaml; single-session always uses 1.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--proposal-hash <hash> SDK decision guard from the current Wait or blocked Child continuation; required with --accept-result, --revise-implementation, --retry-verifier, --continue-builder, or --resolve-verifier-blocker, and with --revise-requirements for pending Shape or failed ordinary Builder recovery.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, known_limits, optional review. Cover every confirmed acceptance ID with its actual status, evidence and note. Only implemented-with-evidence entries with nonempty evidence are ready for handoff. checks contain actual Agent platform reports. An optional review records status=passed, summary and reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind. Run development checks through Agent platform tools and hand the current candidate to the selected Verifier."," retry-checks is a retired compatibility input that returns platform execution guidance without running a command."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (final-result). Copy the current candidate and receiving session from the dispatch and report every acceptance item."," verifier-started is optional compatibility progress reporting for the existing Verifier session; it does not supervise a process or authorize completion."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef. Record the actual platform capability failure; it never grants a passing result."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks is retired and returns platform execution guidance without starting a process or generating a receipt."," supervisor-verifier-result evidence fields: summary, checks (actual platform reports), acceptance [{id,result,reason}]. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once."," supervisor-integrate fields: child, integrationCommit and checks [{name,status,reason}], reporting the actual merge and platform checks."],output:"SDK-owned changes return the current Run Action or Wait and the same continuation as status/show, including current decision guards and pending Action claimRequest templates. Fill the template with the host session and claim token; the successful claim returns the current Action input. Authorized internal business steps and Archive continue from the original Run. Builder and Verifier handoffs use `comet runtime dispatch --application native`; never resubmit running/unknown work. Compat Runtime changes return the portable state, Runner result, continuation.inputOptions, and userCommunication. The compat JSON bridge is not trusted identity attestation: a passing skill-coordinated result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --revise-requirements --summary "User changed the pending Shape or stopped Builder requirements" --proposal-hash <hash> --expected-state-version <n> --expected-action revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --continue-builder --summary "Continue the inspected partial work" --proposal-hash <hash> --expected-state-version <n> --expected-action continue-builder','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},cancel:{usage:"comet native cancel <change-name> [--reason <text>] [--dry-run]",purpose:"Cancel an unfinished SDK Native change: it stops counting as active without verification or a fake Archive.",options:["--reason <text> Record why the change is cancelled; defaults to a neutral user-cancellation note.","--dry-run List what cancellation would stop, release, and retain without changing any state."],output:"The cancellation status and its outstanding acknowledgements. Code, commits, branches, and the workspace are always retained; deleting implementations or worktrees stays a separate explicit Git operation. Completed changes are rejected in favor of archive; legacy 0.4 runtime changes keep their original lifecycle."},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
|
|
452
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]
|
|
453
|
+
comet native archive <sdk-change-name> --recover [--legacy-spec-backup <json-file>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> For compat changes, set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> For compat changes, set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it.","--legacy-spec-backup <json-file> SDK only: read a bounded original-Spec backup for an existing legacy Archive transaction. Use a new file outside the project so it does not change the old candidate. Requires exact schema/runId/transactionId/path/hash and original candidate digest matches; never writes the source file or Git index. See docs/operations/native-archive-recovery.zh.md.","--recover For an SDK-owned change, reconcile one unknown Supervisor delivery, Archive, or cleanup Action only after confirming the original execution process has stopped; never retry it as new work."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair] [--confirmed] [--migrate-history]",purpose:"Inspect Native business state and existing transactions, or recover the original Run checkpoint.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary.","--migrate-history Validate and close built-in Native terminal Runs whose business cleanup is complete. Preserve documents and checkpoints; unfinished or invalid Runs remain active. Safe to rerun after interruption. Upgrade CLI and platform Hooks together: older Runtime versions cannot write the new storage format. Ordinary inspection never migrates.","--confirmed With --repair and a named managed change whose local Run history is missing, recover its saved Run checkpoint. Original business approvals and task claims are preserved."],output:"Health, original business records, and structured recovery with diagnosticArgs, recoveryArgs and preconditions. Inspection does not change the Run."},transfer:{usage:`comet native transfer export <change-name> --output <directory> --confirmed-stopped
|
|
454
|
+
comet native transfer import --input <directory>`,purpose:"Carry a prepared Supervisor Child Builder and its Git worktrees to another checkout before handing the next Child task to an Agent.",subcommands:["export Snapshot the parent checkpoint, Supervisor branches, and non-ignored uncommitted work.","import Validate the package and restore its Run and worktrees in a checkout at the same target commit."],options:["--output <directory> New private directory for the transfer package; must not already exist.","--input <directory> Existing transfer package to import.","--confirmed-stopped Confirm the original Builder and other Supervisor agents stopped before export."],output:"The package path or restored change and worktree paths. An in-flight Builder becomes outcome-unknown and must be reconciled; import never reports its work as completed."}});function wh(e,t){return`${e}:
|
|
455
|
+
${t.map(r=>` ${r}`).join(`
|
|
456
|
+
`)}`}function o4(e){let t=e.filter(n=>n!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return fN[r]||t.length>1&&fN[t[0]]?.subcommands?r:t[0]}function a4(e=[]){let t=o4(e),r=fN[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let n=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&n.push("",wh("Agent Quick Start",r.agentQuickStart)),r.subcommands&&n.push("",wh("Commands",r.subcommands));let i=t===""?r.options:[...r.options??[],...Oj];return i&&i.length>0&&n.push("",wh("Options",i)),n.push("",`Output:
|
|
457
|
+
${r.output}`),r.examples&&n.push("",wh("Examples",r.examples)),t===""&&n.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${n.join(`
|
|
458
|
+
`)}
|
|
459
|
+
`}}var s4=a4().usage;var Vn=class extends Error{};function yh(e,t){let r=e.flatMap((n,i)=>n===t?[i]:[]);if(r.length>1)throw new Vn(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function kh(e,t){let r=e.flatMap((o,a)=>o===t?[a]:[]);if(r.length>1)throw new Vn(`${t} may only be provided once`);if(r.length===0)return;let n=r[0],i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Vn(`${t} requires a value`);return e.splice(n,2),i}function jj(e){if(e.length>0)throw new Vn(`Unexpected argument: ${e[0]}`)}function pN(e,t){let r=qu.normalize($j(e)),n=qu.normalize($j(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function $j(e){let t=qu.resolve(e);try{return c4.native(t)}catch{return t}}function l4(e,t){let r=qu.resolve(t,e),n=ye(t);if(!n.isSecondaryWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null)return r;let i=ye(r);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!pN(n.primaryWorktreeRoot,i.primaryWorktreeRoot)||pN(n.currentWorktreeRoot,i.currentWorktreeRoot)?r:pN(t,n.currentWorktreeRoot)?qu.resolve(t):n.currentWorktreeRoot}async function Dj(e,t=process.cwd()){return e?l4(e,t):aA(t)}function Bj(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function u4(e){return JSON.stringify(e,null,2)+`
|
|
460
|
+
`}function d4(e,t){if(t instanceof Ks)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof mo)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof Vl)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Vn)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Up)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Os)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof ya)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Zn)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof vh)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Wj(e,t){let r=d4(e,t),n=r.error;if(!n)return r;let i=Tj({code:n.code,message:n.message,data:r.data});return i?{...r,envelope:i}:r}function f4(e,t,r=!1){let n=e.envelope??Pj(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Nj(e.data,e.executionCwd),...n===void 0?{}:{summary:n.summary,...n.next===void 0?{}:{next:n.next},...n.user_message===void 0?{}:{user_message:n.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
461
|
+
`}:e.error?{exitCode:e.exitCode,stderr:n?Ej(n,e.error.message,r?e.data:void 0):e.error.message}:n?{exitCode:e.exitCode,stdout:Sj(n,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==u4(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
462
|
+
${ii.details}
|
|
463
|
+
${JSON.stringify(e.data,null,2)}
|
|
464
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function p4(e,t,r=!1){let n=f4(e,t,r),i=!1;if(n.stdout?.trim())try{let o=JSON.parse(n.stdout);i=!!o&&typeof o=="object"&&!Array.isArray(o)}catch{i=!1}return{output:n,structuredDataVisible:i}}function Lj(e,t,r=!1){return p4(e,t,r).output}async function Vj(e,t){let r=kh(e,"--hook-output");if(r!==void 0&&r!=="copilot")throw new Vn("--hook-output must be copilot");jj(e);let n=await Aj(t,await kj());return r==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{}
|
|
465
|
+
`:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:n.reason})}
|
|
466
|
+
`}:n.allowed?{command:"hook-guard",exitCode:0,data:n}:{command:"hook-guard",exitCode:2,data:n,error:{code:"blocked",message:n.reason}}}import{Buffer as Mj}from"node:buffer";var m4=new Set(["continuation","input","commandArgs","userCommunication","current","pendingAction","changedPaths","artifactRefs","artifacts"]);function h4(e){if("outputView"in e)return e;let t={},r=new Map,n=new WeakMap,i=u=>u.replace(/~/gu,"~0").replace(/\//gu,"~1"),o=(u,f)=>/requests?$/iu.test(u)||f!==null&&typeof f=="object"&&"operation"in f,a=u=>{if(u===null||typeof u!="object")return!1;let f=n.get(u);if(f!==void 0)return f;let d=Object.entries(u).some(([p,h])=>o(p,h)||a(h));return n.set(u,d),d},s=(u,f,d,p)=>{if(o(d,u)||/(?:hash|revision|attempt|claim|token|blockers|workspace)$/iu.test(d))return u;if(p&&(typeof u=="string"&&u.length>=160||m4.has(d)&&u!==null&&typeof u=="object"&&!a(u))){let m=JSON.stringify(u);if(m.length>=160){let g=r.get(m);if(g!==void 0&&g.length+f.length+8<m.length){t[f]=g;return}return r.set(m,f),u}}return Array.isArray(u)?u.map((m,g)=>s(m,`${f}/${g}`,"",!1)):u!==null&&typeof u=="object"?Object.fromEntries(Object.entries(u).flatMap(([m,g])=>{let v=s(g,`${f}/${i(m)}`,m,!0);return v===void 0?[]:[[m,v]]})):u},c={..."data"in e?{data:e.data}:{},...e};return{...s(c,"","",!1),outputView:{schema:"comet.cli.compact.v1",mode:"compact",references:t,instruction:"references maps omitted JSON Pointers to equal values in this response (RFC 6901). Resolve references recursively to restore the full JSON. Request templates remain complete. Omit --compact for the full envelope."}}}function qj(e,t){if(!t||!e)return e;let r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))return e;let n=h4(r),i=n.outputView;if(!i?.references||Object.keys(i.references).length===0)return e;let o=`${JSON.stringify(n)}
|
|
467
|
+
`;return Mj.byteLength(o)<Mj.byteLength(e)?o:e}Ur();import Ah from"node:path";function Fj(e,t){return[...e,...t&&!e.includes("--project-root")?["--project-root",t]:[],...e.includes("--json")?[]:["--json"]]}function oi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function Hj(e,t){if(e.error?.code==="usage"||e.command==="hook-guard")return e;let r=oi(e.data),n=oi(r.continuation);if(oi(r.builderReadiness).ready===!1&&n.action==="builder-handoff")return e;let i=typeof r.change=="string"?r.change:typeof r.name=="string"?r.name:t.name,o=i&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i)?i:void 0,a=e.executionCwd??Ah.resolve(t.projectRoot);o&&e.exitCode!==0&&!e.executionCwd&&(a=await lj(a,o,{readOnly:!0}).catch(()=>a));let s=w=>Fj(w,a),c=s(["comet","native","doctor",...o?[o]:[]]),l=oi(r.state),u=oi(r.workspaceFinishResult),f=typeof u.message=="string"?u.message:e.error?.message??"",d=f.toLowerCase(),p=d.split(`
|
|
468
|
+
`),h=p.some(w=>{let A=w.indexOf("worktree");return A!==-1&&w.indexOf("locked",A+8+1)!==-1}),m=d.includes("index.lock")||d.includes("cannot lock ref")||h||p.some(w=>{let A=w.indexOf("unable to create");return A!==-1&&w.indexOf(".lock",A+16+1)!==-1}),g={schema:"comet.native.recovery.v1",code:"runtime-recovery-required",reason:e.error?.message??(typeof oi(r.recovery).reason=="string"?oi(r.recovery).reason:"Inspect the original execution and its retained evidence."),affectedPaths:[],owner:null,diagnosticArgs:c,recoveryArgs:null,preconditions:["Inspect the original Action before retrying; preserve its receipts."],preserved:{candidateId:oi(l.builder_handoff).candidate_id??r.candidateId??null,shapeConfirmationHash:l.shape_confirmation_hash??r.shapeConfirmationHash??null}},v=oi(r.recovery).schema?r.recovery:oi(n.recovery).schema?n.recovery:void 0;if(m){let w=typeof u.targetRoot=="string"?u.targetRoot:a,A=[];try{/index\.lock/iu.test(f)?A.push(Ah.resolve(w,ce(w,["rev-parse","--git-path","index.lock"]))):h&&A.push(Ah.join(Ah.resolve(w,ce(w,["rev-parse","--git-dir"])),"locked"))}catch{}v={...g,code:"git-lock",reason:f,affectedPaths:A,owner:null,diagnosticArgs:["git","-C",w,"status","--short"],recoveryArgs:Array.isArray(u.recoveryArgs)?s(u.recoveryArgs):Array.isArray(n.commandArgs)?s(n.commandArgs):e.command==="archive"&&o?s(["comet","native","archive",o]):null,preconditions:["Inspect the original Git command result and resolve its reported Git condition before retrying.","Resolve the reported Git lock or worktree condition, then retry the retained workflow step."]}}else if(!v&&(e.exitCode!==0||n.disposition==="blocked")){let w=Array.isArray(u.recoveryArgs)?u.recoveryArgs:n.commandArgs;v={...g,code:u.status==="blocked"?"workspace-conflict":e.command==="archive"?"archive-blocked":"runtime-recovery-required",reason:typeof u.message=="string"?u.message:g.reason,affectedPaths:Array.isArray(u.blockedPaths)?u.blockedPaths:[],diagnosticArgs:Array.isArray(u.diagnosticArgs)?u.diagnosticArgs:c,recoveryArgs:Array.isArray(w)&&w.every(A=>typeof A=="string")?s(w):null,preconditions:["Resolve the reported file, transaction, or execution conflict, then retry the original step."]}}return v?{...e,data:{...r,recovery:v,...n.schema?{continuation:{...n,recovery:v}}:{}},...e.error?{envelope:{summary:v.reason,next:{command:(v.recoveryArgs??v.diagnosticArgs).map(w=>/^[\w./:=+@-]+$/u.test(w)?w:JSON.stringify(w)).join(" ")}}}:{}}:e}_t();async function Qj(e,t,r=process.argv.slice(2)){let n=r.indexOf("--"),i=n<0?[...r]:r.slice(0,n),o=n<0?[]:r.slice(n),a=i.includes("--json"),s=i.includes("--verbose"),c=i.includes("--compact"),l,u,f,d;try{if(yh(i,"--json"),yh(i,"--compact"),c&&!a)throw new Vn("--compact requires --json");yh(i,"--verbose"),l=kh(i,"--project-root");let h=[...i,...o];u=h[0]?.startsWith("--")?void 0:h[0];let m=async()=>{let g=await Dj(l);return{executionCwd:g,...await t(h,g)}};d=Bj(e,h)?await VT(m):await m()}catch(h){f=h,d=Wj(e,h)}d=await Hj(d,{projectRoot:d.executionCwd??l??process.cwd(),name:u,error:f});let p=Lj(d,a,s);return p.stdout&&process.stdout.write(qj(p.stdout,c&&a)),p.stderr&&process.stderr.write(p.stderr+(p.stderr.endsWith(`
|
|
469
|
+
`)?"":`
|
|
470
|
+
`)),p.exitCode}process.exitCode=await Qj("hook-guard",Vj);
|