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,466 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var B$=Object.create;var qm=Object.defineProperty;var W$=Object.getOwnPropertyDescriptor;var L$=Object.getOwnPropertyNames;var V$=Object.getPrototypeOf,M$=Object.prototype.hasOwnProperty;var Ru=(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 I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var j=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Fm=(e,t)=>{for(var r in t)qm(e,r,{get:t[r],enumerable:!0})},q$=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of L$(t))!M$.call(e,i)&&i!==r&&qm(e,i,{get:()=>t[i],enumerable:!(n=W$(t,i))||n.enumerable});return e};var or=(e,t,r)=>(r=e!=null?B$(V$(e)):{},q$(t||!e||!e.__esModule?qm(r,"default",{value:e,enumerable:!0}):r,e));var Ea,Eo,Nu,Ln,_a=I(()=>{"use strict";Ea=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"},Eo=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"},Nu=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"},Ln=class extends Error{constructor(r,n,i){super(r,i);this.preparation=n;this.name="NativeWorkspacePreparationError"}preparation}});function xi(e){return e!==0&&e!==0n&&e!=="0"}function zs(e,t){return xi(e.dev)&&xi(t.dev)&&xi(e.ino)&&xi(t.ino)}function ht(e,t){let r=xi(e.dev)&&xi(t.dev);if(r&&e.dev!==t.dev)return!1;let n=xi(e.ino)&&xi(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var Ca=I(()=>{"use strict"});import{constants as Pi,promises as Ar}from"fs";import{createHash as F$}from"node:crypto";function Hm(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Su(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Oi(e){return{dev:e.dev,ino:e.ino,birthtime:Hm(e)}}function H$(e,t){let r=Oi(e),n=Oi(t);return zs(r,n)?ht(r,n):ht(r,n)&&Hm(e)===Hm(t)&&Su(e)===Su(t)&&e.size===t.size}function Ti(e,t){let r=n=>"mtimeNs"in n?n.mtimeNs:n.mtimeMs;return H$(e,t)&&e.size===t.size&&e.mode===t.mode&&r(e)===r(t)&&Su(e)===Su(t)}async function $i(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 Qt("not-regular-file",`${n} must be a regular file`);if(BigInt(o.size)>BigInt(t))throw new Qt("too-large",`${n} exceeds ${t} bytes`);let a=await Ar.realpath(e);await r.verify?.("pre-open",{realPath:a,identity:Oi(o)});let s=process.platform==="win32"?Pi.O_RDONLY:Pi.O_RDONLY|Pi.O_NOFOLLOW|Pi.O_NONBLOCK,c;try{c=await Ar.open(e,s)}catch(l){throw l.code==="ELOOP"?new Qt("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||!Ti(o,l)||!Ti(o,u))throw new Qt("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Oi(l)}),await r.hooks?.afterOpen?.();let d=[],m=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-m,{bytesRead:A}=await c.read(h,0,Math.min(h.length,w),null);if(A===0)break;if(m+=A,m>t)throw new Qt("too-large",`${n} exceeds ${t} bytes`);d.push(Buffer.from(h.subarray(0,A)))}await r.hooks?.beforeFinalCheck?.();let[p,g,v]=await Promise.all([c.stat({bigint:i}),Ar.lstat(e,{bigint:i}),Ar.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==a||!Ti(o,p)||!Ti(o,g))throw new Qt("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:Oi(p)}),{bytes:Buffer.concat(d,m),stat:p,realPath:v}}finally{await c.close()}}async function Sb(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 Qt("not-regular-file",`${r} must be a regular file`);let o=await Ar.realpath(e);await t.verify?.("pre-open",{realPath:o,identity:Oi(i)});let a=process.platform==="win32"?Pi.O_RDONLY:Pi.O_RDONLY|Pi.O_NOFOLLOW|Pi.O_NONBLOCK,s;try{s=await Ar.open(e,a)}catch(c){throw c.code==="ELOOP"?new Qt("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||!Ti(i,c)||!Ti(i,l))throw new Qt("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:Oi(c)}),await t.hooks?.afterOpen?.();let f=F$(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[m,h,p]=await Promise.all([s.stat({bigint:n}),Ar.lstat(e,{bigint:n}),Ar.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||p!==o||!Ti(i,m)||!Ti(i,h))throw new Qt("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:p,identity:Oi(m)}),{digest:f.digest("hex"),stat:m,realPath:p}}finally{await s.close()}}var Qt,ji=I(()=>{"use strict";Ca();Qt=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});var Qm=I(()=>{"use strict"});import{AsyncLocalStorage as _b}from"node:async_hooks";import{performance as Eb}from"node:perf_hooks";function z$(e=0){Q$+=1,U$+=e;for(let t of J$.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}function Ks(e){let t=Eb.now();try{return e()}finally{z$(Eb.now()-t)}}var Q$,U$,J$,bY,Eu=I(()=>{"use strict";Q$=0,U$=0,J$=new _b,bY=new _b});var Cb=I(()=>{"use strict"});var SY,Um=I(()=>{"use strict";SY=["$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 $Y,Jm=I(()=>{"use strict";Cb();Eu();Um();$Y=8*1024*1024});var Ib=I(()=>{"use strict"});import{execFileSync as X$}from"child_process";import xb from"fs";import Di from"path";import{AsyncLocalStorage as Km}from"node:async_hooks";function Tb(e){return Gs.getStore()?e():Gs.run(new Map,e)}function ej(e){let t=Gs.getStore();for(let r of e)t?.set(Bi(r.root),e);return e}function Ys(e,t){return Ks(()=>X$("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function me(e,t){return Bi(e)===Bi(t)}function Bi(e){let t=Di.resolve(e);try{let r=xb.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function Ae(e){let t=Z$.getStore()?.get(Bi(e));if(t)return{...t};try{let r=Pb.getStore()?.get(Bi(e)),n=Gs.getStore()?.get(r??Bi(e));if(n){let c=zm(r??e,n);if(c)return c;if(n.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Ob(e),o=zm(e,i);if(o&&xb.existsSync(Di.join(e,".git")))return o;let a=Di.resolve(Ys(e,["rev-parse","--show-toplevel"])),s=zm(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 _u(e){try{let t=Gs.getStore()?.get(Pb.getStore()?.get(Bi(e))??Bi(e));return t?t.map(r=>({...r})):Ob(e)}catch{return[]}}function Ob(e){let t=tj(Ys(e,["worktree","list","--porcelain","-z"]));return ej(t),t.map(r=>({...r}))}function tj(e){let t=e.split("\0"),r=[],n=null;for(let i of t)i.startsWith("worktree ")?(n&&r.push(n),n={root:Di.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 qt(e){return _u(e).map(t=>t.root)}function zm(e,t){let r=t.find(o=>me(Di.resolve(o.root),Di.resolve(e)));if(!r)return null;let n=Di.resolve(t[0].root),i=Di.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!me(n,i),currentWorktreeRoot:i,primaryWorktreeRoot:n,currentBranch:r.branch}}function Xs(e,t){try{return Ys(e,["check-ref-format","--branch",t]),Ys(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function he(e,t){try{let r=Ys(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 Gs,Pb,Z$,wt=I(()=>{"use strict";Eu();Jm();Ib();Um();Gs=new Km,Pb=new Km,Z$=new Km});import{AsyncLocalStorage as rj}from"node:async_hooks";function Cu(){let e=Gm.getStore();return e?.active?e:null}function Lb(){Cu()?.entries.clear()}async function Iu(e){if(Cu()!==null)return e();let t={entries:new Map,active:!0};return Gm.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function Mn(e){return Gm.run({entries:new Map,active:!1},e)}function Vb(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function Zr(e,t){return(...r)=>{let n=Cu();if(n===null)return t(...r);let i=Vb(`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 si(e,t){return(...r)=>{let n=Cu();if(n===null)return t(...r);let i=Vb(`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 Gm,qn=I(()=>{"use strict";Gm=new rj});import{createHash as nj}from"node:crypto";import{lstatSync as Zs,readFileSync as ij,realpathSync as Mb}from"node:fs";import oj from"node:os";import ar from"node:path";function Ym(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function xu(e){return process.platform==="win32"?Mb.native(e):Mb(e)}function sj(e){return aj(e)}function cj(e){let t=xu(ar.resolve(e)),r=Zs(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=Ym(r),i=(c,l)=>({projectRoot:t,workspaceId:nj("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,c,l])).digest("hex")}),o=ar.join(t,".git"),a,s;try{let c=Zs(o);if(c.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${o}`);if(c.isDirectory())a=xu(o),s=Ym(Zs(a,{bigint:!0}));else if(c.isFile()){let l=/^gitdir: (.+)\r?\n?$/u.exec(ij(o,"utf8"));if(!l)throw new Error(`工作区 .git 文件格式无效:${o}`);a=xu(ar.resolve(t,l[1].trim()));let u=Zs(a,{bigint:!0});if(!u.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${a}`);s=Ym(u)}else throw new Error(`工作区 .git 类型无效:${o}`)}catch(c){if(c.code!=="ENOENT")throw c;try{Zs(o)}catch(l){if(l.code==="ENOENT")return i(o,null);throw l}throw c}return i(a,s)}function qb(e){let t=ar.dirname(e);if(t===e)return e;try{return ar.join(xu(t),ar.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return ar.join(qb(t),ar.basename(e))}}function Xm(e){let t=sj(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!ar.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=lj(r??ar.join(oj.homedir(),".comet")),i=ar.relative(t.projectRoot,n);if(i===""||!ar.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ar.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let o=ar.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:o,runtimeRoot:ar.join(o,"runtime")}}function it(e){return Xm(e).runtimeRoot}var aj,lj,Zm=I(()=>{"use strict";qn();aj=si("workspaceIdentity",cj);lj=si("workspaceRuntimeParent",qb)});import{promises as ec}from"node:fs";import Fb from"node:path";async function Wi(e){return it(e)}async function eh(e){return[it(e)]}async function Hb(e){let t=Fb.dirname(e);if(t!==e){await Hb(t);try{await ec.mkdir(e,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}}let r=await ec.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function ci(e){let t=it(e);return await Hb(t),t}async function th(e,t,r){try{let n=await ec.lstat(e);if(n.isSymbolicLink())throw new Error("旧 Runtime 路径不能是符号链接:"+e);let i=n.isDirectory()?Fb.join(e,".comet-runtime-migration.json"):e,o=await ec.lstat(i);if(!o.isFile()||o.isSymbolicLink())return!1;let a;try{a=JSON.parse((await $i(i,Number.MAX_SAFE_INTEGER,{label:"旧 Runtime 标记"})).bytes.toString("utf8"))}catch(s){if(s instanceof SyntaxError)return!1;throw s}return a?.schema!=="comet.workspace-runtime-migration.v1"||typeof a.workspaceId!="string"||typeof a.source!="string"||typeof a.target!="string"||!["file","directory"].includes(a.kind)?!1:!n.isDirectory()||(await ec.readdir(e)).every(s=>s===".comet-runtime-migration.json")}catch(n){if(n.code==="ENOENT")return!1;throw n}}var Lr=I(()=>{"use strict";Zm();ji()});var $e=j(Ut=>{"use strict";var rh=Symbol.for("yaml.alias"),Qb=Symbol.for("yaml.document"),Pu=Symbol.for("yaml.map"),Ub=Symbol.for("yaml.pair"),nh=Symbol.for("yaml.scalar"),Tu=Symbol.for("yaml.seq"),li=Symbol.for("yaml.node.type"),uj=e=>!!e&&typeof e=="object"&&e[li]===rh,dj=e=>!!e&&typeof e=="object"&&e[li]===Qb,fj=e=>!!e&&typeof e=="object"&&e[li]===Pu,pj=e=>!!e&&typeof e=="object"&&e[li]===Ub,Jb=e=>!!e&&typeof e=="object"&&e[li]===nh,mj=e=>!!e&&typeof e=="object"&&e[li]===Tu;function zb(e){if(e&&typeof e=="object")switch(e[li]){case Pu:case Tu:return!0}return!1}function hj(e){if(e&&typeof e=="object")switch(e[li]){case rh:case Pu:case nh:case Tu:return!0}return!1}var gj=e=>(Jb(e)||zb(e))&&!!e.anchor;Ut.ALIAS=rh;Ut.DOC=Qb;Ut.MAP=Pu;Ut.NODE_TYPE=li;Ut.PAIR=Ub;Ut.SCALAR=nh;Ut.SEQ=Tu;Ut.hasAnchor=gj;Ut.isAlias=uj;Ut.isCollection=zb;Ut.isDocument=dj;Ut.isMap=fj;Ut.isNode=hj;Ut.isPair=pj;Ut.isScalar=Jb;Ut.isSeq=mj});var tc=j(ih=>{"use strict";var $t=$e(),br=Symbol("break visit"),Kb=Symbol("skip children"),Fn=Symbol("remove node");function Ou(e,t){let r=Gb(t);$t.isDocument(e)?Ia(null,e.contents,r,Object.freeze([e]))===Fn&&(e.contents=null):Ia(null,e,r,Object.freeze([]))}Ou.BREAK=br;Ou.SKIP=Kb;Ou.REMOVE=Fn;function Ia(e,t,r,n){let i=Yb(e,t,r,n);if($t.isNode(i)||$t.isPair(i))return Xb(e,n,i),Ia(e,i,r,n);if(typeof i!="symbol"){if($t.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=Ia(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===br)return br;a===Fn&&(t.items.splice(o,1),o-=1)}}}else if($t.isPair(t)){n=Object.freeze(n.concat(t));let o=Ia("key",t.key,r,n);if(o===br)return br;o===Fn&&(t.key=null);let a=Ia("value",t.value,r,n);if(a===br)return br;a===Fn&&(t.value=null)}}return i}async function $u(e,t){let r=Gb(t);$t.isDocument(e)?await xa(null,e.contents,r,Object.freeze([e]))===Fn&&(e.contents=null):await xa(null,e,r,Object.freeze([]))}$u.BREAK=br;$u.SKIP=Kb;$u.REMOVE=Fn;async function xa(e,t,r,n){let i=await Yb(e,t,r,n);if($t.isNode(i)||$t.isPair(i))return Xb(e,n,i),xa(e,i,r,n);if(typeof i!="symbol"){if($t.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=await xa(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===br)return br;a===Fn&&(t.items.splice(o,1),o-=1)}}}else if($t.isPair(t)){n=Object.freeze(n.concat(t));let o=await xa("key",t.key,r,n);if(o===br)return br;o===Fn&&(t.key=null);let a=await xa("value",t.value,r,n);if(a===br)return br;a===Fn&&(t.value=null)}}return i}function Gb(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 Yb(e,t,r,n){if(typeof r=="function")return r(e,t,n);if($t.isMap(t))return r.Map?.(e,t,n);if($t.isSeq(t))return r.Seq?.(e,t,n);if($t.isPair(t))return r.Pair?.(e,t,n);if($t.isScalar(t))return r.Scalar?.(e,t,n);if($t.isAlias(t))return r.Alias?.(e,t,n)}function Xb(e,t,r){let n=t[t.length-1];if($t.isCollection(n))n.items[e]=r;else if($t.isPair(n))e==="key"?n.key=r:n.value=r;else if($t.isDocument(n))n.contents=r;else{let i=$t.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}ih.visit=Ou;ih.visitAsync=$u});var oh=j(eR=>{"use strict";var Zb=$e(),vj=tc(),wj={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},yj=e=>e.replace(/[!,[\]{}]/g,t=>wj[t]),rc=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+yj(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&&Zb.isNode(t.contents)){let o={};vj.visit(t.contents,(a,s)=>{Zb.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(`
|
|
5
|
+
`)}};rc.defaultYaml={explicit:!1,version:"1.2"};rc.defaultTags={"!!":"tag:yaml.org,2002:"};eR.Directives=rc});var ju=j(nc=>{"use strict";var tR=$e(),kj=tc();function Aj(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 rR(e){let t=new Set;return kj.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function nR(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function bj(e,t){let r=[],n=new Map,i=null;return{onAnchor:o=>{r.push(o),i??(i=rR(e));let a=nR(t,i);return i.add(a),a},setAnchors:()=>{for(let o of r){let a=n.get(o);if(typeof a=="object"&&a.anchor&&(tR.isScalar(a.node)||tR.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}}nc.anchorIsValid=Aj;nc.anchorNames=rR;nc.createNodeAnchors=bj;nc.findNewAnchor=nR});var ah=j(iR=>{"use strict";function ic(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=ic(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=ic(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=ic(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=ic(e,n,i,o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}return e.call(t,r,n)}iR.applyReviver=ic});var Li=j(aR=>{"use strict";var Rj=$e();function oR(e,t,r){if(Array.isArray(e))return e.map((n,i)=>oR(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!Rj.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}aR.toJS=oR});var Du=j(cR=>{"use strict";var Nj=ah(),sR=$e(),Sj=Li(),sh=class{constructor(t){Object.defineProperty(this,sR.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(!sR.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=Sj.toJS(this,"",a);if(typeof i=="function")for(let{count:c,res:l}of a.anchors.values())i(l,c);return typeof o=="function"?Nj.applyReviver(o,{"":s},"",s):s}};cR.NodeBase=sh});var oc=j(lR=>{"use strict";var Ej=ju(),_j=tc(),Pa=$e(),Cj=Du(),Ij=Li(),ch=class extends Cj.NodeBase{constructor(t){super(Pa.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=[],_j.visit(t,{Node:(o,a)=>{(Pa.isAlias(a)||Pa.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||(Ij.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=Bu(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(Ej.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 Bu(e,t,r){if(Pa.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(Pa.isCollection(t)){let n=0;for(let i of t.items){let o=Bu(e,i,r);o>n&&(n=o)}return n}else if(Pa.isPair(t)){let n=Bu(e,t.key,r),i=Bu(e,t.value,r);return Math.max(n,i)}return 1}lR.Alias=ch});var St=j(lh=>{"use strict";var xj=$e(),Pj=Du(),Tj=Li(),Oj=e=>!e||typeof e!="function"&&typeof e!="object",Vi=class extends Pj.NodeBase{constructor(t){super(xj.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Tj.toJS(this.value,t,r)}toString(){return String(this.value)}};Vi.BLOCK_FOLDED="BLOCK_FOLDED";Vi.BLOCK_LITERAL="BLOCK_LITERAL";Vi.PLAIN="PLAIN";Vi.QUOTE_DOUBLE="QUOTE_DOUBLE";Vi.QUOTE_SINGLE="QUOTE_SINGLE";lh.Scalar=Vi;lh.isScalarValue=Oj});var ac=j(dR=>{"use strict";var $j=oc(),_o=$e(),uR=St(),jj="tag:yaml.org,2002:";function Dj(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 Bj(e,t,r){if(_o.isDocument(e)&&(e=e.contents),_o.isNode(e))return e;if(_o.isPair(e)){let f=r.schema[_o.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 $j.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=jj+t.slice(2));let l=Dj(e,t,a.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new uR.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?a[_o.MAP]:Symbol.iterator in Object(e)?a[_o.SEQ]:a[_o.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 uR.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}dR.createNode=Bj});var Lu=j(Wu=>{"use strict";var Wj=ac(),Hn=$e(),Lj=Du();function uh(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 Wj.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 fR=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,dh=class extends Lj.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=>Hn.isNode(n)||Hn.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(fR(t))this.add(r);else{let[n,...i]=t,o=this.get(n,!0);if(Hn.isCollection(o))o.addIn(i,r);else if(o===void 0&&this.schema)this.set(n,uh(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(Hn.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&&Hn.isScalar(o)?o.value:o:Hn.isCollection(o)?o.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Hn.isPair(r))return!1;let n=r.value;return n==null||t&&Hn.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 Hn.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(Hn.isCollection(o))o.setIn(i,r);else if(o===void 0&&this.schema)this.set(n,uh(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};Wu.Collection=dh;Wu.collectionFromPath=uh;Wu.isEmptyPath=fR});var sc=j(Vu=>{"use strict";var Vj=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function fh(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Mj=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?fh(r,t):r.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+fh(r,t):(e.endsWith(" ")?"":" ")+r;Vu.indentComment=fh;Vu.lineComment=Mj;Vu.stringifyComment=Vj});var mR=j(cc=>{"use strict";var qj="flow",ph="block",Mu="quoted";function Fj(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,m,h=!1,p=-1,g=-1,v=-1;r===ph&&(p=pR(e,p,t.length),p!==-1&&(f=p+c));for(let A;A=e[p+=1];){if(r===Mu&&A==="\\"){switch(g=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}v=p}if(A===`
|
|
9
|
+
`)r===ph&&(p=pR(e,p,t.length)),f=p+t.length+c,d=void 0;else{if(A===" "&&m&&m!==" "&&m!==`
|
|
10
|
+
`&&m!==" "){let b=e[p+1];b&&b!==" "&&b!==`
|
|
11
|
+
`&&b!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===Mu){for(;m===" "||m===" ";)m=A,A=e[p+=1],h=!0;let b=p>v+1?p-2:g-1;if(u[b])return e;l.push(b),u[b]=!0,f=b+c,d=void 0}else h=!0}m=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 b=l[A],R=l[A+1]||e.length;b===0?w=`
|
|
12
|
+
${t}${e.slice(0,R)}`:(r===Mu&&u[b]&&(w+=`${e[b]}\\`),w+=`
|
|
13
|
+
${t}${e.slice(b+1,R)}`)}return w}function pR(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!==`
|
|
14
|
+
`);n=t,i=t+1,o=e[i]}return n}cc.FOLD_BLOCK=ph;cc.FOLD_FLOW=qj;cc.FOLD_QUOTED=Mu;cc.foldFlowLines=Fj});var uc=j(hR=>{"use strict";var bn=St(),Mi=mR(),Fu=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Hu=e=>/^(%|---|\.\.\.)/m.test(e);function Hj(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]===`
|
|
15
|
+
`){if(o-a>n)return!0;if(a=o+1,i-a<=n)return!1}return!0}function lc(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(Hu(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)+`
|
|
16
|
+
|
|
17
|
+
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)a+=`
|
|
18
|
+
`,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:Mi.foldFlowLines(a,o,Mi.FOLD_QUOTED,Fu(t,!1))}function mh(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return lc(e,t);let r=t.indent||(Hu(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?n:Mi.foldFlowLines(n,r,Mi.FOLD_FLOW,Fu(t,!1))}function Ta(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=lc;else{let i=e.includes('"'),o=e.includes("'");i&&!o?n=mh:o&&!i?n=lc:n=r?mh:lc}return n(e,t)}var hh;try{hh=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{hh=/\n+(?!\n|$)/g}function qu({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 Ta(r,n);let l=n.indent||(n.forceBlockIndent||Hu(r)?" ":""),u=a==="literal"?!0:a==="folded"||t===bn.Scalar.BLOCK_FOLDED?!1:t===bn.Scalar.BLOCK_LITERAL?!0:!Hj(r,c,l.length);if(!r)return u?`|
|
|
24
|
+
`:`>
|
|
25
|
+
`;let f,d;for(d=r.length;d>0;--d){let R=r[d-1];if(R!==`
|
|
26
|
+
`&&R!==" "&&R!==" ")break}let m=r.substring(d),h=m.indexOf(`
|
|
27
|
+
`);h===-1?f="-":r===m||h!==m.length-1?(f="+",o&&o()):f="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
|
|
28
|
+
`&&(m=m.slice(0,-1)),m=m.replace(hh,`$&${l}`));let p=!1,g,v=-1;for(g=0;g<r.length;++g){let R=r[g];if(R===" ")p=!0;else if(R===`
|
|
29
|
+
`)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 b=(p?l?"2":"1":"")+f;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let R=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),_=!1,W=Fu(n,!0);a!=="folded"&&t!==bn.Scalar.BLOCK_FOLDED&&(W.onOverflow=()=>{_=!0});let O=Mi.foldFlowLines(`${w}${R}${m}`,l,Mi.FOLD_BLOCK,W);if(!_)return`>${b}
|
|
31
|
+
${l}${O}`}return r=r.replace(/\n+/g,`$&${l}`),`|${b}
|
|
32
|
+
${l}${w}${r}${m}`}function Qj(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(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(o))return Ta(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return s||u||!o.includes(`
|
|
34
|
+
`)?Ta(o,t):qu(e,t,r,n);if(!s&&!u&&i!==bn.Scalar.PLAIN&&o.includes(`
|
|
35
|
+
`))return qu(e,t,r,n);if(Hu(o)){if(c==="")return t.forceBlockIndent=!0,qu(e,t,r,n);if(s&&c===l)return Ta(o,t)}let f=o.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(a){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:m,tags:h}=t.doc.schema;if(h.some(d)||m?.some(d))return Ta(o,t)}return s?f:Mi.foldFlowLines(f,c,Mi.FOLD_FLOW,Fu(t,!1))}function Uj(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!==bn.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(s=bn.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case bn.Scalar.BLOCK_FOLDED:case bn.Scalar.BLOCK_LITERAL:return i||o?Ta(a.value,t):qu(a,t,r,n);case bn.Scalar.QUOTE_DOUBLE:return lc(a.value,t);case bn.Scalar.QUOTE_SINGLE:return mh(a.value,t);case bn.Scalar.PLAIN:return Qj(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}hR.stringifyString=Uj});var dc=j(gh=>{"use strict";var Jj=ju(),qi=$e(),zj=sc(),Kj=uc();function Gj(e,t){let r=Object.assign({blockQuote:!0,commentString:zj.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 Yj(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(qi.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 Xj(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],o=(qi.isScalar(e)||qi.isCollection(e))&&e.anchor;o&&Jj.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 Zj(e,t,r,n){if(qi.isPair(e))return e.toString(t,r,n);if(qi.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=qi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=Yj(t.doc.schema.tags,o));let a=Xj(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):qi.isScalar(o)?Kj.stringifyString(o,t,r,n):o.toString(t,r,n);return a?qi.isScalar(o)||s[0]==="{"||s[0]==="["?`${a} ${s}`:`${a}
|
|
37
|
+
${t.indent}${s}`:s}gh.createStringifyContext=Gj;gh.stringify=Zj});var yR=j(wR=>{"use strict";var ui=$e(),gR=St(),vR=dc(),fc=sc();function eD({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=ui.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(ui.isCollection(e)||!ui.isNode(e)&&typeof e=="object"){let W="With simple keys, collection cannot be used as a key value";throw new Error(W)}}let m=!f&&(!e||d&&t==null&&!r.inFlow||ui.isCollection(e)||(ui.isScalar(e)?e.type===gR.Scalar.BLOCK_FOLDED||e.type===gR.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(f||!o),indent:s+c});let h=!1,p=!1,g=vR.stringify(e,r,()=>h=!0,()=>p=!0);if(!m&&!r.inFlow&&g.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(o||t==null)return h&&n&&n(),g===""?"?":m?`? ${g}`:g}else if(o&&!f||t==null&&m)return g=`? ${g}`,d&&!h?g+=fc.lineComment(g,r.indent,l(d)):p&&i&&i(),g;h&&(d=null),m?(d&&(g+=fc.lineComment(g,r.indent,l(d))),g=`? ${g}
|
|
38
|
+
${s}:`):(g=`${g}:`,d&&(g+=fc.lineComment(g,r.indent,l(d))));let v,w,A;ui.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,!m&&!d&&ui.isScalar(t)&&(r.indentAtStart=g.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!m&&ui.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let b=!1,R=vR.stringify(t,r,()=>b=!0,()=>p=!0),_=" ";if(d||v||w){if(_=v?`
|
|
39
|
+
`:"",w){let W=l(w);_+=`
|
|
40
|
+
${fc.indentComment(W,r.indent)}`}R===""&&!r.inFlow?_===`
|
|
41
|
+
`&&A&&(_=`
|
|
42
|
+
|
|
43
|
+
`):_+=`
|
|
44
|
+
${r.indent}`}else if(!m&&ui.isCollection(t)){let W=R[0],O=R.indexOf(`
|
|
45
|
+
`),G=O!==-1,Z=r.inFlow??t.flow??t.items.length===0;if(G||!Z){let J=!1;if(G&&(W==="&"||W==="!")){let F=R.indexOf(" ");W==="&"&&F!==-1&&F<O&&R[F+1]==="!"&&(F=R.indexOf(" ",F+1)),(F===-1||O<F)&&(J=!0)}J||(_=`
|
|
46
|
+
${r.indent}`)}}else(R===""||R[0]===`
|
|
47
|
+
`)&&(_="");return g+=_+R,r.inFlow?b&&n&&n():A&&!b?g+=fc.lineComment(g,r.indent,l(A)):p&&i&&i(),g}wR.stringifyPair=eD});var wh=j(vh=>{"use strict";var kR=Ru("process");function tD(e,...t){e==="debug"&&console.log(...t)}function rD(e,t){(e==="debug"||e==="warn")&&(typeof kR.emitWarning=="function"?kR.emitWarning(t):console.warn(t))}vh.debug=tD;vh.warn=rD});var Ku=j(zu=>{"use strict";var Ju=$e(),AR=St(),Qu="<<",Uu={identify:e=>e===Qu||typeof e=="symbol"&&e.description===Qu,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new AR.Scalar(Symbol(Qu)),{addToJSMap:bR}),stringify:()=>Qu},nD=(e,t)=>(Uu.identify(t)||Ju.isScalar(t)&&(!t.type||t.type===AR.Scalar.PLAIN)&&Uu.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Uu.tag&&r.default);function bR(e,t,r){let n=RR(e,r);if(Ju.isSeq(n))for(let i of n.items)yh(e,t,i);else if(Array.isArray(n))for(let i of n)yh(e,t,i);else yh(e,t,n)}function yh(e,t,r){let n=RR(e,r);if(!Ju.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 RR(e,t){return e&&Ju.isAlias(t)?t.resolve(e.doc,e):t}zu.addMergeToJSMap=bR;zu.isMergeKey=nD;zu.merge=Uu});var Ah=j(ER=>{"use strict";var iD=wh(),NR=Ku(),oD=dc(),SR=$e(),kh=Li();function aD(e,t,{key:r,value:n}){if(SR.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(NR.isMergeKey(e,r))NR.addMergeToJSMap(e,t,n);else{let i=kh.toJS(r,"",e);if(t instanceof Map)t.set(i,kh.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let o=sD(r,i,e),a=kh.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 sD(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(SR.isNode(e)&&r?.doc){let n=oD.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)+'..."'),iD.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)}ER.addPairToJSMap=aD});var Fi=j(bh=>{"use strict";var _R=ac(),cD=yR(),lD=Ah(),Gu=$e();function uD(e,t,r){let n=_R.createNode(e,void 0,r),i=_R.createNode(t,void 0,r);return new Yu(n,i)}var Yu=class e{constructor(t,r=null){Object.defineProperty(this,Gu.NODE_TYPE,{value:Gu.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return Gu.isNode(r)&&(r=r.clone(t)),Gu.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return lD.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?cD.stringifyPair(this,t,r,n):JSON.stringify(this)}};bh.Pair=Yu;bh.createPair=uD});var Rh=j(IR=>{"use strict";var Co=$e(),CR=dc(),Xu=sc();function dD(e,t,r){return(t.inFlow??e.flow?pD:fD)(e,t,r)}function fD({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 p=t[h],g=null;if(Co.isNode(p))!f&&p.spaceBefore&&d.push(""),Zu(r,d,p.commentBefore,f),p.comment&&(g=p.comment);else if(Co.isPair(p)){let w=Co.isNode(p.key)?p.key:null;w&&(!f&&w.spaceBefore&&d.push(""),Zu(r,d,w.commentBefore,f))}f=!1;let v=CR.stringify(p,u,()=>g=null,()=>f=!0);g&&(v+=Xu.lineComment(v,o,l(g))),f&&g&&(f=!1),d.push(n+v)}let m;if(d.length===0)m=i.start+i.end;else{m=d[0];for(let h=1;h<d.length;++h){let p=d[h];m+=p?`
|
|
48
|
+
${c}${p}`:`
|
|
49
|
+
`}}return e?(m+=`
|
|
50
|
+
`+Xu.indentComment(l(e),c),s&&s()):f&&a&&a(),m}function pD({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 p=e[h],g=null;if(Co.isNode(p))p.spaceBefore&&f.push(""),Zu(t,f,p.commentBefore,!1),p.comment&&(g=p.comment);else if(Co.isPair(p)){let w=Co.isNode(p.key)?p.key:null;w&&(w.spaceBefore&&f.push(""),Zu(t,f,w.commentBefore,!1),w.comment&&(l=!0));let A=Co.isNode(p.value)?p.value:null;A?(A.comment&&(g=A.comment),A.commentBefore&&(l=!0)):p.value==null&&w?.comment&&(g=w.comment)}g&&(l=!0);let v=CR.stringify(p,c,()=>g=null);l||(l=f.length>u||v.includes(`
|
|
51
|
+
`)),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+=Xu.lineComment(v,n,s(g))),f.push(v),u=f.length}let{start:d,end:m}=r;if(f.length===0)return d+m;if(!l){let h=f.reduce((p,g)=>p+g.length+2,2);l=t.options.lineWidth>0&&h>t.options.lineWidth}if(l){let h=d;for(let p of f)h+=p?`
|
|
52
|
+
${o}${i}${p}`:`
|
|
53
|
+
`;return`${h}
|
|
54
|
+
${i}${m}`}else return`${d}${a}${f.join(" ")}${a}${m}`}function Zu({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let o=Xu.indentComment(t(n),e);r.push(o.trimStart())}}IR.stringifyCollection=dD});var Qi=j(Sh=>{"use strict";var mD=Rh(),hD=Ah(),gD=Lu(),Hi=$e(),ed=Fi(),vD=St();function pc(e,t){let r=Hi.isScalar(t)?t.value:t;for(let n of e)if(Hi.isPair(n)&&(n.key===t||n.key===r||Hi.isScalar(n.key)&&n.key.value===r))return n}var Nh=class extends gD.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Hi.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(ed.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;Hi.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new ed.Pair(t,t?.value):n=new ed.Pair(t.key,t.value);let i=pc(this.items,n.key),o=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Hi.isScalar(i.value)&&vD.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=pc(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=pc(this.items,t)?.value;return(!r&&Hi.isScalar(i)?i.value:i)??void 0}has(t){return!!pc(this.items,t)}set(t,r){this.add(new ed.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)hD.addPairToJSMap(r,i,o);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Hi.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})),mD.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};Sh.YAMLMap=Nh;Sh.findPair=pc});var Oa=j(PR=>{"use strict";var wD=$e(),xR=Qi(),yD={collection:"map",default:!0,nodeClass:xR.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return wD.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>xR.YAMLMap.from(e,t,r)};PR.map=yD});var Ui=j(TR=>{"use strict";var kD=ac(),AD=Rh(),bD=Lu(),rd=$e(),RD=St(),ND=Li(),Eh=class extends bD.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(rd.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=td(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=td(t);if(typeof n!="number")return;let i=this.items[n];return!r&&rd.isScalar(i)?i.value:i}has(t){let r=td(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=td(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];rd.isScalar(i)&&RD.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(ND.toJS(o,String(i++),r));return n}toString(t,r,n){return t?AD.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(kD.createNode(s,void 0,n))}}return o}};function td(e){let t=rd.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}TR.YAMLSeq=Eh});var $a=j($R=>{"use strict";var SD=$e(),OR=Ui(),ED={collection:"seq",default:!0,nodeClass:OR.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return SD.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>OR.YAMLSeq.from(e,t,r)};$R.seq=ED});var mc=j(jR=>{"use strict";var _D=uc(),CD={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),_D.stringifyString(e,t,r,n)}};jR.string=CD});var nd=j(WR=>{"use strict";var DR=St(),BR={identify:e=>e==null,createNode:()=>new DR.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new DR.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&BR.test.test(e)?e:t.options.nullStr};WR.nullTag=BR});var _h=j(VR=>{"use strict";var ID=St(),LR={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ID.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&LR.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};VR.boolTag=LR});var ja=j(MR=>{"use strict";function xD({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}MR.stringifyNumber=xD});var Ih=j(id=>{"use strict";var PD=St(),Ch=ja(),TD={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:Ch.stringifyNumber},OD={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():Ch.stringifyNumber(e)}},$D={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 PD.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Ch.stringifyNumber};id.float=$D;id.floatExp=OD;id.floatNaN=TD});var Ph=j(ad=>{"use strict";var qR=ja(),od=e=>typeof e=="bigint"||Number.isInteger(e),xh=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function FR(e,t,r){let{value:n}=e;return od(n)&&n>=0?r+n.toString(t):qR.stringifyNumber(e)}var jD={identify:e=>od(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>xh(e,2,8,r),stringify:e=>FR(e,8,"0o")},DD={identify:od,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>xh(e,0,10,r),stringify:qR.stringifyNumber},BD={identify:e=>od(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>xh(e,2,16,r),stringify:e=>FR(e,16,"0x")};ad.int=DD;ad.intHex=BD;ad.intOct=jD});var QR=j(HR=>{"use strict";var WD=Oa(),LD=nd(),VD=$a(),MD=mc(),qD=_h(),Th=Ih(),Oh=Ph(),FD=[WD.map,VD.seq,MD.string,LD.nullTag,qD.boolTag,Oh.intOct,Oh.int,Oh.intHex,Th.floatNaN,Th.floatExp,Th.float];HR.schema=FD});var zR=j(JR=>{"use strict";var HD=St(),QD=Oa(),UD=$a();function UR(e){return typeof e=="bigint"||Number.isInteger(e)}var sd=({value:e})=>JSON.stringify(e),JD=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:sd},{identify:e=>e==null,createNode:()=>new HD.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:sd},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:sd},{identify:UR,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})=>UR(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:sd}],zD={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},KD=[QD.map,UD.seq].concat(JD,zD);JR.schema=KD});var jh=j(KR=>{"use strict";var hc=Ru("buffer"),$h=St(),GD=uc(),YD={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof hc.Buffer=="function")return hc.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 hc.Buffer=="function")s=a instanceof hc.Buffer?a.toString("base64"):hc.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=$h.Scalar.BLOCK_LITERAL),t!==$h.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===$h.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return GD.stringifyString({comment:e,type:t,value:s},n,i,o)}};KR.binary=YD});var ud=j(ld=>{"use strict";var cd=$e(),Dh=Fi(),XD=St(),ZD=Ui();function GR(e,t){if(cd.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!cd.isPair(n)){if(cd.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new Dh.Pair(new XD.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
56
|
+
${i.key.commentBefore}`:n.commentBefore),n.comment){let o=i.value??i.key;o.comment=o.comment?`${n.comment}
|
|
57
|
+
${o.comment}`:n.comment}n=i}e.items[r]=cd.isPair(n)?n:new Dh.Pair(n)}}else t("Expected a sequence for this tag");return e}function YR(e,t,r){let{replacer:n}=r,i=new ZD.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(Dh.createPair(s,c,r))}return i}var eB={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:GR,createNode:YR};ld.createPairs=YR;ld.pairs=eB;ld.resolvePairs=GR});var Lh=j(Wh=>{"use strict";var XR=$e(),Bh=Li(),gc=Qi(),tB=Ui(),ZR=ud(),Io=class e extends tB.YAMLSeq{constructor(){super(),this.add=gc.YAMLMap.prototype.add.bind(this),this.delete=gc.YAMLMap.prototype.delete.bind(this),this.get=gc.YAMLMap.prototype.get.bind(this),this.has=gc.YAMLMap.prototype.has.bind(this),this.set=gc.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(XR.isPair(i)?(o=Bh.toJS(i.key,"",r),a=Bh.toJS(i.value,o,r)):o=Bh.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=ZR.createPairs(t,r,n),o=new this;return o.items=i.items,o}};Io.tag="tag:yaml.org,2002:omap";var rB={collection:"seq",identify:e=>e instanceof Map,nodeClass:Io,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=ZR.resolvePairs(e,t),n=[];for(let{key:i}of r.items)XR.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Io,r)},createNode:(e,t,r)=>Io.from(e,t,r)};Wh.YAMLOMap=Io;Wh.omap=rB});var iN=j(Vh=>{"use strict";var eN=St();function tN({value:e,source:t},r){return t&&(e?rN:nN).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var rN={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 eN.Scalar(!0),stringify:tN},nN={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 eN.Scalar(!1),stringify:tN};Vh.falseTag=nN;Vh.trueTag=rN});var oN=j(dd=>{"use strict";var nB=St(),Mh=ja(),iB={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:Mh.stringifyNumber},oB={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():Mh.stringifyNumber(e)}},aB={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 nB.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:Mh.stringifyNumber};dd.float=aB;dd.floatExp=oB;dd.floatNaN=iB});var sN=j(wc=>{"use strict";var aN=ja(),vc=e=>typeof e=="bigint"||Number.isInteger(e);function fd(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 qh(e,t,r){let{value:n}=e;if(vc(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return aN.stringifyNumber(e)}var sB={identify:vc,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>fd(e,2,2,r),stringify:e=>qh(e,2,"0b")},cB={identify:vc,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>fd(e,1,8,r),stringify:e=>qh(e,8,"0")},lB={identify:vc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>fd(e,0,10,r),stringify:aN.stringifyNumber},uB={identify:vc,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>fd(e,2,16,r),stringify:e=>qh(e,16,"0x")};wc.int=lB;wc.intBin=sB;wc.intHex=uB;wc.intOct=cB});var Hh=j(Fh=>{"use strict";var hd=$e(),pd=Fi(),md=Qi(),xo=class e extends md.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;hd.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new pd.Pair(t.key,null):r=new pd.Pair(t,null),md.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=md.findPair(this.items,t);return!r&&hd.isPair(n)?hd.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=md.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new pd.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(pd.createPair(a,null,n));return o}};xo.tag="tag:yaml.org,2002:set";var dB={collection:"map",identify:e=>e instanceof Set,nodeClass:xo,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>xo.from(e,t,r),resolve(e,t){if(hd.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new xo,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Fh.YAMLSet=xo;Fh.set=dB});var Uh=j(gd=>{"use strict";var fB=ja();function Qh(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 cN(e){let{value:t}=e,r=a=>a;if(typeof t=="bigint")r=a=>BigInt(a);else if(isNaN(t)||!isFinite(t))return fB.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 pB={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})=>Qh(e,r),stringify:cN},mB={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=>Qh(e,!1),stringify:cN},lN={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(lN.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=Qh(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$/,"")??""};gd.floatTime=mB;gd.intTime=pB;gd.timestamp=lN});var fN=j(dN=>{"use strict";var hB=Oa(),gB=nd(),vB=$a(),wB=mc(),yB=jh(),uN=iN(),Jh=oN(),vd=sN(),kB=Ku(),AB=Lh(),bB=ud(),RB=Hh(),zh=Uh(),NB=[hB.map,vB.seq,wB.string,gB.nullTag,uN.trueTag,uN.falseTag,vd.intBin,vd.intOct,vd.int,vd.intHex,Jh.floatNaN,Jh.floatExp,Jh.float,yB.binary,kB.merge,AB.omap,bB.pairs,RB.set,zh.intTime,zh.floatTime,zh.timestamp];dN.schema=NB});var bN=j(Yh=>{"use strict";var gN=Oa(),SB=nd(),vN=$a(),EB=mc(),_B=_h(),Kh=Ih(),Gh=Ph(),CB=QR(),IB=zR(),wN=jh(),yc=Ku(),yN=Lh(),kN=ud(),pN=fN(),AN=Hh(),wd=Uh(),mN=new Map([["core",CB.schema],["failsafe",[gN.map,vN.seq,EB.string]],["json",IB.schema],["yaml11",pN.schema],["yaml-1.1",pN.schema]]),hN={binary:wN.binary,bool:_B.boolTag,float:Kh.float,floatExp:Kh.floatExp,floatNaN:Kh.floatNaN,floatTime:wd.floatTime,int:Gh.int,intHex:Gh.intHex,intOct:Gh.intOct,intTime:wd.intTime,map:gN.map,merge:yc.merge,null:SB.nullTag,omap:yN.omap,pairs:kN.pairs,seq:vN.seq,set:AN.set,timestamp:wd.timestamp},xB={"tag:yaml.org,2002:binary":wN.binary,"tag:yaml.org,2002:merge":yc.merge,"tag:yaml.org,2002:omap":yN.omap,"tag:yaml.org,2002:pairs":kN.pairs,"tag:yaml.org,2002:set":AN.set,"tag:yaml.org,2002:timestamp":wd.timestamp};function PB(e,t,r){let n=mN.get(t);if(n&&!e)return r&&!n.includes(yc.merge)?n.concat(yc.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(mN.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(yc.merge)),i.reduce((o,a)=>{let s=typeof a=="string"?hN[a]:a;if(!s){let c=JSON.stringify(a),l=Object.keys(hN).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},[])}Yh.coreKnownTags=xB;Yh.getTags=PB});var eg=j(RN=>{"use strict";var Xh=$e(),TB=Oa(),OB=$a(),$B=mc(),yd=bN(),jB=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Zh=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:o,sortMapEntries:a,toStringDefaults:s}){this.compat=Array.isArray(t)?yd.getTags(t,"compat"):t?yd.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?yd.coreKnownTags:{},this.tags=yd.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Xh.MAP,{value:TB.map}),Object.defineProperty(this,Xh.SCALAR,{value:$B.string}),Object.defineProperty(this,Xh.SEQ,{value:OB.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?jB:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};RN.Schema=Zh});var SN=j(NN=>{"use strict";var DB=$e(),tg=dc(),kc=sc();function BB(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=tg.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=o(e.commentBefore);r.unshift(kc.indentComment(c,""))}let a=!1,s=null;if(e.contents){if(DB.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let u=o(e.contents.commentBefore);r.push(kc.indentComment(u,""))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>a=!0,l=tg.stringify(e.contents,i,()=>s=null,c);s&&(l+=kc.lineComment(l,"",o(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(tg.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(kc.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(kc.indentComment(o(c),"")))}return r.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}NN.stringifyDocument=BB});var Ac=j(EN=>{"use strict";var WB=oc(),Da=Lu(),en=$e(),LB=Fi(),VB=Li(),MB=eg(),qB=SN(),rg=ju(),FB=ah(),HB=ac(),ng=oh(),ig=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,en.NODE_TYPE,{value:en.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 ng.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,{[en.NODE_TYPE]:{value:en.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=en.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ba(this.contents)&&this.contents.add(t)}addIn(t,r){Ba(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=rg.anchorNames(this);t.anchor=!r||n.has(r)?rg.findNewAnchor(r||"a",n):r}return new WB.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:m}=rg.createNodeAnchors(this,a||"a"),h={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:m},p=HB.createNode(t,u,h);return s&&en.isCollection(p)&&(p.flow=!0),d(),p}createPair(t,r,n={}){let i=this.createNode(t,null,n),o=this.createNode(r,null,n);return new LB.Pair(i,o)}delete(t){return Ba(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Da.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ba(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return en.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Da.isEmptyPath(t)?!r&&en.isScalar(this.contents)?this.contents.value:this.contents:en.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return en.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Da.isEmptyPath(t)?this.contents!==void 0:en.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Da.collectionFromPath(this.schema,[t],r):Ba(this.contents)&&this.contents.set(t,r)}setIn(t,r){Da.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Da.collectionFromPath(this.schema,Array.from(t),r):Ba(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 ng.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 ng.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 MB.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=VB.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"?FB.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 qB.stringifyDocument(this,t)}};function Ba(e){if(en.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}EN.Document=ig});var Nc=j(Rc=>{"use strict";var bc=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},og=class extends bc{constructor(t,r,n){super("YAMLParseError",t,r,n)}},ag=class extends bc{constructor(t,r,n){super("YAMLWarning",t,r,n)}},QB=(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)+`…
|
|
61
|
+
`),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+=`:
|
|
62
|
+
|
|
63
|
+
${a}
|
|
64
|
+
${l}
|
|
65
|
+
`}};Rc.YAMLError=bc;Rc.YAMLParseError=og;Rc.YAMLWarning=ag;Rc.prettifyError=QB});var Sc=j(_N=>{"use strict";function UB(e,{flow:t,indicator:r,next:n,offset:i,onError:o,parentIndent:a,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",m=!1,h=!1,p=null,g=null,v=null,w=null,A=null,b=null,R=null;for(let O of e)switch(h&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&o(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),p&&(l&&O.type!=="comment"&&O.type!=="newline"&&o(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),O.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&O.source.includes(" ")&&(p=O),u=!0;break;case"comment":{u||o(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let G=O.source.substring(1)||" ";f?f+=d+G:f=G,d="",l=!1;break}case"newline":l?f?f+=O.source:(!b||r!=="seq-item-ind")&&(c=!0):d+=O.source,l=!0,m=!0,(g||v)&&(w=O),u=!0;break;case"anchor":g&&o(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&o(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=O,R??(R=O.offset),l=!1,u=!1,h=!0;break;case"tag":{v&&o(O,"MULTIPLE_TAGS","A node can have at most one tag"),v=O,R??(R=O.offset),l=!1,u=!1,h=!0;break}case r:(g||v)&&o(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),b&&o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${t??"collection"}`),b=O,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){A&&o(O,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),A=O,l=!1,u=!1;break}default:o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),l=!1,u=!1}let _=e[e.length-1],W=_?_.offset+_.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"),p&&(l&&p.indent<=a||n?.type==="block-map"||n?.type==="block-seq")&&o(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:b,spaceBefore:c,comment:f,hasNewline:m,anchor:g,tag:v,newlineAfterProp:w,end:W,start:R??W}}_N.resolveProps=UB});var kd=j(CN=>{"use strict";function sg(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(sg(t.key)||sg(t.value))return!0}return!1;default:return!0}}CN.containsNewline=sg});var cg=j(IN=>{"use strict";var JB=kd();function zB(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&JB.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}IN.flowIndentCheck=zB});var lg=j(PN=>{"use strict";var xN=$e();function KB(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(o,a)=>o===a||xN.isScalar(o)&&xN.isScalar(a)&&o.value===a.value;return t.some(o=>i(o.key,r))}PN.mapIncludes=KB});var BN=j(DN=>{"use strict";var TN=Fi(),GB=Qi(),ON=Sc(),YB=kd(),$N=cg(),XB=lg(),jN="All mapping items must start at the same column";function ZB({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??GB.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:m,value:h}=u,p=ON.resolveProps(f,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!p.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",jN)),!p.anchor&&!p.tag&&!m){l=p.end,p.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||YB.containsNewline(d))&&i(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&i(c,"BAD_INDENT",jN);r.atKey=!0;let v=p.end,w=d?e(r,d,p,i):t(r,v,f,null,p,i);r.schema.compat&&$N.flowIndentCheck(n.indent,d,i),r.atKey=!1,XB.mapIncludes(r,s.items,w)&&i(v,"DUPLICATE_KEY","Map keys must be unique");let A=ON.resolveProps(m??[],{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&&p.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 b=h?e(r,h,A,i):t(r,c,m,null,A,i);r.schema.compat&&$N.flowIndentCheck(n.indent,h,i),c=b.range[2];let R=new TN.Pair(w,b);r.options.keepSourceTokens&&(R.srcToken=u),s.items.push(R)}else{g&&i(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(w.comment?w.comment+=`
|
|
68
|
+
`+A.comment:w.comment=A.comment);let b=new TN.Pair(w);r.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}DN.resolveBlockMap=ZB});var LN=j(WN=>{"use strict";var eW=Ui(),tW=Sc(),rW=cg();function nW({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??eW.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=tW.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 m=f?e(r,f,d,i):t(r,d.end,u,null,d,i);r.schema.compat&&rW.flowIndentCheck(n.indent,f,i),c=m.range[2],s.items.push(m)}return s.range=[n.offset,c,l??c],s}WN.resolveBlockSeq=nW});var Wa=j(VN=>{"use strict";function iW(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}}VN.resolveEnd=iW});var HN=j(FN=>{"use strict";var oW=$e(),aW=Fi(),MN=Qi(),sW=Ui(),cW=Wa(),qN=Sc(),lW=kd(),uW=lg(),ug="Block collections are not allowed within flow collections",dg=e=>e&&(e.type==="block-map"||e.type==="block-seq");function dW({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=n.start.source==="{",s=a?"flow map":"flow sequence",c=o?.nodeClass??(a?MN.YAMLMap:sW.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:b,value:R}=v,_=qN.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:A??b?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!_.found){if(!_.anchor&&!_.tag&&!b&&!R){g===0&&_.comma?i(_.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<n.items.length-1&&i(_.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),_.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+_.comment:l.comment=_.comment),f=_.end;continue}!a&&r.options.strict&&lW.containsNewline(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)_.comma&&i(_.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(_.comma||i(_.start,"MISSING_CHAR",`Missing , between ${s} items`),_.comment){let W="";e:for(let O of w)switch(O.type){case"comma":case"space":break;case"comment":W=O.source.substring(1);break e;default:break e}if(W){let O=l.items[l.items.length-1];oW.isPair(O)&&(O=O.value??O.key),O.comment?O.comment+=`
|
|
70
|
+
`+W:O.comment=W,_.comment=_.comment.substring(W.length+1)}}if(!a&&!b&&!_.found){let W=R?e(r,R,_,i):t(r,_.end,b,null,_,i);l.items.push(W),f=W.range[2],dg(R)&&i(W.range,"BLOCK_IN_FLOW",ug)}else{r.atKey=!0;let W=_.end,O=A?e(r,A,_,i):t(r,W,w,null,_,i);dg(A)&&i(O.range,"BLOCK_IN_FLOW",ug),r.atKey=!1;let G=qN.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:R,offset:O.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(G.found){if(!a&&!_.found&&r.options.strict){if(b)for(let F of b){if(F===G.found)break;if(F.type==="newline"){i(F,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}_.start<G.found.offset-1024&&i(G.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else R&&("source"in R&&R.source?.[0]===":"?i(R,"MISSING_CHAR",`Missing space after : in ${s}`):i(G.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Z=R?e(r,R,G,i):G.found?t(r,G.end,b,null,G,i):null;Z?dg(R)&&i(Z.range,"BLOCK_IN_FLOW",ug):G.comment&&(O.comment?O.comment+=`
|
|
71
|
+
`+G.comment:O.comment=G.comment);let J=new aW.Pair(O,Z);if(r.options.keepSourceTokens&&(J.srcToken=v),a){let F=l;uW.mapIncludes(r,F.items,O)&&i(W,"DUPLICATE_KEY","Map keys must be unique"),F.items.push(J)}else{let F=new MN.YAMLMap(r.schema);F.flow=!0,F.items.push(J);let X=(Z??O).range;F.range=[O.range[0],X[1],X[2]],l.items.push(F)}f=Z?Z.range[2]:G.end}}let d=a?"}":"]",[m,...h]=n.end,p=f;if(m?.source===d)p=m.offset+m.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),m&&m.source.length!==1&&h.unshift(m)}if(h.length>0){let g=cW.resolveEnd(h,p,r.options.strict,i);g.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+g.comment:l.comment=g.comment),l.range=[n.offset,p,g.offset]}else l.range=[n.offset,p,p];return l}FN.resolveFlowCollection=dW});var UN=j(QN=>{"use strict";var fW=$e(),pW=St(),mW=Qi(),hW=Ui(),gW=BN(),vW=LN(),wW=HN();function fg(e,t,r,n,i,o){let a=r.type==="block-map"?gW.resolveBlockMap(e,t,r,n,o):r.type==="block-seq"?vW.resolveBlockSeq(e,t,r,n,o):wW.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 yW(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:m}=n,h=d&&o?d.offset>o.offset?d:o:d??o;h&&(!m||m.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===mW.YAMLMap.tagName&&s==="map"||a===hW.YAMLSeq.tagName&&s==="seq")return fg(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),fg(e,t,r,i,a)}let l=fg(e,t,r,i,a,c),u=c.resolve?.(l,d=>i(o,"TAG_RESOLVE_FAILED",d),t.options)??l,f=fW.isNode(u)?u:new pW.Scalar(u);return f.range=l.range,f.tag=a,c?.format&&(f.format=c.format),f}QN.composeCollection=yW});var mg=j(JN=>{"use strict";var pg=St();function kW(e,t,r){let n=t.offset,i=AW(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let o=i.mode===">"?pg.Scalar.BLOCK_FOLDED:pg.Scalar.BLOCK_LITERAL,a=t.source?bW(t.source):[],s=a.length;for(let p=a.length-1;p>=0;--p){let g=a[p][1];if(g===""||g==="\r")s=p;else break}if(s===0){let p=i.chomp==="+"&&a.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,a.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:p,type:o,comment:i.comment,range:[n,g,g]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let p=0;p<s;++p){let[g,v]=a[p];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=p,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 p=a.length-1;p>=s;--p)a[p][0].length>c&&(s=p+1);let f="",d="",m=!1;for(let p=0;p<u;++p)f+=a[p][0].slice(c)+`
|
|
74
|
+
`;for(let p=u;p<s;++p){let[g,v]=a[p];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 b=`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",b),g=""}o===pg.Scalar.BLOCK_LITERAL?(f+=d+g.slice(c)+v,d=`
|
|
75
|
+
`):g.length>c||v[0]===" "?(d===" "?d=`
|
|
76
|
+
`:!m&&d===`
|
|
77
|
+
`&&(d=`
|
|
78
|
+
|
|
79
|
+
`),f+=d+g.slice(c)+v,d=`
|
|
80
|
+
`,m=!0):v===""?d===`
|
|
81
|
+
`?f+=`
|
|
82
|
+
`:d=`
|
|
83
|
+
`:(f+=d+v,d=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let p=s;p<a.length;++p)f+=`
|
|
84
|
+
`+a[p][0].slice(c);f[f.length-1]!==`
|
|
85
|
+
`&&(f+=`
|
|
86
|
+
`);break;default:f+=`
|
|
87
|
+
`}let h=n+i.length+t.source.length;return{value:f,type:o,comment:i.comment,range:[n,h,h]}}function AW({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 m=i[d];if(!s&&(m==="-"||m==="+"))s=m;else{let h=Number(m);!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 m=t[d];switch(m.type){case"space":l=!0;case"newline":f+=m.source.length;break;case"comment":r&&!l&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,u=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{let h=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",h);let p=m.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:o,indent:a,chomp:s,comment:u,length:f}}function bW(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}JN.resolveBlockScalar=kW});var gg=j(KN=>{"use strict";var hg=St(),RW=Wa();function NW(e,t,r){let{offset:n,type:i,source:o,end:a}=e,s,c,l=(d,m,h)=>r(n+d,m,h);switch(i){case"scalar":s=hg.Scalar.PLAIN,c=SW(o,l);break;case"single-quoted-scalar":s=hg.Scalar.QUOTE_SINGLE,c=EW(o,l);break;case"double-quoted-scalar":s=hg.Scalar.QUOTE_DOUBLE,c=_W(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=RW.resolveEnd(a,u,t,r);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function SW(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}`),zN(e)}function EW(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zN(e.slice(1,-1)).replace(/''/g,"'")}function zN(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
|
+
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],o=" ",a=t.lastIndex;for(r.lastIndex=a;n=r.exec(e);)n[1]===""?o===`
|
|
90
|
+
`?i+=o:o=`
|
|
91
|
+
`:(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 _W(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
|
|
92
|
+
`))if(i===`
|
|
93
|
+
`){let{fold:o,offset:a}=CW(e,n);r+=o,n=a}else if(i==="\\"){let o=e[++n],a=IW[o];if(a)r+=a;else if(o===`
|
|
94
|
+
`)for(o=e[n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="\r"&&e[n+1]===`
|
|
95
|
+
`)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+=xW(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!==`
|
|
96
|
+
`&&!(a==="\r"&&e[n+2]===`
|
|
97
|
+
`)&&(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 CW(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
|
|
98
|
+
`||n==="\r")&&!(n==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)n===`
|
|
100
|
+
`&&(r+=`
|
|
101
|
+
`),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var IW={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function xW(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}}KN.resolveFlowScalar=NW});var XN=j(YN=>{"use strict";var Po=$e(),GN=St(),PW=mg(),TW=gg();function OW(e,t,r,n){let{value:i,type:o,comment:a,range:s}=t.type==="block-scalar"?PW.resolveBlockScalar(e,t,n):TW.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[Po.SCALAR]:c?l=$W(e.schema,i,c,r,n):t.type==="scalar"?l=jW(e,i,t,n):l=e.schema[Po.SCALAR];let u;try{let f=l.resolve(i,d=>n(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=Po.isScalar(f)?f:new GN.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(r??t,"TAG_RESOLVE_FAILED",d),u=new GN.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 $W(e,t,r,n,i){if(r==="!")return e[Po.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[Po.SCALAR])}function jW({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[Po.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[Po.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}YN.composeScalar=OW});var eS=j(ZN=>{"use strict";function DW(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}ZN.emptyScalarPosition=DW});var nS=j(wg=>{"use strict";var BW=oc(),WW=$e(),LW=UN(),tS=XN(),VW=Wa(),MW=eS(),qW={composeNode:rS,composeEmptyNode:vg};function rS(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=FW(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=tS.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=LW.composeCollection(qW,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=vg(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&&(!WW.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 vg(e,t,r,n,{spaceBefore:i,comment:o,anchor:a,tag:s,end:c},l){let u={type:"scalar",offset:MW.emptyScalarPosition(t,r,n),indent:-1,source:""},f=tS.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 FW({options:e},{offset:t,source:r,end:n},i){let o=new BW.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=VW.resolveEnd(n,a,e.strict,i);return o.range=[t,a,s.offset],s.comment&&(o.comment=s.comment),o}wg.composeEmptyNode=vg;wg.composeNode=rS});var aS=j(oS=>{"use strict";var HW=Ac(),iS=nS(),QW=Wa(),UW=Sc();function JW(e,t,{offset:r,start:n,value:i,end:o},a){let s=Object.assign({_directives:t},e),c=new HW.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=UW.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?iS.composeNode(l,i,u,a):iS.composeEmptyNode(l,u.end,n,null,u,a);let f=c.contents.range[2],d=QW.resolveEnd(o,f,!1,a);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}oS.composeDoc=JW});var kg=j(lS=>{"use strict";var zW=Ru("process"),KW=oh(),GW=Ac(),Ec=Nc(),sS=$e(),YW=aS(),XW=Wa();function _c(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 cS(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?`
|
|
103
|
+
|
|
104
|
+
`:`
|
|
105
|
+
`)+(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 yg=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,o)=>{let a=_c(r);o?this.warnings.push(new Ec.YAMLWarning(a,n,i)):this.errors.push(new Ec.YAMLParseError(a,n,i))},this.directives=new KW.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=cS(this.prelude);if(n){let o=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${n}`:n;else if(i||t.directives.docStart||!o)t.commentBefore=n;else if(sS.isCollection(o)&&!o.flow&&o.items.length>0){let a=o.items[0];sS.isPair(a)&&(a=a.key);let s=a.commentBefore;a.commentBefore=s?`${n}
|
|
107
|
+
${s}`:n}else{let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
108
|
+
${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:cS(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(zW.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let o=_c(t);o[0]+=r,this.onError(o,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=YW.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 Ec.YAMLParseError(_c(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 Ec.YAMLParseError(_c(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=XW.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Ec.YAMLParseError(_c(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 GW.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}}};lS.Composer=yg});var fS=j(Ad=>{"use strict";var ZW=mg(),eL=gg(),tL=Nc(),uS=uc();function rL(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 tL.YAMLParseError([s,s+1],o,a)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return eL.resolveFlowScalar(e,t,n);case"block-scalar":return ZW.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function nL(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:o=-1,type:a="PLAIN"}=t,s=uS.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:`
|
|
110
|
+
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
|
+
`),u=s.substring(0,l),f=s.substring(l+1)+`
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:o,indent:n,source:u}];return dS(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{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 iL(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=uS.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">":oL(e,c);break;case'"':Ag(e,c,"double-quoted-scalar");break;case"'":Ag(e,c,"single-quoted-scalar");break;default:Ag(e,c,"scalar")}}function oL(e,t){let r=t.indexOf(`
|
|
114
|
+
`),n=t.substring(0,r),i=t.substring(r+1)+`
|
|
115
|
+
`;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}];dS(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:a,source:`
|
|
116
|
+
`});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 dS(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 Ag(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:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(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})}}}Ad.createScalarToken=nL;Ad.resolveAsScalar=rL;Ad.setScalarValue=iL});var mS=j(pS=>{"use strict";var aL=e=>"type"in e?Rd(e):bd(e);function Rd(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Rd(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=bd(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=bd(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=bd(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 bd({start:e,key:t,sep:r,value:n}){let i="";for(let o of e)i+=o.source;if(t&&(i+=Rd(t)),r)for(let o of r)i+=o.source;return n&&(i+=Rd(n)),i}pS.stringify=aL});var wS=j(vS=>{"use strict";var bg=Symbol("break visit"),sL=Symbol("skip children"),hS=Symbol("remove item");function To(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),gS(Object.freeze([]),e,t)}To.BREAK=bg;To.SKIP=sL;To.REMOVE=hS;To.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};To.parentCollection=(e,t)=>{let r=To.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 gS(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=gS(Object.freeze(e.concat([[i,a]])),o.items[a],r);if(typeof s=="number")a=s-1;else{if(s===bg)return bg;s===hS&&(o.items.splice(a,1),a-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}vS.visit=To});var Nd=j(Rr=>{"use strict";var Rg=fS(),cL=mS(),lL=wS(),Ng="\uFEFF",Sg="",Eg="",_g="",uL=e=>!!e&&"items"in e,dL=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function fL(e){switch(e){case Ng:return"<BOM>";case Sg:return"<DOC>";case Eg:return"<FLOW_END>";case _g:return"<SCALAR>";default:return JSON.stringify(e)}}function pL(e){switch(e){case Ng:return"byte-order-mark";case Sg:return"doc-mode";case Eg:return"flow-error-end";case _g:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
|
+
`:case`\r
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Rr.createScalarToken=Rg.createScalarToken;Rr.resolveAsScalar=Rg.resolveAsScalar;Rr.setScalarValue=Rg.setScalarValue;Rr.stringify=cL.stringify;Rr.visit=lL.visit;Rr.BOM=Ng;Rr.DOCUMENT=Sg;Rr.FLOW_END=Eg;Rr.SCALAR=_g;Rr.isCollection=uL;Rr.isScalar=dL;Rr.prettyToken=fL;Rr.tokenType=pL});var xg=j(kS=>{"use strict";var Cc=Nd();function Rn(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var yS=new Set("0123456789ABCDEFabcdef"),mL=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Sd=new Set(",[]{}"),hL=new Set(` ,[]{}
|
|
121
|
+
\r `),Cg=e=>!e||hL.has(e),Ig=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
|
+
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
|
|
124
|
+
`||!i&&!this.atEnd)return t+n+1}return r===`
|
|
125
|
+
`||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Rn(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Cc.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 Cc.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==="...")&&Rn(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&&!Rn(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===":")&&Rn(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(Cg),"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("..."))&&Rn(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Cc.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(Cg),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||Rn(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(`
|
|
127
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=n.indexOf(`
|
|
128
|
+
`,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=>Rn(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`
|
|
129
|
+
`:t=o,r=0;break;case"\r":{let a=this.buffer[o+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if(a===`
|
|
130
|
+
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,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===`
|
|
132
|
+
`;)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===`
|
|
133
|
+
`&&o>=this.pos&&o+1+r>s)t=o;else break}while(!0);return yield Cc.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(Rn(o)||t&&Sd.has(o))break;r=n}else if(Rn(i)){let o=this.buffer[n+1];if(i==="\r"&&(o===`
|
|
134
|
+
`?(n+=1,i=`
|
|
135
|
+
`,o=this.buffer[n+1]):r=n),o==="#"||t&&Sd.has(o))break;if(i===`
|
|
136
|
+
`){let a=this.continueScalar(n+1);if(a===-1)break;n=Math.max(n,a-2)}}else{if(t&&Sd.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Cc.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(Cg),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(Rn(n)||r&&Sd.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(;!Rn(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(mL.has(r))r=this.buffer[++t];else if(r==="%"&&yS.has(this.buffer[t+1])&&yS.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};kS.Lexer=Ig});var Tg=j(AS=>{"use strict";var Pg=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}}}};AS.LineCounter=Pg});var $g=j(ES=>{"use strict";var gL=Ru("process"),bS=Nd(),vL=xg();function Ji(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function RS(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 SS(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 Ed(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 La(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 _d(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 NS(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ji(t.start,"explicit-key-ind")&&!Ji(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,SS(t.value)?t.value.end?_d(t.value.end,t.sep):t.value.end=t.sep:_d(t.start,t.sep),delete t.sep)}var Og=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 vL.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,gL.env.LOG_TOKENS&&console.log("|",bS.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=bS.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"&&NS(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&&RS(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":{RS(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=Ed(this.peek(2)),n=La(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(`
|
|
139
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){_d(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(Ji(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(SS(r.key)&&!Ji(r.sep,"newline")){let a=La(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(Ji(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let a=La(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]}):Ji(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&&!Ji(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)){_d(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||Ji(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=Ed(n),o=La(i);NS(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(`
|
|
141
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Ed(t),n=La(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=Ed(t),n=La(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())}}};ES.Parser=Og});var PS=j(xc=>{"use strict";var _S=kg(),wL=Ac(),Ic=Nc(),yL=wh(),kL=$e(),AL=Tg(),CS=$g();function IS(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new AL.LineCounter||null,prettyErrors:t}}function bL(e,t={}){let{lineCounter:r,prettyErrors:n}=IS(t),i=new CS.Parser(r?.addNewLine),o=new _S.Composer(t),a=Array.from(o.compose(i.parse(e)));if(n&&r)for(let s of a)s.errors.forEach(Ic.prettifyError(e,r)),s.warnings.forEach(Ic.prettifyError(e,r));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function xS(e,t={}){let{lineCounter:r,prettyErrors:n}=IS(t),i=new CS.Parser(r?.addNewLine),o=new _S.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 Ic.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(a.errors.forEach(Ic.prettifyError(e,r)),a.warnings.forEach(Ic.prettifyError(e,r))),a}function RL(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=xS(e,r);if(!i)return null;if(i.warnings.forEach(o=>yL.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 NL(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 kL.isDocument(e)&&!n?e.toString(r):new wL.Document(e,n,r).toString(r)}xc.parse=RL;xc.parseAllDocuments=bL;xc.parseDocument=xS;xc.stringify=NL});var Vr=j(Ve=>{"use strict";var SL=kg(),EL=Ac(),_L=eg(),jg=Nc(),CL=oc(),zi=$e(),IL=Fi(),xL=St(),PL=Qi(),TL=Ui(),OL=Nd(),$L=xg(),jL=Tg(),DL=$g(),Cd=PS(),TS=tc();Ve.Composer=SL.Composer;Ve.Document=EL.Document;Ve.Schema=_L.Schema;Ve.YAMLError=jg.YAMLError;Ve.YAMLParseError=jg.YAMLParseError;Ve.YAMLWarning=jg.YAMLWarning;Ve.Alias=CL.Alias;Ve.isAlias=zi.isAlias;Ve.isCollection=zi.isCollection;Ve.isDocument=zi.isDocument;Ve.isMap=zi.isMap;Ve.isNode=zi.isNode;Ve.isPair=zi.isPair;Ve.isScalar=zi.isScalar;Ve.isSeq=zi.isSeq;Ve.Pair=IL.Pair;Ve.Scalar=xL.Scalar;Ve.YAMLMap=PL.YAMLMap;Ve.YAMLSeq=TL.YAMLSeq;Ve.CST=OL;Ve.Lexer=$L.Lexer;Ve.LineCounter=jL.LineCounter;Ve.Parser=DL.Parser;Ve.parse=Cd.parse;Ve.parseAllDocuments=Cd.parseAllDocuments;Ve.parseDocument=Cd.parseDocument;Ve.stringify=Cd.stringify;Ve.visit=TS.visit;Ve.visitAsync=TS.visitAsync});import Ki from"path";import{isDeepStrictEqual as OS}from"node:util";function VS(e,t){return Oo[t][e]}function WL(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 Oo.en)return o;if(i===2&&t){let a=`${t}.${o}`;if(a in Oo.en)return a}if(i===4&&t==="knowledge"&&r==="remote"){let a=`knowledge.remote.${o}`;if(a in Oo.en)return a}if(i===4&&t==="knowledge"&&r==="local"){let a=`knowledge.local.${o}`;if(a in Oo.en)return a}return i===2&&t===null&&o==="hook"?"hook":i===2&&t==="hook"&&o==="allow_paths"?"hook.allow_paths":null}function Oc(e,t,r){let n=[],i=null,o=null;for(let g of(0,be.stringify)(e).trimEnd().split(`
|
|
143
|
+
`)){let v=WL(g,i,o);if(v){let w=g.match(/^\s*/u)?.[0]??"";for(let A of VS(v,t).split(`
|
|
144
|
+
`))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(`
|
|
145
|
+
`);if(!r)return a;let s=(0,be.parseDocument)(r,{uniqueKeys:!0});if(s.errors.length>0)throw new Error(s.errors[0].message);let c=(0,be.parseDocument)(a);if(!(0,be.isMap)(s.contents)||!(0,be.isMap)(c.contents))return a;let l=g=>{if(!(0,be.isMap)(g))return;let v=g.items[0];g.commentBefore&&v&&(0,be.isScalar)(v.key)&&(v.key.commentBefore=[g.commentBefore,v.key.commentBefore].filter(Boolean).join(`
|
|
146
|
+
`),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,be.isMap)(f))for(let g of[...s.contents.items]){if(!(0,be.isScalar)(g.key)||c.has(g.key))continue;let v=String(g.key.value);if(!Object.hasOwn(Oo.en,`classic.${v}`)||!f.has(v))continue;let w=s.get("classic",!0);if(!(0,be.isMap)(w)){let b=s.createPair("classic",{});s.contents.items.push(b),w=b.value}if(!(0,be.isMap)(w))continue;let A=w.items.find(b=>(0,be.isScalar)(b.key)&&b.key.value===v);A?((0,be.isScalar)(A.key)&&(A.key.commentBefore=[g.key.commentBefore,A.key.commentBefore].filter(Boolean).join(`
|
|
147
|
+
`)||void 0),(0,be.isNode)(A.value)&&(0,be.isNode)(g.value)&&(A.value.comment=[g.value.comment,A.value.comment].filter(Boolean).join(`
|
|
148
|
+
`)||void 0)):(w.items.push(g),u.classic={...u.classic,[v]:u[v]})}let d=new Set(Object.values(Oo).flatMap(g=>Object.values(g).flatMap(v=>v.split(`
|
|
149
|
+
`).map(w=>w.replace(/^#\s?/u,"").trim())))),m=(g,v,w,A)=>{for(let b of[...g.items])v.has(b.key)||g.delete(b.key);for(let b of v.items){let R=String((0,be.isScalar)(b.key)?b.key.value:b.key),_=g.items.find(W=>(0,be.isScalar)(W.key)&&(0,be.isScalar)(b.key)?W.key.value===b.key.value:!1);if(!_){let W=s.createPair(R,A[R]);(0,be.isScalar)(W.key)&&(0,be.isScalar)(b.key)&&(W.key.commentBefore=b.key.commentBefore),g.items.push(W),(0,be.isMap)(W.value)&&(0,be.isMap)(b.value)&&m(W.value,b.value,A[R],A[R]);continue}if((0,be.isScalar)(_.key)&&(0,be.isScalar)(b.key)){let W=_.key.commentBefore?.split(`
|
|
150
|
+
`).filter(O=>!d.has(O.trim())).join(`
|
|
151
|
+
`);_.key.commentBefore=[b.key.commentBefore,W].filter(Boolean).join(`
|
|
152
|
+
`)||void 0}if((0,be.isMap)(_.value)&&(0,be.isMap)(b.value))m(_.value,b.value,w[R]??{},A[R]);else if(!OS(w[R],A[R])){let W=_.value;_.value=s.createNode(A[R]),(0,be.isNode)(W)&&(0,be.isNode)(_.value)&&(_.value.comment=W.comment,_.value.commentBefore=W.commentBefore,_.value.spaceBefore=W.spaceBefore)}}};m(s.contents,c.contents,u,e);let h=(g,v)=>{if((0,be.isAlias)(g)){let w=!1;try{w=OS(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,be.isMap)(g))for(let w of g.items){let A=String((0,be.isScalar)(w.key)?w.key.value:w.key);w.value=h(w.value,v[A])}else(0,be.isSeq)(g)&&Array.isArray(v)&&(g.items=g.items.map((w,A)=>h(w,v[A])));return g};h(s.contents,e);let p=s.toString();return r.includes(`\r
|
|
153
|
+
`)?p.replaceAll(`
|
|
154
|
+
`,`\r
|
|
155
|
+
`):p}function LL(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ki.posix.isAbsolute(r)||Ki.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 Va(e){let t=LL(e,"native.artifact_root");return t.length===0?".":t.join("/")}function MS(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 Yi(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||Ki.posix.isAbsolute(n)||Ki.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 Gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function qS(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 VL(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 WS(e,t,r){let n=VL(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 ML(e){if(e===void 0)return;let t=Gi(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=Gi(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:Va(n),toArtifactRoot:Va(i),stage:o,...a?{cleanup:a}:{}}}function qL(e){if(e===void 0)return;let t=Gi(e,"native.finish");if(t.pull_request===void 0)return{};let r=Gi(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(Ki.posix.isAbsolute(n[0])||Ki.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??BL;if(!Number.isSafeInteger(i)||i<1||i>BS)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${BS}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function FL(e,t={}){let r=Gi(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??Tc;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?Pd: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=ML(r.pending_root_move),u=qL(r.finish);return{artifact_root:Va(n),language:qS(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 HL(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>DS)throw new Error(`${t} must be an integer between 1 and ${DS} milliseconds`);return e}function QL(e){let t=Gi(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&&HL(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:MS(t.artifact_layout),language:qS(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 UL(e){let r=Gi(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)=>Yi(n,`hook.allow_paths[${i}]`)))]}}function JL(e){if(e===void 0)return{...Id};let t=Gi(e,"memory"),r=t.learning??Id.learning,n=t.retrieval??Id.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 Dg(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zL(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")||Ki.posix.isAbsolute(r)||Ki.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>$S)throw new Error(`${t} exceeds ${$S} 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>jS)throw new Error(`${t} contains more than ${jS} wildcard tokens`);return r}function KL(e){let t=Dg(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)=>zL(i,`knowledge.local.include[${o}]`)))],max_file_mb:WS(t.max_file_mb,xd.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:WS(t.max_total_mb,xd.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 GL(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 YL(e){let t=Dg(e,"knowledge.remote"),r=GL(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 XL(e){if(e===void 0)return{...LS};let t=Dg(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:KL(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:YL(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 Bg(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function ZL(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function eV(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:Bg(e.change_walkthrough),...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...o?{classic:o}:{}}}function Ma(e,t={}){let r=(0,be.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=ZL(i.ambient_resume),a=Bg(i.change_walkthrough),s=i.hook===void 0?void 0:UL(i.hook),c=JL(i.memory),l=XL(i.knowledge),u=i.native===void 0?void 0:FL(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=i.classic===void 0?void 0:QL(i.classic),d=eV(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 FS(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 HS(e){let t=e.knowledge??{...LS};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??{...Id},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??xd.max_file_mb,max_total_mb:t.local.max_total_mb??xd.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??Pd,...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:FS(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 Mr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function $c(e,t){let r=HS({...t,change_walkthrough:t.change_walkthrough??Bg(e.change_walkthrough)}),n=Ma((0,be.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={...Mr(e.hook),allow_paths:[...n.hook.allow_paths]}),n.memory){let o=Mr(e.memory);i.memory={...o,learning:n.memory.learning,retrieval:n.memory.retrieval}}if(n.knowledge){let o=Mr(e.knowledge),a={...o,provider:n.knowledge.provider};if(n.knowledge.local?a.local={...Mr(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={...Mr(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=Mr(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=Mr(o.finish);a.finish={...s,pull_request:{...Mr(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={...Mr(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=Mr(o.pending_root_move),c=FS(n.native.pending_root_move),l=Mr(s.cleanup),u=Mr(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={...Mr(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 be,Pc,$S,jS,Tc,Pd,Id,xd,LS,DS,BL,BS,Oo,di=I(()=>{"use strict";be=or(Vr(),1),Pc=Number.MAX_SAFE_INTEGER,$S=1024,jS=64,Tc=5,Pd=2,Id={learning:!0,retrieval:!0},xd={include:[],max_file_mb:1,max_total_mb:32},LS={provider:"local"},DS=36e5,BL=12e4,BS=6e5,Oo={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.
|
|
156
|
+
# 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.
|
|
157
|
+
# 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.
|
|
158
|
+
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
159
|
+
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
160
|
+
# 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.
|
|
161
|
+
# 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.
|
|
162
|
+
# clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
|
|
163
|
+
# 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.
|
|
164
|
+
# 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.
|
|
165
|
+
# artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
|
|
166
|
+
# language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
|
|
167
|
+
# context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
|
|
168
|
+
# review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
|
|
169
|
+
# 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.
|
|
170
|
+
# document_evidence: neutral | strict`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",change_walkthrough:`# 是否生成可直接打开的 HTML 变更说明,同时作用于 Native 和 Classic;开启会增加讲解内容的 token 消耗。
|
|
171
|
+
# change_walkthrough: true | false(默认 true)`,ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
|
|
172
|
+
# ambient_resume: true | false`,memory:"# 当前项目的个人记忆自动学习与注入策略。","memory.learning":`# 是否允许当前项目通过工作流事件自动沉淀新的个人记忆。
|
|
173
|
+
# 可选值:true | false`,"memory.retrieval":`# 是否允许当前项目把个人记忆自动注入 Agent 上下文。
|
|
174
|
+
# 可选值:true | false`,knowledge:"# 普通 Comet 任务使用的项目知识检索 Provider。","knowledge.provider":`# 项目知识 Provider。
|
|
175
|
+
# 可选值: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 工作流文档使用的产物语言。
|
|
176
|
+
# 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
|
|
177
|
+
# 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
|
|
178
|
+
# 可选值: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 恢复严格行为。
|
|
179
|
+
# 可选值:allow | revert`,"native.finish":"# 可选的仓库自有收尾 provider;提交、推送、通用远端核验和恢复仍由 Native 负责。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
|
|
180
|
+
# 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
|
|
181
|
+
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
182
|
+
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
183
|
+
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
184
|
+
# 可选值:true | false`,"classic.check_timeout_ms":"# 检查命令默认超时,单位毫秒,范围 1-3600000,缺省为 300000;命令行 --timeout-ms 优先。","classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
185
|
+
# 可选值:neutral | strict`}}});import{promises as qa}from"fs";import Ge from"path";import tV from"os";async function Wg(e){try{return await qa.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function nV(e){try{let t=await qa.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function jc(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}async function Dc(e){let t=[],r=e;for(;!await Wg(r);){let i=Ge.dirname(r);if(i===r)break;t.push(Ge.basename(r)),r=i}let n=await qa.realpath(r);return Ge.resolve(n,...t.reverse())}async function Lg(e){try{return(await qa.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Vg(e){let t=Ge.resolve(e);try{(await qa.stat(t)).isDirectory()||(t=Ge.dirname(t))}catch(i){if(i.code!=="ENOENT")throw i}let r=t,n=Ge.resolve(tV.homedir());for(;;){if(!(t===n&&r!==n)){let a=Ge.join(t,...Td.split("/")),s=t===r||await nV(a);if(await Wg(a)&&s)return t}if(await Wg(Ge.join(t,".git")))return t;let o=Ge.dirname(t);if(o===t)return r;t=o}}function Mg(e){return Va(e)}async function iV(e,t){let r=Mg(t),n=Ge.resolve(e,...r.split("/")),i=await qa.realpath(e),o=await Dc(n);if(!jc(i,o))throw new Error("native.artifact_root resolves outside the project root");return n}async function Ne(e,t,r={}){let n=Mg(t),i=await iV(e,n),o=Ge.join(i,"comet");if(await Lg(o))throw new Error("The configured Native comet root must not be a symbolic link");let[a,s]=await Promise.all([Dc(i),Dc(o)]);if(!jc(a,s))throw new Error("The configured Native comet root resolves outside its artifact root");let c=Ge.resolve(e),l=it(c),u=Ge.join(l,"native");if(await Lg(u))throw new Error("The Native Runtime root must not be a symbolic link");return await fi(l,u),{projectRoot:c,configFile:Ge.join(e,...Td.split("/")),artifactRoot:i,artifactRootRef:n,nativeRoot:o,specsDir:Ge.join(o,"specs"),changesDir:Ge.join(o,"changes"),archiveDir:Ge.join(o,"archive"),workspaceRuntimeRoot:l,runtimeDir:u,changesRuntimeDir:Ge.join(u,"changes"),transactionsDir:Ge.join(u,"transactions")}}function oV(e){if(!rV.test(e))throw new Error(`Invalid Native change name: ${e}`)}function qg(e,t){oV(t);let r=Ge.join(e.changesRuntimeDir,t);if(!qr(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function qr(e,t){return jc(Ge.resolve(e),Ge.resolve(t))}async function fi(e,t){let r=Ge.resolve(e),n=Ge.resolve(t);if(!jc(r,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Lg(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[i,o]=await Promise.all([Dc(r),Dc(n)]);if(!jc(i,o))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Td,rV,Ye=I(()=>{"use strict";Lr();di();Td=".comet/config.yaml",rV=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{promises as Nr}from"fs";import Me from"path";import{AsyncLocalStorage as aV}from"node:async_hooks";async function Od(e,t,r={}){let n=Me.resolve(e),i=await Hg(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,m)=>JSON.stringify((await Nr.readdir(d,{withFileTypes:!0})).filter(h=>!m(h)).map(h=>[h.name,h.isDirectory(),h.isSymbolicLink()]).sort((h,p)=>String(h[0]).localeCompare(String(p[0]),"en"))),u=d=>{let m=o.get(d);return m||(m=(async()=>{let h=await Nr.lstat(d,{bigint:!0});if(!h.isDirectory()||h.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Me.relative(n,d)||"."}`);let p=await Nr.realpath(d);if(!Fa(i,p))throw new Error(`${t} resolves outside the project root`);let g=r.ignoredDirectoryEntries?.(Me.relative(n,d).replaceAll("\\","/")||".");return{stat:h,real:p,...g?{ignoreEntry:g,namespace:await l(d,g)}:{}}})(),m=m.catch(h=>{throw o.delete(d),h}),o.set(d,m)),m};await u(n);let f=async d=>{if(a)throw new Error(`${t} read session is already finished`);let m=Yi(d,t),h=n;for(let p of m.split("/").slice(0,-1))h=Me.join(h,p),await u(h);return Me.resolve(n,...m.split("/"))};return{observePath:f,async observeDirectory(d){let m=await f(d);return await u(m),m},async stat(d){let m=await f(d),h=await Nr.lstat(m,{bigint:!0});if(!h.isFile()||h.isSymbolicLink())throw new Error(`${t} must be a real file: ${d}`);return{target:m,stat:h}},async hash(d){let m=await f(d);return Sb(m,{bigint:!0,label:`${t} ${d}`,verify:async(h,p)=>{if(!Fa(i,p.realPath))throw new Error(`${t} resolves outside the project root`);let g=n,v=[n];for(let w of Me.relative(n,Me.dirname(m)).split(Me.sep).filter(Boolean))g=Me.join(g,w),v.push(g);for(let w of v){let A=await o.get(w),b=await Nr.lstat(w,{bigint:!0});if(!b.isDirectory()||b.isSymbolicLink()||c(b)!==c(A.stat))throw new Error(`${t} directory changed while reading: ${Me.relative(n,w)||"."}`)}}})},async read(d,m,h={}){let p=await f(d);return $i(p,m,{...h,label:`${t} ${d}`,verify:async(g,v)=>{if(!Fa(i,v.realPath))throw new Error(`${t} resolves outside the project root`);if(r.deferDirectoryChecks)return;let w=n,A=[n];for(let b of Me.relative(n,Me.dirname(p)).split(Me.sep).filter(Boolean))w=Me.join(w,b),A.push(w);for(let b of A){let R=await o.get(b),_=await Nr.lstat(b,{bigint:!0});if(!_.isDirectory()||_.isSymbolicLink()||c(_)!==c(R.stat))throw new Error(`${t} directory changed while reading: ${Me.relative(n,b)||"."}`)}}})},async finish(d={}){if(a)throw new Error(`${t} read session is already finished`);a=!0;let m=[];for(let[h,p]of o){let g=await p,v=await Nr.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 Nr.realpath(h)!==g.real)throw new Error(`${t} directory changed while observing: ${Me.relative(n,h)||"."}`);s(g.stat)!==s(v)&&m.push(Me.relative(n,h).replaceAll("\\","/")||".")}return{changedDirectories:m}}}}function QS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Fa(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}async function Hg(e,t){let r=Me.resolve(e),n=await US(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return JS(r)}async function zS(e,t,r,n){let i=e;for(let o=0;o<r.length;o++){i=Me.join(i,r[o]);let a;try{a=await US(i)}catch(l){if(QS(l))return{exists:!1,kind:"missing"};throw l}if(a.isSymbolicLink()){let l=Me.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=Me.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 JS(i);if(!cV(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 KS(e,t,r){let n=Yi(t,r.label),i=Me.resolve(e),o=await Hg(i,r.label),a=n.split("/"),s=Me.resolve(i,...a);if(!Fa(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await zS(i,o,a,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ce(e,t,r){if(r.expected===void 0)return KS(e,t,r);try{return await lV(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 yt(e,t,r){let n=Yi(t,r.label),i=Me.resolve(e),o=await Hg(i,r.label),a=n.split("/"),s=i;for(let c of a){s=Me.join(s,c);let l;try{l=await Nr.lstat(s)}catch(d){if(!QS(d))throw d;try{await Nr.mkdir(s)}catch(m){if(m.code!=="EEXIST")throw m}l=await Nr.lstat(s)}let u=Me.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 Nr.realpath(s);if(!Fa(o,f))throw new Error(`${r.label} resolves outside the project root`)}return await zS(i,o,a,{label:r.label,expected:"directory"}),s}async function GS(e,t,r,n){let i=!n.hooks&&!n.bigint?sV.getStore():void 0;if(i){let s=Me.resolve(e),c=i.get(s);return c||(c=Od(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 Od(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 GS(e,t,r,n);try{return await uV(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(Fg)&&(i.message=i.message.replaceAll(Fg,n.label)),i}}var sV,US,JS,cV,lV,Fg,uV,ot=I(()=>{"use strict";ji();di();qn();sV=new aV;US=Zr("protectedChainLstat",e=>Nr.lstat(e)),JS=Zr("protectedChainRealpath",e=>Nr.realpath(e)),cV=si("protectedChainInside",Fa);lV=Zr("protectedInspectPath",(e,t,r)=>KS(e,t,{label:"Protected project path",expected:r}));Fg="Cached protected project read",uV=Zr("protectedReadFile",(e,t,r)=>GS(e,t,r,{label:Fg}))});import{createHash as dV}from"crypto";function Qg(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function fV(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function $d(e,t={}){return(await Wc(e,t)).document}async function YS(e){try{return(await qe(e,Bc,Pc,{label:Bc})).bytes}catch(t){if(fV(t))return null;throw t}}function XS(e){return e?{exists:!0,sha256:dV("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function jd(e){return XS(await YS(e))}async function Wc(e,t={}){let r=await YS(e);return{source:r?.toString("utf8")??null,document:r?Ma(r.toString("utf8"),t):null,identity:XS(r)}}async function Ug(e){return(await $d(e))?.config??null}var Bc,Ha=I(()=>{"use strict";di();ot();Bc=".comet/config.yaml"});import{promises as zg}from"node:fs";async function Kg(e,t){let r;for(let n=0;n<=Jg.length;n+=1)try{return await e()}catch(i){r=i;let o=i.code;if(n===Jg.length||!pV.has(o??""))throw i;await new Promise(a=>setTimeout(a,Jg[n]))}throw r}async function $o(e,t){await Kg(()=>zg.rename(e,t),`rename ${t}`)}async function Lc(e){await Kg(()=>zg.unlink(e),`unlink ${e}`)}async function Qa(e,t){await Kg(()=>zg.link(e,t),`link ${t}`)}var pV,Jg,Dd=I(()=>{"use strict";pV=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Jg=[50,100,200]});import{randomUUID as ZS}from"crypto";import{constants as mV,promises as at}from"fs";import ut from"path";async function Gg(e,t){try{return await Qa(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await at.copyFile(e,t,mV.COPYFILE_EXCL),{linked:!1}}function Do(e,t){let r=ut.relative(e,t);return r===""||!ut.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ut.sep}`)}function Bd(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function hV(e,t){return ht(e,Bd(t))}function jo(e,t){return ht(Bd(e),Bd(t))}function eE(e,t){return jo(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wd(e){let t=await at.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 at.realpath(e),...Bd(t)}}async function Yt(e){for(let t of e){let r=await at.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hV(t,r)||await at.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function gV(e,t,r){let[n,i]=await Promise.all([at.lstat(e),at.realpath(e),Yt(r)]);if(!n.isFile()||n.isSymbolicLink()||!jo(n,t)||!Do(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function tE(e,t){let r=await Yg(e,t);if(r)return r;let n=ut.resolve(e),i=ut.resolve(t);if(!Do(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let o=[await Wd(n)],a=ut.relative(n,i).split(ut.sep).filter(Boolean),s=n;for(let c of a){await Yt(o),s=ut.join(s,c);try{await at.mkdir(s)}catch(u){if(u.code!=="EEXIST")throw u}let l=await Wd(s);if(!Do(o[0].realPath,l.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${s}`);o.push(l)}return await Yt(o),o}async function Yg(e,t){let r=ut.resolve(e),n=ut.resolve(t);if(!Do(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await Wd(r)],o=ut.relative(r,n).split(ut.sep).filter(Boolean),a=r;for(let s of o){a=ut.join(a,s);try{let c=await Wd(a);if(!Do(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 Yt(i),i}async function Xg(e){let t;try{t=await at.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 rE(e,t,r){let n=ut.dirname(e),i=await tE(r.containedRoot,n),o=ut.join(n,`.${ut.basename(e)}.${ZS()}.tmp`),a,s,c;try{await r.beforeTemporaryOpen?.(),a=await at.open(o,"wx"),s=await a.stat();let[l,u]=await Promise.all([at.lstat(o),at.realpath(o)]);if(await Yt(i),!l.isFile()||l.isSymbolicLink()||!jo(s,l)||!Do(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(),!jo(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 gV(o,c,i),await r.beforeCommit?.(),await Yt(i);let f=await at.lstat(o);if(!f.isFile()||f.isSymbolicLink()||!c||!eE(f,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(r.requireAtomicPublication?await Qa(o,e):await Gg(o,e),await at.unlink(o)):await $o(o,e),await Xg(n)}catch(l){await a?.close();try{await Yt(i),await at.rm(o,{force:!0})}catch{}throw l}}async function Et(e,t,r){await rE(e,t,r)}async function Ua(e,t,r){await rE(e,t,r)}async function nE(e,t,r){let n=await Yg(r.containedRoot,ut.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await tE(r.containedRoot,ut.dirname(t)),o=await at.lstat(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("Contained link source must be a regular file");let a=ut.join(ut.dirname(t),`.${ut.basename(t)}.${ZS()}.tmp`);try{await Yt(n),await Yt(i),await Qa(e,a),await r.beforeCommit?.(),await Yt(n),await Yt(i);let s=await at.lstat(a),c=await at.lstat(e);if(!s.isFile()||s.isSymbolicLink()||!c.isFile()||c.isSymbolicLink()||!jo(o,c)||!jo(c,s)||o.size!==c.size||o.mtimeMs!==c.mtimeMs)throw new Error("Contained link source changed before publication");let l=await at.lstat(t).catch(u=>{if(u.code==="ENOENT")return null;throw u});l?.isFile()&&!l.isSymbolicLink()&&jo(c,l)?await Lc(a):await $o(a,t),await Xg(ut.dirname(t)),await Yt(n),await Yt(i)}catch(s){try{await Yt(i),await at.unlink(a)}catch{}throw s}}async function Bo(e,t){let r=ut.dirname(e),n=await Yg(t.containedRoot,r);if(!n)return!1;let i,o;try{i=await at.lstat(e),o=await at.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Do(n[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Yt(n);let[a,s]=await Promise.all([at.lstat(e),at.realpath(e)]);if(!a.isFile()||a.isSymbolicLink()||!eE(i,a)||s!==o)throw new Error("Contained file removal target changed before removal");return await Lc(e),await Yt(n),await Xg(r),!0}var Nn=I(()=>{"use strict";Dd();Ca()});var r4,Zg=I(()=>{"use strict";Nn();Ha();ot();r4=Number.MAX_SAFE_INTEGER});async function ev(e,t){if(!t)return;let r=await jd(e);if(!Qg(r,t))throw new Error("Project config changed before commit; rerun the operation")}var tv=I(()=>{"use strict";Nn();di();Ha();ot();Zg()});var Vc=I(()=>{"use strict";Ca()});import{randomUUID as yV}from"crypto";import{promises as sr}from"fs";import Sn from"path";function Ld(e,t){let r=Sn.relative(e,t);return r===""||!Sn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Sn.sep}`)}function kV(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vd(e,t){return ht({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function AV(e,t){return Vd(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function iE(e){let t=await sr.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 sr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ja(e){for(let t of e){let r=await sr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!kV(t,r)||await sr.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function bV(e,t,r){let[n,i]=await Promise.all([sr.lstat(e),sr.realpath(e),r?Ja(r):Promise.resolve()]);if(!n.isFile()||n.isSymbolicLink()||!Vd(n,t)||r&&!Ld(r[0].realPath,i))throw new Error("Native atomic write temporary file changed after close");return n}async function RV(e,t){let r=Sn.resolve(e),n=Sn.resolve(t);if(!Ld(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let i=[await iE(r)],o=Sn.relative(r,n).split(Sn.sep).filter(Boolean),a=r;for(let s of o){await Ja(i),a=Sn.join(a,s);try{await sr.mkdir(a)}catch(l){if(l.code!=="EEXIST")throw l}let c=await iE(a);if(!Ld(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${a}`);i.push(c)}return await Ja(i),i}async function Mc(e){let t;try{t=await sr.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 NV(e,t,r={}){let n=Sn.dirname(e),i=r.containedRoot?await RV(r.containedRoot,n):null;i||await sr.mkdir(n,{recursive:!0});let o=Sn.join(n,`.${Sn.basename(e)}.${yV()}.tmp`),a,s,c;try{if(await r.beforeTemporaryOpen?.(),a=await sr.open(o,"wx"),s=await a.stat(),i){let[l,u]=await Promise.all([sr.lstat(o),sr.realpath(o)]);if(await Ja(i),!l.isFile()||l.isSymbolicLink()||!Vd(s,l)||!Ld(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(),!Vd(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 bV(o,c,i),await r.beforeCommit?.(),i){await Ja(i);let l=await sr.lstat(o);if(!l.isFile()||l.isSymbolicLink()||!c||!AV(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await Qa(o,e),await Lc(o)):await $o(o,e),await Mc(n)}catch(l){if(await a?.close(),!i)await sr.rm(o,{force:!0});else try{await Ja(i),await sr.rm(o,{force:!0})}catch{}throw l}}async function Ue(e,t,r={}){await NV(e,t,r)}async function pi(e,t,r={}){await Ue(e,JSON.stringify(t,null,2)+`
|
|
186
|
+
`,r)}var jt=I(()=>{"use strict";Dd();Vc()});import SV from"path";async function We(e){let t=(await $d(e))?.config??null;return t?.native?t:null}async function Md(e){let t=await We(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 qd(e,t,r={}){let n=await Wc(e,{allowPartialProject:!0}),i=$c(n.document?.value??{},t),o=SV.join(e,...Td.split("/"));await Ue(o,Oc(i,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await ev(e,n.identity)}})}var qc,_t=I(()=>{"use strict";di();Ha();tv();jt();Ye();qc=Pd});function Wo(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 Fc({code:"invalid-fields",path:n,context:r,missingFields:o,unknownFields:a,expectedFields:[...t]})}var Fc,Hd=I(()=>{"use strict";Fc=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 VV(e){return e.toLowerCase().startsWith(".env")}function fE(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>VV(n))?"environment-file":r.some(n=>LV.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>WV.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var WV,LV,pE=I(()=>{"use strict";WV=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),LV=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as MV}from"node:crypto";import{promises as Ft}from"node:fs";import Sr from"node:path";import{TextDecoder as hE}from"node:util";function Qd(e,t){let r=Sr.relative(e,t);return r===""||!Sr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Sr.sep}`)}function vE(e){let t=Sr.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})||Sr.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=fE(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 wE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function qV(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xi(e,t){let r={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ht(r,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mE(e){let t=await Ft.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ft.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function yE(e,t){let r=Sr.resolve(e),n=Sr.resolve(t);if(!Qd(r,n))throw new Error("Native artifact path is outside its root");let i=[await mE(r)],o=r;for(let a of Sr.relative(r,n).split(Sr.sep).filter(Boolean)){o=Sr.join(o,a);let s=await mE(o);if(!Qd(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${o}`);i.push(s)}return i}async function Ud(e){for(let t of e){let r=await Ft.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!qV(t,r)||await Ft.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Je(e){let t=vE(e.ref),r=e.maxBytes===null?null:wE(e.maxBytes??gE),n=Sr.resolve(e.root,...t.split("/")),i=await yE(e.root,Sr.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Ft.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 Ft.realpath(n);if(!Qd(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ft.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Ud(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!Xi(o,c)||!Xi(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let A=r===null?m.length:r+1-d,b=await s.read(m,0,Math.min(m.length,A),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);f.push(Buffer.from(m.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,p,g]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Ud(i),!p.isFile()||p.isSymbolicLink()||g!==a||!Xi(c,h)||!Xi(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(f,d),w;try{w=new hE("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:MV("sha256").update(v).digest("hex"),text:w}}finally{await s.close()}}async function kE(e){let t=vE(e.ref),r=wE(e.maxBytes),n=Sr.resolve(e.root,...t.split("/")),i=await yE(e.root,Sr.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Ft.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);let a=await Ft.realpath(n);if(!Qd(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ft.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Ud(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!Xi(o,c)||!Xi(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=Math.min(c.size,r),d=[],m=0,h=Buffer.allocUnsafe(Math.min(64*1024,r));for(;m<f;){let R=await s.read(h,0,Math.min(h.length,f-m),null);if(R.bytesRead===0)break;m+=R.bytesRead,d.push(Buffer.from(h.subarray(0,R.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[p,g,v]=await Promise.all([s.stat(),Ft.lstat(n),Ft.realpath(n)]);if(await Ud(i),!g.isFile()||g.isSymbolicLink()||v!==a||!Xi(c,p)||!Xi(c,g)||m!==f)throw new Error(`Native artifact changed while reading: ${t}`);let w=c.size>r,A=Buffer.concat(d,m),b;try{b=new hE("utf-8",{fatal:!0}).decode(A,{stream:w})}catch(R){throw new Error(`Native artifact prefix is not valid UTF-8: ${t}`,{cause:R})}return{ref:t,size:c.size,text:b,truncated:w}}finally{await s.close()}}var gE,tn=I(()=>{"use strict";pE();Vc();gE=Number.MAX_SAFE_INTEGER});import{types as FV}from"node:util";import{createHash as HV}from"node:crypto";function RE(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=bE.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&bE.set(e,n),n}function QV(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,m=new Map,h=new Map,p=v=>{let w=v&&typeof v=="object"?f.get(v):void 0;if(w!==void 0)return w;let A=RE(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),b=s.length;return s.push({...A===void 0?{}:{base:A},entries:v.entries.map(([R,_])=>[R,p(_)]),removed:[...v.removed]}),h.set(v,b),b};for(let v of t){let w=o,A=e;for(let G of v.path.slice(0,-1)){A=A[G];let Z=i(A);Object.defineProperty(w,G,{value:Z,enumerable:!0,writable:!0,configurable:!0}),w=Z}let b=v.path.at(-1),R=w[b];if(!R||typeof R!="object"||Array.isArray(R))continue;if(r?.(R)){let G=AE.get(R);if(!G){let Z=R,J=m.get(v.group),F=Object.entries(Z),X=J?F.filter(([Le,D])=>!Object.hasOwn(J.source,Le)||p(J.source[Le])!==p(D)):F,U=J?Object.keys(J.source).filter(Le=>!Object.hasOwn(Z,Le)):[],pe=J&&X.length+U.length<F.length;G={...pe?{base:J.node}:{},entries:pe?X:F,removed:pe?U:[]},AE.set(R,G)}m.set(v.group,{source:R,node:G}),c.push({path:v.path,map:g(G)}),Object.defineProperty(w,b,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let _=new Map;for(let[G,Z]of Object.entries(R)){let J=Z&&typeof Z=="object"?f.get(Z):void 0;if(J===void 0){let F=RE(Z,r);J=l.get(F),J===void 0&&(J=a.length,a.push(Z),l.set(F,J)),Z&&typeof Z=="object"&&f.set(Z,J)}_.set(G,J)}let W=JSON.stringify([..._]),O=u.get(W);if(O===void 0){let G=d.get(v.group),Z=[..._].filter(([X,U])=>G?.entries.get(X)!==U),J=G?[...G.entries.keys()].filter(X=>!_.has(X)):[],F=G&&Z.length+J.length<_.size;O=s.length,s.push({...F?{base:G.id}:{},entries:F?Z:[..._],removed:F?J:[]}),u.set(W,O)}d.set(v.group,{id:O,entries:_}),c.push({path:v.path,map:O}),Object.defineProperty(w,b,{value:{},enumerable:!0,writable:!0,configurable:!0})}return c.length?{record:o,pool:{version:1,values:a,maps:s,bindings:c}}:{record:o}}function UV(){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 SE(e){let{nodes:t,set:r}=UV(),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),m=i.length;return i.push({...u,left:f,right:d}),o.set(c,m),m},s=n.map(a);return{version:3,values:e.values,nodes:i,maps:s,bindings:e.bindings}}function EE(e,t,r){let n=QV(e,t,r);return{record:n.record,...n.pool?{pool:SE(n.pool)}:{}}}function*Jd(e,t=e.root){if(t===null)return;let r=e.pool.nodes[t];yield*Jd(e,r.left),yield[r.key,e.pool.values[r.value]],yield*Jd(e,r.right)}function JV(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:()=>[...Jd(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 mi.set(r,e),r}function _E(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return gt("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(o=>!["version","values","maps","bindings"].includes(o))&>("JSON 引用池字段无效"),i.maps.forEach((o,a)=>{(!o||!Array.isArray(o.entries)||!Array.isArray(o.removed)||o.base!==void 0&&!za(o.base,a)||Object.keys(o).some(c=>!["base","entries","removed"].includes(c)))&>("JSON 映射引用无效");let s=new Set;for(let c of o.removed)(typeof c!="string"||s.has(c))&>("JSON 删除键无效"),s.add(c);for(let c of o.entries)(!Array.isArray(c)||c.length!==2||typeof c[0]!="string"||!za(c[1],i.values.length)||s.has(c[0]))&>("JSON 值引用无效"),s.add(c[0])}),_E(SE(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 gt("JSON 引用池版本或字段无效");let n=[];return r.nodes.forEach((i,o)=>{(!i||typeof i.key!="string"||!za(i.value,r.values.length)||![i.left,i.right].every(c=>c===null||za(c,o))||Object.keys(i).some(c=>!["key","value","left","right","height"].includes(c)))&>("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)&>("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&&!za(i,r.nodes.length))&>("JSON 映射根无效"),r}function zV(e,t){let r=(h,p=0,g=new Set)=>{if(p>64&>("JSON 数据嵌套过深"),!(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"&&Number.isFinite(h))){if(typeof h!="object"||h===null||FV.isProxy(h)||g.has(h))return gt("JSON 数据无效");Object.getPrototypeOf(h)!==Object.prototype&&Object.getPrototypeOf(h)!==null&&!Array.isArray(h)&>("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))&>("JSON 数据不能包含访问器"),r(w.value,p+1,g)}Array.isArray(h)&&Object.keys(h).length!==h.length&>("JSON 数组不能稀疏"),g.delete(h)}};r(e),r(t);let n=_E(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))||!za(h.map,n.maps.length)||Object.keys(h).some(w=>!["path","map"].includes(w)))&>("JSON 池绑定无效");let p=JSON.stringify(h.path);(s.has(p)||h.path.some((w,A)=>a.has(JSON.stringify(h.path.slice(0,A+1)))))&>("JSON 池绑定重复或重叠"),a.add(p),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))&>("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)&>("JSON 池绑定必须替换空对象"),Object.defineProperty(g,v,{value:JV({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 p=u.get(h);if(p!==void 0)return p;let g=mi.get(h),v=A=>{if(A===null)return 0;let b=f.get(A);if(b!==void 0)return b;let R=n.nodes[A],_=Math.max(1+d(n.values[R.value]),v(R.left),v(R.right));return f.set(A,_),_},w=g?v(g.root):Object.values(h).reduce((A,b)=>Math.max(A,1+d(b)),0);return u.set(h,w),w};d(i)>64&>("JSON 逻辑数据嵌套超过 64 层"),Qc(n),Qc(i);let m=h=>{if(!(!h||typeof h!="object"||mi.has(h)||Hc.has(h))){Hc.set(h,o);for(let p of Object.values(h))m(p)}};return m(i),{value:i,stats:o,materialize:(h=[])=>cr(h.reduce((p,g)=>p?.[g],i)),hash:()=>En(i)}}function Qc(e){let t=new WeakSet,r=n=>{if(!(!n||typeof n!="object"||mi.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=mi.get(e);if(t){t.stats.materializedMaps++;let r=[...Jd(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 zd(e,t){let r=mi.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 Kd(e,t,r){let n=mi.get(e),i=(s,c)=>{let l=c.sequence;return t.get(l)!==s&>("WorkflowRun 结果来源不一致"),l};if(!n){for(let[s,c]of Object.entries(e))i(s,c)>=r&>("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&>("WorkflowRun 结果序号无效")}function KV(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 En(e,t={}){let r=HV("sha256"),n=e&&typeof e=="object"?Hc.get(e):void 0,i=l=>{if(!l||typeof l!="object")return;let u=mi.get(l)?.stats??Hc.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?NE.get(n):void 0;n&&!o&&t.cachePrefixes!==!1&&(o={root:{hash:r.copy(),next:new Map},size:0},NE.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("{"),KV(l).forEach((u,f)=>{f&&s(","),s(JSON.stringify(u)+":"),c(l[u])}),s("}")};return c(e),r.digest("hex")}function Uc(e){return Hc.get(e)??mi.get(e)?.stats}function Gd(e,t,r=!0){let n=zV(e,t);return r?n.materialize():n.value}var AE,bE,mi,Hc,gt,za,NE,Lo=I(()=>{"use strict";AE=new WeakMap,bE=new WeakMap;mi=new WeakMap,Hc=new WeakMap;gt=e=>{throw new Error(e)},za=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;NE=new WeakMap});var CE,k,rn=I(()=>{"use strict";CE=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(CE,r)?CE[r]:"manual-review"}code;recovery}});import{createHash as GV}from"node:crypto";import{types as YV}from"node:util";function nn(e){return ov.has(e)}function Yd(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(YV.isProxy(s))throw new k("INVALID_JSON","仅接受无执行行为的 JSON 数据");let l=ov.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?Fe(u.value):r?u.value:s}i.add(s);let f=0,d=h=>h&&typeof h=="object"?o.get(h)?.height??0:0,m=h=>(o.set(s,{value:h,height:f}),n&&(Object.freeze(s),ov.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 b=a(A.value,c+1);f=Math.max(f,1+d(A.value)),(t||r)&&v.push(b)}return m(r?`[${v.join(",")}]`:t?v:s)}let h=Object.getPrototypeOf(s);if(h!==Object.prototype&&h!==null)throw new k("INVALID_JSON","仅接受普通 JSON 对象");let p=[],g=Reflect.ownKeys(s);(t||r)&&g.sort((v,w)=>{let A=String(v),b=String(w),R=String(Number(A))===A&&Number.isInteger(Number(A))&&Number(A)>=0&&Number(A)<4294967295,_=String(Number(b))===b&&Number.isInteger(Number(b))&&Number(b)>=0&&Number(b)<4294967295;return R||_?R&&_?Number(A)-Number(b):R?-1:1:A<b?-1:A>b?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)&&p.push([v,A])}return m(r?`{${p.map(([v,w])=>`${JSON.stringify(v)}:${w}`).join(",")}}`:t?Object.fromEntries(p):s)}finally{i.delete(s)}}return a(e,0)}function Qn(e){return Yd(e,!1,!0)}function st(e){return Yd(e)}function Fe(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(Fe(e[n]));return r}let t={};for(let r of Object.keys(e)){let n=Fe(e[r]);r==="__proto__"?Object.defineProperty(t,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):t[r]=n}return t}function on(e){Yd(e,!1)}function T(e){let t=e!==null&&typeof e=="object"&&nn(e),r=t?IE.get(e):void 0;if(r!==void 0)return r;let n=GV("sha256").update(Qn(e)).digest("hex");return t&&IE.set(e,n),n}function Vo(e){return Yd(e,!1,!1,!0),e}var ov,IE,lr=I(()=>{"use strict";rn();ov=new WeakMap,IE=new WeakMap});function Dt(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new k("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function Un(e){return nn(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function av(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new k("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function sv(e){return["succeeded","failed","cancelled"].includes(e.status)}function xE(e){return PE(e,e.input)}function PE(e,t,r){for(let a of["id","runId","stepId","type"])Dt(e[a],a);e.ref!==void 0&&Dt(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)Dt(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(t),status:"pending",retry:i,requiredCapabilities:[...new Set(o)],receipts:[],reconciliations:[]}}function cv(e,t){av(e,t.attempt,t.inputHash),Dt(t.executorId,"executorId"),Dt(t.token,"token"),t.sessionId!==void 0&&Dt(t.sessionId,"sessionId");let r={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if(T(e.claim)===T(r)&&e.status==="running")return Un(e);throw new k("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new k("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...Un(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Xd(e,t){if(t=ef(t),Dt(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new k("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&Dt(t.event,"event");let r=T(t),n=e.rejectedOutcomes?.find(o=>o.outcome.outcomeId===t.outcomeId);if(n)throw T(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:Un(e),duplicate:!0}}if(av(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new k("STALE_ACTION","结果不属于当前 Action");if(sv(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(Dt(o.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(o.sha256))throw new k("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...Un(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function TE(e,t){if(Dt(t,"reason"),!["running","unknown"].includes(e.status))throw new k("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...Un(e),status:"unknown",reason:t}}function OE(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=Un(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:st(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 Zd(e,t){return Dt(t,"reason"),sv(e)?Un(e):{...Un(e),status:"cancelled",reason:t}}function $E(e,t){_n(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])Dt(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new k("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(av(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new k("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function lv(e,t){if($E(e,t),e.status!=="cancelled")throw new k("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&T(e.cancellation)!==T(t))throw new k("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Un(e),cancellation:structuredClone(t)}}function uv(e,t){if($E(e,t),!sv(e))throw new k("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&T(e.executionStop)!==T(t))throw new k("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Un(e),executionStop:structuredClone(t)}}function _n(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 ef(e){let t=st(e),r=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(_n(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(_n(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 jE(e){return dv(st(e))}function dv(e,t){if(_n(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=PE(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&&Dt(r.reason,"reason"),r.claim!==void 0&&(_n(r.claim,["executorId","sessionId","token"]),Dt(r.claim.executorId,"executorId"),Dt(r.claim.token,"token"),r.claim.sessionId!==void 0&&Dt(r.claim.sessionId,"sessionId")),r.status==="pending"&&r.claim||["running","unknown","succeeded","failed"].includes(r.status)&&!r.claim)throw new k("INVALID_ACTION","Action 状态与执行归属不一致");if(r.executionOrigin!==void 0&&(_n(r.executionOrigin,["workflow"]),_n(r.executionOrigin.workflow,["id","version","hash"]),Dt(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),Dt(r.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!r.claim||!/^[a-f0-9]{64}$/u.test(r.executionOrigin.workflow.hash)))throw new k("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");r.cancellation!==void 0&&lv({...r,input:null},r.cancellation),r.executionStop!==void 0&&uv({...r,input:null},r.executionStop);let i=new Set;for(let a of r.receipts){if(_n(a,["outcomeId","hash"]),Dt(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(_n(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=ef(s.outcome),l=r.receipts.find(u=>u.outcomeId===c.outcomeId);if(a.has(c.outcomeId)||!l||l.hash!==T(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(_n(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(_n(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!==T(r.outcome))throw new k("INVALID_ACTION","终态结果与已接受摘要不一致");Xd({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new k("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}var Mo=I(()=>{"use strict";rn();lr()});function fv(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function oe(e){throw new k("INVALID_RUN",e)}function Ct(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&oe(`${t} 必须是 JSON 对象`),e}function an(e,t,r){for(let n of Object.keys(e))t.includes(n)||oe(`${r} 包含不支持的字段:${n}`)}function ze(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&oe(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Ka(e,t,r=0){return(!Number.isSafeInteger(e)||e<r)&&oe(`${t} 必须是大于等于 ${r} 的安全整数`),e}function Zi(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&oe(`${t} 必须是 SHA-256 摘要`),e}function BE(e,t,r=!1){let n=Ct(e,t);an(n,r?["id","version","hash"]:["id","version"],t);let i={id:ze(n.id,`${t}.id`),version:ze(n.version,`${t}.version`)};return r&&(i.hash=Zi(n.hash,`${t}.hash`)),i}function Jc(e,t,r){let n=Ct(e,t);if(!r&&nn(n)&&VE.has(n))return n;let i=(o,a)=>{ze(o,`${t} step id`);let s=Ct(a,`${t}.${o}`);an(s,["sequence","value"],`${t}.${o}`),(!Object.hasOwn(s,"sequence")||!Object.hasOwn(s,"value"))&&oe(`${t}.${o} 缺少 sequence 或 value`),Ka(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 WE(e,t,r){let n=Ct(e,t);return an(n,["from","to","results","activation"],t),(!Object.hasOwn(n,"from")||!Object.hasOwn(n,"to")||!Object.hasOwn(n,"results"))&&oe(`${t} 缺少 from、to 或 results`),{from:n.from===null?null:ze(n.from,`${t}.from`),to:ze(n.to,`${t}.to`),results:Jc(n.results,`${t}.results`,r),...Object.hasOwn(n,"activation")?{activation:n.activation}:{}}}function tf(e,t,r,n){let i=`${t}:`;e.startsWith(i)||oe(`${r} 不属于当前 Run`);let o=e.slice(i.length);/^[1-9][0-9]*$/.test(o)||oe(`${r} 的步骤序号无效`);let a=Number(o);return(!Number.isSafeInteger(a)||a>n)&&oe(`${r} 的步骤序号超出 Run 范围`),a}function XV(e,t,r,n){let i=Ct(e,"Wait");an(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)||oe(`Wait 缺少 ${f}`);let o=ze(i.id,"Wait.id"),a=ze(i.stepId,"Wait.stepId"),s=Ka(i.sequence,"Wait.sequence",1);(s>r||tf(o,t,"Wait.id",r)!==s)&&oe("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||oe("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&oe("Wait.choices 必须是非空数组");let c=i.choices.map(f=>ze(f,"Wait.choices"));new Set(c).size!==c.length&&oe("Wait.choices 不能重复");let l=Zi(i.proposalHash,"Wait.proposalHash");T(i.proposal)!==l&&oe("Wait.proposal 与 proposalHash 不一致");let u={id:o,stepId:a,sequence:s,status:i.status,proposal:i.proposal,proposalHash:l,choices:c,results:Jc(i.results,"Wait.results",n)};if(i.decision!==void 0){let f=Ct(i.decision,"Wait.decision");an(f,["id","choice","proposalHash","reason"],"Wait.decision"),f.reason!==void 0&&!fv(f.reason)&&oe("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let d={id:ze(f.id,"Wait.decision.id"),choice:ze(f.choice,"Wait.decision.choice"),proposalHash:Zi(f.proposalHash,"Wait.decision.proposalHash"),...f.reason===void 0?{}:{reason:f.reason}};(i.status!=="resolved"||!c.includes(d.choice)||d.proposalHash!==l)&&oe("Wait.decision 与 Wait 状态、选择或提案不一致"),u.decision=d}else i.status==="resolved"&&oe("已解决的 Wait 必须保存对应 decision");return u}function ZV(e,t,r,n){let i=Ct(e,"EvidenceWait");an(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let o=ze(i.id,"EvidenceWait.id"),a=Ka(i.sequence,"EvidenceWait.sequence",1);(a>r||tf(o,t,"EvidenceWait.id",r)!==a)&&oe("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||oe("EvidenceWait.status 无效");let s={id:o,stepId:ze(i.stepId,"EvidenceWait.stepId"),sequence:a,kind:ze(i.kind,"EvidenceWait.kind"),status:i.status,results:Jc(i.results,"EvidenceWait.results",n)};if(i.receipt!==void 0){let c=Ct(i.receipt,"EvidenceWait.receipt");an(c,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),s.receipt={ref:ze(c.ref,"EvidenceWait.receipt.ref"),contentHash:Zi(c.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:ze(c.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let c=Ct(i.invalidation,"EvidenceWait.invalidation");an(c,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),s.invalidation={ref:ze(c.ref,"EvidenceWait.invalidation.ref"),contentHash:Zi(c.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:ze(c.submissionId,"EvidenceWait.invalidation.submissionId"),reason:ze(c.reason,"EvidenceWait.invalidation.reason")}}return(s.status==="resolved"!=!!s.receipt||s.status==="invalidated"!=!!s.invalidation)&&oe("EvidenceWait.receipt 与状态不一致"),s}function sn(e,t){let r=Ct(st(e),"WorkflowRun");return of(r,t)}function ME(e,t){if(e&&typeof e=="object"&&pv.has(e)&&nn(e)){let r=e;return t!==void 0&&r.runId!==t&&oe("WorkflowRun.runId 与存储键不一致"),r}return on(e),qE(of(Ct(structuredClone(e),"WorkflowRun"),t))}function rf(e,t,r){return of(Ct(e,"WorkflowRun"),t,void 0,r)}function nf(e,t){return on(e),of(Ct(e,"WorkflowRun"),e.runId,t&&pv.has(t)&&nn(t)?t:void 0),qE(e)}function qE(e){Vo(e),pv.add(e);for(let r of e.actions)LE.add(r);let t=r=>VE.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 of(e,t,r,n){an(e,DE,"WorkflowRun");for(let D of DE.filter(re=>re!=="reason"&&re!=="state"&&re!=="evidenceWaits"&&re!=="initialStateHash"&&re!=="commands"))Object.hasOwn(e,D)||oe(`WorkflowRun 缺少 ${D}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new k("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=ze(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&oe("WorkflowRun.runId 与存储键不一致");let o=Ka(e.revision,"WorkflowRun.revision",1),a=Ka(e.sequence,"WorkflowRun.sequence"),s=BE(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||oe("WorkflowRun.status 无效"),e.reason!==void 0&&ze(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||oe("WorkflowRun 缺少 input");let c=Ct(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(c).length===0&&oe("WorkflowRun.definitionHashes 不能为空");for(let[D,re]of Object.entries(c)){let ge;try{ge=JSON.parse(D)}catch{oe("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(ge)||ge.length!==2||typeof ge[0]!="string"||typeof ge[1]!="string"||JSON.stringify(ge)!==D)&&oe("WorkflowRun.definitionHashes 包含非规范的工作流引用"),Zi(re,`WorkflowRun.definitionHashes.${D}`)}let l=JSON.stringify([s.id,s.version]);c[l]!==s.hash&&oe("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&oe("WorkflowRun.lineage 必须是最多 32 层的数组");let u=e.lineage.map(D=>ze(D,"WorkflowRun.lineage"));(new Set(u).size!==u.length||u.includes(i))&&oe("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&oe("WorkflowRun.actions 和 waits 必须是数组");let f=e.actions.map(D=>{let re;try{re=D&&typeof D=="object"&&LE.has(D)&&nn(D)?D:dv(D,n?.hash(D.input))}catch(ge){if(ge instanceof k&&ge.code==="UNSUPPORTED_PROTOCOL")throw ge;oe(`WorkflowRun.actions 包含无效 Action:${ge.message}`)}return re.executionOrigin&&re.executionOrigin.workflow.id!==s.id&&oe("Action 执行来源不属于当前工作流"),re.runId!==i&&oe(`Action ${re.id} 不属于当前 Run`),new Set(re.requiredCapabilities).size!==re.requiredCapabilities.length&&oe(`Action ${re.id} 的 requiredCapabilities 不能重复`),re}),d=new Map(f.map(D=>[D.id,D]));e.commands!==void 0&&!Array.isArray(e.commands)&&oe("WorkflowRun.commands 必须是数组");let m=e.commands?.map(D=>{let re=Ct(D,"WorkflowRun.commands item");an(re,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let ge={id:ze(re.id,"WorkflowRun.commands.id"),name:ze(re.name,"WorkflowRun.commands.name"),inputHash:Zi(re.inputHash,"WorkflowRun.commands.inputHash"),actionId:ze(re.actionId,"WorkflowRun.commands.actionId")};return d.has(ge.actionId)||oe("WorkflowRun.commands 指向不存在的 Action"),ge});m&&new Set(m.map(D=>D.id)).size!==m.length&&oe("WorkflowRun.commands 标识不能重复");let h=e.waits.map(D=>XV(D,i,a,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&oe("WorkflowRun.evidenceWaits 必须是数组");let p=e.evidenceWaits?.map(D=>ZV(D,i,a,n))??[],g=new Map;for(let D of f){let re=tf(D.id,i,"Action.id",a);g.has(re)&&oe("WorkflowRun 的步骤序号不能重复"),g.set(re,D.stepId)}for(let D of h)g.has(D.sequence)&&oe("WorkflowRun 的步骤序号不能重复"),g.set(D.sequence,D.stepId);for(let D of p)g.has(D.sequence)&&oe("WorkflowRun 的步骤序号不能重复"),g.set(D.sequence,D.stepId);g.size!==a&&oe("WorkflowRun.sequence 与已激活步骤数量不一致");let v=Ct(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(v).length!==f.length&&oe("WorkflowRun.actionContexts 必须与 actions 一一对应");let w=new Map,A=r?new Map([...r.actions.map(D=>[r.actionContexts[D.id].sequence,D.stepId]),...r.waits.map(D=>[D.sequence,D.stepId]),...(r.evidenceWaits??[]).map(D=>[D.sequence,D.stepId])]):void 0;if(r&&A&&r.runId===i&&[...A].every(([D,re])=>g.get(D)===re)){let D=(re,ge)=>w.set(re,Math.min(w.get(re)??1/0,ge));for(let re of Object.values(r.actionContexts))D(re.results,re.sequence);for(let re of r.waits)D(re.results,re.sequence);for(let re of r.evidenceWaits??[])D(re.results,re.sequence);for(let re of r.ready)D(re.results,r.sequence+1);for(let re of Object.values(r.joins))for(let ge of Object.values(re))for(let mt of ge)D(mt.results,r.sequence+1);D(r.outputs,r.sequence+1)}let b=new Map;function R(D,re){let ge=re??a+1;if(n){n.validateOrigins(D,g,ge);return}let mt=w.get(D);if(!(mt!==void 0&&ge>=mt&&nn(D))&&!((b.get(D)??1/0)<=ge)){b.set(D,ge);for(let[S,N]of Object.entries(D))(N.sequence>=(re??a+1)||g.get(N.sequence)!==S)&&oe(`WorkflowRun 结果 ${S} 的序号或来源不一致`)}}for(let D of f){Object.hasOwn(v,D.id)||oe(`Action ${D.id} 缺少上下文`);let re=Ct(v[D.id],`actionContexts.${D.id}`);an(re,["sequence","results"],`actionContexts.${D.id}`);let ge=Ka(re.sequence,`actionContexts.${D.id}.sequence`,1);ge!==tf(D.id,i,"Action.id",a)&&oe(`Action ${D.id} 的上下文序号不一致`);let mt=Jc(re.results,`actionContexts.${D.id}.results`,n);R(mt,ge)}for(let D of h)R(D.results,D.sequence);for(let D of p)R(D.results,D.sequence);Array.isArray(e.ready)||oe("WorkflowRun.ready 必须是数组");let _=e.ready.map(D=>WE(D,"WorkflowRun.ready token",n));for(let D of _)R(D.results);let W=Ct(e.joins,"WorkflowRun.joins"),O=Object.fromEntries(Object.entries(W).map(([D,re])=>{ze(D,"WorkflowRun.joins step id");let ge=Ct(re,`WorkflowRun.joins.${D}`),mt=Object.fromEntries(Object.entries(ge).map(([S,N])=>{ze(S,"WorkflowRun.joins parent id"),Array.isArray(N)||oe(`WorkflowRun.joins.${D}.${S} 必须是数组`);let C=N.map(B=>{let L=WE(B,`WorkflowRun.joins.${D}.${S}`,n);return(L.to!==D||L.from!==S)&&oe(`WorkflowRun.joins.${D}.${S} 包含错误来源的 token`),R(L.results),L});return[S,C]}));return[D,mt]})),G=Jc(e.outputs,"WorkflowRun.outputs",n);R(G),Array.isArray(e.children)||oe("WorkflowRun.children 必须是数组");let Z=e.children.map(D=>{let re=Ct(D,"WorkflowRun.children item");an(re,["actionId","runId","workflow"],"WorkflowRun.children item");let ge=BE(re.workflow,"WorkflowRun.children.workflow"),mt=ze(re.actionId,"WorkflowRun.children.actionId"),S=ze(re.runId,"WorkflowRun.children.runId"),N=d.get(mt);return(!N||N.type!=="child_workflow"||N.ref!==`${ge.id}@${ge.version}`||S!==`child-${T(mt)}`||!Object.hasOwn(c,JSON.stringify([ge.id,ge.version])))&&oe("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:mt,runId:S,workflow:ge}});(new Set(Z.map(D=>D.actionId)).size!==Z.length||f.filter(D=>D.type==="child_workflow").length!==Z.length)&&oe("每个子工作流 Action 必须恰好对应一个 Child Run");let F=f.some(D=>["pending","running","unknown"].includes(D.status)),X=h.some(D=>D.status==="pending"),U=p.some(D=>D.status==="pending"),pe=Object.values(O).some(D=>Object.values(D).some(re=>re.length>0));return e.status==="running"&&!F&&_.length===0&&oe("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(F||!X&&!U&&!pe||_.length>0)&&oe("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(F||X||U||pe||_.length>0)&&oe("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&oe(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:o,workflow:s,definitionHashes:c,...e.initialStateHash===void 0?{}:{initialStateHash:Zi(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:a,actions:f,...m===void 0?{}:{commands:m},actionContexts:v,waits:h,...e.evidenceWaits===void 0?{}:{evidenceWaits:p},ready:_,joins:O,outputs:G,children:Z,lineage:u,...e.reason===void 0?{}:{reason:e.reason}}}var LE,VE,pv,DE,zc=I(()=>{"use strict";Mo();rn();lr();LE=new WeakSet,VE=new WeakSet,pv=new WeakSet,DE=["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 eM}from"node:crypto";async function qo(e,t){let r=await(e.readProjection?e.readProjection(t):e.read(t));if(!r)throw new k("RUN_NOT_FOUND",`找不到工作流实例:${t}`);Uc(r)||(on(r),r=structuredClone(r),Qc(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=rf(n,t,{hash:En,visitResults:zd,validateOrigins:Kd})}catch(s){throw s instanceof k?s:new k("INVALID_RUN",s instanceof Error?s.message:String(s))}Qc(i);let o=Uc(r);o&&(o.validationActions=i.actions.length,o.validationMaterializedEntries=o.materializedEntries);let a=e.queryScope??FE.get(e);return a||(a=eM(),FE.set(e,a)),Object.freeze({record:r,run:i,scope:a,stats:o,materialize:(s=[])=>cr(s.reduce((c,l)=>c?.[l],i)),hash:()=>En(i)})}function mv(e,t){let{run:r,scope:n}=e;["current","summary","history","action","artifact"].includes(t.view)||eo("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(p=>p.id===t.actionId);if(d||eo("query.actionId 不属于当前 Run"),t.view==="action")return cr({...i,action:d,context:r.actionContexts[d.id]});let m=(d.outcome?.artifacts??[]).map(p=>({...p,artifactId:T({actionId:d.id,...p})})),h=t.artifactId===void 0?m:m.filter(p=>p.artifactId===t.artifactId);return t.artifactId!==void 0&&!h.length&&eo("query.artifactId 不属于所选 Action"),cr({...i,actionId:d.id,artifacts:h})}let s=t.limit??25;(!Number.isSafeInteger(s)||s<1||s>100)&&eo("query.limit 必须在 1–100 之间");let c=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(c)||eo("query.filter 无效");let l=T({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(m=>!["binding","offset"].includes(m)))&&eo("query.cursor 与当前存储、版本或筛选不匹配"),u=d.offset}catch{eo("query.cursor 无效或已经过期")}let f=[...c==="all"||c==="actions"?r.actions.map((d,m)=>({kind:"action",sequence:r.actionContexts[d.id].sequence,path:["actions",String(m)]})):[],...c==="all"||c==="waits"?r.waits.map((d,m)=>({kind:"wait",sequence:d.sequence,path:["waits",String(m)]})):[],...c==="all"||c==="evidenceWaits"?(r.evidenceWaits??[]).map((d,m)=>({kind:"evidenceWait",sequence:d.sequence,path:["evidenceWaits",String(m)]})):[]].sort((d,m)=>m.sequence-d.sequence);return u>f.length&&eo("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 FE,eo,hv=I(()=>{"use strict";Lo();rn();zc();lr();FE=new WeakMap;eo=e=>{throw new k("INVALID_REQUEST",e)}});var Yc=j(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.regexpCode=Be.getEsmExportName=Be.getProperty=Be.safeStringify=Be.stringify=Be.strConcat=Be.addCodeArg=Be.str=Be._=Be.nil=Be._Code=Be.Name=Be.IDENTIFIER=Be._CodeOrName=void 0;var Kc=class{};Be._CodeOrName=Kc;Be.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fo=class extends Kc{constructor(t){if(super(),!Be.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}}};Be.Name=Fo;var cn=class extends Kc{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 Fo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Be._Code=cn;Be.nil=new cn("");function HE(e,...t){let r=[e[0]],n=0;for(;n<t.length;)vv(r,t[n]),r.push(e[++n]);return new cn(r)}Be._=HE;var gv=new cn("+");function QE(e,...t){let r=[Gc(e[0])],n=0;for(;n<t.length;)r.push(gv),vv(r,t[n]),r.push(gv,Gc(e[++n]));return tM(r),new cn(r)}Be.str=QE;function vv(e,t){t instanceof cn?e.push(...t._items):t instanceof Fo?e.push(t):e.push(iM(t))}Be.addCodeArg=vv;function tM(e){let t=1;for(;t<e.length-1;){if(e[t]===gv){let r=rM(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function rM(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Fo||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 Fo))return`"${e}${t.slice(1)}`}function nM(e,t){return t.emptyStr()?e:e.emptyStr()?t:QE`${e}${t}`}Be.strConcat=nM;function iM(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Gc(Array.isArray(e)?e.join(","):e)}function oM(e){return new cn(Gc(e))}Be.stringify=oM;function Gc(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Be.safeStringify=Gc;function aM(e){return typeof e=="string"&&Be.IDENTIFIER.test(e)?new cn(`.${e}`):HE`[${e}]`}Be.getProperty=aM;function sM(e){if(typeof e=="string"&&Be.IDENTIFIER.test(e))return new cn(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Be.getEsmExportName=sM;function cM(e){return new cn(e.toString())}Be.regexpCode=cM});var kv=j(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.ValueScope=_r.ValueScopeName=_r.Scope=_r.varKinds=_r.UsedValueState=void 0;var Er=Yc(),wv=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},af;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(af||(_r.UsedValueState=af={}));_r.varKinds={const:new Er.Name("const"),let:new Er.Name("let"),var:new Er.Name("var")};var sf=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Er.Name?t:this.name(t)}name(t){return new Er.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}}};_r.Scope=sf;var cf=class extends Er.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Er._)`.${new Er.Name(r)}[${n}]`}};_r.ValueScopeName=cf;var lM=(0,Er._)`\n`,yv=class extends sf{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?lM:Er.nil}}get(){return this._scope}name(t){return new cf(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,Er._)`${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=Er.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,af.Started);let u=r(l);if(u){let f=this.opts.es5?_r.varKinds.var:_r.varKinds.const;o=(0,Er._)`${o}${f} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,Er._)`${o}${u}${this.opts._n}`;else throw new wv(l);c.set(l,af.Completed)})}return o}};_r.ValueScope=yv});var Ce=j(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.or=_e.and=_e.not=_e.CodeGen=_e.operators=_e.varKinds=_e.ValueScopeName=_e.ValueScope=_e.Scope=_e.Name=_e.regexpCode=_e.stringify=_e.getProperty=_e.nil=_e.strConcat=_e.str=_e._=void 0;var Oe=Yc(),Cn=kv(),to=Yc();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return to._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return to.str}});Object.defineProperty(_e,"strConcat",{enumerable:!0,get:function(){return to.strConcat}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return to.nil}});Object.defineProperty(_e,"getProperty",{enumerable:!0,get:function(){return to.getProperty}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return to.stringify}});Object.defineProperty(_e,"regexpCode",{enumerable:!0,get:function(){return to.regexpCode}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return to.Name}});var ff=kv();Object.defineProperty(_e,"Scope",{enumerable:!0,get:function(){return ff.Scope}});Object.defineProperty(_e,"ValueScope",{enumerable:!0,get:function(){return ff.ValueScope}});Object.defineProperty(_e,"ValueScopeName",{enumerable:!0,get:function(){return ff.ValueScopeName}});Object.defineProperty(_e,"varKinds",{enumerable:!0,get:function(){return ff.varKinds}});_e.operators={GT:new Oe._Code(">"),GTE:new Oe._Code(">="),LT:new Oe._Code("<"),LTE:new Oe._Code("<="),EQ:new Oe._Code("==="),NEQ:new Oe._Code("!=="),NOT:new Oe._Code("!"),OR:new Oe._Code("||"),AND:new Oe._Code("&&"),ADD:new Oe._Code("+")};var hi=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Av=class extends hi{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Cn.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=Ya(this.rhs,t,r)),this}get names(){return this.rhs instanceof Oe._CodeOrName?this.rhs.names:{}}},lf=class extends hi{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 Oe.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Ya(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Oe.Name?{}:{...this.lhs.names};return df(t,this.rhs)}},bv=class extends lf{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Rv=class extends hi{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Nv=class extends hi{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Sv=class extends hi{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ev=class extends hi{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=Ya(this.code,t,r),this}get names(){return this.code instanceof Oe._CodeOrName?this.code.names:{}}},Xc=class extends hi{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)||(uM(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Uo(t,r.names),{})}},gi=class extends Xc{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},_v=class extends Xc{},Ga=class extends gi{};Ga.kind="else";var Ho=class e extends gi{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 Ga(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(UE(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=Ya(this.condition,t,r),this}get names(){let t=super.names;return df(t,this.condition),this.else&&Uo(t,this.else.names),t}};Ho.kind="if";var Qo=class extends gi{};Qo.kind="for";var Cv=class extends Qo{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=Ya(this.iteration,t,r),this}get names(){return Uo(super.names,this.iteration.names)}},Iv=class extends Qo{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?Cn.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=df(super.names,this.from);return df(t,this.to)}},uf=class extends Qo{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=Ya(this.iterable,t,r),this}get names(){return Uo(super.names,this.iterable.names)}},Zc=class extends gi{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)}};Zc.kind="func";var el=class extends Xc{render(t){return"return "+super.render(t)}};el.kind="return";var xv=class extends gi{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&&Uo(t,this.catch.names),this.finally&&Uo(t,this.finally.names),t}},tl=class extends gi{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};tl.kind="catch";var rl=class extends gi{render(t){return"finally"+super.render(t)}};rl.kind="finally";var Pv=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
187
|
+
`:""},this._extScope=t,this._scope=new Cn.Scope({parent:t}),this._nodes=[new _v]}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 Av(t,o,n)),o}const(t,r,n){return this._def(Cn.varKinds.const,t,r,n)}let(t,r,n){return this._def(Cn.varKinds.let,t,r,n)}var(t,r,n){return this._def(Cn.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new lf(t,r,n))}add(t,r){return this._leafNode(new bv(t,_e.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Oe.nil&&this._leafNode(new Ev(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,Oe.addCodeArg)(r,i));return r.push("}"),new Oe._Code(r)}if(t,r,n){if(this._blockNode(new Ho(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 Ho(t))}else(){return this._elseNode(new Ga)}endIf(){return this._endBlockNode(Ho,Ga)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Cv(t),r)}forRange(t,r,n,i,o=this.opts.es5?Cn.varKinds.var:Cn.varKinds.let){let a=this._scope.toName(t);return this._for(new Iv(o,a,r,n),()=>i(a))}forOf(t,r,n,i=Cn.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let a=r instanceof Oe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Oe._)`${a}.length`,s=>{this.var(o,(0,Oe._)`${a}[${s}]`),n(o)})}return this._for(new uf("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?Cn.varKinds.var:Cn.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Oe._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new uf("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Qo)}label(t){return this._leafNode(new Rv(t))}break(t){return this._leafNode(new Nv(t))}return(t){let r=new el;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(el)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new xv;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new tl(o),r(o)}return n&&(this._currNode=i.finally=new rl,this.code(n)),this._endBlockNode(tl,rl)}throw(t){return this._leafNode(new Sv(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=Oe.nil,n,i){return this._blockNode(new Zc(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Zc)}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 Ho))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}};_e.CodeGen=Pv;function Uo(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function df(e,t){return t instanceof Oe._CodeOrName?Uo(e,t.names):e}function Ya(e,t,r){if(e instanceof Oe.Name)return n(e);if(!i(e))return e;return new Oe._Code(e._items.reduce((o,a)=>(a instanceof Oe.Name&&(a=n(a)),a instanceof Oe._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 Oe._Code&&o._items.some(a=>a instanceof Oe.Name&&t[a.str]===1&&r[a.str]!==void 0)}}function uM(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function UE(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Oe._)`!${Tv(e)}`}_e.not=UE;var dM=JE(_e.operators.AND);function fM(...e){return e.reduce(dM)}_e.and=fM;var pM=JE(_e.operators.OR);function mM(...e){return e.reduce(pM)}_e.or=mM;function JE(e){return(t,r)=>t===Oe.nil?r:r===Oe.nil?t:(0,Oe._)`${Tv(t)} ${e} ${Tv(r)}`}function Tv(e){return e instanceof Oe.Name?e:(0,Oe._)`(${e})`}});var je=j(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.checkStrictMode=Ie.getErrorPath=Ie.Type=Ie.useFunc=Ie.setEvaluated=Ie.evaluatedPropsToName=Ie.mergeEvaluated=Ie.eachItem=Ie.unescapeJsonPointer=Ie.escapeJsonPointer=Ie.escapeFragment=Ie.unescapeFragment=Ie.schemaRefOrVal=Ie.schemaHasRulesButRef=Ie.schemaHasRules=Ie.checkUnknownRules=Ie.alwaysValidSchema=Ie.toHash=void 0;var Xe=Ce(),hM=Yc();function gM(e){let t={};for(let r of e)t[r]=!0;return t}Ie.toHash=gM;function vM(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(GE(e,t),!YE(t,e.self.RULES.all))}Ie.alwaysValidSchema=vM;function GE(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]||e_(e,`unknown keyword: "${o}"`)}Ie.checkUnknownRules=GE;function YE(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}Ie.schemaHasRules=YE;function wM(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Ie.schemaHasRulesButRef=wM;function yM({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Xe._)`${r}`}return(0,Xe._)`${e}${t}${(0,Xe.getProperty)(n)}`}Ie.schemaRefOrVal=yM;function kM(e){return XE(decodeURIComponent(e))}Ie.unescapeFragment=kM;function AM(e){return encodeURIComponent($v(e))}Ie.escapeFragment=AM;function $v(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Ie.escapeJsonPointer=$v;function XE(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Ie.unescapeJsonPointer=XE;function bM(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}Ie.eachItem=bM;function zE({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,a,s)=>{let c=a===void 0?o:a instanceof Xe.Name?(o instanceof Xe.Name?e(i,o,a):t(i,o,a),a):o instanceof Xe.Name?(t(i,a,o),o):r(o,a);return s===Xe.Name&&!(c instanceof Xe.Name)?n(i,c):c}}Ie.mergeEvaluated={props:zE({mergeNames:(e,t,r)=>e.if((0,Xe._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Xe._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Xe._)`${r} || {}`).code((0,Xe._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Xe._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Xe._)`${r} || {}`),jv(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:ZE}),items:zE({mergeNames:(e,t,r)=>e.if((0,Xe._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Xe._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Xe._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Xe._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function ZE(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,Xe._)`{}`);return t!==void 0&&jv(e,r,t),r}Ie.evaluatedPropsToName=ZE;function jv(e,t,r){Object.keys(r).forEach(n=>e.assign((0,Xe._)`${t}${(0,Xe.getProperty)(n)}`,!0))}Ie.setEvaluated=jv;var KE={};function RM(e,t){return e.scopeValue("func",{ref:t,code:KE[t.code]||(KE[t.code]=new hM._Code(t.code))})}Ie.useFunc=RM;var Ov;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ov||(Ie.Type=Ov={}));function NM(e,t,r){if(e instanceof Xe.Name){let n=t===Ov.Num;return r?n?(0,Xe._)`"[" + ${e} + "]"`:(0,Xe._)`"['" + ${e} + "']"`:n?(0,Xe._)`"/" + ${e}`:(0,Xe._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Xe.getProperty)(e).toString():"/"+$v(e)}Ie.getErrorPath=NM;function e_(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Ie.checkStrictMode=e_});var vi=j(Dv=>{"use strict";Object.defineProperty(Dv,"__esModule",{value:!0});var Xt=Ce(),SM={data:new Xt.Name("data"),valCxt:new Xt.Name("valCxt"),instancePath:new Xt.Name("instancePath"),parentData:new Xt.Name("parentData"),parentDataProperty:new Xt.Name("parentDataProperty"),rootData:new Xt.Name("rootData"),dynamicAnchors:new Xt.Name("dynamicAnchors"),vErrors:new Xt.Name("vErrors"),errors:new Xt.Name("errors"),this:new Xt.Name("this"),self:new Xt.Name("self"),scope:new Xt.Name("scope"),json:new Xt.Name("json"),jsonPos:new Xt.Name("jsonPos"),jsonLen:new Xt.Name("jsonLen"),jsonPart:new Xt.Name("jsonPart")};Dv.default=SM});var nl=j(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.extendErrors=Zt.resetErrorsCount=Zt.reportExtraError=Zt.reportError=Zt.keyword$DataError=Zt.keywordError=void 0;var De=Ce(),pf=je(),ur=vi();Zt.keywordError={message:({keyword:e})=>(0,De.str)`must pass "${e}" keyword validation`};Zt.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,De.str)`"${e}" keyword must be ${t} ($data)`:(0,De.str)`"${e}" keyword is invalid ($data)`};function EM(e,t=Zt.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:a,allErrors:s}=i,c=n_(e,t,r);n??(a||s)?t_(o,c):r_(i,(0,De._)`[${c}]`)}Zt.reportError=EM;function _M(e,t=Zt.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:a}=n,s=n_(e,t,r);t_(i,s),o||a||r_(n,ur.default.vErrors)}Zt.reportExtraError=_M;function CM(e,t){e.assign(ur.default.errors,t),e.if((0,De._)`${ur.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,De._)`${ur.default.vErrors}.length`,t),()=>e.assign(ur.default.vErrors,null)))}Zt.resetErrorsCount=CM;function IM({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,De._)`${ur.default.vErrors}[${s}]`),e.if((0,De._)`${a}.instancePath === undefined`,()=>e.assign((0,De._)`${a}.instancePath`,(0,De.strConcat)(ur.default.instancePath,o.errorPath))),e.assign((0,De._)`${a}.schemaPath`,(0,De.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,De._)`${a}.schema`,r),e.assign((0,De._)`${a}.data`,n))})}Zt.extendErrors=IM;function t_(e,t){let r=e.const("err",t);e.if((0,De._)`${ur.default.vErrors} === null`,()=>e.assign(ur.default.vErrors,(0,De._)`[${r}]`),(0,De._)`${ur.default.vErrors}.push(${r})`),e.code((0,De._)`${ur.default.errors}++`)}function r_(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,De._)`new ${e.ValidationError}(${t})`):(r.assign((0,De._)`${n}.errors`,t),r.return(!1))}var Jo={keyword:new De.Name("keyword"),schemaPath:new De.Name("schemaPath"),params:new De.Name("params"),propertyName:new De.Name("propertyName"),message:new De.Name("message"),schema:new De.Name("schema"),parentSchema:new De.Name("parentSchema")};function n_(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,De._)`{}`:xM(e,t,r)}function xM(e,t,r={}){let{gen:n,it:i}=e,o=[PM(i,r),TM(e,r)];return OM(e,t,o),n.object(...o)}function PM({errorPath:e},{instancePath:t}){let r=t?(0,De.str)`${e}${(0,pf.getErrorPath)(t,pf.Type.Str)}`:e;return[ur.default.instancePath,(0,De.strConcat)(ur.default.instancePath,r)]}function TM({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,De.str)`${t}/${e}`;return r&&(i=(0,De.str)`${i}${(0,pf.getErrorPath)(r,pf.Type.Str)}`),[Jo.schemaPath,i]}function OM(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([Jo.keyword,i],[Jo.params,typeof t=="function"?t(e):t||(0,De._)`{}`]),c.messages&&n.push([Jo.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Jo.schema,a],[Jo.parentSchema,(0,De._)`${u}${f}`],[ur.default.data,o]),l&&n.push([Jo.propertyName,l])}});var o_=j(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.boolOrEmptySchema=Xa.topBoolOrEmptySchema=void 0;var $M=nl(),jM=Ce(),DM=vi(),BM={message:"boolean schema is false"};function WM(e){let{gen:t,schema:r,validateName:n}=e;r===!1?i_(e,!1):typeof r=="object"&&r.$async===!0?t.return(DM.default.data):(t.assign((0,jM._)`${n}.errors`,null),t.return(!0))}Xa.topBoolOrEmptySchema=WM;function LM(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),i_(e)):r.var(t,!0)}Xa.boolOrEmptySchema=LM;function i_(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,$M.reportError)(i,BM,void 0,t)}});var Bv=j(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.getRules=Za.isJSONType=void 0;var VM=["string","number","integer","boolean","null","object","array"],MM=new Set(VM);function qM(e){return typeof e=="string"&&MM.has(e)}Za.isJSONType=qM;function FM(){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:{}}}Za.getRules=FM});var Wv=j(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.shouldUseRule=ro.shouldUseGroup=ro.schemaHasRulesForType=void 0;function HM({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&a_(e,n)}ro.schemaHasRulesForType=HM;function a_(e,t){return t.rules.some(r=>s_(e,r))}ro.shouldUseGroup=a_;function s_(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))}ro.shouldUseRule=s_});var il=j(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.reportTypeError=er.checkDataTypes=er.checkDataType=er.coerceAndCheckDataType=er.getJSONTypes=er.getSchemaTypes=er.DataType=void 0;var QM=Bv(),UM=Wv(),JM=nl(),Re=Ce(),c_=je(),es;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(es||(er.DataType=es={}));function zM(e){let t=l_(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}er.getSchemaTypes=zM;function l_(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(QM.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}er.getJSONTypes=l_;function KM(e,t){let{gen:r,data:n,opts:i}=e,o=GM(t,i.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,UM.schemaHasRulesForType)(e,t[0]));if(a){let s=Vv(t,n,i.strictNumbers,es.Wrong);r.if(s,()=>{o.length?YM(e,t,o):Mv(e)})}return a}er.coerceAndCheckDataType=KM;var u_=new Set(["string","number","integer","boolean","null"]);function GM(e,t){return t?e.filter(r=>u_.has(r)||t==="array"&&r==="array"):[]}function YM(e,t,r){let{gen:n,data:i,opts:o}=e,a=n.let("dataType",(0,Re._)`typeof ${i}`),s=n.let("coerced",(0,Re._)`undefined`);o.coerceTypes==="array"&&n.if((0,Re._)`${a} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,Re._)`${i}[0]`).assign(a,(0,Re._)`typeof ${i}`).if(Vv(t,i,o.strictNumbers),()=>n.assign(s,i))),n.if((0,Re._)`${s} !== undefined`);for(let l of r)(u_.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),Mv(e),n.endIf(),n.if((0,Re._)`${s} !== undefined`,()=>{n.assign(i,s),XM(e,s)});function c(l){switch(l){case"string":n.elseIf((0,Re._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,Re._)`"" + ${i}`).elseIf((0,Re._)`${i} === null`).assign(s,(0,Re._)`""`);return;case"number":n.elseIf((0,Re._)`${a} == "boolean" || ${i} === null
|
|
188
|
+
|| (${a} == "string" && ${i} && ${i} == +${i})`).assign(s,(0,Re._)`+${i}`);return;case"integer":n.elseIf((0,Re._)`${a} === "boolean" || ${i} === null
|
|
189
|
+
|| (${a} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(s,(0,Re._)`+${i}`);return;case"boolean":n.elseIf((0,Re._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(s,!1).elseIf((0,Re._)`${i} === "true" || ${i} === 1`).assign(s,!0);return;case"null":n.elseIf((0,Re._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(s,null);return;case"array":n.elseIf((0,Re._)`${a} === "string" || ${a} === "number"
|
|
190
|
+
|| ${a} === "boolean" || ${i} === null`).assign(s,(0,Re._)`[${i}]`)}}}function XM({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,Re._)`${t} !== undefined`,()=>e.assign((0,Re._)`${t}[${r}]`,n))}function Lv(e,t,r,n=es.Correct){let i=n===es.Correct?Re.operators.EQ:Re.operators.NEQ,o;switch(e){case"null":return(0,Re._)`${t} ${i} null`;case"array":o=(0,Re._)`Array.isArray(${t})`;break;case"object":o=(0,Re._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=a((0,Re._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=a();break;default:return(0,Re._)`typeof ${t} ${i} ${e}`}return n===es.Correct?o:(0,Re.not)(o);function a(s=Re.nil){return(0,Re.and)((0,Re._)`typeof ${t} == "number"`,s,r?(0,Re._)`isFinite(${t})`:Re.nil)}}er.checkDataType=Lv;function Vv(e,t,r,n){if(e.length===1)return Lv(e[0],t,r,n);let i,o=(0,c_.toHash)(e);if(o.array&&o.object){let a=(0,Re._)`typeof ${t} != "object"`;i=o.null?a:(0,Re._)`!${t} || ${a}`,delete o.null,delete o.array,delete o.object}else i=Re.nil;o.number&&delete o.integer;for(let a in o)i=(0,Re.and)(i,Lv(a,t,r,n));return i}er.checkDataTypes=Vv;var ZM={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,Re._)`{type: ${e}}`:(0,Re._)`{type: ${t}}`};function Mv(e){let t=e1(e);(0,JM.reportError)(t,ZM)}er.reportTypeError=Mv;function e1(e){let{gen:t,data:r,schema:n}=e,i=(0,c_.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var f_=j(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});mf.assignDefaults=void 0;var ts=Ce(),t1=je();function r1(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)d_(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>d_(e,o,i.default))}mf.assignDefaults=r1;function d_(e,t,r){let{gen:n,compositeRule:i,data:o,opts:a}=e;if(r===void 0)return;let s=(0,ts._)`${o}${(0,ts.getProperty)(t)}`;if(i){(0,t1.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,ts._)`${s} === undefined`;a.useDefaults==="empty"&&(c=(0,ts._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,ts._)`${s} = ${(0,ts.stringify)(r)}`)}});var ln=j(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.validateUnion=Ke.validateArray=Ke.usePattern=Ke.callValidateCode=Ke.schemaProperties=Ke.allSchemaProperties=Ke.noPropertyInData=Ke.propertyInData=Ke.isOwnProperty=Ke.hasPropFunc=Ke.reportMissingProp=Ke.checkMissingProp=Ke.checkReportMissingProp=void 0;var rt=Ce(),qv=je(),no=vi(),n1=je();function i1(e,t){let{gen:r,data:n,it:i}=e;r.if(Hv(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,rt._)`${t}`},!0),e.error()})}Ke.checkReportMissingProp=i1;function o1({gen:e,data:t,it:{opts:r}},n,i){return(0,rt.or)(...n.map(o=>(0,rt.and)(Hv(e,t,o,r.ownProperties),(0,rt._)`${i} = ${o}`)))}Ke.checkMissingProp=o1;function a1(e,t){e.setParams({missingProperty:t},!0),e.error()}Ke.reportMissingProp=a1;function p_(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,rt._)`Object.prototype.hasOwnProperty`})}Ke.hasPropFunc=p_;function Fv(e,t,r){return(0,rt._)`${p_(e)}.call(${t}, ${r})`}Ke.isOwnProperty=Fv;function s1(e,t,r,n){let i=(0,rt._)`${t}${(0,rt.getProperty)(r)} !== undefined`;return n?(0,rt._)`${i} && ${Fv(e,t,r)}`:i}Ke.propertyInData=s1;function Hv(e,t,r,n){let i=(0,rt._)`${t}${(0,rt.getProperty)(r)} === undefined`;return n?(0,rt.or)(i,(0,rt.not)(Fv(e,t,r))):i}Ke.noPropertyInData=Hv;function m_(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Ke.allSchemaProperties=m_;function c1(e,t){return m_(t).filter(r=>!(0,qv.alwaysValidSchema)(e,t[r]))}Ke.schemaProperties=c1;function l1({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:a},s,c,l){let u=l?(0,rt._)`${e}, ${t}, ${n}${i}`:t,f=[[no.default.instancePath,(0,rt.strConcat)(no.default.instancePath,o)],[no.default.parentData,a.parentData],[no.default.parentDataProperty,a.parentDataProperty],[no.default.rootData,no.default.rootData]];a.opts.dynamicRef&&f.push([no.default.dynamicAnchors,no.default.dynamicAnchors]);let d=(0,rt._)`${u}, ${r.object(...f)}`;return c!==rt.nil?(0,rt._)`${s}.call(${c}, ${d})`:(0,rt._)`${s}(${d})`}Ke.callValidateCode=l1;var u1=(0,rt._)`new RegExp`;function d1({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,rt._)`${i.code==="new RegExp"?u1:(0,n1.useFunc)(e,i)}(${r}, ${n})`})}Ke.usePattern=d1;function f1(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,rt._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:qv.Type.Num},o),t.if((0,rt.not)(o),s)})}}Ke.validateArray=f1;function p1(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,qv.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,rt._)`${a} || ${s}`),e.mergeValidEvaluated(u,s)||t.if((0,rt.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}Ke.validateUnion=p1});var v_=j(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.validateKeywordUsage=Jn.validSchemaType=Jn.funcKeywordCode=Jn.macroKeywordCode=void 0;var dr=Ce(),zo=vi(),m1=ln(),h1=nl();function g1(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:a}=e,s=t.macro.call(a.self,i,o,a),c=g_(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))}Jn.macroKeywordCode=g1;function v1(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:a,$data:s,it:c}=e;y1(c,t);let l=!s&&t.compile?t.compile.call(c.self,o,a,c):t.validate,u=g_(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)p(),t.modifying&&h_(e),g(()=>e.error());else{let v=t.async?m():h();t.modifying&&h_(e),g(()=>w1(e,v))}}function m(){let v=n.let("ruleErrs",null);return n.try(()=>p((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),p(dr.nil),v}function p(v=t.async?(0,dr._)`await `:dr.nil){let w=c.opts.passContext?zo.default.this:zo.default.self,A=!("compile"in t&&!s||t.schema===!1);n.assign(f,(0,dr._)`${v}${(0,m1.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)}}Jn.funcKeywordCode=v1;function h_(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,dr._)`${n.parentData}[${n.parentDataProperty}]`))}function w1(e,t){let{gen:r}=e;r.if((0,dr._)`Array.isArray(${t})`,()=>{r.assign(zo.default.vErrors,(0,dr._)`${zo.default.vErrors} === null ? ${t} : ${zo.default.vErrors}.concat(${t})`).assign(zo.default.errors,(0,dr._)`${zo.default.vErrors}.length`),(0,h1.extendErrors)(e)},()=>e.error())}function y1({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function g_(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 k1(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")}Jn.validSchemaType=k1;function A1({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)}}Jn.validateKeywordUsage=A1});var y_=j(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.extendSubschemaMode=io.extendSubschemaData=io.getSubschema=void 0;var zn=Ce(),w_=je();function b1(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,zn._)`${e.schemaPath}${(0,zn.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,zn._)`${e.schemaPath}${(0,zn.getProperty)(t)}${(0,zn.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,w_.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')}io.getSubschema=b1;function R1(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,zn._)`${t.data}${(0,zn.getProperty)(r)}`,!0);c(d),e.errorPath=(0,zn.str)`${l}${(0,w_.getErrorPath)(r,n,f.jsPropertySyntax)}`,e.parentDataProperty=(0,zn._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(i!==void 0){let l=i instanceof zn.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]}}io.extendSubschemaData=R1;function N1(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}io.extendSubschemaMode=N1});var Qv=j((y3,k_)=>{"use strict";k_.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 b_=j((k3,A_)=>{"use strict";var oo=A_.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(){};hf(t,n,i,e,"",e)};oo.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};oo.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};oo.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};oo.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 hf(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 oo.arrayKeywords)for(var d=0;d<f.length;d++)hf(e,t,r,f[d],i+"/"+u+"/"+d,o,i,u,n,d)}else if(u in oo.propsKeywords){if(f&&typeof f=="object")for(var m in f)hf(e,t,r,f[m],i+"/"+u+"/"+S1(m),o,i,u,n,m)}else(u in oo.keywords||e.allKeys&&!(u in oo.skipKeywords))&&hf(e,t,r,f,i+"/"+u,o,i,u,n)}r(n,i,o,a,s,c,l)}}function S1(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ol=j(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getSchemaRefs=Cr.resolveUrl=Cr.normalizeId=Cr._getFullPath=Cr.getFullPath=Cr.inlineRef=void 0;var E1=je(),_1=Qv(),C1=b_(),I1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function x1(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Uv(e):t?R_(e)<=t:!1}Cr.inlineRef=x1;var P1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Uv(e){for(let t in e){if(P1.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Uv)||typeof r=="object"&&Uv(r))return!0}return!1}function R_(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!I1.has(r)&&(typeof e[r]=="object"&&(0,E1.eachItem)(e[r],n=>t+=R_(n)),t===1/0))return 1/0}return t}function N_(e,t="",r){r!==!1&&(t=rs(t));let n=e.parse(t);return S_(e,n)}Cr.getFullPath=N_;function S_(e,t){return e.serialize(t).split("#")[0]+"#"}Cr._getFullPath=S_;var T1=/#\/?$/;function rs(e){return e?e.replace(T1,""):""}Cr.normalizeId=rs;function O1(e,t,r){return r=rs(r),e.resolve(t,r)}Cr.resolveUrl=O1;var $1=/^[a-z_][-a-z0-9._]*$/i;function j1(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=rs(e[r]||t),o={"":i},a=N_(n,i,!1),s={},c=new Set;return C1(e,{allKeys:!0},(f,d,m,h)=>{if(h===void 0)return;let p=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 b=this.opts.uriResolver.resolve;if(A=rs(g?b(g,A):A),c.has(A))throw u(A);c.add(A);let R=this.refs[A];return typeof R=="string"&&(R=this.refs[R]),typeof R=="object"?l(f,R.schema,A):A!==rs(p)&&(A[0]==="#"?(l(f,s[A],A),s[A]=f):this.refs[A]=p),A}function w(A){if(typeof A=="string"){if(!$1.test(A))throw new Error(`invalid anchor "${A}"`);v.call(this,`#${A}`)}}}),s;function l(f,d,m){if(d!==void 0&&!_1(f,d))throw u(m)}function u(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Cr.getSchemaRefs=j1});var cl=j(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.getData=ao.KeywordCxt=ao.validateFunctionCode=void 0;var x_=o_(),E_=il(),zv=Wv(),gf=il(),D1=f_(),sl=v_(),Jv=y_(),le=Ce(),ye=vi(),B1=ol(),wi=je(),al=nl();function W1(e){if(O_(e)&&($_(e),T_(e))){M1(e);return}P_(e,()=>(0,x_.topBoolOrEmptySchema)(e))}ao.validateFunctionCode=W1;function P_({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,le._)`${ye.default.data}, ${ye.default.valCxt}`,n.$async,()=>{e.code((0,le._)`"use strict"; ${__(r,i)}`),V1(e,i),e.code(o)}):e.func(t,(0,le._)`${ye.default.data}, ${L1(i)}`,n.$async,()=>e.code(__(r,i)).code(o))}function L1(e){return(0,le._)`{${ye.default.instancePath}="", ${ye.default.parentData}, ${ye.default.parentDataProperty}, ${ye.default.rootData}=${ye.default.data}${e.dynamicRef?(0,le._)`, ${ye.default.dynamicAnchors}={}`:le.nil}}={}`}function V1(e,t){e.if(ye.default.valCxt,()=>{e.var(ye.default.instancePath,(0,le._)`${ye.default.valCxt}.${ye.default.instancePath}`),e.var(ye.default.parentData,(0,le._)`${ye.default.valCxt}.${ye.default.parentData}`),e.var(ye.default.parentDataProperty,(0,le._)`${ye.default.valCxt}.${ye.default.parentDataProperty}`),e.var(ye.default.rootData,(0,le._)`${ye.default.valCxt}.${ye.default.rootData}`),t.dynamicRef&&e.var(ye.default.dynamicAnchors,(0,le._)`${ye.default.valCxt}.${ye.default.dynamicAnchors}`)},()=>{e.var(ye.default.instancePath,(0,le._)`""`),e.var(ye.default.parentData,(0,le._)`undefined`),e.var(ye.default.parentDataProperty,(0,le._)`undefined`),e.var(ye.default.rootData,ye.default.data),t.dynamicRef&&e.var(ye.default.dynamicAnchors,(0,le._)`{}`)})}function M1(e){let{schema:t,opts:r,gen:n}=e;P_(e,()=>{r.$comment&&t.$comment&&D_(e),U1(e),n.let(ye.default.vErrors,null),n.let(ye.default.errors,0),r.unevaluated&&q1(e),j_(e),K1(e)})}function q1(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,le._)`${r}.evaluated`),t.if((0,le._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,le._)`${e.evaluated}.props`,(0,le._)`undefined`)),t.if((0,le._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,le._)`${e.evaluated}.items`,(0,le._)`undefined`))}function __(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,le._)`/*# sourceURL=${r} */`:le.nil}function F1(e,t){if(O_(e)&&($_(e),T_(e))){H1(e,t);return}(0,x_.boolOrEmptySchema)(e,t)}function T_({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 O_(e){return typeof e.schema!="boolean"}function H1(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&D_(e),J1(e),z1(e);let o=n.const("_errs",ye.default.errors);j_(e,o),n.var(t,(0,le._)`${o} === ${ye.default.errors}`)}function $_(e){(0,wi.checkUnknownRules)(e),Q1(e)}function j_(e,t){if(e.opts.jtd)return C_(e,[],!1,t);let r=(0,E_.getSchemaTypes)(e.schema),n=(0,E_.coerceAndCheckDataType)(e,r);C_(e,r,!n,t)}function Q1(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,wi.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function U1(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,wi.checkStrictMode)(e,"default is ignored in the schema root")}function J1(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,B1.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function z1(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function D_({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,le._)`${ye.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let a=(0,le.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,le._)`${ye.default.self}.opts.$comment(${o}, ${a}, ${s}.schema)`)}}function K1(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,le._)`${ye.default.errors} === 0`,()=>t.return(ye.default.data),()=>t.throw((0,le._)`new ${i}(${ye.default.vErrors})`)):(t.assign((0,le._)`${n}.errors`,ye.default.vErrors),o.unevaluated&&G1(e),t.return((0,le._)`${ye.default.errors} === 0`))}function G1({gen:e,evaluated:t,props:r,items:n}){r instanceof le.Name&&e.assign((0,le._)`${t}.props`,r),n instanceof le.Name&&e.assign((0,le._)`${t}.items`,n)}function C_(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,wi.schemaHasRulesButRef)(o,u))){i.block(()=>W_(e,"$ref",u.all.$ref.definition));return}c.jtd||Y1(e,t),i.block(()=>{for(let d of u.rules)f(d);f(u.post)});function f(d){(0,zv.shouldUseGroup)(o,d)&&(d.type?(i.if((0,gf.checkDataType)(d.type,a,c.strictNumbers)),I_(e,d),t.length===1&&t[0]===d.type&&r&&(i.else(),(0,gf.reportTypeError)(e)),i.endIf()):I_(e,d),s||i.if((0,le._)`${ye.default.errors} === ${n||0}`))}}function I_(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,D1.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,zv.shouldUseRule)(n,o)&&W_(e,o.keyword,o.definition,t.type)})}function Y1(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(X1(e,t),e.opts.allowUnionTypes||Z1(e,t),eq(e,e.dataTypes))}function X1(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{B_(e.dataTypes,r)||Kv(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),rq(e,t)}}function Z1(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Kv(e,"use allowUnionTypes to allow union type keyword")}function eq(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,zv.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(a=>tq(t,a))&&Kv(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function tq(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function B_(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function rq(e,t){let r=[];for(let n of e.dataTypes)B_(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Kv(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,wi.checkStrictMode)(e,t,e.opts.strictTypes)}var vf=class{constructor(t,r,n){if((0,sl.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,wi.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",L_(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,sl.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",ye.default.errors))}result(t,r,n){this.failResult((0,le.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,le.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,le._)`${r} !== undefined && (${(0,le.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?al.reportExtraError:al.reportError)(this,this.def.error,r)}$dataError(){(0,al.reportError)(this,this.def.$dataError||al.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,al.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=le.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=le.nil,r=le.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:a}=this;n.if((0,le.or)((0,le._)`${i} === undefined`,r)),t!==le.nil&&n.assign(t,!0),(o.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==le.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,le.or)(a(),s());function a(){if(n.length){if(!(r instanceof le.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,le._)`${(0,gf.checkDataTypes)(c,r,o.opts.strictNumbers,gf.DataType.Wrong)}`}return le.nil}function s(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,le._)`!${c}(${r})`}return le.nil}}subschema(t,r){let n=(0,Jv.getSubschema)(this.it,t);(0,Jv.extendSubschemaData)(n,this.it,t),(0,Jv.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return F1(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=wi.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=wi.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,le.Name)),!0}};ao.KeywordCxt=vf;function W_(e,t,r,n){let i=new vf(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,sl.funcKeywordCode)(i,r):"macro"in r?(0,sl.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,sl.funcKeywordCode)(i,r)}var nq=/^\/(?:[^~]|~0|~1)*$/,iq=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function L_(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return ye.default.rootData;if(e[0]==="/"){if(!nq.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=ye.default.rootData}else{let l=iq.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,le._)`${o}${(0,le.getProperty)((0,wi.unescapeJsonPointer)(l))}`,a=(0,le._)`${a} && ${o}`);return a;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}ao.getData=L_});var wf=j(Yv=>{"use strict";Object.defineProperty(Yv,"__esModule",{value:!0});var Gv=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Yv.default=Gv});var ll=j(ew=>{"use strict";Object.defineProperty(ew,"__esModule",{value:!0});var Xv=ol(),Zv=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Xv.resolveUrl)(t,r,n),this.missingSchema=(0,Xv.normalizeId)((0,Xv.getFullPath)(t,this.missingRef))}};ew.default=Zv});var kf=j(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.resolveSchema=un.getCompilingSchema=un.resolveRef=un.compileSchema=un.SchemaEnv=void 0;var In=Ce(),oq=wf(),Ko=vi(),xn=ol(),V_=je(),aq=cl(),ns=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,xn.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};un.SchemaEnv=ns;function rw(e){let t=M_.call(this,e);if(t)return t;let r=(0,xn.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,a=new In.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),s;e.$async&&(s=a.scopeValue("Error",{ref:oq.default,code:(0,In._)`require("ajv/dist/runtime/validation_error").default`}));let c=a.scopeName("validate");e.validateName=c;let l={gen:a,allErrors:this.opts.allErrors,data:Ko.default.data,parentData:Ko.default.parentData,parentDataProperty:Ko.default.parentDataProperty,dataNames:[Ko.default.data],dataPathArr:[In.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,In.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:In.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,In._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,aq.validateFunctionCode)(l),a.optimize(this.opts.code.optimize);let f=a.toString();u=`${a.scopeRefs(Ko.default.scope)}return ${f}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let m=new Function(`${Ko.default.self}`,`${Ko.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:f,scopeValues:a._values}),this.opts.unevaluated){let{props:h,items:p}=l;m.evaluated={props:h instanceof In.Name?void 0:h,items:p instanceof In.Name?void 0:p,dynamicProps:h instanceof In.Name,dynamicItems:p instanceof In.Name},m.source&&(m.source.evaluated=(0,In.stringify)(m.evaluated))}return e.validate=m,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)}}un.compileSchema=rw;function sq(e,t,r){var n;r=(0,xn.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=uq.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 ns({schema:a,schemaId:s,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=cq.call(this,o)}un.resolveRef=sq;function cq(e){return(0,xn.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:rw.call(this,e)}function M_(e){for(let t of this._compilations)if(lq(t,e))return t}un.getCompilingSchema=M_;function lq(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function uq(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||yf.call(this,e,t)}function yf(e,t){let r=this.opts.uriResolver.parse(t),n=(0,xn._getFullPath)(this.opts.uriResolver,r),i=(0,xn.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return tw.call(this,r,e);let o=(0,xn.normalizeId)(n),a=this.refs[o]||this.schemas[o];if(typeof a=="string"){let s=yf.call(this,e,a);return typeof s?.schema!="object"?void 0:tw.call(this,r,s)}if(typeof a?.schema=="object"){if(a.validate||rw.call(this,a),o===(0,xn.normalizeId)(t)){let{schema:s}=a,{schemaId:c}=this.opts,l=s[c];return l&&(i=(0,xn.resolveUrl)(this.opts.uriResolver,i,l)),new ns({schema:s,schemaId:c,root:e,baseId:i})}return tw.call(this,r,a)}}un.resolveSchema=yf;var dq=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tw(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,V_.unescapeFragment)(s)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!dq.has(s)&&l&&(t=(0,xn.resolveUrl)(this.opts.uriResolver,t,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,V_.schemaHasRulesButRef)(r,this.RULES)){let s=(0,xn.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=yf.call(this,n,s)}let{schemaId:a}=this.opts;if(o=o||new ns({schema:r,schemaId:a,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var q_=j((E3,fq)=>{fq.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 cw=j((_3,G_)=>{"use strict";var pq=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),iw=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),mq=RegExp.prototype.test.bind(/^\d*$/u),Go=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ow=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),H_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),aw=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),hq=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ir=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Ir[t]="%"+e[t>>4]+e[t&15]}function tr(e){return e<2048?Ir[192|e>>6]+Ir[128|e&63]:e<65536?Ir[224|e>>12]+Ir[128|e>>6&63]+Ir[128|e&63]:Ir[240|e>>18]+Ir[128|e>>12&63]+Ir[128|e>>6&63]+Ir[128|e&63]}function gq(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 vq=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),wq=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),yq=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),kq=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Aq(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!yq(e[t])){if(e[t]==="%"&&t+2<e.length&&Go(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function F_(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 bq(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||!iw(c))return;o+=2;continue}if(!vq(c))return;i[s]=parseInt(c,16).toString(16),o++}if(t===-1)return o!==8?void 0:F_(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 F_(a)}function nw(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&&wq(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(Rq(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),!Aq(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,o)}let a=bq(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(i?"%"+i:""),escapedHost:a+(i?"%25"+i:""),isIPV6:!0}}function Rq(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Q_(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 Nq(e){if(e===""||e[0]==="/")return Q_(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 Sq={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Eq=/[@/?#:]/g,_q=/[@/?#]/g;function U_(e,t){let r=t?_q:Eq;return r.lastIndex=0,e.replace(r,n=>Sq[n])}function J_(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(Go(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));t&&ow(a)?r+=a:r+="%"+o,n+=2;continue}}r+=e[n]}return r}function Cq(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Go(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));a!=="."&&ow(a)?t+=a:t+="%"+o,r+=2;continue}}if(H_(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=K_(i)?n:Ir[i];else if(i<55296||i>57343)t+=tr(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=tr(65536+(i-55296<<10)+(o-56320)),r++):t+=tr(65533)}else t+=tr(65533)}}return t}function Iq(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(Go(a)){r+="%"+a.toUpperCase(),i+=2;continue}}if(o==="/"&&(n=!1),H_(o)&&(o!==":"||!n))r+=o;else{let a=e.charCodeAt(i);if(a<128)r+=Ir[a];else if(a<55296||a>57343)r+=tr(a);else if(a<=56319&&i+1<e.length){let s=e.charCodeAt(i+1);s>=56320&&s<=57343?(r+=tr(65536+(a-55296<<10)+(s-56320)),i++):r+=tr(65533)}else r+=tr(65533)}}return r}function sw(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(Go(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{let o=e.charCodeAt(n);if(o<128)r+=Ir[o];else if(o<55296||o>57343)r+=tr(o);else if(o<=56319&&n+1<e.length){let a=e.charCodeAt(n+1);a>=56320&&a<=57343?(r+=tr(65536+(o-55296<<10)+(a-56320)),n++):r+=tr(65533)}else r+=tr(65533)}}return r}function z_(e){return sw(e,hq)}function xq(e){return sw(e,aw)}function Pq(e){return sw(e,aw)}function K_(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 Tq(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(Go(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));ow(a)?t+=a:t+="%"+o,r+=2;continue}}if(aw(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=K_(i)?n:Ir[i];else if(i<55296||i>57343)t+=tr(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=tr(65536+(i-55296<<10)+(o-56320)),r++):t+=tr(65533)}else t+=tr(65533)}}return t}function Oq(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(Go(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function $q(e){let t=[];if(e.userinfo!==void 0&&(t.push(z_(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!iw(r)){let n=nw(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=J_(r,!0),n=nw(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=U_(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!mq(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}G_.exports={nonSimpleDomain:kq,recomposeAuthority:$q,reescapeHostDelimiters:U_,normalizePercentEncoding:J_,normalizePathEncoding:Cq,serializePathEncoding:Iq,normalizeQueryFragmentEncoding:Tq,encodeUserinfo:z_,encodeQuery:xq,encodeFragment:Pq,escapePreservingEscapes:Oq,removeDotSegments:Q_,removeDotSegmentsRelative:Nq,isIPv4:iw,isUUID:pq,normalizeIPv6:nw,stringArrayToHexStripped:gq}});var tC=j((C3,eC)=>{"use strict";var{isUUID:jq}=cw(),Dq=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,Bq=["http","https","ws","wss","urn","urn:uuid"];function Wq(e){return Bq.indexOf(e)!==-1}function lw(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 Y_(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function X_(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 Lq(e){return e.secure=lw(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Vq(e){if((e.port===(lw(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 Mq(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Dq);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=uw(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function qq(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=uw(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 Fq(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!jq(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Hq(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Z_={scheme:"http",domainHost:!0,parse:Y_,serialize:X_},Qq={scheme:"https",domainHost:Z_.domainHost,parse:Y_,serialize:X_},Af={scheme:"ws",domainHost:!0,parse:Lq,serialize:Vq},Uq={scheme:"wss",domainHost:Af.domainHost,parse:Af.parse,serialize:Af.serialize},Jq={scheme:"urn",parse:Mq,serialize:qq,skipNormalize:!0},zq={scheme:"urn:uuid",parse:Fq,serialize:Hq,skipNormalize:!0},bf={http:Z_,https:Qq,ws:Af,wss:Uq,urn:Jq,"urn:uuid":zq};Object.setPrototypeOf(bf,null);function uw(e){return e&&(bf[e]||bf[e.toLowerCase()])||void 0}eC.exports={wsIsSecure:lw,SCHEMES:bf,isValidSchemeName:Wq,getSchemeHandler:uw}});var gC=j((I3,_f)=>{"use strict";var{normalizeIPv6:aC,removeDotSegments:dl,removeDotSegmentsRelative:sC,recomposeAuthority:Kq,normalizePercentEncoding:dw,normalizePathEncoding:Gq,serializePathEncoding:rC,normalizeQueryFragmentEncoding:nC,encodeQuery:Yq,encodeFragment:Xq,reescapeHostDelimiters:Zq,isIPv4:cC,nonSimpleDomain:eF}=cw(),{SCHEMES:lC,getSchemeHandler:fw}=tC(),uC=/^[A-Za-z][A-Za-z0-9+.-]*$/u,dC="URI scheme is malformed.",Rf="URI host is malformed.",tF=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function iC(e){let t=String(e);if(!uC.test(t))throw new TypeError(dC);return t}function rF(e,t){return typeof e=="string"?e=dF(e,t):typeof e=="object"&&(e=Sf(Yo(e,t),t)),e}function nF(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}=Nf(e,n),{parsed:u,malformedAuthorityOrPort:f,malformedPercentEncoding:d,malformedSchemeSpecific:m,malformedHost:h,malformedScheme:p}=Nf(t,n);if(o||f||a||d||s||m||c||h||l||p)throw new Error(i.error||u.error||"URI is malformed.");let g=fC(i,u,n,!0),v=fw(r&&r.scheme||g.scheme),w=g.host,A=w!==void 0&&w!==""&&(cC(w)||aC(w).isIPV6);if(mC(g,r||{},v,A))throw new Error(Rf);pC(g,r||{},v,A);let b=w&&w.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(w);if(g.error&&!b)throw new Error(g.error);return n.skipEscape=!0,Yo(g,n)}function fC(e,t,r,n){let i={};if(n||(e=Sf(Yo(e,r),r),t=Sf(Yo(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=dl(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=dl(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=dl(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]!=="/"?sC(i.path):dl(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 iF(e,t,r){let n=oC(e,r),i=oC(t,r);return n!==void 0&&i!==void 0&&n===i}function Yo(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=iC(r.scheme));let o=fw(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=dw(r.path):r.path=rC(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=iC(r.scheme),i.push(r.scheme,":"));let l=Kq(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]!=="/"?sC(u):dl(u)),s&&(u=rC(u,!0)),l===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),i.push(u)}return r.query!==void 0&&i.push("?",Yq(r.query)),r.fragment!==void 0&&i.push("#",Xq(r.fragment)),i.join("")}var oF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,aF=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,sF=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function cF(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 ul(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 Ef(e){return e[0]==="["&&e[e.length-1]==="]"}function lF(e){let t=e[4];return ul(e[3])||t!==void 0&&!Ef(t)&&ul(t)||ul(e[6])||ul(e[7])||ul(e[8])}function pC(e,t,r,n){if(mC(e,t,r,n))return e.error=e.error||Rf,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Ef(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&eF(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(!uF(i))return e.error=e.error||Rf,!0;e.host=i.hostname}return!1}function mC(e,t,r,n){return!!(e.host&&n===!1&&!Ef(e.host)&&(t.domainHost||r&&r.domainHost)&&tF.test(e.host))}function uF(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Nf(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(aF);f!==null&&f[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let d=e.match(sF);if(d!==null){let h=d[1],p=h.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):h.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let m=e.match(oF);if(m){n.scheme=m[1],n.userinfo=m[3],n.host=m[4],n.port=parseInt(m[5],10),n.path=m[6]||"",n.query=m[7],n.fragment=m[8],n.scheme!==void 0&&(uC.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||dC,l=!0)),o=lF(m),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=m[5]);let h=cF(n,m);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(cC(n.host)===!1){let v=Ef(n.host),w=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,A=aC(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||Rf,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 p=fw(r.scheme||n.scheme);if(c||(s=pC(n,r,p,u)),e.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=u?n.host:dw(n.host,!0);u||(g=dw(g.toLowerCase())),n.host=u||r.scheme!=="null"?Zq(g,u):g}(!p||p&&!p.skipNormalize)&&(n.path&&(n.path=Gq(n.path)),n.query&&(n.query=nC(n.query)),n.fragment&&(n.fragment=nC(n.fragment))),p&&p.parse&&(p.parse(n,r),p===lC.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 Sf(e,t){return Nf(e,t).parsed}function dF(e,t){return hC(e,t).normalized}function hC(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}=Nf(e,t);return{normalized:n||i||o||a||s?e:Yo(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}}function oC(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Yo(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:c}=hC(r,t);return i||o||a||s||c?void 0:n}var pw={SCHEMES:lC,normalize:rF,resolve:nF,resolveComponent:fC,equal:iF,serialize:Yo,parse:Sf};_f.exports=pw;_f.exports.default=pw;_f.exports.fastUri=pw});var wC=j(mw=>{"use strict";Object.defineProperty(mw,"__esModule",{value:!0});var vC=gC();vC.code='require("ajv/dist/runtime/uri").default';mw.default=vC});var EC=j(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 fF=cl();Object.defineProperty(Jt,"KeywordCxt",{enumerable:!0,get:function(){return fF.KeywordCxt}});var is=Ce();Object.defineProperty(Jt,"_",{enumerable:!0,get:function(){return is._}});Object.defineProperty(Jt,"str",{enumerable:!0,get:function(){return is.str}});Object.defineProperty(Jt,"stringify",{enumerable:!0,get:function(){return is.stringify}});Object.defineProperty(Jt,"nil",{enumerable:!0,get:function(){return is.nil}});Object.defineProperty(Jt,"Name",{enumerable:!0,get:function(){return is.Name}});Object.defineProperty(Jt,"CodeGen",{enumerable:!0,get:function(){return is.CodeGen}});var pF=wf(),RC=ll(),mF=Bv(),fl=kf(),hF=Ce(),pl=ol(),Cf=il(),gw=je(),yC=q_(),gF=wC(),NC=(e,t)=>new RegExp(e,t);NC.code="new RegExp";var vF=["removeAdditional","useDefaults","coerceTypes"],wF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yF={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."},kF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},kC=200;function AF(e){var t,r,n,i,o,a,s,c,l,u,f,d,m,h,p,g,v,w,A,b,R,_,W,O,G;let Z=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,F=J===!0||J===void 0?1:J||0,X=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:NC,U=(i=e.uriResolver)!==null&&i!==void 0?i:gF.default;return{strictSchema:(a=(o=e.strictSchema)!==null&&o!==void 0?o:Z)!==null&&a!==void 0?a:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:Z)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Z)!==null&&u!==void 0?u:"log",strictTuples:(d=(f=e.strictTuples)!==null&&f!==void 0?f:Z)!==null&&d!==void 0?d:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:Z)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:F,regExp:X}:{optimize:F,regExp:X},loopRequired:(p=e.loopRequired)!==null&&p!==void 0?p:kC,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:kC,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:(b=e.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(R=e.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(_=e.validateSchema)!==null&&_!==void 0?_:!0,validateFormats:(W=e.validateFormats)!==null&&W!==void 0?W:!0,unicodeRegExp:(O=e.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(G=e.int32range)!==null&&G!==void 0?G:!0,uriResolver:U}}var ml=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,...AF(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new hF.ValueScope({scope:{},prefixes:wF,es5:r,lines:n}),this.logger=_F(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,mF.getRules)(),AC.call(this,yF,t,"NOT SUPPORTED"),AC.call(this,kF,t,"DEPRECATED","warn"),this._metaOpts=SF.call(this),t.formats&&RF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&NF.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),bF.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=yC;n==="id"&&(i={...yC},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 RC.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,pl.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=bC.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new fl.SchemaEnv({schema:{},schemaId:n});if(r=fl.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=bC.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,pl.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(IF.call(this,n,r),!r)return(0,gw.eachItem)(n,o=>hw.call(this,o)),this;PF.call(this,r);let i={...r,type:(0,Cf.getJSONTypes)(r.type),schemaType:(0,Cf.getJSONTypes)(r.schemaType)};return(0,gw.eachItem)(n,i.type.length===0?o=>hw.call(this,o,i):o=>i.type.forEach(a=>hw.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]=SC(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,pl.normalizeId)(a||n);let l=pl.getSchemaRefs.call(this,t,n);return c=new fl.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):fl.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{fl.compileSchema.call(this,t)}finally{this.opts=r}}};ml.ValidationError=pF.default;ml.MissingRefError=RC.default;Jt.default=ml;function AC(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 bC(e){return e=(0,pl.normalizeId)(e),this.schemas[e]||this.refs[e]}function bF(){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 RF(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function NF(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 SF(){let e={...this.opts};for(let t of vF)delete e[t];return e}var EF={log(){},warn(){},error(){}};function _F(e){if(e===!1)return EF;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 CF=/^[a-z_$][a-z0-9_$:-]*$/i;function IF(e,t){let{RULES:r}=this;if((0,gw.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!CF.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 hw(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,Cf.getJSONTypes)(t.type),schemaType:(0,Cf.getJSONTypes)(t.schemaType)}};t.before?xF.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 xF(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 PF(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=SC(t)),e.validateSchema=this.compile(t,!0))}var TF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function SC(e){return{anyOf:[e,TF]}}});var _C=j(vw=>{"use strict";Object.defineProperty(vw,"__esModule",{value:!0});var OF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vw.default=OF});var PC=j(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.callRef=Xo.getValidate=void 0;var $F=ll(),CC=ln(),xr=Ce(),os=vi(),IC=kf(),If=je(),jF={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=IC.resolveRef.call(c,l,i,r);if(u===void 0)throw new $F.default(n.opts.uriResolver,i,r);if(u instanceof IC.SchemaEnv)return d(u);return m(u);function f(){if(o===l)return xf(e,a,o,o.$async);let h=t.scopeValue("root",{ref:l});return xf(e,(0,xr._)`${h}.validate`,l,l.$async)}function d(h){let p=xC(e,h);xf(e,p,h,h.$async)}function m(h){let p=t.scopeValue("schema",s.code.source===!0?{ref:h,code:(0,xr.stringify)(h)}:{ref:h}),g=t.name("valid"),v=e.subschema({schema:h,dataTypes:[],schemaPath:xr.nil,topSchemaRef:p,errSchemaPath:r},g);e.mergeEvaluated(v),e.ok(g)}}};function xC(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,xr._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Xo.getValidate=xC;function xf(e,t,r,n){let{gen:i,it:o}=e,{allErrors:a,schemaEnv:s,opts:c}=o,l=c.passContext?os.default.this:xr.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,xr._)`await ${(0,CC.callValidateCode)(e,t,l)}`),m(t),a||i.assign(h,!0)},p=>{i.if((0,xr._)`!(${p} instanceof ${o.ValidationError})`,()=>i.throw(p)),d(p),a||i.assign(h,!1)}),e.ok(h)}function f(){e.result((0,CC.callValidateCode)(e,t,l),()=>m(t),()=>d(t))}function d(h){let p=(0,xr._)`${h}.errors`;i.assign(os.default.vErrors,(0,xr._)`${os.default.vErrors} === null ? ${p} : ${os.default.vErrors}.concat(${p})`),i.assign(os.default.errors,(0,xr._)`${os.default.vErrors}.length`)}function m(h){var p;if(!o.opts.unevaluated)return;let g=(p=r?.validate)===null||p===void 0?void 0:p.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=If.mergeEvaluated.props(i,g.props,o.props));else{let v=i.var("props",(0,xr._)`${h}.evaluated.props`);o.props=If.mergeEvaluated.props(i,v,o.props,xr.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=If.mergeEvaluated.items(i,g.items,o.items));else{let v=i.var("items",(0,xr._)`${h}.evaluated.items`);o.items=If.mergeEvaluated.items(i,v,o.items,xr.Name)}}}Xo.callRef=xf;Xo.default=jF});var TC=j(ww=>{"use strict";Object.defineProperty(ww,"__esModule",{value:!0});var DF=_C(),BF=PC(),WF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",DF.default,BF.default];ww.default=WF});var OC=j(yw=>{"use strict";Object.defineProperty(yw,"__esModule",{value:!0});var Pf=Ce(),so=Pf.operators,Tf={maximum:{okStr:"<=",ok:so.LTE,fail:so.GT},minimum:{okStr:">=",ok:so.GTE,fail:so.LT},exclusiveMaximum:{okStr:"<",ok:so.LT,fail:so.GTE},exclusiveMinimum:{okStr:">",ok:so.GT,fail:so.LTE}},LF={message:({keyword:e,schemaCode:t})=>(0,Pf.str)`must be ${Tf[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Pf._)`{comparison: ${Tf[e].okStr}, limit: ${t}}`},VF={keyword:Object.keys(Tf),type:"number",schemaType:"number",$data:!0,error:LF,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Pf._)`${r} ${Tf[t].fail} ${n} || isNaN(${r})`)}};yw.default=VF});var $C=j(kw=>{"use strict";Object.defineProperty(kw,"__esModule",{value:!0});var hl=Ce(),MF={message:({schemaCode:e})=>(0,hl.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,hl._)`{multipleOf: ${e}}`},qF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:MF,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,a=t.let("res"),s=o?(0,hl._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${o}`:(0,hl._)`${a} !== parseInt(${a})`;e.fail$data((0,hl._)`(${n} === 0 || (${a} = ${r}/${n}, ${s}))`)}};kw.default=qF});var DC=j(Aw=>{"use strict";Object.defineProperty(Aw,"__esModule",{value:!0});function jC(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}Aw.default=jC;jC.code='require("ajv/dist/runtime/ucs2length").default'});var BC=j(bw=>{"use strict";Object.defineProperty(bw,"__esModule",{value:!0});var Zo=Ce(),FF=je(),HF=DC(),QF={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Zo.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Zo._)`{limit: ${e}}`},UF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QF,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?Zo.operators.GT:Zo.operators.LT,a=i.opts.unicode===!1?(0,Zo._)`${r}.length`:(0,Zo._)`${(0,FF.useFunc)(e.gen,HF.default)}(${r})`;e.fail$data((0,Zo._)`${a} ${o} ${n}`)}};bw.default=UF});var WC=j(Rw=>{"use strict";Object.defineProperty(Rw,"__esModule",{value:!0});var JF=ln(),zF=je(),as=Ce(),KF={message:({schemaCode:e})=>(0,as.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,as._)`{pattern: ${e}}`},GF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KF,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,as._)`new RegExp`:(0,zF.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,as._)`${l}(${o}, ${s}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,as._)`!${u}`)}else{let c=(0,JF.usePattern)(e,i);e.fail$data((0,as._)`!${c}.test(${r})`)}}};Rw.default=GF});var LC=j(Nw=>{"use strict";Object.defineProperty(Nw,"__esModule",{value:!0});var gl=Ce(),YF={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,gl.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,gl._)`{limit: ${e}}`},XF={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YF,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?gl.operators.GT:gl.operators.LT;e.fail$data((0,gl._)`Object.keys(${r}).length ${i} ${n}`)}};Nw.default=XF});var VC=j(Sw=>{"use strict";Object.defineProperty(Sw,"__esModule",{value:!0});var vl=ln(),wl=Ce(),ZF=je(),eH={message:({params:{missingProperty:e}})=>(0,wl.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,wl._)`{missingProperty: ${e}}`},tH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eH,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 m=e.parentSchema.properties,{definedProperties:h}=e.it;for(let p of r)if(m?.[p]===void 0&&!h.has(p)){let g=a.schemaEnv.baseId+a.errSchemaPath,v=`required property "${p}" is not defined at "${g}" (strictRequired)`;(0,ZF.checkStrictMode)(a,v,a.opts.strictRequired)}}function l(){if(c||o)e.block$data(wl.nil,f);else for(let m of r)(0,vl.checkReportMissingProp)(e,m)}function u(){let m=t.let("missing");if(c||o){let h=t.let("valid",!0);e.block$data(h,()=>d(m,h)),e.ok(h)}else t.if((0,vl.checkMissingProp)(e,r,m)),(0,vl.reportMissingProp)(e,m),t.else()}function f(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,vl.noPropertyInData)(t,i,m,s.ownProperties),()=>e.error())})}function d(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,vl.propertyInData)(t,i,m,s.ownProperties)),t.if((0,wl.not)(h),()=>{e.error(),t.break()})},wl.nil)}}};Sw.default=tH});var MC=j(Ew=>{"use strict";Object.defineProperty(Ew,"__esModule",{value:!0});var yl=Ce(),rH={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,yl.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,yl._)`{limit: ${e}}`},nH={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rH,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?yl.operators.GT:yl.operators.LT;e.fail$data((0,yl._)`${r}.length ${i} ${n}`)}};Ew.default=nH});var Of=j(_w=>{"use strict";Object.defineProperty(_w,"__esModule",{value:!0});var qC=Qv();qC.code='require("ajv/dist/runtime/equal").default';_w.default=qC});var FC=j(Iw=>{"use strict";Object.defineProperty(Iw,"__esModule",{value:!0});var Cw=il(),zt=Ce(),iH=je(),oH=Of(),aH={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}}`},sH={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:aH,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,Cw.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`),p=t.let("j");e.setParams({i:h,j:p}),t.assign(c,!0),t.if((0,zt._)`${h} > 1`,()=>(f()?d:m)(h,p))}function f(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function d(h,p){let g=t.name("item"),v=(0,Cw.checkDataTypes)(l,g,s.opts.strictNumbers,Cw.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(p,(0,zt._)`${w}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,zt._)`${w}[${g}] = ${h}`)})}function m(h,p){let g=(0,iH.useFunc)(t,oH.default),v=t.name("outer");t.label(v).for((0,zt._)`;${h}--;`,()=>t.for((0,zt._)`${p} = ${h}; ${p}--;`,()=>t.if((0,zt._)`${g}(${r}[${h}], ${r}[${p}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};Iw.default=sH});var HC=j(Pw=>{"use strict";Object.defineProperty(Pw,"__esModule",{value:!0});var xw=Ce(),cH=je(),lH=Of(),uH={message:"must be equal to constant",params:({schemaCode:e})=>(0,xw._)`{allowedValue: ${e}}`},dH={keyword:"const",$data:!0,error:uH,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,xw._)`!${(0,cH.useFunc)(t,lH.default)}(${r}, ${i})`):e.fail((0,xw._)`${o} !== ${r}`)}};Pw.default=dH});var QC=j(Tw=>{"use strict";Object.defineProperty(Tw,"__esModule",{value:!0});var kl=Ce(),fH=je(),pH=Of(),mH={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,kl._)`{allowedValues: ${e}}`},hH={keyword:"enum",schemaType:"array",$data:!0,error:mH,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,fH.useFunc)(t,pH.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 m=t.const("vSchema",o);u=(0,kl.or)(...i.map((h,p)=>d(m,p)))}e.pass(u);function f(){t.assign(u,!1),t.forOf("v",o,m=>t.if((0,kl._)`${l()}(${r}, ${m})`,()=>t.assign(u,!0).break()))}function d(m,h){let p=i[h];return typeof p=="object"&&p!==null?(0,kl._)`${l()}(${r}, ${m}[${h}])`:(0,kl._)`${r} === ${p}`}}};Tw.default=hH});var UC=j(Ow=>{"use strict";Object.defineProperty(Ow,"__esModule",{value:!0});var gH=OC(),vH=$C(),wH=BC(),yH=WC(),kH=LC(),AH=VC(),bH=MC(),RH=FC(),NH=HC(),SH=QC(),EH=[gH.default,vH.default,wH.default,yH.default,kH.default,AH.default,bH.default,RH.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},NH.default,SH.default];Ow.default=EH});var jw=j(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.validateAdditionalItems=void 0;var ea=Ce(),$w=je(),_H={message:({params:{len:e}})=>(0,ea.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ea._)`{limit: ${e}}`},CH={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:_H,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,$w.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}JC(e,n)}};function JC(e,t){let{gen:r,schema:n,data:i,keyword:o,it:a}=e;a.items=!0;let s=r.const("len",(0,ea._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,ea._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,$w.alwaysValidSchema)(a,n)){let l=r.var("valid",(0,ea._)`${s} <= ${t.length}`);r.if((0,ea.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,s,u=>{e.subschema({keyword:o,dataProp:u,dataPropType:$w.Type.Num},l),a.allErrors||r.if((0,ea.not)(l),()=>r.break())})}}Al.validateAdditionalItems=JC;Al.default=CH});var Dw=j(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.validateTuple=void 0;var zC=Ce(),$f=je(),IH=ln(),xH={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return KC(e,"additionalItems",t);r.items=!0,!(0,$f.alwaysValidSchema)(r,t)&&e.ok((0,IH.validateArray)(e))}};function KC(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=$f.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),l=n.const("len",(0,zC._)`${o}.length`);r.forEach((f,d)=>{(0,$f.alwaysValidSchema)(s,f)||(n.if((0,zC._)`${l} > ${d}`,()=>e.subschema({keyword:a,schemaProp:d,dataProp:d},c)),e.ok(c))});function u(f){let{opts:d,errSchemaPath:m}=s,h=r.length,p=h===f.minItems&&(h===f.maxItems||f[t]===!1);if(d.strictTuples&&!p){let g=`"${a}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,$f.checkStrictMode)(s,g,d.strictTuples)}}}bl.validateTuple=KC;bl.default=xH});var GC=j(Bw=>{"use strict";Object.defineProperty(Bw,"__esModule",{value:!0});var PH=Dw(),TH={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,PH.validateTuple)(e,"items")};Bw.default=TH});var XC=j(Ww=>{"use strict";Object.defineProperty(Ww,"__esModule",{value:!0});var YC=Ce(),OH=je(),$H=ln(),jH=jw(),DH={message:({params:{len:e}})=>(0,YC.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,YC._)`{limit: ${e}}`},BH={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:DH,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,OH.alwaysValidSchema)(n,t)&&(i?(0,jH.validateAdditionalItems)(e,i):e.ok((0,$H.validateArray)(e)))}};Ww.default=BH});var ZC=j(Lw=>{"use strict";Object.defineProperty(Lw,"__esModule",{value:!0});var dn=Ce(),jf=je(),WH={message:({params:{min:e,max:t}})=>t===void 0?(0,dn.str)`must contain at least ${e} valid item(s)`:(0,dn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,dn._)`{minContains: ${e}}`:(0,dn._)`{minContains: ${e}, maxContains: ${t}}`},LH={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WH,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,dn._)`${i}.length`);if(e.setParams({min:a,max:s}),s===void 0&&a===0){(0,jf.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&a>s){(0,jf.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,jf.alwaysValidSchema)(o,r)){let p=(0,dn._)`${u} >= ${a}`;s!==void 0&&(p=(0,dn._)`${p} && ${u} <= ${s}`),e.pass(p);return}o.items=!0;let f=t.name("valid");s===void 0&&a===1?m(f,()=>t.if(f,()=>t.break())):a===0?(t.let(f,!0),s!==void 0&&t.if((0,dn._)`${i}.length > 0`,d)):(t.let(f,!1),d()),e.result(f,()=>e.reset());function d(){let p=t.name("_valid"),g=t.let("count",0);m(p,()=>t.if(p,()=>h(g)))}function m(p,g){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:jf.Type.Num,compositeRule:!0},p),g()})}function h(p){t.code((0,dn._)`${p}++`),s===void 0?t.if((0,dn._)`${p} >= ${a}`,()=>t.assign(f,!0).break()):(t.if((0,dn._)`${p} > ${s}`,()=>t.assign(f,!1).break()),a===1?t.assign(f,!0):t.if((0,dn._)`${p} >= ${a}`,()=>t.assign(f,!0)))}}};Lw.default=LH});var rI=j(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.validateSchemaDeps=Kn.validatePropertyDeps=Kn.error=void 0;var Vw=Ce(),VH=je(),Rl=ln();Kn.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Vw.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Vw._)`{property: ${e},
|
|
191
|
+
missingProperty: ${n},
|
|
192
|
+
depsCount: ${t},
|
|
193
|
+
deps: ${r}}`};var MH={keyword:"dependencies",type:"object",schemaType:"object",error:Kn.error,code(e){let[t,r]=qH(e);eI(e,t),tI(e,r)}};function qH({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 eI(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,Rl.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,Rl.checkReportMissingProp)(e,l)}):(r.if((0,Vw._)`${c} && (${(0,Rl.checkMissingProp)(e,s,o)})`),(0,Rl.reportMissingProp)(e,o),r.else())}}Kn.validatePropertyDeps=eI;function tI(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,a=r.name("valid");for(let s in t)(0,VH.alwaysValidSchema)(o,t[s])||(r.if((0,Rl.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))}Kn.validateSchemaDeps=tI;Kn.default=MH});var iI=j(Mw=>{"use strict";Object.defineProperty(Mw,"__esModule",{value:!0});var nI=Ce(),FH=je(),HH={message:"property name must be valid",params:({params:e})=>(0,nI._)`{propertyName: ${e.propertyName}}`},QH={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:HH,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,FH.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,nI.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};Mw.default=QH});var Fw=j(qw=>{"use strict";Object.defineProperty(qw,"__esModule",{value:!0});var Df=ln(),Pn=Ce(),UH=vi(),Bf=je(),JH={message:"must NOT have additional properties",params:({params:e})=>(0,Pn._)`{additionalProperty: ${e.additionalProperty}}`},zH={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:JH,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,Bf.alwaysValidSchema)(a,r))return;let l=(0,Df.allSchemaProperties)(n.properties),u=(0,Df.allSchemaProperties)(n.patternProperties);f(),e.ok((0,Pn._)`${o} === ${UH.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,Bf.schemaRefOrVal)(a,n.properties,"properties");v=(0,Df.isOwnProperty)(t,w,g)}else l.length?v=(0,Pn.or)(...l.map(w=>(0,Pn._)`${g} === ${w}`)):v=Pn.nil;return u.length&&(v=(0,Pn.or)(v,...u.map(w=>(0,Pn._)`${(0,Df.usePattern)(e,w)}.test(${g})`))),(0,Pn.not)(v)}function m(g){t.code((0,Pn._)`delete ${i}[${g}]`)}function h(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,Bf.alwaysValidSchema)(a,r)){let v=t.name("valid");c.removeAdditional==="failing"?(p(g,v,!1),t.if((0,Pn.not)(v),()=>{e.reset(),m(g)})):(p(g,v),s||t.if((0,Pn.not)(v),()=>t.break()))}}function p(g,v,w){let A={keyword:"additionalProperties",dataProp:g,dataPropType:Bf.Type.Str};w===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(A,v)}}};qw.default=zH});var sI=j(Qw=>{"use strict";Object.defineProperty(Qw,"__esModule",{value:!0});var KH=cl(),oI=ln(),Hw=je(),aI=Fw(),GH={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&&aI.default.code(new KH.KeywordCxt(o,aI.default,"additionalProperties"));let a=(0,oI.allSchemaProperties)(r);for(let f of a)o.definedProperties.add(f);o.opts.unevaluated&&a.length&&o.props!==!0&&(o.props=Hw.mergeEvaluated.props(t,(0,Hw.toHash)(a),o.props));let s=a.filter(f=>!(0,Hw.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,oI.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)}}};Qw.default=GH});var dI=j(Uw=>{"use strict";Object.defineProperty(Uw,"__esModule",{value:!0});var cI=ln(),Wf=Ce(),lI=je(),uI=je(),YH={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,cI.allSchemaProperties)(r),c=s.filter(p=>(0,lI.alwaysValidSchema)(o,r[p]));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 Wf.Name)&&(o.props=(0,uI.evaluatedPropsToName)(t,o.props));let{props:f}=o;d();function d(){for(let p of s)l&&m(p),o.allErrors?h(p):(t.var(u,!0),h(p),t.if(u))}function m(p){for(let g in l)new RegExp(p).test(g)&&(0,lI.checkStrictMode)(o,`property ${g} matches pattern ${p} (use allowMatchingProperties)`)}function h(p){t.forIn("key",n,g=>{t.if((0,Wf._)`${(0,cI.usePattern)(e,p)}.test(${g})`,()=>{let v=c.includes(p);v||e.subschema({keyword:"patternProperties",schemaProp:p,dataProp:g,dataPropType:uI.Type.Str},u),o.opts.unevaluated&&f!==!0?t.assign((0,Wf._)`${f}[${g}]`,!0):!v&&!o.allErrors&&t.if((0,Wf.not)(u),()=>t.break())})})}}};Uw.default=YH});var fI=j(Jw=>{"use strict";Object.defineProperty(Jw,"__esModule",{value:!0});var XH=je(),ZH={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,XH.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"}};Jw.default=ZH});var pI=j(zw=>{"use strict";Object.defineProperty(zw,"__esModule",{value:!0});var eQ=ln(),tQ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eQ.validateUnion,error:{message:"must match a schema in anyOf"}};zw.default=tQ});var mI=j(Kw=>{"use strict";Object.defineProperty(Kw,"__esModule",{value:!0});var Lf=Ce(),rQ=je(),nQ={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Lf._)`{passingSchemas: ${e.passing}}`},iQ={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nQ,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,rQ.alwaysValidSchema)(i,u)?t.var(c,!0):d=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,Lf._)`${c} && ${a}`).assign(a,!1).assign(s,(0,Lf._)`[${s}, ${f}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(s,f),d&&e.mergeEvaluated(d,Lf.Name)})})}}};Kw.default=iQ});var hI=j(Gw=>{"use strict";Object.defineProperty(Gw,"__esModule",{value:!0});var oQ=je(),aQ={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,oQ.alwaysValidSchema)(n,o))return;let s=e.subschema({keyword:"allOf",schemaProp:a},i);e.ok(i),e.mergeEvaluated(s)})}};Gw.default=aQ});var wI=j(Yw=>{"use strict";Object.defineProperty(Yw,"__esModule",{value:!0});var Vf=Ce(),vI=je(),sQ={message:({params:e})=>(0,Vf.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Vf._)`{failingKeyword: ${e.ifClause}}`},cQ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:sQ,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,vI.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=gI(n,"then"),o=gI(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,Vf.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,Vf._)`${u}`):e.setParams({ifClause:u})}}}};function gI(e,t){let r=e.schema[t];return r!==void 0&&!(0,vI.alwaysValidSchema)(e,r)}Yw.default=cQ});var yI=j(Xw=>{"use strict";Object.defineProperty(Xw,"__esModule",{value:!0});var lQ=je(),uQ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,lQ.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Xw.default=uQ});var kI=j(Zw=>{"use strict";Object.defineProperty(Zw,"__esModule",{value:!0});var dQ=jw(),fQ=GC(),pQ=Dw(),mQ=XC(),hQ=ZC(),gQ=rI(),vQ=iI(),wQ=Fw(),yQ=sI(),kQ=dI(),AQ=fI(),bQ=pI(),RQ=mI(),NQ=hI(),SQ=wI(),EQ=yI();function _Q(e=!1){let t=[AQ.default,bQ.default,RQ.default,NQ.default,SQ.default,EQ.default,vQ.default,wQ.default,gQ.default,yQ.default,kQ.default];return e?t.push(fQ.default,mQ.default):t.push(dQ.default,pQ.default),t.push(hQ.default),t}Zw.default=_Q});var AI=j(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});var kt=Ce(),CQ={message:({schemaCode:e})=>(0,kt.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,kt._)`{format: ${e}}`},IQ={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CQ,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():m();function d(){let h=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),p=r.const("fDef",(0,kt._)`${h}[${a}]`),g=r.let("fType"),v=r.let("format");r.if((0,kt._)`typeof ${p} == "object" && !(${p} instanceof RegExp)`,()=>r.assign(g,(0,kt._)`${p}.type || "string"`).assign(v,(0,kt._)`${p}.validate`),()=>r.assign(g,(0,kt._)`"string"`).assign(v,p)),e.fail$data((0,kt.or)(w(),A()));function w(){return c.strictSchema===!1?kt.nil:(0,kt._)`${a} && !${v}`}function A(){let b=u.$async?(0,kt._)`(${p}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,kt._)`${v}(${n})`,R=(0,kt._)`(typeof ${v} == "function" ? ${b} : ${v}.test(${n}))`;return(0,kt._)`${v} && ${v} !== true && ${g} === ${t} && !${R}`}}function m(){let h=f.formats[o];if(!h){w();return}if(h===!0)return;let[p,g,v]=A(h);p===t&&e.pass(b());function w(){if(c.strictSchema===!1){f.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function A(R){let _=R instanceof RegExp?(0,kt.regexpCode)(R):c.code.formats?(0,kt._)`${c.code.formats}${(0,kt.getProperty)(o)}`:void 0,W=r.scopeValue("formats",{key:o,ref:R,code:_});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,kt._)`${W}.validate`]:["string",R,W]}function b(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,kt._)`await ${v}(${n})`}return typeof g=="function"?(0,kt._)`${v}(${n})`:(0,kt._)`${v}.test(${n})`}}}};ey.default=IQ});var bI=j(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});var xQ=AI(),PQ=[xQ.default];ty.default=PQ});var RI=j(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.contentVocabulary=ss.metadataVocabulary=void 0;ss.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ss.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var SI=j(ry=>{"use strict";Object.defineProperty(ry,"__esModule",{value:!0});var TQ=TC(),OQ=UC(),$Q=kI(),jQ=bI(),NI=RI(),DQ=[TQ.default,OQ.default,(0,$Q.default)(),jQ.default,NI.metadataVocabulary,NI.contentVocabulary];ry.default=DQ});var _I=j(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});Mf.DiscrError=void 0;var EI;(function(e){e.Tag="tag",e.Mapping="mapping"})(EI||(Mf.DiscrError=EI={}))});var II=j(iy=>{"use strict";Object.defineProperty(iy,"__esModule",{value:!0});var cs=Ce(),ny=_I(),CI=kf(),BQ=ll(),WQ=je(),LQ={message:({params:{discrError:e,tagName:t}})=>e===ny.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,cs._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},VQ={keyword:"discriminator",type:"object",schemaType:"object",error:LQ,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,cs._)`${r}${(0,cs.getProperty)(s)}`);t.if((0,cs._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:ny.DiscrError.Tag,tag:l,tagName:s})),e.ok(c);function u(){let m=d();t.if(!1);for(let h in m)t.elseIf((0,cs._)`${l} === ${h}`),t.assign(c,f(m[h]));t.else(),e.error(!1,{discrError:ny.DiscrError.Mapping,tag:l,tagName:s}),t.endIf()}function f(m){let h=t.name("valid"),p=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(p,cs.Name),h}function d(){var m;let h={},p=v(i),g=!0;for(let b=0;b<a.length;b++){let R=a[b];if(R?.$ref&&!(0,WQ.schemaHasRulesButRef)(R,o.self.RULES)){let W=R.$ref;if(R=CI.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,W),R instanceof CI.SchemaEnv&&(R=R.schema),R===void 0)throw new BQ.default(o.opts.uriResolver,o.baseId,W)}let _=(m=R?.properties)===null||m===void 0?void 0:m[s];if(typeof _!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);g=g&&(p||v(R)),w(_,b)}if(!g)throw new Error(`discriminator: "${s}" must be required`);return h;function v({required:b}){return Array.isArray(b)&&b.includes(s)}function w(b,R){if(b.const)A(b.const,R);else if(b.enum)for(let _ of b.enum)A(_,R);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function A(b,R){if(typeof b!="string"||b in h)throw new Error(`discriminator: "${s}" values must be unique strings`);h[b]=R}}}};iy.default=VQ});var xI=j((v8,MQ)=>{MQ.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 Ff=j((nt,oy)=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.MissingRefError=nt.ValidationError=nt.CodeGen=nt.Name=nt.nil=nt.stringify=nt.str=nt._=nt.KeywordCxt=nt.Ajv=void 0;var qQ=EC(),FQ=SI(),HQ=II(),PI=xI(),QQ=["/properties"],qf="http://json-schema.org/draft-07/schema",ls=class extends qQ.default{_addVocabularies(){super._addVocabularies(),FQ.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(HQ.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(PI,QQ):PI;this.addMetaSchema(t,qf,!1),this.refs["http://json-schema.org/schema"]=qf}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qf)?qf:void 0)}};nt.Ajv=ls;oy.exports=nt=ls;oy.exports.Ajv=ls;Object.defineProperty(nt,"__esModule",{value:!0});nt.default=ls;var UQ=cl();Object.defineProperty(nt,"KeywordCxt",{enumerable:!0,get:function(){return UQ.KeywordCxt}});var us=Ce();Object.defineProperty(nt,"_",{enumerable:!0,get:function(){return us._}});Object.defineProperty(nt,"str",{enumerable:!0,get:function(){return us.str}});Object.defineProperty(nt,"stringify",{enumerable:!0,get:function(){return us.stringify}});Object.defineProperty(nt,"nil",{enumerable:!0,get:function(){return us.nil}});Object.defineProperty(nt,"Name",{enumerable:!0,get:function(){return us.Name}});Object.defineProperty(nt,"CodeGen",{enumerable:!0,get:function(){return us.CodeGen}});var JQ=wf();Object.defineProperty(nt,"ValidationError",{enumerable:!0,get:function(){return JQ.default}});var zQ=ll();Object.defineProperty(nt,"MissingRefError",{enumerable:!0,get:function(){return zQ.default}})});var TI,OI=I(()=>{"use strict";TI=new Map});function Hf(e){let t=Qn(e),r=ta.get(t);if(r)return ta.delete(t),ta.set(t,r),r;let i=TI.get(t)??new sy.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),o={validate:i,errorsText:()=>sy.Ajv.prototype.errorsText(i.errors)};if(t.length<=$I){for(;ta.size>=KQ||ay+t.length>$I;){let a=ta.keys().next().value;ta.delete(a),ay-=a.length}ta.set(t,o),ay+=t.length}return o}var sy,KQ,$I,ta,ay,cy=I(()=>{"use strict";sy=or(Ff(),1);OI();lr();KQ=128,$I=1024*1024,ta=new Map,ay=0});function It(e){throw new k("INVALID_WORKFLOW",e)}function co(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&It(`${t} 必须是 JSON 对象`),e}function Nl(e,t,r){for(let n of Object.keys(e))t.includes(n)||It(`${r} 包含不支持的字段:${n}`)}function rr(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&It(`${t} 必须是非空字符串且不超过 4096 字符`),e}function ly(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&It(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>rr(i,t));return new Set(n).size!==n.length&&It(`${t} 不能包含重复值`),n}function uy(e,t){return ly(typeof e=="string"?[e]:e,t)}function Sl(e,t){let r=co(e,t);return Nl(r,["id","version"],t),{id:rr(r.id,`${t}.id`),version:rr(r.version,`${t}.version`)}}function DI(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))DI(t);Object.freeze(e)}return e}function BI(e,t){try{let r=typeof e=="boolean"?e:co(e,t);typeof r!="boolean"&&r.$async===!0&&It(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),Hf(r)}catch(r){It(`${t} 不是受支持的 JSON Schema:${r.message}`)}}function YQ(e){let t=co(e,"step"),r=rr(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(r)||It(`不支持的步骤类型:${r}`);let n=r==="ask_user"?["proposalFrom","choices"]:r==="child_workflow"?["workflow"]:r==="await_evidence"?["kind"]:[];Nl(t,[...GQ,...n],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&It("step.retry 必须是 manual、idempotent 或 reconcile");let o={...t.ref===void 0?{}:{ref:rr(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:Sl(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:ly(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:ly(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&BI(t.outputSchema,"outputSchema"),r==="ask_user"?{...o,type:r,proposalFrom:uy(t.proposalFrom,"step.proposalFrom"),choices:uy(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...o,type:r,workflow:Sl(t.workflow,"step.workflow")}:r==="await_evidence"?(o.validator||It("await_evidence 必须声明验证器"),{...o,type:r,kind:rr(t.kind,"step.kind"),validator:o.validator}):{...o,type:r,ref:rr(t.ref,"step.ref")}}function fn(e){if(jI.has(e))return e;let t=co(st(e),"workflow");Nl(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=rr(t.id,"workflow.id"),n=rr(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&It("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&It("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&BI(t.stateSchema,"stateSchema");let i=co(t.steps,"workflow.steps");Object.keys(i).length===0&&It("workflow.steps 必须至少包含一个步骤");let o=Object.fromEntries(Object.entries(i).map(([p,g])=>(rr(p,"step id"),[p,YQ(g)])));function a(p,g){Object.hasOwn(o,p)||It(`${g} 引用了不存在的步骤:${p}`)}let s=uy(t.entry,"workflow.entry");for(let p of s)a(p,"workflow.entry");let c=t.commands===void 0?{}:co(t.commands,"workflow.commands"),l={};for(let[p,g]of Object.entries(c)){rr(p,"workflow command name");let v=typeof g=="string"?{stepId:rr(g,`workflow.commands.${p}`)}:co(g,`workflow.commands.${p}`);Nl(v,["stepId","validator"],`workflow.commands.${p}`);let w=rr(v.stepId,`workflow.commands.${p}.stepId`);a(w,`workflow.commands.${p}`);let A=o[w];(A.join||!["invoke_skill","call_tool","handoff"].includes(A.type))&&It(`workflow.commands.${p} 必须指向不带 join 的执行步骤`),Object.defineProperty(l,p,{value:{stepId:w,...v.validator===void 0?{}:{validator:Sl(v.validator,`workflow.commands.${p}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let u=t.transitions===void 0?[]:t.transitions;Array.isArray(u)||It("workflow.transitions 必须是数组");let f=new Set,d=u.map(p=>{let g=co(p,"transition");Nl(g,["from","to","on"],"transition");let v=rr(g.from,"transition.from"),w=rr(g.to,"transition.to"),A=rr(g.on===void 0?"succeeded":g.on,"transition.on");a(v,"transition.from"),a(w,"transition.to");let b=JSON.stringify([v,w,A]);return f.has(b)&&It(`重复的状态转移:${v} -> ${w} (${A})`),f.add(b),{from:v,to:w,on:A}});for(let[p,g]of Object.entries(o)){if(g.join){let v=new Set(d.filter(w=>w.to===p).map(w=>w.from));for(let w of g.join)a(w,`${p}.join`),v.has(w)||It(`${p}.join 依赖缺少对应的进入边:${w}`);v.size!==g.join.length&&It(`${p}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let v of g.proposalFrom)a(v,`${p}.proposalFrom`)}let m=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof m!="number"||!Number.isSafeInteger(m)||m<1)&&It("workflow.maxTransitions 必须是正安全整数");let h=DI({id:r,version:n,entry:s,steps:o,...t.commands===void 0?{}:{commands:l},transitions:d,maxTransitions:m,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:Sl(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:Sl(t.transitionHandler,"workflow.transitionHandler")}});return jI.add(h),h}var GQ,jI,dy=I(()=>{"use strict";rn();lr();cy();GQ=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];jI=new WeakSet});function El(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!0,enumerable:!0,writable:!0})}function Qf(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value]))}function XQ(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)&&El(t,n,i);return t}function yi(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)||El(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=XQ(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:Qf(s),...o.activation===void 0?{}:{activation:o.activation}};if(a.type==="ask_user"){let f=Object.fromEntries(a.proposalFrom.map(m=>{if(!Object.hasOwn(s,m))throw new k("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${m}`);return[m,s[m].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:T(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=xE({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),El(e.actionContexts,l,{sequence:c,results:s}),a.type==="child_workflow"&&e.children.push({actionId:l,runId:`child-${T(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 ds(e,t,r,n,i,o,a,s){let c={sequence:n,value:o},l={...i};El(l,r,c),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&El(e.outputs,r,c);let u=t.transitions.filter(m=>m.from===r),f=u.filter(m=>m.on===a),d=s??f.map(m=>m.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 m of d){let h=typeof m=="string"?m:m.stepId;if(!f.some(p=>p.to===h))throw new k("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:r,to:h,results:l,...typeof m=="string"?{}:{activation:m.input}})}}var WI=I(()=>{"use strict";Mo();rn();lr()});import{randomUUID as fy}from"node:crypto";import{types as hy}from"node:util";function LI(e){return Fe({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 ct(e){return JSON.stringify([e.id,e.version])}function Fr(e){if(e===void 0)return;if(!e||typeof e!="object"||hy.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=st(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new k("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function gy(e,t=new Set){if(e===null||typeof e!="object")return e;if(hy.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:gy(o.value,t)})}return t.delete(e),n}function py(e){if(e===null||typeof e!="object")return e;if(hy.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"?Fr(n.value):gy(n.value)})}return t}function ra(e){let t=gy(e),r=st(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 my(e,t){let r=e.supports(Fe(t));if(typeof r!="boolean")throw new k("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function Gn(e){if(e?.signal?.aborted)throw new k("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function na(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)&&na(e[n],t[n]))}function VI(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 Bt(e){let t=new Map,r=new Map;for(let y of e.workflows){let E=fn(y),$=ct(E);if(t.has($))throw new k("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set($,E);let x=MI.get(E);x===void 0&&(x=T(E),MI.set(E,x)),r.set(E,x)}let n=new Map;for(let y of e.validators??[]){let E=ct(y);if(n.has(E))throw new k("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(E,y)}let i=new Map;for(let y of e.stateValidators??[]){let E=ct(y);if(i.has(E))throw new k("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(E,y)}let o=new Map;function a(y){let E=o.get(y);return E||(E=Hf(y),o.set(y,E)),E}let s=new Map,c=new Map;for(let y of e.transitionHandlers??[]){let E=ct(y);if(c.has(E))throw new k("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");c.set(E,y)}let l=new Map;for(let y of e.evidenceValidators??[]){let E=ct(y);if(l.has(E))throw new k("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");l.set(E,y)}let u=new Map;for(let y of e.commandValidators??[]){let E=ct(y);if(u.has(E))throw new k("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");u.set(E,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 E=t.get(ct(y));if(!E)throw new k("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(y.hash!==void 0&&y.hash!==r.get(E))throw new k("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return E}function d(y){if(y.transitionHandler&&!c.has(ct(y.transitionHandler)))throw new k("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function m(y){if(y.stateValidator&&!i.has(ct(y.stateValidator)))throw new k("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function h(y){for(let E of Object.values(y.steps))if(E.type==="await_evidence"&&!l.has(ct(E.validator)))throw new k("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function p(y){for(let E of Object.values(y.commands??{}))if(E.validator&&!u.has(ct(E.validator)))throw new k("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(y,E,$){if(y.stateSchema!==void 0){let x=a(y.stateSchema);if(!x.validate(E))throw new k($,x.errorsText())}if(y.stateValidator){let x=i.get(ct(y.stateValidator));if(!x)throw new k("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let P=ra(x.validate({state:st(E)}));if(!P.accepted)throw new Error(P.reason??"业务状态未通过验证")}catch(P){throw new k($,P instanceof Error?P.message:String(P))}}}function v(y,E,$,x){if(!E.transitionHandler)return;let P=c.get(ct(E.transitionHandler));if(!P)throw new k("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let z=st(P.apply({run:Fe(y),event:Fe($)})),Y=st(z.state);g(E,Y,"TRANSITION_STATE_INVALID");let ee=new Set(E.transitions.filter(se=>se.from===$.stepId&&se.on===x).map(se=>se.to));if(!Array.isArray(z.next))throw new k("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let K=[],te=new Set;for(let se of z.next){let V;if(typeof se=="string")V=se;else if(se!==null&&typeof se=="object"&&!Array.isArray(se)){let Se=Object.keys(se);if(Se.length!==2||!Se.includes("stepId")||!Se.includes("input")||typeof se.stepId!="string")throw new k("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");V={stepId:se.stepId,input:st(se.input)}}else throw new k("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let ke=typeof V=="string"?V:V.stepId,ie=T(V);if(!ee.has(ke)||te.has(ie))throw new k("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");te.add(ie),K.push(V)}return y.state=Y,K}function w(y,E=T){if(t.size>0)for(let[$,x]of Object.entries(y.definitionHashes)){let[P,z]=JSON.parse($),Y=f({id:P,version:z,hash:x});if(d(Y),m(Y),h(Y),p(Y),P===y.workflow.id&&z===y.workflow.version){let ee=new Map(y.actions.map(K=>[K.id,K]));for(let K of y.commands??[]){let te=ee.get(K.actionId),se=Object.hasOwn(Y.commands??{},K.name),V=te&&!se&&!Object.hasOwn(Y.steps,te.stepId)&&["succeeded","failed","cancelled"].includes(te.status);if(!te||!V&&(!se||Y.commands?.[K.name].stepId!==te.stepId)||te.input===null||typeof te.input!="object"||!Object.hasOwn(te.input,"activation")||E(te.input.activation)!==K.inputHash)throw new k("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(Y.stateSchema!==void 0&&Y.initialState===void 0&&y.initialStateHash===void 0)throw new k("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(Y,y.state,"RUN_STATE_INVALID");for(let K of y.ready){let te=()=>{throw new k("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(Y.steps,K.to)||te(),K.from===null){(!Y.entry.includes(K.to)||Object.keys(K.results).length>0||y.sequence!==0&&!(y.status==="failed"&&y.reason?.startsWith("TRANSITION_LIMIT:")))&&te();continue}let se=K.results[K.from];se||te();let V=y.actions.find(kr=>kr.stepId===K.from&&y.actionContexts[kr.id].sequence===se.sequence),ke=y.waits.find(kr=>kr.stepId===K.from&&kr.sequence===se.sequence),ie=y.evidenceWaits?.find(kr=>kr.stepId===K.from&&kr.sequence===se.sequence),Se=V?.outcome?V.outcome.status==="failed"?"failed":V.outcome.event??"succeeded":ke?.decision?.choice??(ie?.invalidation?"invalidated":ie?.receipt?"succeeded":void 0),lt=V?y.actionContexts[V.id].results:ke?.results??ie?.results,Js=V?.outcome?V.outcome.output:ke?.decision?{choice:ke.decision.choice,proposal:ke.proposal}:ie?.invalidation?{ref:ie.invalidation.ref,contentHash:ie.invalidation.contentHash,reason:ie.invalidation.reason}:ie?.receipt?{ref:ie.receipt.ref,contentHash:ie.receipt.contentHash}:void 0;(!Se||!lt||V&&!["succeeded","failed"].includes(V.status)||ke&&ke.status!=="resolved"||ie&&!["resolved","invalidated"].includes(ie.status)||Js===void 0||E(K.results)!==E({...lt,[K.from]:{sequence:se.sequence,value:Js}})||!Y.transitions.some(kr=>kr.from===K.from&&kr.to===K.to&&kr.on===Se))&&te()}for(let K of y.evidenceWaits??[]){let te=Y.steps[K.stepId];if(!(!te&&K.status!=="pending")&&(!te||te.type!=="await_evidence"||te.kind!==K.kind))throw new k("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function A(y){let E=await e.store.read(y);if(!E)throw new k("RUN_NOT_FOUND",`找不到工作流实例:${y}`);let $=ME(E,y);return w($),Vo($)}async function b(y,E,$){for(let x=0;x<32;x+=1){Gn(y.context);let P=x===0&&$?$:await A(y.runId),z=f(P.workflow);if(y.expectedRevision!==void 0&&y.expectedRevision!==P.revision)throw new k("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let Y=VI(P);if(await E(Y,z),on(Y),na(Y,P))return P;if(Y.revision=P.revision+1,nf(Y,P),w(Y),Vo(Y),Gn(y.context),await e.store.compareAndSwap(y.runId,P.revision,Y))return Y}throw new k("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function R(y,E){let $=y.actions.find(x=>x.id===E);if(!$)throw new k("ACTION_NOT_FOUND","Run 不包含此 Action");return $}function _(y){if(y.status==="cancelled")throw new k("RUN_CANCELLED","Run 已取消,不能继续推进")}function W(y,E={}){let $=ct(y);if(Object.hasOwn(E,$))return E;E[$]=r.get(y);for(let x of Object.values(y.steps))x.type==="child_workflow"&&W(f(x.workflow),E);return E}async function O(y,E){if(Gn(y.context),E.length>32)throw new k("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let $=f(y.workflow);d($),m($),h($),p($);let x=Object.hasOwn(y,"initialState");if(x&&$.initialState!==void 0)throw new k("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let P=x?st(y.initialState):$.initialState;if($.stateSchema!==void 0&&P===void 0)throw new k("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");P!==void 0&&g($,P,"INITIAL_STATE_INVALID");let z=P===void 0?void 0:T(P),Y=y.runId??fy(),ee=st(y.input),K={id:$.id,version:$.version,hash:r.get($)},te=await e.store.read(Y);if(te){if(T(te.workflow)!==T(K)||T(te.input)!==T(ee)||T(te.lineage)!==T(E)||(te.initialStateHash??($.initialState===void 0?void 0:T($.initialState)))!==z)throw new k("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return A(Y)}let se={protocolVersion:1,schemaVersion:1,runId:Y,revision:1,workflow:K,definitionHashes:W($),input:ee,...P===void 0?{}:{state:st(P),initialStateHash:z},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:$.entry.map(V=>({from:null,to:V,results:{}})),joins:{},outputs:{},children:[],lineage:E};return yi(se,$),Vo(se),Gn(y.context),nf(se),w(se),await e.store.compareAndSwap(Y,null,se)?Fe(se):O({...y,runId:Y},E)}async function G(y){return O(y,[])}async function Z(y){let E=st(y.input),$=T(E);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){Gn(y.context);let P=await A(y.runId),z=P.commands?.find(ie=>ie.id===y.commandId);if(z){if(z.name!==y.name||z.inputHash!==$)throw new k("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return P}if(y.expectedRevision!==P.revision)throw new k("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let Y=f(P.workflow),ee=Object.hasOwn(Y.commands??{},y.name)?Y.commands?.[y.name]:void 0;if(!ee)throw new k("COMMAND_NOT_FOUND","工作流未声明此命令");let K=ee.stepId;if(P.status==="cancelled")throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.actions.some(ie=>["running","unknown"].includes(ie.status)))throw new k("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let te=!1,se=!1;if(ee.validator){let ie=u.get(ct(ee.validator));if(!ie)throw new k("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let Se;try{Se=ra(await ie.validate({run:Fe(P),name:y.name,input:Fe(E),context:Fr(y.context)}))}catch(lt){throw new k("COMMAND_VALIDATION_ERROR",lt instanceof Error?lt.message:String(lt))}if(te=Se.accepted&&Se.allowCompleted===!0,se=Se.accepted&&Se.allowFailed===!0,P.status==="failed"&&!se)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="completed"&&!te)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!Se.accepted)throw new k("COMMAND_REJECTED",Se.reason??"命令未通过当前工作流状态验证")}if(P.status==="completed"&&!te)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="failed"&&!se)throw new k("RUN_TERMINAL","已停止的 Run 不能接受命令");let V=Fe(P);P.status==="failed"&&(V.status="running",delete V.reason),V.actions=V.actions.map(ie=>ie.status==="pending"?Zd(ie,`命令 ${y.name} 已取代待执行 Action`):ie);for(let ie of V.waits)ie.status==="pending"&&(ie.status="cancelled");for(let ie of V.evidenceWaits??[])ie.status==="pending"&&(ie.status="cancelled");V.ready=[{from:null,to:K,results:{},activation:E}],V.joins={},yi(V,Y);let ke=V.actions.at(-1);if(!ke||ke.stepId!==K||ke.status!=="pending")throw new k("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(V.commands=[...V.commands??[],{id:y.commandId,name:y.name,inputHash:$,actionId:ke.id}],V.revision=P.revision+1,nf(V,P),w(V),Vo(V),Gn(y.context),await e.store.compareAndSwap(y.runId,P.revision,V))return Fe(V)}throw new k("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function J(y){for(let E of y.children)await e.store.read(E.runId)&&await C({runId:E.runId,reason:y.reason??"父工作流已取消"})}function F(y,E,$){let x=f(y.workflow),P=Object.hasOwn(x.steps,$.stepId)?x.steps[$.stepId]:void 0;if(!P||P.type!=="child_workflow"||ct(P.workflow)!==ct(E.workflow)||$.type!==P.type||$.ref!==`${P.workflow.id}@${P.workflow.version}`||$.attempt!==1||$.retry!==P.retry||!na($.requiredCapabilities,P.requiredCapabilities??[])||$.claim&&($.claim.executorId!=="comet-child-workflow"||$.claim.sessionId!==void 0||![E.runId,`portable-${T(E.runId)}`].includes($.claim.token)))throw new k("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let z=$.input;if(!z||typeof z!="object"||Array.isArray(z)||!na(z,{input:P.input===void 0?y.input:P.input,outputs:Qf(y.actionContexts[$.id].results),...Object.hasOwn(z,"activation")?{activation:z.activation}:{}}))throw new k("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let Y=f({...E.workflow,hash:y.definitionHashes[ct(E.workflow)]});if(Object.entries(W(Y)).some(([ee,K])=>y.definitionHashes[ee]!==K))throw new k("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return Y}function X(y,E,$,x,P){let z=x.initialState===void 0?void 0:T(x.initialState);if(P.runId!==E.runId||ct(P.workflow)!==ct(E.workflow)||P.workflow.hash!==y.definitionHashes[ct(E.workflow)]||!na(P.definitionHashes,W(x))||!na(P.input,$.input)||!na(P.lineage,[...y.lineage,y.runId])||(P.initialStateHash??z)!==z)throw new k("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function U(y){let E=await b(y,($,x)=>yi($,x));if(E.status==="cancelled")return await J(E),E;if(E.status==="failed"||E.children.length===0)return E;for(let $ of E.children){let x=R(E,$.actionId);if(!["pending","running","unknown"].includes(x.status))continue;let P=F(E,$,x);x.status==="pending"&&(E=await pe({runId:E.runId,actionId:x.id,attempt:x.attempt,inputHash:x.inputHash,executorId:"comet-child-workflow",claimToken:$.runId,capabilities:["child-workflow"],context:Fr(y.context)},!0),x=R(E,$.actionId));let z=x.status==="unknown"?await A($.runId):await O({runId:$.runId,workflow:$.workflow,input:x.input,context:Fr(y.context)},[...E.lineage,E.runId]);X(E,$,x,P,z);let Y=await A(E.runId);if(Y.status==="cancelled")return await J(Y),Y;let ee=await U({runId:$.runId,context:y.context});X(E,$,x,P,ee),["completed","failed","cancelled"].includes(ee.status)&&(E=await D({runId:E.runId,context:Fr(y.context),outcome:{actionId:x.id,attempt:x.attempt,inputHash:x.inputHash,claimToken:x.claim.token,outcomeId:`${$.runId}:${ee.revision}`,status:ee.status==="completed"?"succeeded":"failed",output:Qf(ee.outputs)}},!0))}return A(E.runId)}async function pe(y,E=!1,$){let x=y.claimToken??(y.context?.requestId?T({runId:y.runId,actionId:y.actionId,attempt:y.attempt,executorId:y.executorId,requestId:y.context.requestId}):fy());return b(y,async P=>{if(_(P),P.status==="failed")throw new k("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let z=R(P,y.actionId);if(z.type==="child_workflow"&&!E)throw new k("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let Y=cv(z,{executionOrigin:{workflow:{...P.workflow}},attempt:y.attempt,inputHash:y.inputHash,executorId:y.executorId,token:x,...y.sessionId===void 0?{}:{sessionId:y.sessionId}});if(!z.claim){let ee=new Set(y.capabilities??[]);if(z.requiredCapabilities.some(te=>!ee.has(te)))throw new k("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let K=s.get(y.executorId);if(K&&my(K,z)){if(z.requiredCapabilities.some(te=>!K.capabilities.includes(te)))throw new k("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await K.preflight?.(Fe(z),Fr(y.context),K.includeRun===!1?void 0:Fe(P)),Gn(y.context)}}P.actions[P.actions.indexOf(z)]=Y},$)}async function Le(y){return pe(y)}async function D(y,E=!1,$){let x,P;try{x=ef(y.outcome)}catch(ee){P=ee}y={...y,outcome:x};let z,Y=await b(y,async(ee,K)=>{if(z=void 0,_(ee),!x)throw P;let te=R(ee,y.outcome.actionId);if(te.type==="child_workflow"&&!E)throw new k("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let se=Xd(te,y.outcome);if(se.duplicate)return;let V=se.action.outcome,ke=ee.actions.indexOf(te);try{if(e.validateOutcome){let Se=ra(await e.validateOutcome({run:Fe(ee),action:Fe(te),outcome:Fe(V),context:Fr(y.context)}));Se.accepted||(z={code:"OUTCOME_REJECTED",reason:Se.reason??"应用结果契约拒绝此结果"})}let ie=K.steps[te.stepId];if(!z&&V.status==="succeeded"&&ie.outputSchema!==void 0){let Se=a(ie.outputSchema);Se.validate(V.output)||(z={code:"OUTPUT_INVALID",reason:Se.errorsText()})}if(!z&&ie.validator){let Se=n.get(ct(ie.validator));if(!Se)throw new k("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let lt=ra(await Se.validate({run:Fe(ee),action:Fe(te),outcome:Fe(V),context:Fr(y.context)}));lt.accepted||(z={code:"OUTCOME_REJECTED",reason:lt.reason?.trim()?lt.reason:"结果未满足业务验收条件"})}if(!z){let Se=VI(ee);Se.actions[ke]=se.action;let lt=Se.actionContexts[te.id],Js=V.status==="failed"?"failed":V.event??"succeeded",kr=v(Se,K,{kind:"action-outcome",stepId:te.stepId,outcome:V},Js);ds(Se,K,te.stepId,lt.sequence,lt.results,V.output,Js,kr),yi(Se,K),Object.assign(ee,Se)}}catch(ie){z={code:"OUTCOME_PROCESSING_ERROR",reason:ie instanceof Error&&ie.message.trim()?ie.message:"结果处理失败,请检查验证器或工作流定义"}}z&&(ee.actions[ke]={...te,receipts:se.action.receipts,rejectedOutcomes:[...te.rejectedOutcomes??[],{outcome:se.action.outcome,...z}]})},$);if(z)throw new k(z.code,z.reason);return Y}async function re(y){return D(y)}async function ge(y){if(y.reason!==void 0&&!fv(y.reason))throw new k("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return b(y,(E,$)=>{_(E);let x=E.waits.find(z=>z.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(E,$,{kind:"wait-resolved",stepId:x.stepId,choice:y.choice,proposalHash:y.proposalHash,decisionId:y.decisionId},y.choice);ds(E,$,x.stepId,x.sequence,x.results,{choice:y.choice,proposal:x.proposal},y.choice,P),yi(E,$)})}async function mt(y){return b(y,async(E,$)=>{if(_(E),E.status==="failed")throw new k("RUN_FAILED","Run 已因失败停止,不能提交证据");let x=E.evidenceWaits?.find(K=>K.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=$.steps[x.stepId];if(!P||P.type!=="await_evidence"||P.kind!==y.kind)throw new k("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let z=l.get(ct(P.validator));if(!z)throw new k("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let Y=ra(await z.validate({run:Fe(E),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:Fr(y.context)}));if(!Y.accepted||Y.actualHash!==y.contentHash)throw new k("EVIDENCE_REJECTED",Y.reason??"证据未通过验证或内容已改变");x.status="resolved",x.receipt={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId};let ee=v(E,$,{kind:"evidence-recorded",stepId:x.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId},"succeeded");ds(E,$,x.stepId,x.sequence,x.results,{ref:y.ref,contentHash:y.contentHash},"succeeded",ee),yi(E,$)})}async function S(y){return b(y,async(E,$)=>{if(_(E),E.status==="failed")throw new k("RUN_FAILED","Run 已因失败停止,不能使证据失效");let x=E.evidenceWaits?.find(te=>te.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=$.steps[x.stepId];if(!P||P.type!=="await_evidence"||P.kind!==y.kind)throw new k("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!$.transitions.some(te=>te.from===x.stepId&&te.on==="invalidated"))throw new k("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let z=l.get(ct(P.validator));if(!z)throw new k("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let Y=ra(await z.validate({run:Fe(E),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:Fr(y.context)}));if(Y.accepted&&Y.actualHash===y.contentHash)throw new k("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let ee=(Y.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);x.status="invalidated",x.invalidation={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:ee};let K=v(E,$,{kind:"evidence-invalidated",stepId:x.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:ee},"invalidated");ds(E,$,x.stepId,x.sequence,x.results,{ref:y.ref,contentHash:y.contentHash,reason:ee},"invalidated",K),yi(E,$)})}async function N(y){return b(y,E=>{_(E);let $=E.waits.find(x=>x.id===y.waitId);if(!$||$.status!=="pending"||$.proposalHash!==y.proposalHash)throw new k("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");$.proposal=st(y.proposal),$.proposalHash=T($.proposal)})}async function C(y){let E=await b(y,$=>{if($.status==="completed"){if(y.stoppedActions?.length)throw new k("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let x=$.status==="cancelled";if(x||($.actions=$.actions.map(P=>Zd(P,y.reason))),y.stoppedActions!==void 0){if(!Array.isArray(y.stoppedActions))throw new k("INVALID_ACTION","stoppedActions 必须是停止确认数组");let P=new Set;for(let z of y.stoppedActions){if(!z||typeof z!="object"||P.has(z.actionId))throw new k("INVALID_ACTION","停止确认重复或无效");P.add(z.actionId);let Y=R($,z.actionId);$.actions[$.actions.indexOf(Y)]=lv(Y,z)}}if(!x){for(let P of $.waits)P.status==="pending"&&(P.status="cancelled");for(let P of $.evidenceWaits??[])P.status==="pending"&&(P.status="cancelled");$.ready=[],$.status="cancelled",$.reason=y.reason}});return E.status==="cancelled"&&await J(E),E}async function B(y){return b(y,E=>{if(!Array.isArray(y.stoppedActions)||!y.stoppedActions.length)throw new k("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let $=new Set;for(let x of y.stoppedActions){if(!x||typeof x!="object"||$.has(x.actionId))throw new k("INVALID_ACTION","停止确认重复或无效");$.add(x.actionId);let P=R(E,x.actionId);E.actions[E.actions.indexOf(P)]=uv(P,x)}})}async function L(y){return b(y,E=>{_(E);let $=R(E,y.actionId);if($.attempt!==y.attempt)throw new k("STALE_ACTION","Action 执行尝试已经改变");E.actions[E.actions.indexOf($)]=TE($,y.reason)})}async function q(y){return b(y,async(E,$)=>{_(E);let x=R(E,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(E.actions.some(K=>["running","unknown"].includes(K.status)))throw new k("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(E.status!=="completed"||E.ready.length>0||E.actions.some(K=>K.status==="pending")||E.waits.some(K=>K.status==="pending")||E.evidenceWaits?.some(K=>K.status==="pending")||Object.values(E.joins).some(K=>Object.values(K).some(te=>te.length>0))||!x.outcome||x.outcome.status!=="succeeded")throw new k("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let P=ra(await e.validateRecovery({run:Fe(E),action:Fe(x),outcome:Fe(x.outcome),context:Fr(y.context),proposalHash:y.proposalHash}));if(!P.accepted)throw new k("ACTION_TERMINAL",P.reason??"应用拒绝恢复此结果");let z=x.outcome.event??"succeeded",Y=v(E,$,{kind:"action-outcome",stepId:x.stepId,outcome:x.outcome},z);if(Y?.length===0||Y===void 0&&!$.transitions.some(K=>K.from===x.stepId&&K.on===z))throw new k("ACTION_TERMINAL","应用未声明可恢复的后续工作");let ee=E.actionContexts[x.id];ds(E,$,x.stepId,ee.sequence,ee.results,x.outcome.output,z,Y),yi(E,$);return}if(x.status==="failed"){let P=E.actionContexts[x.id].sequence,z=ee=>Object.hasOwn(ee,x.stepId)&&ee[x.stepId].sequence===P;if(Object.values(E.actionContexts).some(ee=>z(ee.results))||E.waits.some(ee=>z(ee.results))||E.evidenceWaits?.some(ee=>z(ee.results))||E.ready.some(ee=>z(ee.results))||Object.values(E.joins).some(ee=>Object.values(ee).some(K=>K.some(te=>z(te.results)))))throw new k("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}E.actions[E.actions.indexOf(x)]=OE(x,y.reconciliation),E.status="running",delete E.reason})}async function Q(y,E){let $=s.get(y.executorId);if(!$)throw new k("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let x=E??await A(y.runId),P=R(x,y.actionId);if(P.status!=="pending")throw new k("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!my($,P))throw new k("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");Gn(y.context);let z=await pe({...y,attempt:P.attempt,inputHash:P.inputHash,claimToken:fy(),capabilities:$.capabilities},!1,x),Y=R(z,y.actionId),ee;try{Gn(y.context),ee=await $.execute(Fe(Y),Fr(y.context),$.includeRun===!1?void 0:Fe(z))}catch(te){let se=await A(y.runId),V=R(se,Y.id);throw se.status!=="cancelled"&&V.status==="running"&&V.attempt===Y.attempt&&await L({runId:y.runId,actionId:Y.id,attempt:Y.attempt,reason:te instanceof Error?te.message:String(te)}),new k("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let K=`${Y.id}:${Y.attempt}:executor-result`;try{return await D({runId:y.runId,context:Fr(y.context),outcome:{...ee,actionId:Y.id,attempt:Y.attempt,inputHash:Y.inputHash,claimToken:Y.claim.token,outcomeId:K}},!1,z)}catch(te){let se=await A(y.runId),V=R(se,Y.id);if(V.receipts.some(ke=>ke.outcomeId===K)){if(V.rejectedOutcomes?.some(ke=>ke.outcome.outcomeId===K))throw te;if(V.outcome?.outcomeId===K)return se}throw se.status!=="cancelled"&&V.status==="running"&&V.attempt===Y.attempt&&await L({runId:y.runId,actionId:Y.id,attempt:Y.attempt,reason:te instanceof Error?te.message.slice(0,4096):"执行结果无法提交"}),new k("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function ae(y){let E=y.maxActions??100;if(!Number.isSafeInteger(E)||E<1)throw new k("INVALID_REQUEST","maxActions 必须是正安全整数");let $=s.get(y.executorId);if(!$)throw new k("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let x=0,P=await A(y.runId),z=ee=>({reason:ee,run:P,actionsExecuted:x}),Y=ee=>{if(P.status==="completed"||P.status==="failed"||P.status==="cancelled")return P.status;if(P.actions.some(K=>K.status==="unknown"&&(!ee||K.type!=="child_workflow")))return"execution-unknown";if(P.actions.some(K=>K.status==="running"&&(!ee||K.type!=="child_workflow")))return"action-in-flight";if(P.waits.some(K=>K.status==="pending"))return"approval-required";if(P.evidenceWaits?.some(K=>K.status==="pending"))return"evidence-required"};for(;;){Gn(y.context);let ee=Y(!0);if(ee)return z(ee);(P.ready.length||P.children.length)&&(P=await U({runId:y.runId,context:y.context}));let K=Y(!1);if(K)return z(K);let te=P.actions.find(se=>se.status==="pending");if(!te)return z("idle");if(x>=E)return z("action-limit");if(!my($,te)||te.requiredCapabilities.some(se=>!$.capabilities.includes(se)))return z("executor-required");x++;try{P=await Q({...y,actionId:te.id},P)}catch(se){if(!(se instanceof k)||se.code!=="EXECUTION_UNKNOWN"||(P=await A(y.runId),!P.actions.some(V=>V.status==="unknown")))throw se;return z("execution-unknown")}}}async function ne(y){let E=await qo(e.store,y);return w(E.run,En),E}async function ve(y){return mv(await ne(y.runId),y)}function fe(y){return async(...E)=>{let $=E.map(x=>py(x));return Fe(await y(...$))}}return{start:fe(G),dispatchCommand:fe(Z),inspect:fe(A),inspectProjection:ne,query:fe(ve),inspectCurrent:async y=>await ve({runId:y,view:"current"}),executeCurrent:async y=>LI(await Q(py(y))),runUntilBlockedCurrent:async y=>{let E=await ae(py(y));return{...E,run:LI(E.run)}},next:fe(U),claim:fe(Le),recordOutcome:fe(re),resolveWait:fe(ge),recordEvidence:fe(mt),invalidateEvidence:fe(S),reviseWait:fe(N),cancel:fe(C),acknowledgeStopped:fe(B),markUnknown:fe(L),retry:fe(q),execute:fe(y=>Q(y)),runUntilBlocked:fe(ae)}}var MI,qI=I(()=>{"use strict";hv();Lo();Mo();rn();lr();cy();zc();dy();WI();MI=new WeakMap});var FI=I(()=>{"use strict";rn();lr()});import{createRequire as ZQ}from"node:module";function Jf(e,t){if(!Uf){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{Uf=eU("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new Uf(e):new Uf(e,t)}var eU,Uf,vy=I(()=>{"use strict";eU=ZQ(import.meta.url??__filename)});import{AsyncLocalStorage as tU}from"node:async_hooks";function QI(e){return Math.max(0,Math.min(e,(HI.getStore()?.deadline??1/0)-performance.now()))}function UI(){let e=HI.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new wy}var HI,wy,JI=I(()=>{"use strict";HI=new tU,wy=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}}});import{randomUUID as rU}from"node:crypto";import{promises as lo}from"node:fs";import _l from"node:path";import{performance as zI}from"node:perf_hooks";async function KI(e){let t,r;try{let n=await lo.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 lo.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 nU(e){let t=e+".sqlite";try{let n=await lo.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=Jf(_l.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 GI(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function iU(e,t={}){e=_l.resolve(e),await lo.mkdir(_l.dirname(e),{recursive:!0});let r=await lo.lstat(_l.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+_l.dirname(e));let n=zI.now()+QI(t.timeoutMs??3e4),i;for(;UI(),i=await nU(e),!i;){if(zI.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:rU(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let s=await KI(e);if(s?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
|
|
194
|
+
Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));s&&await lo.unlink(e),await lo.writeFile(e,JSON.stringify(o),{mode:384,flag:"wx"})}catch(s){throw GI(i),s}let a=!1;return{owner:o,async release(){if(a)return!0;a=!0;let s=!0;try{let c=await KI(e);c?.token===o.nonce?c.owner?.createdAt===o.createdAt&&c.owner.operation===o.operation?await lo.unlink(e):(s=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
|
|
195
|
+
`)):c&&(s=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
|
|
196
|
+
`))}finally{GI(i)}return s}}}async function YI(e,t,r={}){let n=await iU(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)+`
|
|
197
|
+
`)}throw o}return await n.release(),i}var XI=I(()=>{"use strict";vy();JI()});function ex(e){return zf(e).encoded}function zf(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=ZI.get(u)??t.get(u);if(f!==void 0)return f;let d=Object.entries(u),m=2+Math.max(0,d.length-1)+d.reduce((h,[p,g])=>h+(Array.isArray(u)?0:n(p)+1)+n(g),0);return t.set(u,m),nn(u)&&ZI.set(u,m),m},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[m,h]of d.actions.entries())h.input&&typeof h.input=="object"&&Object.hasOwn(h.input,"outputs")&&a.push({path:[...f,"actions",String(m),"input","outputs"],group:"outputs"});for(let[m,h]of Object.entries(d.actionContexts))h?.results&&a.push({path:[...f,"actionContexts",m,"results"],group:"results"});d.outputs&&a.push({path:[...f,"outputs"],group:"results"});for(let m of["ready","waits","evidenceWaits"])for(let[h,p]of(d[m]??[]).entries())p.results&&a.push({path:[...f,m,String(h),"results"],group:"results"})}};if(s(e,[]),s(e.run,["run"]),!a.length)return o();let c=EE(e,a,nn),l=JSON.stringify(c);return l.length<i*.9?{encoded:c,json:l}:o()}var ZI,yy=I(()=>{"use strict";Lo();lr();ZI=new WeakMap});import{createHash as rx,randomUUID as oU}from"node:crypto";import{types as aU}from"node:util";import{promises as pn}from"node:fs";import xt from"node:path";function uo(e){if(typeof e!="string"||e.trim().length===0)throw new k("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function sU(e){return uo(e),rx("sha256").update(JSON.stringify(e)).digest("hex")}function Kf(e){if(!Number.isSafeInteger(e)||e<1)throw new k("STORE_INVALID_REVISION","revision 必须是正安全整数")}function cU(e,t,r){return JSON.stringify(nx(e,t,r))}function nx(e,t,r,n=!0){if(uo(e),aU.isProxy(r))throw new k("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&Kf(t),on(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(Kf(i.revision),i.revision!==(t??0)+1)throw new k("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}function ix(e,t,r){let n=st(r);if(uo(e),!n||n.runId!==e)throw new k("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(Kf(n.revision),t!==null&&t!==1||n.revision<=(t??0))throw new k("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(n)}function ox(e,t,r){let n=st(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 ax(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||Qn(e)===Qn(ox(r,1,n)))}function Gf(){let e=new Map;return{queryScope:`memory:${oU()}`,async read(r){uo(r);let n=e.get(r);return n===void 0?null:JSON.parse(n.serialized)},async restoreCheckpoint(r,n,i){let o=ix(r,n,i),a=JSON.parse(o),s=e.get(r);return ax(s?JSON.parse(s.serialized):null,n,a)?(e.set(r,{revision:a.revision,serialized:o}),!0):!1},async compareAndSwap(r,n,i){let o=cU(r,n,i);return(e.get(r)?.revision??null)!==n?!1:(e.set(r,{revision:(n??0)+1,serialized:o}),!0)}}}function Pt(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new k("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(S=>{if(S!=="run.revision")throw new k("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function r(S){for(let N of t){let C=S;for(let B of N){if(!C||typeof C!="object"||Array.isArray(C)||!Object.hasOwn(C,B))throw new k("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");C=C[B]}if(C!==S.revision)throw new k("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let n=xt.resolve(e.rootDir),i=xt.parse(n).root,o=xt.relative(i,n).replaceAll("\\","/");if(!o)throw new k("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let a={label:"RuntimeStore root",expected:"directory"},s=sU,c="checkpoint.json",l="comet.runtime-store-format.v2",u=".runtime-store-v2",f=S=>`${u}/${s(S)}`,d=S=>`.runtime-store-history/${s(S)}`,m="comet.runtime-store-format.v3",h="comet.runtime-store-snapshot.v2",p=".write.lock",g=/^[0-9]{16}\.json$/u;function v(){return{record:null,compacted:!1,legacyRevision:null,formatPresent:!1}}async function w(S,N){let C=await qe(n,S?`${S}/${N}`:N,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let B=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(C.bytes));return on(B),B}catch{throw new k("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function A(S,N,C){if(!S||typeof S!="object"||Array.isArray(S)||S.runId!==N||S.revision!==C||!Number.isSafeInteger(C)||C<1)throw new k("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");r(S)}async function b(S,N=!1,C=s(S),B=!0){if(uo(S),!(await ce(i,o,a)).exists)return v();let L=await ce(n,C,{label:"RuntimeStore run",expected:"directory"});if(!L.exists)return v();let q=await pn.lstat(L.target),Q=await pn.readdir(L.target,{withFileTypes:!0}),ae=await pn.lstat(L.target);if(await ce(i,`${o}/${C}`,a),!q.isDirectory()||q.isSymbolicLink()||!ae.isDirectory()||ae.isSymbolicLink()||!ht({dev:q.dev,ino:q.ino,birthtime:q.birthtimeMs},{dev:ae.dev,ino:ae.ino,birthtime:ae.birthtimeMs}))throw new k("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let ne=new Set,ve=[],fe=0;for(let V of Q){if((V.name===`${p}.contenders`||V.name==="legacy"&&C===f(S))&&V.isDirectory()&&!V.isSymbolicLink())continue;if(!V.isFile()||V.isSymbolicLink())throw new k("STORE_INVALID_ENTRY",`版本文件无效:${V.name}`);if(/^\..+\.tmp$/u.test(V.name)||V.name===p||[p+".sqlite",p+".sqlite-journal",p+".sqlite-wal",p+".sqlite-shm"].includes(V.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(V.name)||(ne.add(V.name),V.name===c))continue;if(!g.test(V.name))throw new k("STORE_INVALID_ENTRY",`版本文件无效:${V.name}`);let ke=Number(V.name.slice(0,-5));if(!Number.isSafeInteger(ke)||ke<1)throw new k("STORE_INVALID_ENTRY",`版本文件无效:${V.name}`);ve.push(V.name),fe=Math.max(fe,ke)}let y=!1;if([f(S),d(S)].includes(C)&&ve.length>0)throw new k("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(ne.has(c)){if(![f(S),d(S)].includes(C))throw new k("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let V=await w(C,c),ke=V?.record,ie=V?.legacyRevision;if(!V||![h,"comet.runtime-store-snapshot.v3"].includes(String(V.schema))||!ke||Object.keys(V).some(lt=>!["schema","record","hash","legacyRevision",...V.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(lt))||ie!==null&&(!Number.isSafeInteger(ie)||ie<1||ie>ke.revision)||V.hash!==T({record:ke,legacyRevision:ie,...V.schema==="comet.runtime-store-snapshot.v3"?{pool:V.pool}:{}}))throw new k("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let Se;try{Se=V.schema==="comet.runtime-store-snapshot.v3"?Gd(ke,V.pool,B):ke}catch(lt){throw new k("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${lt instanceof Error?lt.message:String(lt)}`)}return A(Se,S,Se.revision),{record:Se,compacted:!0,legacyRevision:ie,formatPresent:y}}if(!fe)return v();let E=new Map,$=V=>`${String(V).padStart(16,"0")}.json`,x=V=>ne.has($(V));async function P(V){if(E.has(V))return E.get(V);let ke=await w(C,$(V));return(V<=2||V===fe)&&E.set(V,ke),ke}async function z(V,ke=0,ie=fe){if(A(V,S,ie),N)for(let Se of ve){let lt=Number(Se.slice(0,-5));lt!==ke&&A(await P(lt),S,lt)}return{record:V,compacted:!1,legacyRevision:V.revision,formatPresent:!1}}let Y=await P(fe);if(fe===ve.length&&(Y?.schema!==tx||Y?.runId!==void 0))return z(Y);if(!x(1))throw new k("STORE_MISSING_REVISION","版本历史缺少 revision 1");let ee=null;for(let V of[1,2]){if(!x(V))break;let ke=await P(V);if(ke?.schema!==tx||"runId"in ke)continue;let ie=ke.record;if(ie&&r(ie),!ie||ie.runId!==S||!Number.isSafeInteger(ie.revision)||ie.revision<V||ke.hash!==T(ie)||Object.keys(ke).some(Se=>!["schema","record","hash"].includes(Se))||V===2&&Qn(await P(1))!==Qn(ox(ie,1,t)))throw new k("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");ee={slot:V,record:ie};break}let K=ee?.record.revision??0,te=ee?.slot??0,se=fe===te?K:fe;if(se<K||ve.length!==se-K+te||ve.some(V=>{let ke=Number(V.slice(0,-5));return ke>te&&ke<=K})){let V=K+1;for(;x(V);)V+=1;throw new k("STORE_MISSING_REVISION",`版本历史缺少 revision ${V}`)}return z(ee&&fe===ee.slot?ee.record:Y,te,ee&&fe===ee.slot?ee.record.revision:fe)}async function R(S){let N=await ce(n,s(S),{label:"RuntimeStore format",expected:"any"}),C=await ce(n,`${f(S)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(N.kind==="directory"&&C.exists&&(N=await ce(n,s(S),{label:"RuntimeStore format",expected:"any"})),N.kind==="directory"&&C.exists)throw new k("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let B=null;if(N.kind==="file"){let L=await w("",s(S));if(!L||L.runId!==S||(L.schema===l?!["pending","ready"].includes(L.state)||Object.keys(L).some(q=>!["schema","runId","state","writerProtocol"].includes(q)):L.schema!==m||!["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","存储协议版本不受支持");B=L}return{original:N,staged:C,marker:B}}function _(S){return Uc(S)?En(S,{cachePrefixes:!1}):T(S)}async function W(S,N){let C=await b(S,!1,f(S),!1),B=await b(S,!1,d(S),!1);if(!C.record&&!B.record||N.state==="closed"&&(C.record||!B.record))throw new k("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(C.record&&B.record){let q=await pn.lstat(xt.join(n,f(S),c)),Q=await pn.lstat(xt.join(n,d(S),c)),ae={dev:q.dev,ino:q.ino,birthtime:q.birthtimeMs},ne={dev:Q.dev,ino:Q.ino,birthtime:Q.birthtimeMs};if(!zs(ae,ne)||!ht(ae,ne))throw new k("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let L=B.record??C.record;if(L.revision!==N.revision||_(L)!==N.recordHash||C.record&&C.record!==L&&_(C.record)!==N.recordHash)throw new k("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:L,active:!!C.record,history:!!B.record}}async function O(S){if(uo(S),!(await ce(i,o,a)).exists)return"missing";let N=await R(S),C=await ce(n,`${f(S)}/${c}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),B=await ce(n,`${d(S)}/${c}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(N.marker?.schema===m){if(!C.exists&&!B.exists||N.marker.state==="closed"&&(C.exists||!B.exists))throw new k("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return N.marker.state}if(B.exists)throw new k("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return N.marker||C.exists||N.original.kind==="directory"||N.staged.exists?"active":"missing"}async function G(S,N,C){await Et(xt.join(n,s(S)),JSON.stringify({schema:m,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:S,state:N,revision:C.revision,recordHash:_(C)})+`
|
|
198
|
+
`,{containedRoot:n,requireAtomicPublication:!0})}async function Z(S){let N=(await R(S)).marker;if(!N||!["closing","reopening"].includes(N.state))return;let C=N.state==="closing",B=(await W(S,N)).record,L=await W(S,N),q=C?f(S):d(S),Q=C?d(S):f(S);await yt(n,Q,{label:"RuntimeStore 历史目标"});let ae=xt.join(n,q,c),ne=xt.join(n,Q,c),ve=C?L.active:L.history;(C?L.history:L.active)||(await ce(n,`${q}/${c}`,{label:"RuntimeStore 历史源",expected:"file"}),await ce(n,Q,{label:"RuntimeStore 历史目标",expected:"directory"}),await pn.link(ae,ne),await W(S,N)),await pe(xt.dirname(ne)),await pe(xt.dirname(xt.dirname(ne))),await pe(n),ve&&(await W(S,N),await Bo(ae,{containedRoot:n,beforeRemove:async()=>{await W(S,N)}}),await pe(xt.dirname(ae))),C?await G(S,"closed",B):await U(S,"ready",!1);let y=await F(S,!1);if(!y||y.revision!==B.revision||_(y)!==_(B))throw new k("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function J(S,N,C){return uo(S),Kf(N),Le(S,async()=>{await Z(S);let B=(await R(S)).marker,L;if(B?.schema===m){if(C&&B.state==="reopening")throw new k("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!C&&B.state==="closing")throw new k("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(L=(await W(S,B)).record,L.revision!==N)return!1;if(C&&B.state==="closed")return!0}else{if(L=(await ge(S,!1)).record,!L||L.revision!==N)return!1;if(!C)return!0}return await G(S,C?"closing":"reopening",L),await Z(S),!0})}async function F(S,N=!0){if(uo(S),!(await ce(i,o,a)).exists)return null;let C=await R(S);if(C.marker?.schema===m){let{record:q}=await W(S,C.marker);return N?cr(q):q}if((await b(S,!1,d(S),!1)).record)throw new k("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let L=await b(S,!1,f(S),N);if(L.record){if(!C.marker&&!(await R(S)).marker)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return L.record}if(C.original.kind==="directory"){let q=(await b(S)).record;if(!q&&(await R(S)).original.kind!=="directory")throw new k("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return q}if(C.marker?.state==="ready")throw new k("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(C.staged.exists){let q;try{q=(await b(S,!1,`${f(S)}/legacy`)).record}catch(Q){throw(await R(S)).marker?.state==="ready"?new k("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):Q}if(!q){let Q=await R(S);if(!Q.staged.exists||Q.marker?.state==="ready")throw new k("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return q}return null}async function X(S,N=!0){for(let C=0;;C+=1)try{return await F(S,N)}catch(B){let L=B instanceof Qt&&B.reason==="changed",q=["ENOENT","ENOTDIR"].includes(B.code??""),Q=B instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(B.message);if(!L&&!q&&!Q||C>=15)throw B}}async function U(S,N,C){await Et(xt.join(n,s(S)),JSON.stringify({schema:l,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:S,state:N})+`
|
|
199
|
+
`,{containedRoot:n,exclusive:C,requireAtomicPublication:!0})}async function pe(S){let N;try{N=await pn.open(S,"r"),await N.sync()}catch(C){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(C.code??""))throw C}finally{await N?.close()}}async function Le(S,N){if(await yt(i,o,a),(await ce(n,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new k("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await yt(n,f(S),{label:"RuntimeStore run"}),await pe(xt.join(n,u)),await pe(n);try{return e.singleWriter?await N():await YI(xt.join(n,f(S),p),N)}catch(B){throw["ENOTSUP","EOPNOTSUPP"].includes(B.code??"")?new k("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):B}}async function D(S,N,C,B=zf(N)){let L=xt.join(n,f(S)),q=C.legacyRevision,{encoded:Q,json:ae}=B,ne=Q.pool?{record:Q.record,legacyRevision:q,pool:Q.pool}:{record:N,legacyRevision:q},ve=Q.pool?"comet.runtime-store-snapshot.v3":h,fe=`{"schema":${JSON.stringify(ve)},${ae.slice(1,-1)},"legacyRevision":${JSON.stringify(q)},"hash":${JSON.stringify(T(ne))}}
|
|
200
|
+
`;await Et(xt.join(L,c),fe,{containedRoot:n,exclusive:!C.compacted,requireAtomicPublication:!0}),C.formatPresent||await U(S,"ready",!1)}async function re(S,N){if(N===null)return;let C=`${f(S)}/legacy`,B=await ce(n,C,{label:"RuntimeStore legacy",expected:"directory"});if(B.exists)try{for(let L of await pn.readdir(B.target,{withFileTypes:!0}))L.isFile()&&!L.isSymbolicLink()&&g.test(L.name)&&Number(L.name.slice(0,-5))<=N&&await Bo(xt.join(B.target,L.name),{containedRoot:n});await ce(n,C,{label:"RuntimeStore legacy",expected:"directory"}),await pn.rmdir(B.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)}
|
|
201
|
+
`)}}async function ge(S,N=!0){let C=(await R(S)).marker;if(C?.writerProtocol&&C.writerProtocol!==e.writerProtocol)throw new k("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await Z(S);let B=await R(S);if(B.marker?.schema===m)throw new k("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await b(S,!1,d(S),!1)).record)throw new k("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let q=await b(S,!1,f(S),N);if(q.record&&!B.marker)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(B.original.kind==="directory"){await b(S,!0);let ae=await pn.lstat(B.original.target);await ce(i,`${o}/${s(S)}`,a),await ce(n,f(S),a),await pn.rename(B.original.target,B.staged.target);let ne=await pn.lstat(B.staged.target);if(!ne.isDirectory()||ne.isSymbolicLink()||!ht({dev:ae.dev,ino:ae.ino,birthtime:ae.birthtimeMs},{dev:ne.dev,ino:ne.ino,birthtime:ne.birthtimeMs}))throw new k("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await pe(xt.join(n,f(S))),await pe(n),B=await R(S)}if(!B.marker){try{await U(S,"pending",!0)}catch(ae){throw["EEXIST","EISDIR","ENOTDIR"].includes(ae.code??"")?new k("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):ae}B=await R(S)}let Q=q;if(!Q.record&&B.marker?.state==="ready")throw new k("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!Q.record&&B.staged.exists?(Q=await b(S,!0,`${f(S)}/legacy`),Q.record&&(await D(S,Q.record,Q),Q={...Q,compacted:!0,formatPresent:!0})):Q.record&&B.marker?.state==="pending"&&await U(S,"ready",!1),Q.record&&(Q.formatPresent=!0,await re(S,Q.legacyRevision)),Q}return{queryScope:`file:${rx("sha256").update(n).digest("hex")}`,read:X,readProjection:S=>X(S,!1),readPartitionMetadata:O,settleRun:S=>Mn(async()=>await O(S)==="missing"?"missing":Le(S,async()=>{await Z(S);let N=(await R(S)).marker;return N&&e.writerProtocol&&N.writerProtocol!==e.writerProtocol&&await Et(xt.join(n,s(S)),JSON.stringify({...N,writerProtocol:e.writerProtocol})+`
|
|
202
|
+
`,{containedRoot:n,requireAtomicPublication:!0}),O(S)})),closeRun:(S,N)=>Mn(()=>J(S,N,!0)),reopenRun:(S,N)=>Mn(()=>J(S,N,!1)),async readDisposition(S){if(!await X(S,!1))return"missing";let C=(await R(S)).marker;return C?.schema===m?C.state:"active"},async restoreCheckpoint(S,N,C){let B=JSON.parse(ix(S,N,C));return r(B),Le(S,async()=>{let L=await ge(S);return ax(L.record,N,B,t)?(await D(S,B,L),!0):!1})},compareAndSwap:async(S,N,C)=>mt(S,N,C)(),prepareCompareAndSwap:mt};function mt(S,N,C){nx(S,N,C,!1),r(C);let{json:B}=zf(C),L=JSON.parse(B);return()=>Le(S,async()=>{let q=await ge(S,!1);return(q.record?.revision??null)!==N?!1:(await D(S,L.record,q,{encoded:L,json:B}),!0)})}}var tx,ky=I(()=>{"use strict";Ca();ji();XI();Nn();ot();lr();qn();rn();yy();Lo();tx="comet.runtime-store-checkpoint.v1"});import{createHash as sx}from"node:crypto";import{promises as ki}from"node:fs";import fo from"node:path";async function Ay(e){let t=fo.resolve(e.rootDir),r=fo.parse(t).root,n=fo.relative(r,t).replaceAll("\\","/");if(!n)throw new k("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");if(!(await ce(r,n,{label:"RuntimeStore discovery",expected:"directory"})).exists)return[];let i=[];for(let o of await ki.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 ce(t,o.name,{label:"RuntimeStore checkpoint directory",expected:"directory"});for(let s of await ki.readdir(a.target))i.push(s);continue}i.push(o.name)}return[...new Set(i)].sort((o,a)=>o.localeCompare(a))}async function lU(e,t,r,n=!1){let i=fo.resolve(e.rootDir),o=r?[...new Set(r)].filter(d=>d&&d!=="."&&d!==".."&&!d.includes("/")&&!d.includes("\\")):await Ay(e),a=r?new Set(r):null,s=[],c=async d=>{let m=await ce(i,d,{label:"RuntimeStore source",expected:"file"});if(!m.exists)return null;let h=await ki.lstat(m.target);return[d,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.dev]},l=async d=>{let m=await ce(i,d,{label:"RuntimeStore source directory",expected:"directory"});if(!m.exists)return null;let h=await ki.lstat(m.target),p=(await ki.readdir(m.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,p]},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 m=>{if(a&&!a.has(m))return;let h=await ki.lstat(fo.join(i,m)).catch(()=>null),p={name:m,isFile:()=>h?.isFile(),isDirectory:()=>h?.isDirectory(),isSymbolicLink:()=>h?.isSymbolicLink()},g=null,v=!1;try{if(!/^[a-f0-9]{64}$/u.test(p.name)||p.isSymbolicLink())throw new k("STORE_INVALID_ENTRY","RuntimeStore 目录含异常项目");let w;if(p.isFile()){let R=await u(p.name);if(!["comet.runtime-store-format.v2","comet.runtime-store-format.v3"].includes(R.schema))throw new k("STORE_CORRUPT_RECORD","RuntimeStore 格式标记无效");if(w=R.runId,n&&R.schema==="comet.runtime-store-format.v3"&&R.state==="closed"){if(!Number.isSafeInteger(R.revision)||R.revision<1||R.writerProtocol!==void 0&&R.writerProtocol!=="application-holder-v1"||typeof R.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(R.recordHash)||Object.keys(R).some(O=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(O)))throw new k("STORE_CORRUPT_RECORD","RuntimeStore 历史标记损坏");let _=await ce(i,`.runtime-store-v2/${p.name}/checkpoint.json`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),W=await ce(i,`.runtime-store-history/${p.name}/checkpoint.json`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(_.exists||!W.exists)throw new k("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");v=!0}}else if(p.isDirectory()){await ce(i,p.name,{label:"RuntimeStore legacy directory",expected:"directory"});let R=(await ki.readdir(fo.join(i,p.name))).filter(W=>/^[0-9]{16}\.json$/u.test(W)).sort();if(!R.length)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 旧记录缺少版本");let _=await u(`${p.name}/${R.at(-1)}`);w=_.schema==="comet.runtime-store-checkpoint.v1"?_.record?.runId:_.runId}else throw new k("STORE_INVALID_ENTRY","RuntimeStore 项目类型无效");if(typeof w!="string"||!w.trim()||sx("sha256").update(JSON.stringify(w)).digest("hex")!==p.name)throw new k("STORE_CORRUPT_RECORD","RuntimeStore 记录身份与目录不匹配");if(g=w,v)return;let A=t?p.isFile()?[p.name,`.runtime-store-v2/${p.name}/checkpoint.json`,`.runtime-store-history/${p.name}/checkpoint.json`]:(await ki.readdir(fo.join(i,p.name))).filter(R=>/^[0-9]{16}\.json$/u.test(R)).sort().map(R=>`${p.name}/${R}`):[],b=sx("sha256").update(JSON.stringify({files:await Promise.all(A.map(c)),directories:t?await Promise.all((p.isFile()?[`.runtime-store-v2/${p.name}`,`.runtime-store-history/${p.name}`]:[p.name]).map(l)):[]})).digest("hex");s.push({storageKey:p.name,runId:g,fingerprint:b,error:null})}catch(w){s.push({storageKey:p.name,runId:g,fingerprint:JSON.stringify(await ki.lstat(fo.join(i,p.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,m)=>d.storageKey.localeCompare(m.storageKey))}async function by(e){return lU(e,!0)}var cx=I(()=>{"use strict";ot();ky();rn()});function Yf(e){return uU.test(e)?e:`portable-${T(e)}`}function Xf(e){let t=ex(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:T(t)}:e}function dU(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=Yf(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=T(n.outcome))}}return t.status==="running"&&(n.status="unknown",n.reason="Portable recovery requires reconciliation of external execution"),n})}}function ia(e){let t=sn(dU(e),e.runId),r=T(t);return{schema:lx,hash:r,run:t,sourceRevision:e.revision,sourceHash:T({hash:r,sourceRevision:e.revision})}}function pU(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`);on(e);let i=e;if(![lx,"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"&&T({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"?Gd(i.run,i.pool,!n):i.run;if((n?En:T)(o)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let a=n?rf(o,t,fU):sn(o,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==T({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 oa(e,t,r={}){return pU(e,t,r)}function Ry(e){let t=structuredClone(e);for(let r of t.actions)r.claim&&!r.executionOrigin&&(r.executionOrigin={workflow:{...e.workflow}});return t}var mn,lx,uU,fU,ux=I(()=>{"use strict";zc();lr();yy();Lo();mn="run_checkpoint",lx="comet.workflow-run-checkpoint.v1",uU=/^portable-[a-f0-9]{64}$/u;fU={hash:En,visitResults:zd,validateOrigins:Kd}});var Ze=I(()=>{"use strict";qI();FI();dy();ky();cx();zc();rn();lr();ux();hv()});import{promises as fx}from"node:fs";import{AsyncLocalStorage as vU}from"node:async_hooks";import nr from"node:path";function fr(e,t,r="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!px.test(t))throw new Error(`Invalid change name: ${t}`);return`${r==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function Zf(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===Hr&&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)&&!Sy.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 Yn(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 Zf(o,r,n)}function mx(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function hx(e,t){return fr(e,t),`change-owner-records/${e}/${t}.json`}async function ep(e,t,r){let n;try{n=await qe(e,hx(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:Zf(i,t,r),identity:mx(n.stat)}}async function gx(e,t,r){let n=await Od(e,"change owner bindings"),i=async s=>{try{let{stat:c}=await n.stat(fr(t,r,s));return mx(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 vx(e,t,r=!1){let n=await gx(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 ep(e,t.workflow,t.change);if(i?.identity&&i.identity===(n.active??n.history))return;let o=hx(t.workflow,t.change);await yt(e,nr.posix.dirname(o),{label:"canonical change runtime owners"});let a=fr(t.workflow,t.change,n.active?"active":"history");try{await nE(nr.join(e,a),nr.join(e,o),{containedRoot:e})}catch(s){if(!["ENOTSUP","EOPNOTSUPP"].includes(s.code??""))throw s}}async function yU(e,t,r){let n;try{n=await ep(e,t,r)}catch(o){if(o instanceof Qt&&o.reason==="changed")return null;throw o}if(!n?.identity)return null;let i=await gx(e,t,r);return i.active===n.identity&&i.history===null||i.history===n.identity&&i.active===null?n:null}async function kx(e){let t=aa.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??wU(e)}async function Ax(e,t,r=!1){let n=aa.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 aa.run(i,()=>Mn(()=>r?Iu(t):t())),a=wx();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 Ny(e,t,r){let n=await yU(e,t,r);return n?n.owner:Ax([e],async()=>{let i=await Yn(e,fr(t,r),t,r),o=await Yn(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 Tn(e,t,r,n={}){if(fr(t,r),!n.readOnly)return aa.run(null,()=>Mn(async()=>Ny(await Wi(e),t,r)));let[i,o]=await kx(e),a=nr.parse(i).root,c=(await ce(a,nr.relative(a,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await Ny(i,t,r):null,l=o?await Ny(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 dx(e,t,r,n={}){let i=await Tn(e,t,r,n),o=i?.format==="sdk"?i:null,a=aa.getStore();return n.readOnly&&a?.active&&a.owners.set(yx(e,t,r),o),o}async function tt(e,t,r,n={}){if(!n.readOnly||aa.getStore()?.active)return dx(e,t,r,n);let i=wx(),o=yx(e,t,r);if(i.has(o))return i.get(o);let a=dx(e,t,r,n).catch(s=>{throw i.get(o)===a&&i.delete(o),s});return i.set(o,a),a}async function kU(e,t,r,n=!1){fr(t,"validate");let i=r.readOnly?await kx(e):[await Wi(e)],o=async()=>{let a={active:new Set,history:new Set};for(let s of i)for(let c of["active","history"]){let l=nr.parse(s).root,u=nr.posix.dirname(fr(t,"validate",c)),f=await ce(l,nr.relative(l,nr.join(s,u)).replaceAll("\\","/"),{label:`${t} ${c} change runtime owners`,expected:"directory"});if(!f.exists)continue;let d=await fx.readdir(f.target,{withFileTypes:!0});for(let m of d){if(m.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(m.name))continue;if(t==="classic"&&c==="active"){let p=/^([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(m.isFile()&&p.test(m.name)||m.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(m.name))continue}if(!m.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${m.name}`);let h=m.name.slice(0,-5);if(!m.isFile()||!px.test(h))throw new Error(`Invalid ${t} change runtime owner entry: ${m.name}`);a[c].add(h)}}return a};return n?o():Ax(i,o)}function Cl(e,t){return JSON.stringify(Object.entries(e).sort())===JSON.stringify(Object.entries(t).sort())}async function Ey(e,t,r){return Lb(),aa.run(null,()=>Mn(async()=>{let n=await ci(e);return fr(t.workflow,t.change),r(n)}))}async function AU(e,t,r){let n=Zf(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 Ey(e,n,i=>bx(i,n,r))}async function bU(e,t){let r=nr.posix.dirname(t).split("/");for(let n=r.length;n>=0;n-=1){let i=nr.join(e,...r.slice(0,n)),o;try{o=await fx.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 bx(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 Yn(e,a,t.workflow,t.change),l=await Yn(e,s,t.workflow,t.change);if(!c&&!l||c&&!Cl(c,i)||l&&!Cl(l,i))throw new Error(`Change runtime owner identity changed for ${t.workflow}/${t.change}`);l||(await yt(e,nr.posix.dirname(s),{label:"change runtime owner directory"}),await Et(nr.join(e,s),`${JSON.stringify(i)}
|
|
203
|
+
`,{containedRoot:e,exclusive:!0,requireAtomicPublication:!0})),await bU(e,s),c&&await Bo(nr.join(e,a),{containedRoot:e,beforeRemove:async()=>{let u=await Yn(e,a,t.workflow,t.change),f=await Yn(e,s,t.workflow,t.change);if(!u||!f||!Cl(u,i)||!Cl(f,i))throw new Error("Change runtime owner changed during partition move")}}),n||await ep(e,t.workflow,t.change),await vx(e,t,n)}async function _y(e,t){await AU(e,t,"history")}async function Rx(e,t,r){return Ey(e,{workflow:t,change:r},async n=>{let i=await Yn(n,fr(t,r),t,r),o=await Yn(n,fr(t,r,"history"),t,r);if(i&&o&&!Cl(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 bx(n,a,"active",!0),a})}async function Nx(e,t,r={}){let n=fr(t.workflow,t.change),i=Zf(t,t.workflow,t.change);return Ey(e,i,async o=>{if(await Yn(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 yt(o,nr.posix.dirname(n),{label:"change runtime owner directory"});try{await Et(nr.join(o,...n.split("/")),`${JSON.stringify(i)}
|
|
204
|
+
`,{containedRoot:o,exclusive:!0,requireAtomicPublication:!0})}catch(s){if(s.code!=="EEXIST")throw s;let c=await Yn(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 ep(o,t.workflow,t.change))&&await vx(o,i),i})}function Xn(e,t,r={}){return Nx(e,t,r)}function Cy(e,t){return Nx(e,t)}var Hr,Sy,wU,px,aa,wx,yx,pX,pr=I(()=>{"use strict";Lr();qn();Nn();ji();ot();Lr();Hr="comet.change-owner.v1",Sy=["native","classic-full","classic-hotfix","classic-tweak"],wU=Zr("changeOwnerRuntimeRoots",e=>eh(e)),px=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;aa=new vU,wx=si("verifiedOwnerBatchResults",()=>new Map),yx=(e,t,r)=>`${JSON.stringify([e,t])}\0${r}`;pX=Zr("changeOwnerPartitions",kU)});var Iy=I(()=>{"use strict"});var Sx=I(()=>{"use strict";ot();qn();Ze();pr();Lr();Iy()});import{promises as Ex}from"node:fs";import NU from"node:path";function sa(e){throw new k("STORE_INDEX_CORRUPT",e)}async function fs(e,t){let r=await ce(e,`applications/${t}`,{expected:"directory",label:"应用 Store 身份"});if(!r.exists)return null;let n=await Ex.lstat(r.target,{bigint:!0});return`${n.dev}:${n.ino}:${n.birthtimeNs}`}async function Il(e){if(!(await ce(e,xy,{expected:"file",label:"工作区应用成员清单"})).exists)return null;try{let{checksum:t,...r}=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await qe(e,xy,Number.MAX_SAFE_INTEGER,{label:"工作区应用成员清单"})).bytes));return(r.schema!==_x||!Array.isArray(r.applications)||!r.applications.every(Py)||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"))||T(r)!==t)&&sa("工作区应用成员清单损坏"),r}catch(t){return sa(`工作区应用成员清单无法读取:${t instanceof Error?t.message:String(t)}`)}}async function Oy(e,t){await Et(NU.join(e,xy),JSON.stringify({...t,checksum:T(t)})+`
|
|
205
|
+
`,{containedRoot:e,requireAtomicPublication:!0})}async function Cx(e,t,r,n=!1){let i=await yt(e,"applications",{label:"工作区应用 Store"}),o=await Ex.readdir(i,{withFileTypes:!0});!n&&o.some(u=>!Py(u.name)||!u.isDirectory())&&sa("工作区应用分区无法确认;请保留现场并检查,不能忽略可能仍占用资源的应用");let a=o.filter(u=>Py(u.name)&&u.isDirectory()).map(u=>u.name).sort(),s=await Il(e),c=s??{schema:_x,applications:[],identities:{},claims:{}};for(let u of c.applications)n||await fs(e,u)!==c.identities[u]&&sa(`已登记应用 ${u} 的 Store 目录缺失或身份改变;请恢复原目录或完整的 portable checkpoint`);a.includes(t)||(await yt(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 fs(e,u),c.applications.push(u),l=!0);return l&&(c.applications.sort(),await Oy(e,c)),c.applications}async function $y(e,t,r,n=!1){if(!r.length)return;let i=await Il(e);(!i||!n&&await fs(e,t)!==i.identities[t])&&sa("领取前必须确认工作区应用成员身份");for(let o of r)i.claims[t].some(a=>Ty(a,o))||i.claims[t].push(o);await Oy(e,i)}async function Ix(e,t,r,n){let i=await Il(e);if(!(!i||await fs(e,t)===i.identities[t]))for(let o of i.claims[t]??[])o.runId===r&&!n.some(a=>Ty(o,a))&&sa(`portable checkpoint 缺少原执行身份:${r} / ${o.actionId};必须保留未知执行并核对停止事实`)}async function jy(e,t,r,n=!1){let i=await Il(e);if(!i||!i.applications.includes(t))return;let o=await fs(e,t),a=await r(t);if(o!==i.identities[t]){if((!n||!o)&&sa("工作区应用 Store 身份已改变"),i.claims[t].some(s=>!a.some(c=>Ty(s,c))))return;i.identities[t]=o}i.claims[t]=a,await Oy(e,i)}async function xx(e,t){let r=await Il(e);if(!r?.applications.includes(t))return!1;try{return await fs(e,t)===r.identities[t]}catch{return!1}}var xy,_x,Py,Ty,Px=I(()=>{"use strict";Ze();Nn();ot();xy="application-scope-locks/workspace-applications.json",_x="comet.workspace-applications.v1",Py=e=>typeof e=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e);Ty=(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 Dy(e,t="@"){if(!xe)return By.then(()=>Dy(e,t));let r=e.length+1,n=(xe.__heap_base.value||xe.__heap_base)+4*r-xe.memory.buffer.byteLength;n>0&&xe.memory.grow(Math.ceil(n/65536));let i=xe.sa(r-1);if(typeof Buffer<"u"?Buffer.from(xe.memory.buffer,i,2*(r-1)).write(e,"utf16le"):(SU?_U:EU)(e,new Uint16Array(xe.memory.buffer,i,r)),!xe.parse())throw Object.assign(new Error(`Parse error ${t}:${e.slice(0,xe.e()).split(`
|
|
206
|
+
`).length}:${xe.e()-e.lastIndexOf(`
|
|
207
|
+
`,xe.e()-1)}`),{idx:xe.e()});let o=[],a=[];for(;xe.ri();){let l=xe.is(),u=xe.ie(),f=xe.it(),d=xe.ai(),m=xe.id(),h=xe.ss(),p=xe.se(),g;xe.ip()&&(g=s(e.slice(m===-1?l-1:l,m===-1?u+1:u)));let v=null;for(v=[],xe.rsa();xe.ra();){let w=xe.aks(),A=xe.ake(),b=xe.avs(),R=xe.ave();v.push([c(e.slice(w,A)),c(e.slice(b,R))])}v.length===0&&(v=null),o.push({n:g,t:f,s:l,e:u,ss:h,se:p,d:m,a:d,at:v})}for(;xe.re();){let l=xe.es(),u=xe.ee(),f=xe.els(),d=xe.ele(),m=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:xe.ess(),n:h,ln:m})}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,!!xe.f(),!!xe.ms()]}function EU(e,t){let r=e.length,n=0;for(;n<r;){let i=e.charCodeAt(n);t[n++]=(255&i)<<8|i>>>8}}function _U(e,t){let r=e.length,n=0;for(;n<r;)t[n]=e.charCodeAt(n++)}var PX,SU,xe,CU,By,Tx=I(()=>{"use strict";PX=(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})({}),SU=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;CU=()=>{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},By=WebAssembly.compile(CU()).then(WebAssembly.instantiate).then(({exports:e})=>{xe=e})});import{existsSync as IU,readFileSync as xU}from"fs";import Ox from"path";import{fileURLToPath as PU}from"url";function TU(){return"0.5.3"}function $x(){return Wy===null&&(Wy=TU()),Wy}var Wy,OU,DX,jx=I(()=>{"use strict";Wy=null,OU="@rpamis/comet",DX=`https://registry.npmjs.org/${OU}/latest`});import{promises as $U}from"node:fs";import jU from"node:path";function rp(e){return jU.join(e,".comet","current-change.json")}function DU(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Dx(e){return e===null||typeof e=="string"}function BU(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(!DU(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&&!Dx(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:tp,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==tp)throw new Error(`current change selection schema must be ${tp}`);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(!Dx(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 Qr(e){let t;try{let n=rp(e),{bytes:i}=await $i(n,Bx,{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",...BU(t)}}async function Ly(e){await $U.rm(rp(e),{force:!0})}async function ps(e,t,r){let n=await Qr(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==r?!1:(await Ly(e),!0)}var tp,Bx,WU,po=I(()=>{"use strict";qn();ji();tp="comet.selection.v2",Bx=Number.MAX_SAFE_INTEGER;WU=Zr("readCometCurrentSelection",e=>Qr(e))});function Fy(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function Qx(e){ua=e}function ms(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 Pe(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(ir.caret,"$1"),r=r.replace(i,a),n},getRegex:()=>new RegExp(r,t)};return n}function Zn(e,t){if(t){if(ir.escapeTest.test(e))return e.replace(ir.escapeReplace,Vx)}else if(ir.escapeTestNoEncode.test(e))return e.replace(ir.escapeReplaceNoEncode,Vx);return e}function Mx(e){try{e=encodeURI(e).replace(ir.percentDecode,"%")}catch{return null}return e}function qx(e,t){let r=e.replace(ir.findPipe,(o,a,s)=>{let c=!1,l=a;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),n=r.split(ir.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(ir.slashPipe,"|");return n}function mo(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 Fx(e){let t=e.split(`
|
|
208
|
+
`),r=t.length-1;for(;r>=0&&ir.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
209
|
+
`)}function P2(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 T2(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 Hx(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 O2(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
|
|
210
|
+
`).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(`
|
|
211
|
+
`)}function et(e,t){return la.parse(e,t)}function j2(...e){return la.use(...e),et.defaults=la.defaults,Qx(et.defaults),et}var ua,ca,LU,ir,VU,MU,qU,Tl,FU,Hy,Ux,Jx,HU,Qy,QU,Uy,UU,JU,sp,Jy,zU,zx,KU,GU,YU,zy,Wx,XU,ZU,e2,t2,Kx,r2,Ai,hs,Ol,n2,i2,Gx,o2,a2,s2,Yx,c2,l2,u2,d2,Xx,f2,p2,m2,h2,g2,v2,w2,y2,k2,A2,b2,R2,N2,S2,ip,E2,Zx,eP,_2,Lx,Ky,C2,Vy,I2,np,xl,x2,Vx,op,mr,ap,Gy,On,Pl,$2,la,FX,HX,tP,QX,UX,JX,Yy=I(()=>{"use strict";ua=Fy();ca={exec:()=>null};LU=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),ir={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:ms(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ms(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ms(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ms(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ms(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ms(e=>new RegExp(`^ {0,${e}}>`))},VU=/^(?:[ \t]*(?:\n|$))+/,MU=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,qU=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Tl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,FU=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Hy=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ux=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Jx=Pe(Ux).replace(/bull/g,Hy).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(),HU=Pe(Ux).replace(/bull/g,Hy).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(),Qy=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,QU=/^[^\n]+/,Uy=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,UU=Pe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Uy).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),JU=Pe(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Hy).getRegex(),sp="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",Jy=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zU=Pe("^ {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",Jy).replace("tag",sp).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),zx=e=>Pe(Qy).replace("hr",Tl).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",sp).getRegex(),KU=zx(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),GU=zx(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),YU=Pe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",GU).getRegex(),zy={blockquote:YU,code:MU,def:UU,fences:qU,heading:FU,hr:Tl,html:zU,lheading:Jx,list:JU,newline:VU,paragraph:KU,table:ca,text:QU},Wx=Pe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Tl).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",sp).getRegex(),XU={...zy,lheading:HU,table:Wx,paragraph:Pe(Qy).replace("hr",Tl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Wx).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",sp).getRegex()},ZU={...zy,html:Pe(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Jy).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:Pe(Qy).replace("hr",Tl).replace("heading",` *#{1,6} *[^
|
|
212
|
+
]`).replace("lheading",Jx).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},e2=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,t2=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Kx=/^( {2,}|\\)\n(?!\s*$)/,r2=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ai=/[\p{P}\p{S}]/u,hs=/[\s\p{P}\p{S}]/u,Ol=/[^\s\p{P}\p{S}]/u,n2=Pe(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,hs).getRegex(),i2=/[\p{Pi}\p{Ps}"']/u,Gx=/(?!~)[\p{P}\p{S}]/u,o2=/(?!~)[\s\p{P}\p{S}]/u,a2=/(?:[^\s\p{P}\p{S}]|~)/u,s2=Pe(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",LU?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Yx=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,c2=Pe(Yx,"u").replace(/punct/g,Ai).getRegex(),l2=Pe(Yx,"u").replace(/punct/g,Gx).getRegex(),u2=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,d2=Pe(u2,"u").replace(/openQuote/g,i2).replace(/punct/g,Ai).getRegex(),Xx="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",f2=Pe(Xx,"gu").replace(/notPunctSpace/g,Ol).replace(/punctSpace/g,hs).replace(/punct/g,Ai).getRegex(),p2=Pe(Xx,"gu").replace(/notPunctSpace/g,a2).replace(/punctSpace/g,o2).replace(/punct/g,Gx).getRegex(),m2="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",h2=Pe(m2,"gu").replace(/notPunctSpace/g,Ol).replace(/punctSpace/g,hs).replace(/punct/g,Ai).getRegex(),g2=Pe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ol).replace(/punctSpace/g,hs).replace(/punct/g,Ai).getRegex(),v2="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",w2=Pe(v2,"gu").replace(/notPunctSpace/g,Ol).replace(/punctSpace/g,hs).replace(/punct/g,Ai).getRegex(),y2=Pe(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ai).getRegex(),k2="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",A2=Pe(k2,"gu").replace(/notPunctSpace/g,Ol).replace(/punctSpace/g,hs).replace(/punct/g,Ai).getRegex(),b2=Pe(/\\(punct)/,"gu").replace(/punct/g,Ai).getRegex(),R2=Pe(/^<(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(),N2=Pe(Jy).replace("(?:-->|$)","-->").getRegex(),S2=Pe("^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",N2).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ip=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,E2=Pe(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ip).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zx=Pe(/^!?\[(label)\]\[(ref)\]/).replace("label",ip).replace("ref",Uy).getRegex(),eP=Pe(/^!?\[(ref)\](?:\[\])?/).replace("ref",Uy).getRegex(),_2=Pe("reflink|nolink(?!\\()","g").replace("reflink",Zx).replace("nolink",eP).getRegex(),Lx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ky={_backpedal:ca,anyPunctuation:b2,autolink:R2,blockSkip:s2,br:Kx,code:t2,del:ca,delLDelim:ca,delRDelim:ca,emStrongLDelim:c2,emStrongRDelimAst:f2,emStrongRDelimUnd:g2,escape:e2,link:E2,nolink:eP,punctuation:n2,reflink:Zx,reflinkSearch:_2,tag:S2,text:r2,url:ca},C2={...Ky,emStrongLDelim:d2,emStrongRDelimAst:h2,emStrongRDelimUnd:w2,link:Pe(/^!?\[(label)\]\((.*?)\)/).replace("label",ip).getRegex(),reflink:Pe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ip).getRegex()},Vy={...Ky,emStrongRDelimAst:p2,emStrongLDelim:l2,delLDelim:y2,delRDelim:A2,url:Pe(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Lx).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:Pe(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Lx).getRegex()},I2={...Vy,br:Pe(Kx).replace("{2,}","*").getRegex(),text:Pe(Vy.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},np={normal:zy,gfm:XU,pedantic:ZU},xl={normal:Ky,gfm:Vy,breaks:I2,pedantic:C2},x2={"&":"&","<":"<",">":">",'"':""","'":"'"},Vx=e=>x2[e];op=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]:Fx(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=O2(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=mo(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:mo(t[0],`
|
|
213
|
+
`),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:mo(t[0],`
|
|
214
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=mo(t[0],`
|
|
215
|
+
`).split(`
|
|
216
|
+
`),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(`
|
|
217
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
218
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
219
|
+
${l}`:l,i=i?`${i}
|
|
220
|
+
${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 m=d,h=r.join(`
|
|
221
|
+
`),p=m.raw+`
|
|
222
|
+
`+h.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(p);o[o.length-1]=g,n=`${n}
|
|
223
|
+
${h}`,i=i.substring(0,i.length-m.text.length)+g.text;break}else if(d?.type==="list"){let m=d,h=m.raw+`
|
|
224
|
+
`+r.join(`
|
|
225
|
+
`),p=this.list(h);o[o.length-1]=p,n=n.substring(0,n.length-d.raw.length)+p.raw,i=i.substring(0,i.length-m.raw.length)+p.raw,r=h.substring(o.at(-1).raw.length).split(`
|
|
226
|
+
`);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=T2(t[2].split(`
|
|
227
|
+
`,1)[0],t[1].length),d=e.split(`
|
|
228
|
+
`,1)[0],m=!f.trim(),h=0;if(this.options.pedantic?(h=2,u=f.trimStart()):m?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),m&&this.rules.other.blankLine.test(d)&&(l+=d+`
|
|
229
|
+
`,e=e.substring(d.length+1),c=!0),!c){let p=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),b=this.rules.other.blockquoteBeginRegex(h);for(;e;){let R=e.split(`
|
|
230
|
+
`,1)[0],_;if(d=R,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),_=d):_=d.replace(this.rules.other.tabCharGlobal," "),v.test(d)||w.test(d)||A.test(d)||b.test(d)||p.test(d)||g.test(d))break;if(_.search(this.rules.other.nonSpaceChar)>=h||!d.trim())u+=`
|
|
231
|
+
`+_.slice(h);else{if(m||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||v.test(f)||w.test(f)||g.test(f))break;u+=`
|
|
232
|
+
`+d}m=!d.trim(),l+=R+`
|
|
233
|
+
`,e=e.substring(R.length+1),f=_.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=Fx(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:mo(t[0],`
|
|
234
|
+
`),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=qx(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
235
|
+
`):[],o={type:"table",raw:mo(t[0],`
|
|
236
|
+
`),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(qx(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:mo(t[0],`
|
|
237
|
+
`),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)===`
|
|
238
|
+
`?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=mo(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=P2(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)),Hx(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 Hx(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,m=e.slice(0,i+n.index+d+a);if(Math.min(i,a)%2){let p=m.slice(1,-1);return{type:"em",raw:m,text:p,tokens:this.lexer.inlineTokens(p)}}let h=m.slice(2,-2);return{type:"strong",raw:m,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 My{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 op,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:ir,block:np.normal,inline:xl.normal};this.options.pedantic?(r.block=np.pedantic,r.inline=xl.pedantic):this.options.gfm&&(r.block=np.gfm,this.options.breaks?r.inline=xl.breaks:r.inline=xl.gfm),this.tokenizer.rules=r}static get rules(){return{block:np,inline:xl}}static lex(t,r){return new My(r).lex(t)}static lexInline(t,r){return new My(r).inlineTokens(t)}lex(t){t=t.replace(ir.carriageReturn,`
|
|
239
|
+
`),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(ir.tabCharGlobal," ").replace(ir.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+=`
|
|
240
|
+
`: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(`
|
|
241
|
+
`)?"":`
|
|
242
|
+
`)+o.raw,s.text+=`
|
|
243
|
+
`+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(`
|
|
244
|
+
`)?"":`
|
|
245
|
+
`)+o.raw,s.text+=`
|
|
246
|
+
`+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(`
|
|
247
|
+
`)?"":`
|
|
248
|
+
`)+o.raw,s.text+=`
|
|
249
|
+
`+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(`
|
|
250
|
+
`)?"":`
|
|
251
|
+
`)+o.raw,s.text+=`
|
|
252
|
+
`+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)}},ap=class{options;parser;constructor(e){this.options=e||ua}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(ir.notSpaceStart)?.[0],i=e.replace(ir.endingNewline,"")+`
|
|
253
|
+
`;return n?'<pre><code class="language-'+Zn(n)+'">'+(r?i:Zn(i,!0))+`</code></pre>
|
|
254
|
+
`:"<pre><code>"+(r?i:Zn(i,!0))+`</code></pre>
|
|
255
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
256
|
+
${this.parser.parse(e)}</blockquote>
|
|
257
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
258
|
+
`}hr(e){return`<hr>
|
|
259
|
+
`}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+`>
|
|
260
|
+
`+n+"</"+i+`>
|
|
261
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
262
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
263
|
+
`}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>
|
|
264
|
+
<thead>
|
|
265
|
+
`+t+`</thead>
|
|
266
|
+
`+n+`</table>
|
|
267
|
+
`}tablerow({text:e}){return`<tr>
|
|
268
|
+
${e}</tr>
|
|
269
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
270
|
+
`}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>${Zn(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=Mx(e);if(i===null)return n;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+Zn(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=Mx(e);if(i===null)return Zn(r);e=i;let o=`<img src="${e}" alt="${Zn(r)}"`;return t&&(o+=` title="${Zn(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Zn(e.text)}},Gy=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 qy{options;renderer;textRenderer;constructor(t){this.options=t||ua,this.options.renderer=this.options.renderer||new ap,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Gy}static parse(t,r){return new qy(r).parse(t)}static parseInline(t,r){return new qy(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}},Pl=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}},$2=class{defaults=Fy();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=On;Renderer=ap;TextRenderer=Gy;Lexer=mr;Tokenizer=op;Hooks=Pl;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 ap(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 op(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 Pl;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];Pl.passThroughHooks.has(o)?i[a]=l=>{if(this.defaults.async&&Pl.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+=`
|
|
271
|
+
Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+Zn(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},la=new $2;et.options=et.setOptions=function(e){return la.setOptions(e),et.defaults=la.defaults,Qx(et.defaults),et};et.getDefaults=Fy;et.defaults=ua;et.use=j2;et.walkTokens=function(e,t){return la.walkTokens(e,t)};et.parseInline=la.parseInline;et.Parser=On;et.parser=On.parse;et.Renderer=ap;et.TextRenderer=Gy;et.Lexer=mr;et.lexer=mr.lex;et.Tokenizer=op;et.Hooks=Pl;et.parse=et;FX=et.options,HX=et.setOptions,tP=et.walkTokens,QX=et.parseInline,UX=On.parse,JX=mr.lex});import{promises as rP}from"node:fs";import gs from"node:path";import{createHash as D2}from"node:crypto";function H(e){throw new k("INVALID_WORKFLOW",`${e};请修正适配契约或恢复已固定的依赖后继续`)}async function ho(e,t={}){let r={},n=async i=>{let o=await rP.readdir(gs.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()&&H(`依赖不允许符号链接:${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 H(`依赖包含非常规文件:${s}`)}};return await n(""),!t.allowEmpty&&Object.keys(r).length===0&&H("依赖目录为空"),r}function go(e){return T(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,D2("sha256").update(Buffer.from(r,"base64")).digest("hex")])))}function B2(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Buffer.from(r,"base64").toString("utf8")]))}function W2(e,t){for(let[l,u]of[[e,"输入"],[t,"输出"]])(!l||typeof l!="object"||Array.isArray(l))&&H(`${u} 必须提供可检查的 JSON Schema`),l.$async===!0&&H(`${u} 不支持异步 Schema,请注册实际 SDK 验证器`);let r=JSON.stringify([e,t]),n=$l.get(r);if(n)return n;let[i,o]=JSON.parse(r),a=new nP.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 $l.size>=64&&$l.delete($l.keys().next().value),$l.set(r,c),c}async function L2(e){let t=await rP.realpath(e),r=await ho(t),n=B2(r);n["SKILL.md"]?.trim()||H(`Skill 缺少真实 SKILL.md:${e}`);for(let[i,o]of Object.entries(n)){if(!i.endsWith(".md"))continue;let a=[];tP(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{H(`Skill 引用路径编码无效:${i} -> ${s}`)}if(!c)continue;let l=gs.posix.normalize(gs.posix.join(gs.posix.dirname(i),c));(l===".."||l.startsWith("../")||gs.posix.isAbsolute(c))&&H(`Skill 引用越过依赖目录:${i} -> ${s}`),!Object.hasOwn(n,l)&&!Object.keys(n).some(u=>u.startsWith(`${l}/`))&&H(`Skill 引用资源缺失:${i} -> ${s}`)}}return{root:t,files:n,contentHash:go(r)}}async function Xy(e,t){(!e||typeof e.id!="string"||!e.id.trim()||typeof e.root!="string")&&H("Skill 依赖缺少身份或目录");let r=await L2(gs.resolve(t,e.root));e.contentHash!==r.contentHash&&H(`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")&&H(`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()))&&H(`Skill 缺少范围或宿主能力:${e.id}`),n.kind==="guidance"&&(n.sideEffect!=="read"||n.controlsApproval||n.interaction!=="none")&&H(`有副作用或审批逻辑的 Skill 不能作为普通指导:${e.id}`),n.sideEffect==="external"&&n.recovery!=="reconcile"&&H(`外部操作缺少未知结果核对契约:${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)&&H(`Skill 必需能力尚未完成内容适配审查:${e.id}`);for(let s of[...i.capabilities,...i.effects])(!s||!s.excerpt?.trim()||!r.files[s.file]?.includes(s.excerpt))&&H(`Skill 审查证据与真实文件不匹配:${e.id}`);i.capabilities.some(s=>typeof s.id!="string"||!s.id.trim())&&H(`Skill 能力证据缺少身份:${e.id}`);let o=W2(n.inputSchema,n.outputSchema),a=(s,c)=>l=>{s(l)||H(`${e.id} ${c} 不匹配:${o.ajv.errorsText(s.errors)}`)};return{...r,id:e.id,adapter:n,validateInput:a(o.input,"输入"),validateOutput:a(o.output,"输出")}}var nP,$l,vs=I(()=>{"use strict";nP=or(Ff(),1);Yy();Ze();ot();$l=new Map});import $n from"node:path";import{realpathSync as V2,existsSync as M2}from"node:fs";function Zy(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 hn(e){return["running","unknown"].includes(e.status)||e.status==="cancelled"&&e.type!=="invoke_skill"&&!!e.claim&&!e.cancellation&&!e.executionStop}function cp(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 lp(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(;!M2(c)&&c!==$n.dirname(c);)c=$n.dirname(c);return{ref:$n.resolve(V2(c),$n.relative(c,s)),workspace:!!n.workspaceFrom,write:!0}})})}function ws(e,t,r,n=[]){let i=(a,s)=>lp(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)&&(hn(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:cp(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 iP(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 ys(e,t,r){let{binding:n,skill:i}=iP(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||T(o.value)!==T({choice:a.decision.choice,proposal:a.proposal}))throw new k("STALE_PROPOSAL","此工作缺少父流程的当前批准记录")}return{binding:n,skill:i}}function oP(e,t){let r=async(n,i,o)=>{if(!o)throw new k("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=ys(e,n,o);if(ws(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}=iP(e,n,o);return await t.invokeSkill({action:n,run:o,binding:a,skill:s,context:i})}}}var up=I(()=>{"use strict";Ze()});import{randomUUID as aP}from"node:crypto";import{promises as q2}from"node:fs";import da from"node:path";function tk(e){let t=e.rootDir,r=m=>{throw new k("STORE_INDEX_CORRUPT",m)},n=async m=>{let h=da.parse(t).root;if(!(await ce(h,da.relative(h,t).replaceAll("\\","/"),{label:"应用 Store",expected:"directory"})).exists)return null;let p=`${ek}/${m}.json`;if(!(await ce(t,p,{label:"应用存储索引",expected:"file"})).exists)return null;try{let g=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await qe(t,p,Number.MAX_SAFE_INTEGER,{label:"应用存储索引"})).bytes));if(m==="inventory"){let{checksum:v,...w}=g;return v!==T(w)&&r("独立成员清单校验值不一致"),w}return g}catch{return r(`应用存储索引 ${m} 无法读取;请保留现场并显式检查`)}},i=async(m,h)=>{await yt(t,ek,{label:"应用存储索引"}),await Et(da.join(t,ek,`${m}.json`),JSON.stringify(["index","inventory"].includes(m)?{...h,checksum:T(h)}:h)+`
|
|
272
|
+
`,{containedRoot:t,requireAtomicPublication:!0})},o=async()=>JSON.stringify(await Promise.all(["",".runtime-store-v2",".runtime-store-history"].map(async m=>{let h=await ce(m?t:da.dirname(t),m||da.basename(t),{label:"应用存储分区",expected:"directory"});if(!h.exists)return null;let p=await q2.lstat(h.target);return[p.dev,p.ino,p.mtimeMs,p.ctimeMs]})));async function a(){let m=await n("index");if(!m)return null;let{checksum:h,...p}=m;return h!==T(p)&&r("应用存储索引校验值不一致"),p&&(p.schema!==dp||typeof p.epoch!="string"||!["building","ready"].includes(p.state)||!Array.isArray(p.holders)||p.holders.some(g=>typeof g!="string")||new Set(p.holders).size!==p.holders.length||!Number.isSafeInteger(p.memberCount)||p.memberCount<0||p.pending!==null&&(!p.pending||typeof p.pending.runId!="string"||typeof p.pending.registering!="boolean"))&&r("应用存储索引格式损坏"),p}async function s(m){let h=await n("inventory");return(!h||h.epoch!==m.epoch||!Array.isArray(h.members)||h.members.some(p=>typeof p!="string")||new Set(h.members).size!==h.members.length||h.aborted!==void 0&&(!Array.isArray(h.aborted)||h.aborted.some(p=>typeof p!="string"||h.members.includes(p))||new Set(h.aborted).size!==h.aborted.length)||h.members.length!==m.memberCount||T(h)!==m.inventoryHash)&&r("应用存储成员清单与 epoch/hash 不一致,不能忽略已登记 Run"),h}async function c(m,h){let p=await by({rootDir:t}),g=[],v=[];for(let w of p){(w.error||!w.runId)&&r(`Run 无法发现:${w.storageKey} (${w.error?.code??"missing identity"})`);let A=w.runId;await e.settle?.(A);let b=await e.read(A);!b&&h?.aborted?.includes(A)&&!h.members.includes(A)||(b||r(`已发现的 Run 正文缺失:${A}`),g.push(A),await e.holds(b)&&v.push(A))}return h?.members.some(w=>!g.includes(w))&&r("已登记 Run 缺失,不能通过重建索引丢弃占用;请恢复原记录"),m.holders=v.sort(),{epoch:m.epoch,members:g.sort(),...h?.aborted?{aborted:h.aborted.filter(w=>!g.includes(w))}:{}}}async function l(){let m=da.parse(t).root;await yt(m,da.relative(m,t).replaceAll("\\","/"),{label:"应用 Store"});let h=await a();if(h?.state==="ready")return h;h||(await n("inventory")&&r("成员清单存在但索引缺失,请显式检查,不能静默初始化"),h={schema:dp,epoch:aP(),state:"building",inventoryHash:null,memberCount:0,holders:[],pending:null,stamps:null},await i("index",h));let p=await n("inventory"),g=await n("repair");g&&g.inventory.epoch===h.epoch&&T(g.inventory)===h.inventoryHash&&p&&T(p)===g.previousHash&&(p=g.inventory),p&&(p.epoch!==h.epoch||!Array.isArray(p.members)||p.members.some(w=>typeof w!="string")||new Set(p.members).size!==p.members.length||h.inventoryHash!==null&&(T(p)!==h.inventoryHash||p.members.length!==h.memberCount))&&r("初始化中的成员清单不匹配");let v=await c(h,p??void 0);return!p&&h.inventoryHash!==null&&T(v)!==h.inventoryHash&&r("初始化期间成员清单发生变化,不能重写并丢弃原成员"),h.inventoryHash=T(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(m){if(!m.pending)return;let{runId:h,registering:p}=m.pending;await e.settle?.(h);let g=await e.read(h);if(!g&&!p&&r(`未完成写入的 Run 缺失:${h}`),!g&&p){let v=await s(m),w=await n("registration");(v.members.includes(h)||w?.epoch===m.epoch&&w.previousHash===m.inventoryHash&&w.inventory.members.includes(h))&&r(`注册已提交或已观测到提交,但 Run 已缺失:${h}`)}if(p){let v=await s(m),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:m.epoch,previousHash:m.inventoryHash,inventory:v}),await i("inventory",v),m.inventoryHash=T(v),m.memberCount=v.members.length)}m.holders=m.holders.filter(v=>v!==h),g&&await e.holds(g)&&m.holders.push(h),m.holders.sort(),m.pending=null,m.stamps=await o(),await i("index",m)}async function f(m){if(!m.pending?.registering)return;let h=await n("registration");if(h?.epoch===m.epoch&&h.previousHash===m.inventoryHash){let p=await n("inventory");p&&T(p)===T(h.inventory)&&(m.inventoryHash=T(p),m.memberCount=p.members.length)}}async function d(){let m=await l();return await f(m),m.pending&&await u(m),m.stamps!==await o()&&r("Store 分区身份已变化,必须显式 audit;不能继续使用占用投影"),m}return{async isAbortedRegistration(m){let h=await a();if(!h||h.state!=="ready"||h.pending)return!1;let p=await s(h);return!p.members.includes(m)&&!!p.aborted?.includes(m)&&await e.read(m)===null},async holders(){let m=await d(),h=[];for(let p of m.holders){await e.settle?.(p);let g=await e.read(p);g||r(`占用 Run 缺失:${p}`),await e.holds(g)&&h.push(g)}return h},async begin(m,h){let p=await d();h&&(await s(p)).members.includes(m)&&r(`已登记 Run 不能作为新记录重建:${m}`),p.pending={runId:m,registering:h},await i("index",p)},async finish(){let m=await a();(!m||m.state!=="ready")&&r("应用存储索引未就绪"),await f(m),await u(m)},async inspect(){try{let m=await a();return!m&&await n("inventory")&&r("成员清单存在但索引缺失"),m}catch(m){let h=await n("inventory");if(!h||typeof h.epoch!="string")throw m;return{schema:dp,epoch:h.epoch,state:"corrupt",error:{code:"STORE_INDEX_CORRUPT",message:m instanceof Error?m.message:String(m)}}}},async repair(m,h){let p;try{p=await a()}catch(w){if(m!=="rebuild")throw w;p=null}if(!p&&m==="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&&(p={schema:dp,epoch:w.epoch,state:"building",inventoryHash:T(w),memberCount:w.members.length,holders:[],pending:null,stamps:null})}if(!p||p.epoch!==h)throw new k("STORE_INDEX_EPOCH_CHANGED","索引 epoch 已变化,请重新 inspect");await f(p),p.pending&&await u(p);let g=await s(p),v=await c(p,g);return m==="rebuild"&&(p.epoch=aP(),v.epoch=p.epoch),await i("repair",{previousHash:p.inventoryHash,inventory:v}),p.inventoryHash=T(v),p.memberCount=v.members.length,p.state="building",await i("index",p),await i("inventory",v),p.state="ready",p.stamps=await o(),await i("index",p),p}}}var ek,dp,sP=I(()=>{"use strict";Nn();ot();Ze();ek=".runtime-store-coordination",dp="comet.application-holder-index.v1"});import F2 from"node:os";import H2 from"node:path";function cP(e,t,r=F2.homedir()){return H2.join(t==="project"?e:r,".comet/applications")}var lP=I(()=>{"use strict"});import gn from"node:path";function Q2(e){return/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e)||H("应用身份无效"),e}function uP(e,t){let r=gn.resolve(e,t),n=gn.parse(r).root;return{volume:n,ref:gn.relative(n,r).replaceAll("\\","/")}}async function dP(e,t,r){let n=uP(e,t);return ce(n.volume,n.ref,{expected:r,label:"SDK application installation"})}async function U2(e,t){let r=`${Q2(t)}/current.json`;if(!(await dP(e,r,"file")).exists)return null;let n=uP(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}`)&&H("安装记录无效;保留文件并重新预览"),o.entry){let a=gn.dirname(gn.dirname(e)),s=gn.dirname(o.entry.root??"");(!gn.isAbsolute(o.entry.root)||![gn.join(a,".claude/skills"),gn.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(gn.basename(o.entry.root)))&&H("宿主入口安装记录无效;保留文件并核对原安装")}return o}async function rk(e,t){let r=cP(e.projectRoot,e.scope,e.userRoot),n=await U2(r,t);if(!n)return null;let i=`${n.packageRef}/application.json`;return await dP(r,i,"file"),go(await ho(gn.join(r,n.packageRef)))!==n.contentHash&&H("已安装版本内容发生漂移;恢复原包后继续"),gn.join(r,i)}var fP=I(()=>{"use strict";ot();lP();vs()});var pP=I(()=>{"use strict";up()});import Wt from"node:path";function bi(e,t){let r=Wt.relative(e,t);return!r||!Wt.isAbsolute(r)&&r!==".."&&!r.startsWith(".."+Wt.sep)}function J2(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"||!Wt.isAbsolute(n))throw new Error("当前 Action 缺少已声明的实际写入工作区");return n}function mP(e){let t=Wt.resolve(e.projectRoot),r=[".git","node_modules",".claude",".agents",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].map(s=>Wt.resolve(t,s)),n={manifest:e.manifest,skills:e.skills,projectRoot:t},i=["AGENTS.md","AGENTS.override.md","CLAUDE.md"].map(s=>Wt.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 b of c.targets){let R=Wt.resolve(t,b),_=Wt.relative(t,R);if(!_||!bi(t,R))throw new Error("写入目标必须位于当前项目内");if(await ce(t,_.replaceAll("\\","/"),{expected:"file",label:"SDK 应用写入"}),bi(Wt.resolve(e.packageRoot),R)||r.some(W=>bi(W,R))||i.some(W=>!Wt.relative(W,R))||!Wt.relative(Wt.join(t,".comet/current-change.json"),R))throw new Error("固定应用、SDK 状态与宿主配置只能由正式 Runtime 或安装入口维护");l.push(R)}let u=Wt.join(t,".comet/requests");if(l.every(b=>bi(u,b)&&b.endsWith(".json")))return{allowed:!0,reason:"临时协议请求不是推进状态;Runtime 仍核对身份与批准"};let f=[],d=new Set,m=0,h=async b=>{if(d.has(b.runId))throw new Error("子流程归属循环");if((["running","waiting"].includes(b.status)||b.actions.some(_=>_.status==="pending"||hn(_))||b.ready.length>0||b.waits.some(_=>_.status==="pending")||(b.evidenceWaits??[]).some(_=>_.status==="pending"))&&++m>128)throw new Error("活跃子流程超出安全读取范围");d.add(b.runId),f.push(b);for(let _ of b.children){let W=b.actions.find(G=>G.id===_.actionId);if(!W||W.type!=="child_workflow")throw new Error("子流程与 SDK Action 归属不一致");if(!W.claim)continue;let O=await e.readChild(_.runId);if(O.runId!==_.runId||O.workflow.id!==_.workflow.id||O.workflow.version!==_.workflow.version||O.lineage.length!==b.lineage.length+1||O.lineage.at(-1)!==b.runId||b.lineage.some((G,Z)=>O.lineage[Z]!==G))throw new Error("子流程没有当前 SDK Run 的有效归属");await h(O)}};await h(s);let p=["completed","cancelled","failed"].includes(s.status),g=[],v=[];for(let b of f)for(let R of o.filter(_=>_.workflowId===b.workflow.id)){let _=e.skills.get(R.skillId),W=b.actions.filter(O=>O.stepId===R.stepId);for(let O of W){let G=J2(e,R,O);v.push(..._.adapter.scope.map(Z=>Wt.resolve(G,Z))),!(p||["cancelled","failed"].includes(b.status)||O.status!=="running")&&(ys(n,O,b),ws(n,b,O,f),g.push(..._.adapter.scope.map(Z=>Wt.resolve(G,Z))))}!R.workspaceFrom&&!W.length&&v.push(..._.adapter.scope.map(O=>Wt.resolve(t,O)))}let w=Wt.join(t,".comet/evidence",e.manifest.id),A=!p&&f.some(b=>b.actions.some(R=>["running","unknown"].includes(R.status)));for(let b of l)if(!(bi(u,b)&&b.endsWith(".json"))&&!(A&&bi(w,b))){if(p){if(v.some(R=>bi(R,b))||bi(Wt.join(t,".comet"),b))throw new Error("已结束 Run 的声明产物保持固定;继续修改应启动新的 Run")}else if((!e.custom||a)&&!g.some(R=>bi(R,b)))throw new Error("当前 SDK Action 没有此写入权限;先确认当前提案并领取允许写入的 Action")}return e.custom?await e.custom(s,c):{allowed:!0,reason:p?"目标不属于已结束应用或控制资源":"写入属于当前已批准且已领取的 SDK Action"}}catch(l){return{allowed:!1,reason:l instanceof Error?l.message:"无法安全核对 SDK 应用写入"}}}}var hP=I(()=>{"use strict";ot();up()});function jl(e,t,r){return(!e||typeof e!="object"||Array.isArray(e))&&H(`${r} 必须是 JSON 对象`),Object.keys(e).some(n=>!t.includes(n))&&H(`${r} 含未声明字段`),e}function jn(e,t,r=256){(typeof e!="string"||!e.trim()||e.length>r)&&H(`${t} 必须是长度不超过 ${r} 的非空文本`)}function G2(e,t){let r=jl(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>gP)&&H("步骤展示信息必须是有界数组");let n=new Set;for(let i of r.steps){let o=jl(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)&&H(`重复步骤展示信息:${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)))&&H(`展示信息引用不存在的步骤:${o.workflowId}/${o.stepId}`)}if(o.outputFields===void 0)continue;(!Array.isArray(o.outputFields)||o.outputFields.length>32)&&H("步骤展示输出字段必须是有界数组");let s=new Set;for(let c of o.outputFields){let l=jl(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)))&&H(`展示输出字段路径无效:${l.path}`),s.has(l.path)&&H(`重复展示输出字段:${l.path}`),s.add(l.path)}}}function nk(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))&&H("应用流程定义必须声明固定包内的 JSON 相对路径")}function Y2(e,t){let r=typeof e=="string"?e:Qn(e),n=jl(JSON.parse(r),["schema","application","workflows","presentation"],"应用流程定义");n.schema!=="comet.workflow.application.definition.v1"&&H("应用流程定义格式不受支持");let i=jl(n.application,["id","version"],"流程定义应用身份");jn(i.id,"流程定义应用 ID"),jn(i.version,"流程定义应用版本"),t&&(t.id!==i.id||t.version!==i.version)&&H("流程定义与应用固定身份不匹配"),(!Array.isArray(n.workflows)||!n.workflows.length||n.workflows.length>z2)&&H("应用流程定义必须包含有界的完整流程数组");let o=0,a=0,s=n.workflows.map(l=>((!l||typeof l!="object"||!l.steps||typeof l.steps!="object")&&H("应用流程定义缺少步骤"),o+=Object.keys(l.steps).length,a+=Array.isArray(l.transitions)?l.transitions.length:0,(o>gP||a>K2)&&H("应用流程定义超过步骤或转移数量限制"),fn(l))),c=new Set;for(let l of s){let u=JSON.stringify([l.id,l.version]);c.has(u)&&H(`重复流程身份:${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]))&&H(`子流程定义不存在:${l.id}/${u}`);return n.presentation!==void 0&&G2(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 vP(e,t){if(t.definition!==void 0)return nk(t.definition),Object.hasOwn(e,t.definition)||H("固定包缺少声明的应用流程定义"),Y2(Buffer.from(e[t.definition],"base64").toString("utf8"),t)}function wP(e,t){let r=n=>n.map(i=>{let o=fn(i);return[o.id,o.version,T(o)]}).sort((i,o)=>JSON.stringify(i).localeCompare(JSON.stringify(o),"en"));T(r(e.workflows))!==T(r(t))&&H("实际工厂的流程与固定流程定义不匹配,请同步确认方案")}function ik(e,t){let r=new Map(e.workflows.map(i=>[JSON.stringify([i.id,i.version]),T(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 z2,gP,K2,yP=I(()=>{"use strict";Ze();lr();vs();z2=256,gP=4096,K2=16384});import{createHash as X2}from"node:crypto";async function AP(e,t){let r={},n={},i=new kP.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 m=/^ {0,3}(`{3,}|~{3,})/u.exec(d);if(m){let p=m[1];l?l.char===p[0]&&p.length>=l.length&&d.slice(m[0].length).trim()===""&&(l=void 0):l={char:p[0],length:p.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]=X2("sha256").update(a.bytes).digest("hex")}return{files:r,artifactHashes:n}}var kP,bP=I(()=>{"use strict";kP=or(Ff(),1);Ze();ot();vs()});import NP from"node:path";function ok(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=ak(n.input,i.workspaceFrom);if(typeof o!="string"||!NP.isAbsolute(o))throw new Error("产物检查缺少当前 Action 已声明的实际工作区");return o}function SP(e){(typeof e!="string"||!e||e.length>4096||e.includes("\\")||e.includes(":")||e.includes("\0")||NP.posix.isAbsolute(e)||e.split("/").some(r=>!r||r==="."||r===".."||/[ .]$/u.test(r)))&&H("产物引用必须是项目内安全相对路径"),([".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()))&&H(`产物引用不能指向控制资源:${e}`)}function RP(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)))&&H("产物字段选择器无效")}function sk(e){(!Array.isArray(e)||e.length>256)&&H("阶段产物契约必须是有界数组");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)))&&H("阶段产物契约含未声明字段");let n=r;(typeof n.workflowId!="string"||!n.workflowId.trim()||typeof n.stepId!="string"||!n.stepId.trim()||t.has(fp(n.workflowId,n.stepId))||!Array.isArray(n.artifacts)||n.artifacts.length>64)&&H("阶段产物契约缺少唯一流程、步骤或产物列表"),t.add(fp(n.workflowId,n.stepId)),!n.artifacts.length&&(typeof n.noArtifactsReason!="string"||!n.noArtifactsReason.trim())&&H(`无强制产物的阶段需要说明原因:${fp(n.workflowId,n.stepId)}`),n.artifacts.length&&n.noArtifactsReason!==void 0&&H("必需产物与无产物声明不能同时存在"),n.replaces&&(!Array.isArray(n.replaces)||n.replaces.some(o=>typeof o!="string"||!o.trim())||new Set(n.replaces).size!==n.replaces.length)&&H("替代产物的步骤声明无效");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)&&H("必需产物需要唯一的 ref 或 refFrom"),o.ref!==void 0&&SP(o.ref),o.refFrom!==void 0&&RP(o.refFrom),o.sha256From!==void 0&&RP(o.sha256From);let a=o.ref??`output:${o.refFrom}`;i.has(a)&&H("阶段产物引用重复"),i.add(a),o.nonEmpty!==void 0&&typeof o.nonEmpty!="boolean"&&H("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()))&&H("产物内容检查必须是非空文本数组")}}}function Z2(e,t){for(let r of t){let n=e.workflows.find(i=>i.id===r.workflowId);n?.steps[r.stepId]||H(`阶段产物契约引用不存在的步骤:${fp(r.workflowId,r.stepId)}`);for(let i of r.replaces??[])n.steps[i]||H(`替代产物的步骤不存在:${i}`);r.artifacts.length&&!["handoff","invoke_skill","call_tool","child_workflow"].includes(n.steps[r.stepId].type)&&H("必需产物必须绑定可回传结果的执行步骤"),n.steps[r.stepId].type==="child_workflow"&&r.artifacts.some(i=>!i.sha256From)&&H("子流程产物需要 sha256From,读取子流程结果中的实际摘要")}}async function EP(e,t,r){let n=t.artifacts.map(o=>{let a=o.ref??ak(r,o.refFrom);return SP(a),{...o,ref:a,nonEmpty:o.nonEmpty!==!1}}),i=await AP(e,n);return{...i,artifacts:n.map(({ref:o})=>({uri:o,sha256:i.artifactHashes[o]}))}}async function _P(e,t,r){if(r.status!=="succeeded"||!t.artifacts.length)return;let n=await EP(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?ak(r.output,a.sha256From):r.artifacts?.find(c=>c.uri===o.uri)?.sha256)!==o.sha256)throw new Error(`必需产物缺少当前结果的实际摘要或内容已变化:${o.uri}`)}}async function Dl(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||T(u.outcome.output)!==T(l.value))throw new Error(`依赖产物没有对应的原 Action 证据:${c.stepId}`);await _P(o?ok(e,o,r,u):e,c,u.outcome)}}function CP(e,t){let r=t.manifest.artifactContracts;if(r===void 0)return e;sk(r),Z2(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 Dl(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 _P(ok(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 Dl(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 EP(ok(t.projectRoot,t.manifest,c,a),u,l.output);return{...l,artifacts:[...(l.artifacts??[]).filter(d=>!f.artifacts.some(m=>m.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 ak,fp,IP=I(()=>{"use strict";Ze();bP();vs();ak=(e,t)=>t.split(".").reduce((r,n)=>r&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),fp=(e,t)=>`${e}/${t}`});import{promises as ck}from"node:fs";import hr from"node:path";import{createRequire as eJ,isBuiltin as tJ}from"node:module";function jP(e){return["completed","cancelled"].includes(e.status)&&!e.actions.some(t=>t.status==="pending"||hn(t))&&e.children.length===0&&!e.ready.length&&!e.waits.some(t=>t.status==="pending")&&!(e.evidenceWaits??[]).some(t=>t.status==="pending")}function ks(e){return(typeof e!="string"||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e))&&H("应用身份必须是小写名称"),e}async function lk(e,t,r=!1,n=!1){let i=it(e),o=()=>{if(it(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=Pt({rootDir:hr.join(i,"applications",ks(t)),mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...n?{singleWriter:!0}:{}}),c=(u,f,d)=>{let m=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 p=await m();return p&&d.application.base==="standalone"&&jP(d.run)&&await s.closeRun(u,d.revision),p}},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 PP(e){let t=await ho(e.application.packageRoot),r=dk(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||T({package:go(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 TP(e,t,r){return e.actions.filter(n=>n.type==="invoke_skill"&&hn(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?Yf(n.claim.token):null}))}async function DP(e){let t=sn(e.run,e.runId),r=t.actions.filter(n=>n.type==="invoke_skill"&&hn(n));if(!r.length)return!1;try{let n=await ho(e.application.packageRoot),i=dk(JSON.parse(Buffer.from(n["application.json"],"base64").toString("utf8")));return T({package:go(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 OP(e,t,r=!1){let n=hr.join(it(e),"applications",ks(t)),i=Pt({rootDir:n,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...r?{singleWriter:!0}:{}});return tk({rootDir:n,read:o=>i.read(o),settle:o=>i.settleRun(o),holds:DP})}async function uk(e,t,r){return(await rJ(e,t,r))?.run??null}async function rJ(e,t,r){let n=await(await lk(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=sn(n.run,r),n}function dk(e){(!e||typeof e!="object"||Array.isArray(e))&&H("应用文件必须是 JSON 对象");let t=e;return t.artifactContracts!==void 0&&sk(t.artifactContracts),t.schema!=="comet.workflow.application.v1"&&H("应用格式不受支持,请重新生成 SDK 应用;原文件会保留"),t.definition!==void 0&&nk(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===".."))&&H("应用规则 Rule 必须声明固定包内的 Markdown 相对路径"),ks(t.id),Sy.includes(t.id)&&H(`应用身份 ${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))&&H("应用定义缺少版本、基础流程、入口或绑定"),t}async function fk(e,t,r){let n=await(await lk(await ck.realpath(e),t,!0)).readProjection(r);return n?hr.join(n.application.packageRoot,"application.json"):await rk({projectRoot:e,scope:"project"},ks(t))??await rk({projectRoot:e,scope:"user"},ks(t))??hr.join(e,".comet/applications",ks(t),"application.json")}async function As(e){let t=await ck.realpath(e.projectRoot),r=hr.resolve(e.file);hr.basename(r)!=="application.json"&&H("应用入口文件必须命名为 application.json");let n=await ck.realpath(hr.dirname(r));n===t&&H("应用包须放在独立目录,不能包含项目的运行状态");let i=await ho(n),o=dk(JSON.parse(Buffer.from(i["application.json"]??"","base64").toString("utf8"))),a=vP(i,o);o.rule&&(!o.rule.endsWith(".md")||!i[o.rule]||!Buffer.from(i[o.rule],"base64").toString("utf8").trim())&&H("应用规则 Rule 必须是固定包内的非空 Markdown 文件");let s=$x(),c=o.runtimeVersion==="0.5.2"&&s==="0.5.3"&&!!e.runId&&(o.base==="native"||o.base.startsWith("classic-"));o.runtimeVersion!==s&&!c&&H(`应用要求 Runtime ${o.runtimeVersion},当前是 ${s}`),(!i[o.entrySkill]||!i[o.module])&&H("应用入口 Skill 或执行模块缺失");let l=new Map;for(let N of o.skills)l.has(N.id)&&H(`重复 Skill 身份:${N.id}`),l.set(N.id,await Xy(N,n));let u={id:o.id,version:o.version,base:o.base,runtimeVersion:o.runtimeVersion,projectRoot:t,packageRoot:n,contentHash:T({package:go(i),skills:[...l.values()].map(N=>({id:N.id,contentHash:N.contentHash}))})},f=async()=>{let N=await ho(n),C=await Promise.all(o.skills.map(L=>Xy(L,n)));if(T({package:go(N),skills:C.map(L=>({id:L.id,contentHash:L.contentHash}))})!==u.contentHash)throw new k("WORKFLOW_CHANGED","运行中的应用或依赖发生漂移;恢复原内容后继续原 Action")};if(e.expectedIdentity&&T(u)!==T(e.expectedIdentity))throw new k("WORKFLOW_CHANGED","恢复需要原固定应用包、依赖和工作区");let d=o.base!=="standalone",m=await lk(t,o.id,e.readOnly,d),h=N=>{if(T(N.application)!==T(u))throw new k("WORKFLOW_CHANGED","应用定义、执行/验证绑定、Skill 或工作区归属发生变化;请恢复原应用包和依赖后继续原 Run");if(N.revision!==N.run.revision||N.runId!==N.run.runId)throw new k("INVALID_RUN","应用归属与 SDK Run 不一致")},p;if(e.runId){let N=await m.readProjection(e.runId);N&&(h(N),p=(await qo({...m,readProjection:async()=>N},e.runId)).run)}await By;for(let[N,C]of Object.entries(i)){if(!N.endsWith(".mjs"))continue;let B=Buffer.from(C,"base64").toString("utf8");for(let L of Dy(B)[0]){if(L.d===-2)continue;let q=L.n;if(q||H(`应用模块不能动态选择未固定的导入:${N}`),tJ(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(".")||H(`应用模块依赖未固定:${N} -> ${q},请 bundle 后再加载`);let Q=hr.posix.normalize(hr.posix.join(hr.posix.dirname(N),q));(!i[Q]||Q.startsWith("../"))&&H(`应用模块依赖缺失或越过包目录:${N} -> ${q}`),!Q.endsWith(".mjs")&&!Q.endsWith(".json")&&H(`执行依赖必须是可检查的 .mjs 或 JSON:${N} -> ${q},请先 bundle`)}}let g=xP.get(n);g&&g!==u.contentHash&&H("当前进程已加载不同的应用实现,请在新进程加载新版本"),xP.set(n,u.contentHash);let v=eJ(r)(hr.join(n,o.module));typeof v.createApplication!="function"&&H("应用模块必须导出 createApplication");let w={manifest:structuredClone(o),skills:l,projectRoot:t,packageRoot:n,identity:u,createSkillExecutor:N=>oP({manifest:o,skills:l,projectRoot:t},N)};if(p&&!e.useLatestDefinition){let N;Object.defineProperty(w,"existingRun",{enumerable:!0,get:()=>N??=cr(p)})}let A=await v.createApplication(w);(!A||!Array.isArray(A.workflows)||!A.workflows.length)&&H("应用模块必须提供完整 SDK 工作流"),A=CP(A,{manifest:o,projectRoot:t});let b=A.workflows.map(fn);a&&(c?p&&!ik(a,p)&&!ik({...a,workflows:b},p)&&H("旧固定应用 Run 不匹配原定义或当前业务定义"):wP(a,b));let R=new Set;for(let N of o.bindings){let C=`${N.workflowId}/${N.stepId}/${N.usage}${N.usage==="guidance"?`/${N.skillId}`:""}`;N.workspaceFrom!==void 0&&!/^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)*$/u.test(N.workspaceFrom)&&H(`工作区输入路径无效:${C}`),R.has(C)&&H(`重复 Skill 绑定:${C}`),R.add(C);let B=b.find(Q=>Q.id===N.workflowId),L=B?.steps[N.stepId],q=l.get(N.skillId);if((!L||!q)&&H(`绑定的工作或 Skill 不存在:${C}`),(!N.capability?.trim()||!q.adapter.review.capabilities.some(Q=>Q.id===N.capability))&&H(`真实 Skill 没有已审查的所需能力:${C}`),N.usage==="guidance"){q.adapter.kind!=="guidance"&&H("只有只读指导 Skill 可附加为 guidance");continue}if(N.usage==="subworkflow"){(q.adapter.kind!=="subworkflow"||L.type!=="child_workflow")&&H("完整流程必须绑定显式 child_workflow");continue}if((N.usage!=="action"||!["action","check"].includes(q.adapter.kind)||L.type!=="invoke_skill"||L.ref!==N.skillId)&&H(`Skill 工作类型或引用不匹配:${C}`),q.adapter.controlsApproval&&H("接管审批的 Skill 必须适配为隔离的子流程"),(L.outputSchema===void 0||T(L.outputSchema)!==T(q.adapter.outputSchema))&&H(`Skill 输出与工作流契约不匹配:${C}`),q.adapter.completion!=="self-report"&&!(q.adapter.completion==="machine-check"&&o.artifactContracts?.some(Q=>Q.workflowId===N.workflowId&&Q.stepId===N.stepId&&Q.artifacts.length))&&(!L.validator||!A.validators?.some(Q=>Q.id===L.validator?.id&&Q.version===L.validator.version))&&H(`机器检查或独立评审需要真实验证器:${C}`),q.adapter.requiredCapabilities.some(Q=>!L.requiredCapabilities?.includes(Q))&&H(`Skill 必需宿主能力未传到 Action:${C}`),q.adapter.sideEffect!=="read"){let Q=N.authorizationFrom?B.steps[N.authorizationFrom]:void 0,ae=N.authorizationChoices??["approved"];(Q?.type!=="ask_user"||!Array.isArray(ae)||!ae.length||ae.some(ne=>typeof ne!="string"||!Q.choices.includes(ne)))&&H(`有副作用的 Skill 缺少有效父流程审批:${C}`)}q.adapter.sideEffect==="external"&&L.retry!=="reconcile"&&H(`外部 Skill 必须先核对再重试:${C}`)}for(let N of b){let C=(q,Q,ae)=>{q&&!Q?.some(ne=>ne.id===q.id&&ne.version===q.version)&&H(`${ae} 未注册固定实现:${q.id}@${q.version}`)};C(N.transitionHandler,A.transitionHandlers,"转移处理器"),C(N.stateValidator,A.stateValidators,"状态验证器");for(let q of Object.values(N.commands??{}))C(q.validator,A.commandValidators,"命令验证器");for(let[q,Q]of Object.entries(N.steps))Q.type==="await_evidence"?C(Q.validator,A.evidenceValidators,"证据验证器"):C(Q.validator,A.validators,"工作验证器"),Q.type==="invoke_skill"&&!o.bindings.some(ae=>ae.workflowId===N.id&&ae.stepId===q&&ae.usage==="action")&&H(`Skill Action 缺少适配绑定:${N.id}/${q}`);let B=o.bindings.filter(q=>q.workflowId===N.id&&q.usage==="action"&&l.get(q.skillId).adapter.sideEffect!=="read"),L=(q,Q,ae=new Set)=>q===Q?!0:ae.has(q)?!1:(ae.add(q),N.transitions.some(ne=>ne.from===q&&L(ne.to,Q,ae)));for(let q=0;q<B.length;q++)for(let Q of B.slice(q+1)){let ae=B[q];l.get(ae.skillId).adapter.sideEffect==="write"&&l.get(Q.skillId).adapter.sideEffect==="write"&&!!ae.workspaceFrom!=!!Q.workspaceFrom&&!L(ae.stepId,Q.stepId)&&!L(Q.stepId,ae.stepId)&&H(`并行写入不能混用声明工作区和默认范围:${ae.stepId} / ${Q.stepId}`),!ae.workspaceFrom&&!Q.workspaceFrom&&l.get(ae.skillId).adapter.scope.some(ne=>l.get(Q.skillId).adapter.scope.some(ve=>l.get(ae.skillId).adapter.sideEffect==="write"&&l.get(Q.skillId).adapter.sideEffect==="write"?cp(hr.resolve(t,ne),hr.resolve(t,ve)):ve===ne))&&!L(ae.stepId,Q.stepId)&&!L(Q.stepId,ae.stepId)&&H(`并行 Skill 的写入范围冲突:${ae.stepId} / ${Q.stepId},请声明隔离或执行顺序`)}}let _=()=>{if(e.readOnly)throw new k("READ_ONLY_OPERATION","应用诊断不能恢复或推进 Run")},W=it(t),O=async N=>{if(it(t)!==W)throw new k("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");return await ci(t),N()},G=hr.join(W,"applications",o.id),Z=Pt({rootDir:G,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...d?{singleWriter:!0}:{}}),J=(N,C)=>C.type==="invoke_skill"&&o.bindings.some(B=>{let L=l.get(B.skillId);return B.workflowId===N.workflow.id&&B.stepId===C.stepId&&B.usage==="action"&&L&&L.adapter.sideEffect!=="read"&&L.adapter.scope.length>0}),F=tk({rootDir:G,read:N=>Z.read(N),settle:N=>Z.settleRun(N),holds:N=>N.application.contentHash!==u.contentHash?DP(N):sn(N.run,N.runId).actions.some(C=>hn(C)&&J(N.run,C))}),X=N=>JSON.stringify(N?.actions.filter(C=>J(N,C)&&hn(C)).map(C=>[C.id,C.status,C.claim?.token,C.inputHash]).sort()??[]),U=N=>TP(N,o,u.contentHash),pe=async N=>{let C=await OP(t,N,N===o.id&&d).holders(),B=[];for(let L of C){let q=L.application.id===u.id&&L.application.contentHash===u.contentHash?o:await PP(L);B.push(...TP(sn(L.run,L.runId),q,L.application.contentHash))}return B},Le=(N=!1)=>Cx(W,o.id,pe,N),D=async(N,C,B=!1)=>{if(!o.bindings.some(ne=>{if(ne.workflowId!==N.workflow.id||ne.stepId!==C.stepId||ne.usage!=="action")return!1;let ve=l.get(ne.skillId);return ve&&ve.adapter.sideEffect!=="read"&&ve.adapter.scope.length>0}))return[];let q=lp({manifest:o,projectRoot:t},N,C);for(let ne of await Le(B)){if(ne===o.id||B&&!await xx(W,ne))continue;let ve=await OP(t,ne).holders();for(let fe of ve){let y=sn(fe.run,fe.runId);if(fe.application.id!==ne||fe.application.projectRoot!==t)throw new k("SCOPE_HELD",`应用 ${ne} 的固定占用身份无法验证:${y.runId}`);let E=await PP(fe);for(let $ of y.actions.filter(hn))if(lp({manifest:E,projectRoot:t},y,$).some(P=>q.some(z=>P.write&&z.write?cp(P.ref,z.ref):P.ref===z.ref))){let P=new k("SCOPE_HELD",`写入范围仍由应用 ${ne} 的 Run ${y.runId} / Action ${$.id} 占用;请停止原执行或提交真实结果`);throw Object.assign(P,{blockedRunIds:[y.runId],blockedApplicationIds:[ne]}),P}}}let Q=await F.holders(),ae=[];for(let ne of Q){if(ne.runId===N.runId)continue;let ve=sn(ne.run,ne.runId);if(ne.application.contentHash!==u.contentHash)throw new k("SCOPE_HELD",`其他固定版本仍占用应用工作区:${ve.runId}`);ae.push(ve)}return ae},re={queryScope:m.queryScope,async readProjection(N){await f();let C=await m.readProjection(N);return C?(h(C),C.run):null},async read(N){await f();let C=await m.read(N);return C?(h(C),C.run):null},async restoreCheckpoint(N,C,B){return B=structuredClone(B),_(),await f(),O(async()=>{await f();let q=await m.read(N);if(q&&h(q),B.runId!==N||B.actions.some(ne=>ne.status==="running"))throw new k("INVALID_RUN","应用恢复必须使用同一 Run 的 portable checkpoint,活跃领取须先转为 unknown");let Q=o.base==="native"?"native":o.base.startsWith("classic-")?"classic":null;if(Q){let ne=await Tn(t,Q,N);if(!ne||ne.format!=="sdk"||ne.application!==u.id||ne.runId!==N)throw new k("INVALID_RUN","恢复 Run 前须验证相同的固定应用和 change 归属")}let ae={runId:N,revision:B.revision,application:u,run:B};h(ae),await Ix(W,o.id,N,U(B)),await Le(!0);for(let ne of B.actions.filter(ve=>hn(ve)&&ve.type==="invoke_skill"))ws({manifest:o,skills:l,projectRoot:t},B,ne,await D(B,ne,!0));await $y(W,o.id,U(B),!0);try{return await F.begin(N,!q),await m.restoreCheckpoint(N,C,ae)}finally{await F.finish(),await jy(W,o.id,pe,!0)}})},async compareAndSwap(N,C,B){_(),await f(),B=structuredClone(B);let L=m.prepareCompareAndSwap(N,C,{runId:N,revision:B.revision,application:u,run:B}),q=await m.read(N),Q=(await F.inspect())?.state!=="ready"||!q||X(q.run)!==X(B)||jP(B),ae=async()=>{await f();let ne=await m.read(N);if(ne&&h(ne),ne||await Le(),(ne?.revision??null)!==C)return!1;for(let ve of B.actions)if(ve.status==="running"&&!ne?.run.actions.some(fe=>fe.id===ve.id&&fe.status==="running"&&fe.claim?.token===ve.claim?.token)&&(ws({manifest:o,skills:l,projectRoot:t},B,ve,await D(B,ve)),o.artifactContracts&&await Dl(t,o.artifactContracts,B,ve.stepId,B.actionContexts[ve.id]?.results??{},o),ve.type==="invoke_skill")){ys({manifest:o,skills:l},ve,B);let fe=A.executors?.find(y=>y.id===ve.claim?.executorId);if(!fe)throw new k("EXECUTOR_UNAVAILABLE","Skill 必须由应用已配置的执行端口领取");if(fe.supports(Zy(ve))!==!0||!fe.preflight)throw new k("EXECUTOR_UNSUPPORTED","Skill 执行端口缺少对应的领取预检");if(ve.requiredCapabilities.some(y=>!fe.capabilities.includes(y)))throw new k("CAPABILITY_REQUIRED","已配置执行端口缺少 Skill 所需能力")}if(o.artifactContracts)for(let ve of B.waits)ve.status==="resolved"&&ve.decision?.choice==="approved"&&ne?.run.waits.some(fe=>fe.id===ve.id&&fe.status==="pending")&&await Dl(t,o.artifactContracts,B,ve.stepId,ve.results,o);if((ne?.revision??null)!==C||!Q&&X(ne?.run)!==X(B))return!1;if(Q){let ve=new Set(ne?U(ne.run).map(T):[]),fe=U(B).filter(y=>!ve.has(T(y)));fe.length&&(await Le(),await $y(W,o.id,fe))}try{return Q&&await F.begin(N,!ne),await L()}finally{Q&&(await F.finish(),await jy(W,o.id,pe))}};return Q?O(ae):ae()}},ge=A.wrapStore?A.wrapStore(re,u,{readOnly:e.readOnly}):re;if(e.runId&&!p&&!e.readOnly&&A.wrapStore){let C=await ge.read(e.runId)?await m.read(e.runId):null;if(C)return h(C),As(e)}let mt={...A,...o.base==="standalone"?{inspectHook:mP({projectRoot:t,packageRoot:n,manifest:o,skills:l,custom:A.inspectHook,readChild:async N=>(await Bt({...A,store:ge}).inspectProjection(N)).run})}:{},async validateOutcome(N){if(N.action.type==="invoke_skill")try{ys({manifest:o,skills:l},N.action,N.run)}catch(C){return{accepted:!1,reason:C instanceof Error?C.message:"Skill 结果不满足应用契约"}}return A.validateOutcome?.(N)??{accepted:!0}}},S=Bt({...mt,store:ge});return c&&await S.inspect(e.runId),{manifest:o,definition:a,identity:u,implementation:mt,skills:l,store:ge}}var xP,bs=I(()=>{"use strict";Lo();Lr();Px();Tx();Ze();jx();po();pr();vs();up();sP();fP();pP();hP();yP();IP();xP=new Map});function nJ(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Tt(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(nJ(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 Ri=I(()=>{"use strict"});function Rs(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}var BP,Bl,pk,WP,LP,VP,Wl=I(()=>{"use strict";BP=["passed","failed","not-run"],Bl=["pass","fail","blocked"],pk=["passed","failed","blocked"],WP=["aligned","conflict","blocked"],LP=["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"],VP=["final-result"]});function mk(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 pp(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(()=>Wo(d,["id","status","evidence","note"],f,`/${r}/${u}`));let m=i(()=>mk(d.id,`${f}.id`));m&&(a.includes(m)&&n.push(`${f}.id contains duplicate ID: ${m}`),a.push(m),o&&!o.has(m)&&s.push({index:u,id:m}));let h=m&&o?.has(m)?f+" ("+m+")":f,p=i(()=>Rs(d.status,LP,`${f}.status`)),g;Array.isArray(d.evidence)?g=d.evidence.map((w,A)=>i(()=>mk(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(()=>mk(d.note,`${h}.note`));return m&&p&&g&&v?[{id:m,status:p,evidence:g,note:v}]:[]});if(t&&!n.length)return Ll(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(`
|
|
273
|
+
`));return c}function Ll(e,t){if(!t)throw new vo(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 vo(a,s)}var vo,mp=I(()=>{"use strict";Hd();Wl();vo=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}});import{promises as iJ}from"node:fs";import oJ from"node:path";function gp(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function hp(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 qP(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 dJ(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 FP(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 JP(e,t,r){let n={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===gk&&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=>!HP(e.children,l)),QP(n)?n:null}if(e.schema===fa&&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=>!HP(e.children,o)),QP(n)?n:null}return null}function HP(e,t){return e.some(r=>r.covers.includes(t))}function QP(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ni(e){return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[],allowedAcceptanceIds:e.acceptance.map(({id:t})=>t)}}function fJ(e){let t=gp(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=gp(i,`Native children acceptance_index.${n}`);if(hp(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 pJ(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 vp(e,t,r={}){let n=(0,UP.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${n.errors[0].message}`);let i=gp(n.toJS({mapAsMap:!1}),"Native children contract"),o=i.schema;if(o!==fa&&o!==pa)throw hp(i,MP,"Native children contract"),new Error(`Native children schema must be ${fa} or ${pa}`);let a=o===fa?"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(hp(i,a==="indexed-v2"?sJ:MP,"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,m)=>{let h=gp(d,`Native child ${m}`);if(hp(h,a==="indexed-v2"||a==="referenced-v2"?uJ:a==="summary-v2"?lJ:cJ,`Native ${s} child fields (child ${m})`),typeof h.name!="string"||!aJ.test(h.name))throw new Error(`Native child ${m} name is invalid`);let p=a==="summary-v2";if(p){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:p?h.summary:null,depends_on:qP(h.depends_on,`Native child ${h.name} depends_on`),covers:a==="indexed-v2"||a==="referenced-v2"||a==="v1"?qP(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 m=d.depends_on.filter(h=>!u.has(h));if(m.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${m.join(", ")}`)}dJ(c);let f=r.policy==="advisory";if(o===gk){if(a==="indexed-v2"||a==="referenced-v2"){let d=a==="indexed-v2"?fJ(i.acceptance_index):{},m=[...new Set([...Object.keys(d),...r.requiredAcceptanceIds??[],...c.flatMap(v=>v.covers)])],h=new Map(r.acceptanceCatalog?.map(v=>[v.id,v])),p=Object.fromEntries(m.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||pJ(p,t,r);let g=Object.keys(p);return f||FP(c,g,r.requiredAcceptanceIds??[]),{schema:pa,acceptance_index:p,children:c}}return{schema:pa,children:c}}return t&&!f&&FP(c,t),{schema:fa,children:c}}async function Si(e){let t=oJ.join(e.changeDir,hk);try{await iJ.lstat(t)}catch(a){if(a.code==="ENOENT")return null;throw a}let r=await Je({root:e.changeDir,ref:hk,includeHash:!1}),n=e.policy==="advisory",i=n?{...e.validation,policy:"advisory"}:e.validation??{},o=vp(r.text,e.acceptanceIds,i);return{contract:o,size:r.size,drift:n?JP(o,e.acceptanceIds,e.validation??{}):null}}function He(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 UP,hk,fa,pa,gk,aJ,MP,sJ,cJ,lJ,uJ,Pr=I(()=>{"use strict";UP=or(Vr(),1);tn();hk="children.yaml",fa="comet.native.children.v1",pa="comet.native.children.v2",gk=pa,aJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MP=new Set(["schema","children"]),sJ=new Set(["schema","acceptance_index","children"]),cJ=new Set(["name","depends_on","covers"]),lJ=new Set(["name","summary","depends_on"]),uJ=new Set(["name","depends_on","covers"])});function ma(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}function KP(e,t){let r=(0,wp.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 wo(e,t){let r=e.lastIndexOf(zP);if(e.startsWith(Vl)&&r>=0&&e.endsWith(`
|
|
274
|
+
`)){let n=e.slice(r+zP.length,-1);try{let i=JSON.parse(n);if(JSON.stringify(i)===n){let o=e.slice(0,r+1),a=KP(o,t);if(a&&typeof a=="object"&&!Array.isArray(a)&&!Object.hasOwn(a,mn)&&Vl+(0,wp.stringify)(a)===o)return{...a,[mn]:i}}}catch{}}return KP(e,t)}var wp,Vl,zP,Ml=I(()=>{"use strict";wp=or(Vr(),1);Ze();Vl=`# comet-execution: managed-run
|
|
275
|
+
`;zP=`
|
|
276
|
+
${mn}: `});function vk(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 GP(e,t){let r=vk(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 yp=I(()=>{"use strict";Mo();lr()});function ql(){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 Ns,kp=I(()=>{"use strict";Ns="comet.native.v4"});var bk={};Fm(bk,{NativePortableStateVersionConflictError:()=>Fl,appendNativePortableHistory:()=>Ur,compareAndSwapNativePortableState:()=>eT,createNativePortableState:()=>_s,parseNativePortableState:()=>M,parseNativeReportedChecks:()=>ei,readNativePortableState:()=>yn,writeNativePortableState:()=>Ak});import{promises as mJ}from"node:fs";function kJ(e,t){let r=Ht(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={...Ht(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 vp(JSON.stringify({...r,children:n}),t.map(i=>i.id),{acceptanceCatalog:t})}function Ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gr(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 ft(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 yk(e,t){return e===null?null:ft(e,t)}function XP(e,t){let r=ft(e,t);if(!wJ.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Ss(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function dt(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 AJ(e,t){return e===null?null:dt(e,t,Number.MIN_SAFE_INTEGER)}function Ot(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function vn(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((n,i)=>r(n,i))}function Rp(e,t){return vn(e,t,(r,n)=>ft(r,`${t}[${n}]`))}function ha(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Es(e,t){let r=ft(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function bp(e,t,r=!1){let n=ft(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 wn(e,t){let r=Ht(e,t);return gr(r,new Set(["text","truncated"]),t),{text:ft(r.text,`${t}.text`,{empty:!0}),truncated:Ss(r.truncated,`${t}.truncated`)}}function bJ(e,t){let r=`Native spec_changes[${t}]`,n=Ht(e,r);gr(n,new Set(["capability","operation","source","delta_source","base_hash"]),r);let i=ft(n.capability,`${r}.capability`);if(!gJ.test(i))throw new Error(`${r}.capability is invalid`);let o=Ot(n.operation,["create","modify","remove"],`${r}.operation`),a=n.source===null?null:bp(n.source,`${r}.source`),s=n.delta_source===void 0?void 0:bp(n.delta_source,`${r}.delta_source`),c=n.base_hash===void 0?void 0:n.base_hash===null?null:XP(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 RJ(e){let t="Native workspace",r=Ht(e,t);gr(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let n=Ot(r.isolation,["current","branch","worktree"],`${t}.isolation`),i=yk(r.change_branch,`${t}.change_branch`),o=yk(r.target_branch,`${t}.target_branch`),a=r.finish===null?null:Ot(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 NJ(e){let t="Native loop",r=Ht(e,t);gr(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=Rp(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);ha(n,`${t}.previous_unresolved_ids`);let i=r.stop_reason===void 0?void 0:Ot(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Ot(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:dt(r.goal_cycle,`${t}.goal_cycle`,1),iteration:dt(r.iteration,`${t}.iteration`),attempt:dt(r.attempt,`${t}.attempt`),retry_epoch:dt(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:dt(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:dt(r.no_progress_count,`${t}.no_progress_count`),...i===void 0?{}:{stop_reason:i},execution_failure_count:dt(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:n,next_action:yk(r.next_action,`${t}.next_action`)}}function SJ(e,t){let r=`Native acceptance[${t}]`,n=Ht(e,r);gr(n,new Set(["id","source","text","result","reason"]),r);let i=ft(n.id,`${r}.id`);if(!vJ.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:bp(n.source,`${r}.source`),text:ft(n.text,`${r}.text`),result:Ot(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:wn(n.reason,`${r}.reason`)}}function kk(e,t){let r=`Native builder_handoff.checks[${t}]`,n=Ht(e,r);return gr(n,new Set(["name","result","note"]),r),{name:wn(n.name,`${r}.name`),result:Ot(n.result,BP,`${r}.result`),note:n.note===null?null:wn(n.note,`${r}.note`)}}function ei(e){return vn(e,"Native reported checks",(t,r)=>{let n=Ht(t,`Native reported checks[${r}]`);return kk({name:Tt(ft(n.name,"Reported check name")),result:n.result,note:n.note==null?null:Tt(ft(n.note,"Reported check note"))},r)})}function EJ(e){let t="Native builder_handoff",r=Ht(e,t);gr(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=Rp(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);ha(n,`${t}.addressed_acceptance_ids`);let i=r.review===null||r.review===void 0?null:Ht(r.review,`${t}.review`);return i&&gr(i,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ft(r.candidate_id,`${t}.candidate_id`),identity_provider:ft(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ft(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:dt(r.iteration,`${t}.iteration`,1),summary:wn(r.summary,`${t}.summary`),addressed_acceptance_ids:n,...r.acceptance_review===void 0?{}:{acceptance_review:pp(r.acceptance_review)},checks:vn(r.checks,`${t}.checks`,kk),checks_truncated:Ss(r.checks_truncated,`${t}.checks_truncated`),known_limits:vn(r.known_limits,`${t}.known_limits`,(o,a)=>wn(o,`${t}.known_limits[${a}]`)),known_limits_truncated:Ss(r.known_limits_truncated,`${t}.known_limits_truncated`),review:i?{status:Ot(i.status,["passed"],`${t}.review.status`),summary:wn(i.summary,`${t}.review.summary`),reviewer_execution_ref:ft(i.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Es(r.submitted_at,`${t}.submitted_at`),...r.raw_input_ref!==void 0?{raw_input_ref:ft(r.raw_input_ref,`${t}.raw_input_ref`)}:{}}}function _J(e,t){let r=`Native blockers[${t}]`,n=Ht(e,r);gr(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=Rp(n.acceptance_ids,`${r}.acceptance_ids`);return ha(i,`${r}.acceptance_ids`),{owner:Ot(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:wn(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:Ot(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function CJ(e,t){let r=`Native verification.checks[${t}]`,n=Ht(e,r);return gr(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ft(n.id,`${r}.id`),name:wn(n.name,`${r}.name`),argv_display:vn(n.argv_display,`${r}.argv_display`,(i,o)=>wn(i,`${r}.argv_display[${o}]`)),argv_truncated:Ss(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:bp(n.cwd_ref,`${r}.cwd_ref`,!0),status:Ot(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:AJ(n.exit_code,`${r}.exit_code`),duration_ms:dt(n.duration_ms,`${r}.duration_ms`)}}function IJ(e){let t="Native verification",r=Ht(e,t);gr(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=vn(r.checks,`${t}.checks`,CJ);ha(n.map(o=>o.id),`${t}.checks IDs`);let i=ft(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ft(r.candidate_id,`${t}.candidate_id`),identity_provider:i,verifier_execution_ref:ft(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:dt(r.iteration,`${t}.iteration`,1),attempt:dt(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":Ot(r.assurance,["host-attested","self-reviewed","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Ot(r.verdict,Bl,`${t}.verdict`),checks:n,...r.reported_checks===void 0?{}:{reported_checks:vn(r.reported_checks,`${t}.reported_checks`,kk)},summary:wn(r.summary,`${t}.summary`),risks:vn(r.risks,`${t}.risks`,(o,a)=>wn(o,`${t}.risks[${a}]`)),risks_truncated:Ss(r.risks_truncated,`${t}.risks_truncated`),completed_at:Es(r.completed_at,`${t}.completed_at`)}}function ZP(e,t){let r=`Native history[${t}]`,n=Ht(e,r);gr(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=Rp(n.unresolved_ids,`${r}.unresolved_ids`);return ha(i,`${r}.unresolved_ids`),{goal_cycle:dt(n.goal_cycle,`${r}.goal_cycle`,1),iteration:dt(n.iteration,`${r}.iteration`),attempt:dt(n.attempt,`${r}.attempt`),outcome:Ot(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:wn(n.summary,`${r}.summary`),completed_at:Es(n.completed_at,`${r}.completed_at`)}}function xJ(e){let t="Native history_overflow.outcome_counts",r=Ht(e,t),n=["pass","fail","blocked","execution-error","recovery"];return gr(r,new Set(n),t),{pass:dt(r.pass,`${t}.pass`),fail:dt(r.fail,`${t}.fail`),blocked:dt(r.blocked,`${t}.blocked`),"execution-error":dt(r["execution-error"],`${t}.execution-error`),recovery:dt(r.recovery,`${t}.recovery`)}}function PJ(e){let t="Native history_overflow",r=Ht(e,t);gr(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let n=dt(r.dropped_entries,`${t}.dropped_entries`),i=r.first_dropped_at===null?null:Es(r.first_dropped_at,`${t}.first_dropped_at`),o=r.last_dropped_at===null?null:Es(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=xJ(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 TJ(e){if(e.verifier_action){if(vk(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)&&!GP(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&&Ll(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 OJ(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=Ht(e,"Native portable state");if(gr(t,yJ,"Native portable state"),t.schema!==Ns)throw new Error(`Native portable state schema must be ${Ns}`);let r=ft(t.name,"Native state name");if(!hJ.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=vn(t.spec_changes,"Native spec_changes",bJ);ha(n.map(s=>s.capability),"Native spec change capabilities");let i=vn(t.acceptance,"Native acceptance",SJ);ha(i.map(s=>s.id),"Native acceptance IDs");let o=vn(t.history,"Native history",ZP);if(o.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let a={schema:Ns,name:r,language:Ot(t.language,["en","zh-CN"],"Native state language"),phase:Ot(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Ot(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:dt(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:XP(t.shape_confirmation_hash,"Native Shape confirmation hash")},...(t.children_contract_ref??t.children_contract_hash)===void 0?{}:{children_contract_ref:ft(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:ft(t.children_contract_hash,"Legacy children approval reference")}:{},...t.children_contract===void 0?{}:{children_contract:kJ(t.children_contract,i)},...t.coordination_mode===void 0?{}:{coordination_mode:Ot(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:n,workspace:RJ(t.workspace),loop:NJ(t.loop),acceptance:i,builder_handoff:t.builder_handoff===null?null:EJ(t.builder_handoff),...t.verifier_action===void 0?{}:{verifier_action:jE(t.verifier_action)},blockers:vn(t.blockers,"Native blockers",_J),verification:t.verification===null?null:IJ(t.verification),history:o,history_overflow:PJ(t.history_overflow),verification_result:Ot(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Ot(t.verification_report,["verification.md"],"Native verification_report"),archived:Ss(t.archived,"Native archived"),created_at:Es(t.created_at,"Native created_at")};return TJ(a),OJ(a),a}function _s(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return M({schema:Ns,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:ql(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ur(e,t){let r=M(e),n=ZP(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 yn(e){let t=await mJ.readFile(e,"utf8");return M(wo(t,"Native portable state"))}async function Ak(e,t,r={}){let n=M(t);await Ue(e,(0,YP.stringify)(n),r)}async function $J(e,t){let r=Ap.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),o=r.then(()=>i);Ap.set(e,o),await r;try{return await t()}finally{n(),Ap.get(e)===o&&Ap.delete(e)}}async function eT(e){return $J(e.file,async()=>{let t=dt(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 yn(e.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==t)throw new Fl(t,n.state_version);return await Ak(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let i=await yn(e.file);if(i.state_version!==t)throw new Fl(t,i.state_version)}}),r})}var YP,hJ,gJ,vJ,wJ,yJ,Fl,Ap,Te=I(()=>{"use strict";Ri();mp();Pr();Wl();YP=or(Vr(),1);Mo();Ml();yp();jt();kp();hJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vJ=/^A[1-9][0-9]*$/u,wJ=/^[a-f0-9]{64}$/u,yJ=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"]);Fl=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"};Ap=new Map});import jJ from"node:path";async function Np(e){let t=[],r=new Set,n=e.ownerObservation===void 0?await tt(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,i=Pt({singleWriter:!0,rootDir:jJ.join(it(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 uk(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 Sp(e){if(e.run.status!=="cancelled")return null;let{quiescent:t,outstandingActions:r,outstandingRuns:n}=await Np(e),i=e.ownerObservation===void 0?await tt(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,o=t?await Qr(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}}var Hl=I(()=>{"use strict";Lr();Ze();bs();pr();po();Te()});function rT(e,t){return Rk[e][t]}function aT(e,t){return nT[e][t]??iT[e][t]}function Nk(e){return oT.get(e.trim().toLocaleLowerCase("en-US"))??null}function WJ(e){return Ep[e].section}function Ql(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`# ${rT(e,n)}
|
|
277
|
+
`;let i=[`# ${rT(e,n)}
|
|
278
|
+
`];return i.push(`## ${WJ(e)}
|
|
279
|
+
`),i.push(Tr(e,`<!-- Add only needed level-three categories (Created, Modified, Deleted, Not created), with paths and responsibilities. Omit unused categories. -->
|
|
280
|
+
`,`<!-- 按实际改动添加三级标题(新建、修改、删除、明确不建),写明路径与职责;无内容的类别可省略。 -->
|
|
281
|
+
`)),i.join(`
|
|
282
|
+
`)}).join(`
|
|
283
|
+
`)}function Tr(e,t,r){return e==="zh-CN"?r:t}var Rk,nT,iT,oT,tT,DJ,BJ,Ep,Cs=I(()=>{"use strict";Rk={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:"验证预期"}},nT={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:"结论"}},iT={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:"结论"}},oT=new Map,tT=new Map,DJ=new Set,BJ=new Map,Ep={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(Rk)){for(let[t,r]of Object.entries(Rk[e]))oT.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(nT[e]))tT.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(iT[e]))tT.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(Ep)){DJ.add(Ep[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(Ep[e].subsections))BJ.set(r.toLocaleLowerCase("en-US"),t)}});function Is(e){return e.replaceAll(`\r
|
|
284
|
+
`,`
|
|
285
|
+
`).replaceAll("\r",`
|
|
286
|
+
`)}function dT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new At(`${t} must be an object`);return e}function fT(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new At(`${r} has unknown field(s): ${n.join(", ")}`)}function pT(e,t){if(typeof e!="string"||e.trim().length===0)throw new At(`${t} must be a non-empty string`);return e.trim()}function sT(e,t){if(e!==void 0){if(typeof e!="string")throw new At(`${t} must be text`);return Is(e).replace(/^\n+|\n+$/gu,"")}}function cT(e,t){let r=pT(e,t);if(!uT.test(r))throw new At(`${t} is not a valid stable requirement ID`);return r}function VJ(e,t){let r=pT(e,t);if(!LJ.test(r))throw new At(`${t} is not a valid capability ID`);return r}function MJ(e,t){let r=`Native delta operations[${t}]`,n=dT(e,r);fT(n,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let i=cT(n.id,`${r}.id`),o=n.operation;if(!["add","modify","remove","rename"].includes(String(o)))throw new At(`${r}.operation is invalid`);let a=o,s=n.to_id===void 0?void 0:cT(n.to_id,`${r}.to_id`),c=sT(n.title,`${r}.title`),l=sT(n.body,`${r}.body`);if(a==="add"){if(s!==void 0||!l?.trim())throw new At(`${r} add requires body and forbids to_id`)}else if(a==="modify"){if(s!==void 0||!l?.trim())throw new At(`${r} modify requires body and forbids to_id`)}else if(a==="remove"){if(s!==void 0||c!==void 0||l!==void 0)throw new At(`${r} remove forbids to_id, title, and body`)}else if(s===void 0||s===i||l==="")throw new At(`${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 qJ(e){let t=dT(e,"Native delta");if(fT(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Sk)throw new At(`Native delta schema must be ${Sk}`);let r=VJ(t.capability,"Native delta capability");if(!Array.isArray(t.operations))throw new At("Native delta operations must be an array");let n=t.operations.map(MJ),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 At(`Native delta operations contain duplicate or overlapping requirement ID ${c} at ${o}`);i.add(c)}}return{schema:Sk,capability:r,base_version:Number.isSafeInteger(t.base_version)&&Number(t.base_version)>0?Number(t.base_version):1,operations:n}}function FJ(e){let t=(0,_k.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new At(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Or(e){return qJ(typeof e=="string"?FJ(e):e)}function HJ(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function QJ(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(!uT.test(s))throw new At(`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 _p(e){let t=Is(e),r=t.split(`
|
|
287
|
+
`),n=QJ(r),i=[],o=new Set;for(let l of n){if(o.has(l.id))throw new At(`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(m=>m.line===f)){u=f;break}let d=HJ(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(`
|
|
288
|
+
`)}${l.end<r.length?`
|
|
289
|
+
`:""}`,f=r.slice(l.start+1,l.end).join(`
|
|
290
|
+
`).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(`
|
|
291
|
+
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
292
|
+
`)),{text:t,lines:r,requirements:a,legacyText:s.join(`
|
|
293
|
+
`)}}function Cp(e,t,r,n){let i=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,o=Is(n).replace(/\n+$/u,"");return[i,"",...o.split(`
|
|
294
|
+
`),"",""].join(`
|
|
295
|
+
`)}function Ek(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function Ip(e,t){if(e.operation==="rename"){if(!t)throw new At(`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 UJ(e,t,r){let n=_p(e),i=[...n.lines],o=n.requirements.get(t.id);if(!o)throw new At(`Requirement target disappeared: ${t.id}`);return i.splice(o.startLine,o.endLine-o.startLine,...r.split(`
|
|
296
|
+
`)),i.join(`
|
|
297
|
+
`)}function JJ(e,t){let r=Is(e),n=r.length===0||r.endsWith(`
|
|
298
|
+
|
|
299
|
+
`)?"":`
|
|
300
|
+
`,i=`${r}${n}`;return`${i.endsWith(`
|
|
301
|
+
`)||i.length===0?i:`${i}
|
|
302
|
+
`}${t}`}function zJ(e,t){if(e.operation==="add"||e.operation==="modify"){let o=t.requirements.get(e.id);if(!o)return!1;let a=Ip(e,e.operation==="modify"?o:void 0);return o.raw===Cp(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=Ip(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===Cp(i.level,i.id,i.title,i.body)}function mT(e){let t=Is(e.baselineMarkdown),r=[],n=[];for(let o of e.delta.operations){let a=_p(t),s=a.requirements.get(o.id);if(e.allowAlreadyApplied&&zJ(o,a)){n.push({id:o.id,operation:o.operation,status:"already-applied",targetIds:Ek(o)});continue}if(o.operation==="add"){if(s)throw new Ul([o.id],`Native delta add conflicts with existing requirement ${o.id}`);let c=Ip(o,void 0);t=JJ(t,Cp(c.level,c.id,c.title,c.body))}else{if(!s)throw new Ul([o.id],`Native delta ${o.operation} target does not exist: ${o.id}`);let c=Ip(o,s);if(o.operation==="rename"&&_p(t).requirements.has(o.to_id))throw new Ul([o.id,o.to_id],`Native delta rename destination already exists: ${o.to_id}`);if(o.operation==="remove"){let l=[..._p(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
|
|
303
|
+
`)}else t=UJ(t,s,Cp(c.level,c.id,c.title,c.body))}r.push(...Ek(o)),n.push({id:o.id,operation:o.operation,status:"changed",targetIds:Ek(o)})}return{markdown:Is(t),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:n}}function hT(e){return mT({baselineMarkdown:e.baselineMarkdown,delta:Or(e.delta),allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}function Jl(e){return mT({baselineMarkdown:e.currentMarkdown,delta:Or(e.delta),allowAlreadyApplied:!0,rebased:!1})}var _k,Sk,lT,LJ,uT,At,Ul,xs=I(()=>{"use strict";_k=or(Vr(),1),Sk="comet.native.delta.v1",lT="delta.yaml",LJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uT=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,At=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Ul=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var xp,Ck,Ik,Pp=I(()=>{"use strict";xp="comet.native.v3",Ck="comet.native.v2",Ik="comet.native.v1"});function xk(e){if(!YJ.test(e))throw new Error(`Invalid Native capability id: ${e}`)}var gT,Y7,GJ,X7,YJ,zl=I(()=>{"use strict";Pp();gT=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Y7=new Set(gT),GJ=new Set([...gT,"minimum_runtime_version","revision"]),X7=new Set([...GJ,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),YJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as XJ}from"crypto";function Dn(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ZJ(e,t){t.has(e)&&Dn("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)||Dn("sparse arrays are not supported");return(r.length!==e.length||r.some((n,i)=>n!==String(i)))&&Dn("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Dn("symbol properties are not supported"),`[${e.map(n=>Pk(n,t)).join(",")}]`}finally{t.delete(e)}}function ez(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Dn("only plain objects are supported"),t.has(e)&&Dn("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Dn("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))&&Dn("accessor properties are not supported"),`${JSON.stringify(a)}:${Pk(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Pk(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)||Dn("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ZJ(e,t):ez(e,t);case"bigint":case"function":case"symbol":case"undefined":return Dn(`${typeof e} values are not supported`)}return Dn("unsupported value type")}function tz(e){return Pk(e,new Set)}function Tp(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 XJ("sha256").update(`${e}
|
|
304
|
+
${tz(t)}`).digest("hex")}var Tk=I(()=>{"use strict"});function yT(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 vT(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 wT(e){return e.includes("-->")||e.includes("--!>")}function*Op(e){let t=null,r=!1,n=null,i=new Set(["code","pre","script","style","svg","template"]),o=e.replace(/\r\n?/gu,`
|
|
305
|
+
`),a=0,s=0;for(;a<=o.length;){let c=o.indexOf(`
|
|
306
|
+
`,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=vT(l,t);else if(r)wT(l)&&(r=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=vT(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!wT(d))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);m&&i.has(m[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(d)&&(n=m[1])}}}if(c===-1)break;a=c+1}}function Kl(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function $k(e,t,r,n=[],i="content-hash"){let o=Kl(r),a=t.replaceAll("\\","/").trim(),s=n.map(Kl);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-${Tp(rz,{kind:e,source:a,context:s,text:o})}`:"",kind:e,source:a,context:s,text:o}}function jk(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 nz(e){let t=null,r=null,n=0,i=0;for(let{line:o,body:a,index:s}of Op(e)){i=s+1;let c=a?yT(o):null;c?.level===1&&(Nk(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 kT(e,t="brief.md",r=Ok.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=nz(e);if(i===null)return[];let o=null;for(let{line:l,body:u,index:f}of Op(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let m=d[1].length;o=o===null?m:Math.min(o,m)}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 Op(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(),jk(a.map(l=>$k("brief-example",t,l.join(`
|
|
307
|
+
`),[],n)),"Brief",n)}function AT(e,t="brief.md",r=Ok.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,`
|
|
308
|
+
`)),o=i.flatMap((c,l)=>c.type==="heading"&&Nk(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($k("brief-example",t,u,[],n))}}return jk(s,"Brief",n)}function bT(e,t="spec.md",r=Ok.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({...$k("spec-scenario",t,[s.title,...s.body].join(`
|
|
309
|
+
`),s.context,n),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of Op(e)){let f=u?yT(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 m=Kl(d[1]);if(m.length===0)throw new Error("Scenario title must not be empty");s={level:f.level,title:m,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(),jk(o,"Specification",n)}var rz,oee,Ok,RT=I(()=>{"use strict";Yy();Cs();Tk();rz="comet.native.acceptance.v1",oee=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ok=Object.freeze({maxCriteria:1024})});import NT from"node:path";function ST(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||NT.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||NT.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function iz(e,t){return e.localeCompare(t,"en")}function ET(e){let t=ST(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((s,c)=>iz(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?kT:AT)(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=ST(s.source,`Native spec source for ${s.capability}`);for(let l of bT(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=Kl(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 $p=I(()=>{"use strict";RT()});function fz(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pz(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 IT(e){let t=fz(e,"Native portable migration transaction"),r=Object.keys(t).filter(n=>!sz.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==_T)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!lz.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!cz.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!dz.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!uz.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:_T,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:pz(t.createdAt,"Native portable migration transaction createdAt")}}var _T,sz,cz,lz,uz,dz,xT=I(()=>{"use strict";zl();$p();Te();Ri();kp();Pp();_T="comet.native.portable-migration.v1",sz=new Set(["schema","id","change","fromSchema","status","createdAt"]),cz=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lz=/^[a-z0-9][a-z0-9-]{7,127}$/u,uz=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),dz=new Set([Ik,Ck,xp])});import Bk from"node:path";function $T(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jT(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 Dk(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 PT(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function Az(e,t){let r=`Native portable Archive spec_changes[${t}]`,n=$T(e,r);if(jT(n,kz,r),typeof n.capability!="string"||!OT.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=Dk(n.base_hash,`${r}.base_hash`),s=PT(n.delta_content,`${r}.delta_content`),c=PT(n.source_content,`${r}.source_content`),l=Dk(n.expected_target_hash,`${r}.expected_target_hash`),u=Dk(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&&Or(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 bz(e){let t=$T(e,"Native portable Archive transaction");if(jT(t,yz,"Native portable Archive transaction"),t.schema!==jp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!gz.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!OT.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"||!vz.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"||!wz.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(Az);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:jp,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 Dp(e){let t=mz.exec(e);if(t)return{kind:"archive",change:t[1]};let r=hz.exec(e);return r?{kind:"migration",change:r[1]}:null}function Bp(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,n=Dp(r);if(!n||n.kind!==t.kind||n.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Bk.join(e.transactionsDir,r)}async function Wk(e,t){let r=Dp(t);if(!r)return null;let n=await Je({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),o=Bk.join(e.transactionsDir,t);if(r.kind==="archive"){let s=bz(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=IT(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 Ei(e,t){let r=Bp(e,t);try{return await Wk(e,Bk.basename(r))}catch(n){if(n.code==="ENOENT")return null;throw n}}function DT(e){return e.kind==="archive"||e.journal.status!=="committed"}var jp,TT,mz,hz,gz,vz,wz,yz,kz,OT,Gl=I(()=>{"use strict";tn();xs();xT();jp="comet.native.archive-transaction.v4",TT="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",mz=new RegExp(`^portable-archive-(${TT})\\.json$`,"u"),hz=new RegExp(`^portable-migration-(${TT})\\.json$`,"u"),gz=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vz=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wz=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),yz=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),kz=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),OT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Rz}from"node:crypto";import{constants as Wp,promises as Lt}from"node:fs";import vt from"node:path";function kn(e,t){let r=vt.relative(e,t);return r===""||!vt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${vt.sep}`)}function Nz(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Lk(e,t){return ht({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sz(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lp(e,t){return ht({...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 Ps(e,t){let r=await Lt.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Vk(e,t,r){let n=vt.resolve(e),i=vt.resolve(t);if(!kn(n,i))throw new Error(`${r} is outside its managed root`);let o=[await Ps(n,r)],a=n;for(let s of vt.relative(n,i).split(vt.sep).filter(Boolean)){await Jr(o,r),a=vt.join(a,s);let c=await Ps(a,r);if(!kn(o[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${a}`);o.push(c)}return await Jr(o,r),o}async function Jr(e,t){for(let r of e){let n=await Lt.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!Lk(r,n)||await Lt.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Ez(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 BT(e){let t=e.maxBytes===null?null:Nz(e.maxBytes),r=vt.resolve(e.file),n=await Vk(e.root,vt.dirname(r),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(u=>Ps(vt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Jr(n,e.label);let o=await Lt.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=Sz(o),s=await Lt.realpath(r);if(!kn(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(u=>kn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Wp.O_RDONLY:Wp.O_RDONLY|Wp.O_NOFOLLOW|Wp.O_NONBLOCK,l=await Lt.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([Lt.lstat(r),Lt.realpath(r)]);if(await Jr(n,e.label),await Jr(i,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!Lp(a,u)||!Lp(a,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Ez(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[h,p,g]=await Promise.all([l.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await Jr(n,e.label),await Jr(i,e.label),!p.isFile()||p.isSymbolicLink()||g!==s||!Lp(a,h)||!Lp(a,p))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Rz("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function WT(e){let t=vt.resolve(e.root),r=vt.resolve(e.directory);if(!kn(t,r))throw new Error(`${e.label} is outside its managed root`);let n=[await Ps(t,e.label)],i=t;for(let o of vt.relative(t,r).split(vt.sep).filter(Boolean)){await Jr(n,e.label),i=vt.join(i,o);try{await Lt.mkdir(i)}catch(s){if(s.code!=="EEXIST")throw s}let a=await Ps(i,e.label);if(!kn(n[0].realPath,a.realPath))throw new Error(`${e.label} resolves outside its managed root: ${i}`);n.push(a)}await Jr(n,e.label)}async function LT(e){let t=vt.resolve(e.root),r=vt.resolve(e.source),n=vt.resolve(e.target);if(r===n||!kn(t,r)||!kn(t,n)||kn(r,n)||kn(n,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await WT({root:t,directory:vt.dirname(n),label:`${e.label} target parent`});let i=await Vk(t,vt.dirname(r),e.label),o=await Vk(t,vt.dirname(n),e.label),a=await Ps(r,e.label);if(!kn(i[0].realPath,a.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await Lt.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Jr(i,e.label),Jr(o,e.label)]);let s=await Lt.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!Lk(a,s)||await Lt.realpath(r)!==a.realPath)throw new Error(`${e.label} source changed before move`);await Lt.rename(r,n),await Promise.all([Jr(i,e.label),Jr(o,e.label)]);let c=await Lt.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Lk(a,c)||!kn(i[0].realPath,await Lt.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await Lt.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}var Mk=I(()=>{"use strict";jt();Vc()});import{lstatSync as Cz,promises as Oee}from"fs";import An from"path";import{TextDecoder as Iz}from"util";function Mp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qp(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 FT(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function qk(e,t){if(typeof e!="string"||e.length===0||An.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Vp(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function VT(e,t){if(qk(e,t),e.includes("\\")||e!==An.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 jz(e,t){let r=Mp(e,`transaction operations[${t}]`);if(qp(r,Pz,`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`);qk(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&qk(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 Dz(e){let t=Mp(e,"Native Archive transaction journal");if(qp(t,Tz,"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"||!qT.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(!FT(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Vp(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=Mp(s,`Archive transaction operations[${c}]`);if(qp(l,Oz,`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`);VT(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&VT(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Vp(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(Vp(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`);Vp(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 Bz(e){let t=Mp(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Dz(t);if(qp(t,xz,"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"||!qT.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!An.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!An.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(!FT(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(jz),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 HT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);let r=An.join(e.transactionsDir,t),n=An.join(e.runtimeDir,"transaction-history",t),i=o=>{try{return Cz(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 QT(e,t){let r=await Fk(e,t);if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${t} is unfinished`);let n=HT(e,t),i=An.join(e.runtimeDir,"transaction-history",t);n!==i&&(await LT({root:e.runtimeDir,source:n,target:i,label:"Native completed transaction"}),await Mc(An.dirname(i)),await Mc(e.transactionsDir),await Mc(e.runtimeDir))}function Wz(e,t){let r=HT(e,t);return{directory:r,journal:An.join(r,"transaction.json"),events:An.join(r,"events.jsonl"),staged:An.join(r,"staged"),backups:An.join(r,"backups")}}async function Lz(e,t){let r=Wz(e,t);return await Promise.all(Object.values(r).map(n=>fi(e.runtimeDir,n))),r}async function Fk(e,t,r={}){let n=await Lz(e,t),i=await BT({root:e.runtimeDir,file:n.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),o=JSON.parse($z.decode(i.bytes)),a=Bz(o);if(a.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return a}var xz,Pz,Tz,Oz,qT,$z,UT=I(()=>{"use strict";jt();Ye();Mk();xz=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Pz=new Set(["id","type","source","target","staged","backup"]),Tz=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Oz=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),qT=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),$z=new Iz("utf-8",{fatal:!0})});import{promises as Vz}from"fs";async function Mz(e,t,r){let n;try{n=await Vz.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 Fk(e,i.name);if(o.id!==t&&o.status!=="committed"&&o.status!=="rolled-back")return!0;(o.status==="committed"||o.status==="rolled-back")&&await QT(e,o.id)}catch{return!0}for(let i of n)if(Dp(i.name))try{let o=await Wk(e,i.name);if(!o||r?.kind===o.kind&&r.change===o.change)continue;if(DT(o))return!0}catch{return!0}return!1}async function Qe(e,t,r){if(await Md(e.projectRoot),await Mz(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return t()}var Vt=I(()=>{"use strict";_t();Gl();UT()});var JT=I(()=>{"use strict"});var Fp=I(()=>{"use strict"});var Hp=I(()=>{"use strict"});var zT=I(()=>{"use strict"});var Hk=I(()=>{"use strict";Hp()});var KT=I(()=>{"use strict";Hp();Hk()});var Jz,GT=I(()=>{"use strict";Jz=or(Vr(),1);Nn();di();ot()});var ate,YT=I(()=>{"use strict";Nn();ot();ate=Number.MAX_SAFE_INTEGER});var XT=I(()=>{"use strict"});var ZT=I(()=>{"use strict";Qm();XT()});var eO=I(()=>{"use strict";ZT()});var Ate,tO=I(()=>{"use strict";qn();Ha();eO();Ate=Zr("hookWritePolicy",async e=>(await Ug(e))?.hook??{allow_paths:[]})});var rO=I(()=>{"use strict";Hp();Nn();zT();KT();di();GT();ot();Ha();tv();YT();tO();po();Zg();Hk()});var nO=I(()=>{"use strict";rO();Ca()});var gre,iO=I(()=>{"use strict";nO();gre=Number.MAX_SAFE_INTEGER});var oO=I(()=>{"use strict";iO();Fp()});var Ire,aO=I(()=>{"use strict";Fp();oO();jt();Vc();Ire={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 cO=I(()=>{"use strict";Fp();Vt();Ye();aO()});var Fre,Hre,lO=I(()=>{"use strict";wt();jt();tn();Vt();Ye();Fre=Number.MAX_SAFE_INTEGER,Hre=process.platform});var dO,Rne,Yl=I(()=>{"use strict";_a();_a();Sx();qn();dO=or(Vr(),1);wt();Ze();pr();bs();Hl();Iy();tn();jt();Cs();_t();Vt();Te();Ye();Mk();JT();cO();lO();Pp();zl();zl();Rne=Ql("en")});var fO=I(()=>{"use strict"});function Qk(e){return{valid:e.length===0,findings:e}}function pO(e,t){return Qk(e.trim()?[]:[{code:"spec-document-empty",message:"Native target Spec is empty: "+t,path:t}])}function tK(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(rK(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 rK(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 mO(e,t,r={}){let n;try{n=(await Je({root:e,ref:t,maxBytes:r.maxBytes??null,includeHash:!1})).text}catch(o){return Qk([{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}),tK(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Qk(i)}var Ts,Uk=I(()=>{"use strict";tn();Yl();fO();Ye();Ts=class extends Error{constructor(r,n,i){super(r);this.findings=n;this.change=i;this.name="NativeDocumentConstraintError"}findings;change}});import{execFileSync as dK}from"node:child_process";function bO(e,t,r=pK){try{return Ks(()=>dK("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:fK,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 Xk(e,t,i)}}function de(e,t){return bO(e,t).trim()}function ga(e){return de(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Zk(e,t){de(e,["check-ref-format","--branch",t])}function RO(e){return mK(bO(e,["status","--porcelain=v1","-z","--untracked-files=all"]))}function mK(e){return[...new Set(hK(e).flatMap(t=>t.paths.map(r=>r.replaceAll("\\","/"))))].sort()}function hK(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 fK,pK,Xk,zr=I(()=>{"use strict";Eu();Jm();fK=3e4,pK=8*1024*1024,Xk=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}});import NO from"node:path";function Mt(e,t){if(!Up.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=NO.join(e.changesDir,t);if(!qr(e.changesDir,r))throw new Error("Native change path escaped");return r}function vr(e,t){return NO.join(Mt(e,t),SO)}function eu(e,t){if(!t)return;let r=Ae(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 ti(e,t){return yn(vr(e,t))}var Up,SO,Kt=I(()=>{"use strict";Mo();yp();wt();zr();Te();Ye();Up=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SO="comet-state.yaml"});function eA(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 EO=I(()=>{"use strict"});var _O=I(()=>{"use strict"});import vK from"node:path";function CO(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:vK.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 tu(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()],...CO(e,t)?{userEditedReport:CO(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 tA=I(()=>{"use strict";_O()});function rA(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function nA(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){rA(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:wr,executionRef:rA(t.executionRef,"Native execution ref"),[IO]:!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:rA(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[xO]:!0})}})}function iA(e){return typeof e=="object"&&e!==null&&e[xO]===!0}function PO(e){return typeof e=="object"&&e!==null&&e[IO]===!0}var IO,xO,wr,va=I(()=>{"use strict";IO=Symbol("comet.native.trusted-execution-identity"),xO=Symbol("comet.native.trusted-verifier-envelope"),wr="skill-coordinated"});function Jp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function TO(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function zp(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Kp(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,n)=>{let i=Jp(r,`Native Verifier acceptance ${n}`);Wo(i,["id","result","reason"],`Native Verifier acceptance ${n}`,`${t}/${n}`);let o=zp(i.id,`Native Verifier acceptance ${n} ID`),a=Rs(i.result,pk,`Native Verifier acceptance ${o} result`);return{id:o,result:a,reason:zp(i.reason,`Native Verifier acceptance ${o} reason`)}})}function wK(e,t){let r=Jp(e,"Native Verifier final result");Wo(r,["iteration","attempt","verdict","acceptance","risks","summary",...Object.hasOwn(r,"requestReview")?["requestReview"]:[]],"Native Verifier final result",t);let n=Rs(r.verdict,Bl,"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=Jp(r.requestReview,"Native requestReview");Wo(o,["result","reason"],"Native requestReview",`${t}/requestReview`),i={result:Rs(o.result,WP,"Native requestReview result"),reason:zp(o.reason,"Native requestReview reason")}}return{...i?{requestReview:i}:{},iteration:TO(r.iteration,"Native Verifier iteration"),attempt:TO(r.attempt,"Native Verifier attempt"),verdict:n,acceptance:Kp(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:zp(r.summary,"Native Verifier summary")}}function OO(e,t=""){let r=Jp(e,"Native Verifier response");if(r.kind==="final-result")return Wo(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:wK(r.result,`${t}/result`)};throw new Error(`Native Verifier response kind must be one of: ${VP.join(", ")}`)}function $O(e){if(!iA(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=OO(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=Gp(n.result,r);return{...n,result:{...n.result,acceptance:a}}}function Gp(e,t){Kp(e.acceptance);let r=[...t.acceptanceIds],n=new Set(t.knownAcceptanceIds??r),i=new Set(t.previouslyPassedAcceptanceIds??[]),o=r.filter(p=>!n.has(p)),a=[...i].filter(p=>!n.has(p));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:p})=>p),l=c.filter((p,g)=>c.indexOf(p)!==g),u=c.filter(p=>!n.has(p)),f=r.filter(p=>!c.includes(p)),d=e.acceptance.filter(({id:p,result:g})=>s.has(p)||!n.has(p)?!1:!i.has(p)||g!=="passed").map(({id:p,result:g})=>`${p}=${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 m=e.acceptance.filter(({id:p})=>s.has(p));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let h=m.map(({result:p})=>p);if(e.verdict==="pass"&&h.some(p=>p!=="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 m}var ru=I(()=>{"use strict";Wl();Hd();va()});function nu(e,t){if(!yK.test(e))throw new Error(`${t} must be a Git commit`)}function yo(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 yK,Yp,_i=I(()=>{"use strict";Wl();tA();ru();yK=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Yp="comet.native.supervisor.v2"});import{promises as kK}from"node:fs";import iu from"node:path";function jO(e,t){return iu.join(qg(e,t),"supervisor")}function DO(e,t){return iu.join(jO(e,t),"state.json")}function AK(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!==Yp)throw new Error(`Native Supervisor state schema must be ${Yp}`);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(nu(t.integration.targetCommit,"Native Supervisor target commit"),nu(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&&nu(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(nu(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 ko(e,t,r={}){try{let n=await kK.readFile(DO(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(AK(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(()=>(Te(),bk)),c=await s(iu.join(a.changesDir,t,"comet-state.yaml")),l=await Si({changeDir:iu.join(a.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Ni(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=yo(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(()=>(Te(),bk)),s=await a(iu.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 Ao=I(()=>{"use strict";jt();Pr();Ye();_i()});import Xp from"node:path";function oA(...e){if(e.length===0)return Xp.resolve();if(Xp.win32.isAbsolute(e[0])){let t=Xp.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Xp.resolve(...e)}var BO=I(()=>{"use strict"});import{randomUUID as bK}from"node:crypto";import{promises as ou,lstatSync as aA,readFileSync as RK,realpathSync as NK}from"node:fs";import ri from"node:path";function WO(e){try{if(de(e,["ls-files","--",$s]))return!1;let t=ri.join(e,$s),r=aA(t);if(!r.isFile()||r.isSymbolicLink())return!1;let n=it(e),i=sA(e);for(let s of[n,ri.dirname(i)]){let c=aA(s);if(c.isSymbolicLink()||!c.isDirectory())return!1}let o=aA(i);if(!o.isFile()||o.isSymbolicLink()||NK(i)!==ri.resolve(i))return!1;let a=JSON.parse(RK(i,"utf8"));return a.created===!0||typeof a.hash=="string"}catch{return!1}}async function LO(e){let t=ri.join(e,$s);try{await ou.access(t)}catch(i){if(i.code==="ENOENT")return;throw i}let r=await Wi(e),n=sA(e);await ou.mkdir(ri.dirname(n),{recursive:!0}),await pi(n,{created:!0},{containedRoot:r})}function bo(e,t=[]){return RO(e).every(r=>t.some(n=>r===n||r.startsWith(`${n}/`))||r===$s&&WO(e))}async function VO(e){if(!WO(e))return;let t=await Wi(e),r="native/preserved-configs/"+bK()+".yaml",n=ri.join(t,r);await ou.mkdir(ri.dirname(n),{recursive:!0}),await ou.copyFile(ri.join(e,$s),n),await pi(sA(e),{created:!0,preservedRef:r},{containedRoot:t}),await ou.unlink(ri.join(e,$s))}var $s,sA,au=I(()=>{"use strict";Lr();zr();jt();$s=".comet/config.yaml",sA=e=>ri.join(it(e),"native","workspace-config.json")});import{promises as su}from"node:fs";import jr from"node:path";function HO(e,t){let r=jr.relative(e,t);return r===""||!jr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jr.sep}`)}function MO(e){let t={...e.native};return delete t.max_parallel_children,JSON.stringify(t)}async function Zp(e,t){let r=await We(e);if(r&&t){if(MO(r)!==MO(t))throw new Error(`Native worktree configuration differs from the source project: ${jr.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await qd(e,t),await LO(e),!0):!1}async function qO(e,t){let r=["/.comet/runtime"];if(t&&HO(e,t)){let l=jr.relative(e,t).replaceAll("\\","/");r.push(`/${l.replace(/\/+$/u,"")}/`)}let n=de(e,["rev-parse","--git-common-dir"]),i=jr.resolve(e,n),o=jr.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(jr.dirname(o),{recursive:!0});let c=a.length===0||a.endsWith(`
|
|
310
|
+
`)?"":`
|
|
311
|
+
`;return await su.appendFile(o,`${c}${s.join(`
|
|
312
|
+
`)}
|
|
313
|
+
`,"utf8"),!0}function SK(e,t,r){let n=jr.resolve(e,r??jr.join(".worktrees",t)),i=jr.resolve(e,de(e,["rev-parse","--git-common-dir"]));if(HO(i,n))throw new Error("Native worktree path cannot be inside the Git common directory");if(qt(e).some(o=>me(o,n)))throw new Error(`Native worktree path is already registered: ${n}`);return n}async function EK(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 FO(e){try{return await su.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function cA(e){let t=jr.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=Ae(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=Ae(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}`;Zk(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(Zk(t,o),!Xs(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);let a=await qO(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(!ga(t))throw new Error("Native branch isolation requires a clean current working directory");if(Xs(t,n))throw new Error(`Native change branch already exists: ${n}`);de(t,["switch","-c",n,o]),h=!0}let p;try{p=await Zp(t,e.sourceConfig)}catch(g){throw new Ln(`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:p}}}if(i){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?jr.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!me(h,r.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${r.currentWorktreeRoot}`);let p;try{p=await Zp(t,e.sourceConfig)}catch(g){throw new Ln(`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:p}}}let s=_u(r.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await FO(c.root)){let h=e.worktreePath?jr.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!me(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let p;try{p=await Zp(c.root,e.sourceConfig)}catch(g){throw new Ln(`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:p}}}c&&!await FO(c.root)&&(de(r.primaryWorktreeRoot,["worktree","prune"]),s=_u(r.primaryWorktreeRoot));let l=Xs(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=SK(r.primaryWorktreeRoot,e.name,e.worktreePath);await EK(u);let f=await qO(r.primaryWorktreeRoot,u),m={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a||f,configInitialized:!1};try{de(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),m.createdBranch=!l,m.createdWorktree=!0,m.configInitialized=await Zp(u,e.sourceConfig)}catch(h){throw new Ln(`Native worktree preparation is incomplete: ${h.message}`,m,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:m}}var QO=I(()=>{"use strict";_a();_a();zr();wt();_t();au()});import wa from"node:path";function bt(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 pt(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native Supervisor parent name: ${t}`);return oA(e,".worktrees",`${t}-integration`)}function Rt(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 oA(e,".worktrees",`${t}-${r}`)}async function em(e){let t=wa.join(".worktrees",`${e.parent}-integration`);return cA({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:bt(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function tm(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 cA({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:wa.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function uA(e,t){try{return de(e,["show-ref","--verify","--quiet",`refs/heads/${t}`]),!0}catch{return!1}}function IK(e,t){let r=wa.relative(wa.resolve(e),wa.resolve(t));return r===""||!wa.isAbsolute(r)&&!r.startsWith(`..${wa.sep}`)}function lA(e){if(Ae(e.targetRoot).currentBranch!==e.targetBranch||he(e.targetRoot,e.targetBranch)!==e.targetCommit)throw new Error("Native Supervisor target branch changed during cleanup")}function lu(e){lA(e);let t=qt(e.projectRoot);for(let r of e.candidates){if(t.some(n=>me(n,r.root))){if(IK(r.root,process.cwd()))throw new Error(`Native Supervisor cannot clean the current worktree: ${r.root}`);if(Ae(r.root).currentBranch!==r.branch||!bo(r.root))throw new Error(`Native Supervisor cleanup found a changed worktree: ${r.root}`)}if(uA(e.projectRoot,r.branch))try{de(e.projectRoot,["merge-base","--is-ancestor",r.branch,e.targetCommit])}catch{throw new Error(`Native Supervisor cleanup found an unintegrated branch: ${r.branch}`)}}}function js(e){let t=qt(e.projectRoot);return e.candidates.every(r=>!t.some(n=>me(n,r.root))&&!uA(e.projectRoot,r.branch))}async function dA(e){if(!js(e)){lu(e);for(let t of e.candidates)lA(e),qt(e.projectRoot).some(r=>me(r,t.root))&&(await VO(t.root),de(e.projectRoot,["worktree","remove",t.root]));for(let t of e.candidates)lA(e),uA(e.projectRoot,t.branch)&&de(e.targetRoot,["branch","-d",t.branch]);if(!js(e))throw new Error("Native Supervisor cleanup did not remove every temporary worktree")}}async function UO(e,t){let r=await ko(e,t.name,{diagnostics:!0});if(!r)return null;let n=Ae(e.projectRoot).primaryWorktreeRoot??e.projectRoot,i=pt(n,t.name),o=bt(t.name);if(r.parent!==t.name||!me(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=Rt(n,t.name,s.name);if(!c||!me(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 yr=I(()=>{"use strict";wt();BO();zr();_i();Ao();au();QO()});var uu=I(()=>{"use strict";wt();zr();_t();Vt();_i();Ao();yr()});var GO=I(()=>{"use strict";_i();Ao();yr();uu()});var OK,Ds=I(()=>{"use strict";OK=or(Vr(),1);wt();zr();Pr();_t();Ye();Te();GO();Pr()});function YO(e){return e.replace($K,"$1 [REDACTED]").replace(jK,"[REDACTED PRIVATE KEY]").replace(DK,"$1[REDACTED]@").replace(BK,"[REDACTED TOKEN]").replace(WK,'$1"[REDACTED]"').replace(LK,"$1$2$1$3$4[REDACTED]$4").replace(VK,"$1$2[REDACTED]")}var $K,jK,DK,BK,WK,LK,VK,XO=I(()=>{"use strict";$K=/\b(Bearer|Basic)\s+[^\s"']+/giu,jK=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,DK=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,BK=/\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,WK=/("(?:[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,LK=/(["'])((?:[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,VK=/\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 MK}from"node:crypto";function Dr(e){return Tt(YO(e))}function Kr(e){return e.state_version+1}function FK(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 ZO(e){return e.map(t=>({...t,result:"pending",reason:null}))}function e0(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function HK(e){return(e??[]).map(t=>({name:Dr(t.name),result:t.result,note:t.note?Dr(t.note):null}))}function Bs(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:Dr(e.summary),completed_at:e.completedAt}}function fA(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:Kr(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 pA(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:Kr(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function mA(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(!PO(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=FK(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),i=[],o,a;if(r.acceptanceReview!==void 0)try{a=pp(r.acceptanceReview,t.acceptance,"acceptanceReview")}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}else if(e.requireAcceptanceReview!==!1)try{Ll(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 vo)throw o;if(i.length)throw new Error(i.join(`
|
|
314
|
+
`)+`
|
|
315
|
+
Correct the reported business fields and submit a new outcomeId using the original claim.`);let s=ZO(t.acceptance),c=(r.now??new Date).toISOString();return M({...t,phase:"verify",state_version:Kr(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:s,builder_handoff:{candidate_id:r.candidateId??MK(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:Dr(r.summary),addressed_acceptance_ids:n,acceptance_review:a,checks:HK(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(l=>Dr(l)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:Dr(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 ni(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:Kr(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function QK(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:Dr(e.response.result.summary),risks:e.response.result.risks.map(t=>Dr(t)),risks_truncated:!1,completed_at:e.completedAt}}function hA(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=e0(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let n=$O({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 m=o.get(d.id);return m?{...d,result:m.result,reason:Dr(m.reason)}:d}),s=a.filter(({result:d})=>d==="failed"||d==="blocked").map(({id:d})=>d),c=QK({state:t,envelope:e.envelope,response:n,completedAt:i});if(e.reportedChecks&&(c.reported_checks=e.reportedChecks),n.result.verdict==="pass"){let d=Ur({...t,acceptance:a,verification:c},Bs({state:t,outcome:"pass",summary:n.result.summary,completedAt:i})),m=t.builder_handoff.identity_provider===wr;return{response:n,state:M({...d,phase:m?"verify":"archive",status:m?"await-user":"active",state_version:Kr(t),verification_result:"pass",verification_report:"verification.md",blockers:m?[{owner:"user",reason:Dr(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:m?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:m?"confirm-skill-coordinated-pass":"archive"}})}}if(n.result.verdict==="blocked"){let d=Ur({...t,acceptance:a,verification:c},Bs({state:t,outcome:"blocked",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:M({...d,status:"await-user",state_version:Kr(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:Dr(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=Ur({...t,acceptance:a,verification:c},Bs({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:Kr(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:Dr("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 gA(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:Kr(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function vA(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=Ur(r,Bs({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:Kr(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 wA(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>=qK,o=Ur(t,Bs({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return M({...o,status:i?"blocked":"active",state_version:Kr(t),blockers:i?[{owner:"runtime",reason:Dr(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 yA(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=e0(t),a=t.acceptance.some(({result:s})=>s==="passed");return M({...t,status:"active",state_version:Kr(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 Ws(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=Ur(t,Bs({state:t,outcome:"recovery",summary:e.reason,completedAt:o})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?ZO(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:Kr(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:Dr(`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:Kr(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 qK,ya=I(()=>{"use strict";mp();Te();Ri();va();ru();XO();qK=3});import t0 from"node:path";async function kA(e){let{paths:t,state:r}=e;if(r.phase!=="shape"||r.status!=="active")return;let n=t0.join(t.changesDir,r.name);for(let i of e.specChanges){if(i.operation!=="modify"||!i.delta_source||!i.source)continue;let o=await Je({root:t.specsDir,ref:i.capability+"/spec.md",maxBytes:null,includeHash:!1}),a=await Je({root:n,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=Or(a.text);if(s.capability!==i.capability)throw new Error("Native Delta capability does not match its target");let c=hT({baselineMarkdown:o.text,delta:s,allowAlreadyApplied:!0}),l=await Je({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 Ue(t0.join(n,...i.source.split("/")),c.markdown,{containedRoot:t.nativeRoot})}}}var AA=I(()=>{"use strict";jt();tn();xs()});import{promises as UK}from"node:fs";function r0(e){if(!e.builder_handoff||!e.verification)throw new Error("Native verification result requires a candidate and accepted evidence");return Tp("comet.native.verification-result.v1",{candidateId:e.builder_handoff.candidate_id,acceptance:e.acceptance,verification:e.verification})}function Gr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
316
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Bn(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function JK(e){return e.archived?Tr(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Tr(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Tr(e.language,"Verification passed; ready to archive","验收通过,可归档"):Tr(e.language,"Verification passed","验收通过")}function zK(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Tr(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?JK(e):e.verification_result==="blocked"?Tr(t,"Blocked","已阻塞"):e.verification_result==="fail"?Tr(t,"Failed","未通过"):Tr(t,"Pending","待处理")}function KK(e){if(e.verification?.assurance==="semantic-verification-unavailable")return Tr(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return Tr(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return Tr(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 du(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,n=d=>aT(r,d),i=(d,m)=>Tr(r,d,m),o=e.acceptance.map(d=>`| ${Bn(d.id)} | ${Bn(d.result)} | ${Bn(d.source)} | ${Bn(d.text)} | ${Bn(Gr(d.reason))} |`).join(`
|
|
317
|
+
`),a=e.verification.reported_checks?[`| ${i("Agent-reported check","Agent 报告的检查")} | ${i("Result","结果")} | ${i("Execution and evidence","执行与证据")} |`,"| --- | --- | --- |",...e.verification.reported_checks.map(d=>`| ${Bn(Gr(d.name))} | ${d.result} | ${Bn(Gr(d.note))} |`)].join(`
|
|
318
|
+
`):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 m=d.argv_display.map(Gr).join(" ");return`| ${Bn(Gr(d.name))} | ${Bn(m||"—")} | ${Bn(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
319
|
+
`),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=>`- ${Gr(d.name)}: ${d.result} — ${Gr(d.note)}`),...e.builder_handoff.checks_truncated?[i("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${i("Known limitation","已知限制")}: ${Gr(d)}`),...e.builder_handoff.known_limits_truncated?[i("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
|
|
320
|
+
`):"",c=e.blockers.length===0?`_${i("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Gr(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
321
|
+
`),l=e.verification.risks.length===0?`_${i("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Gr(d)}`).join(`
|
|
322
|
+
`),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(", ")||"—"} | ${Bn(Gr(d.summary))} | ${d.completed_at} |`)].join(`
|
|
323
|
+
`),f=t?.finalVerification.layers?`
|
|
324
|
+
## ${i("Supervisor evidence layers","Supervisor 分层证据")}
|
|
325
|
+
|
|
326
|
+
- ${i("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
|
|
327
|
+
- ${i("Parent integration","父级集成")}: ${t.finalVerification.layers.parentIntegration}
|
|
328
|
+
- ${i("Parent checks","父级检查")}: ${t.finalVerification.layers.parentChecks.join(", ")||"—"}
|
|
329
|
+
- ${i("Not rerun","未重跑")}: ${t.finalVerification.layers.notRerun.join(", ")||"—"}
|
|
330
|
+
- ${i("Incomplete","未完成")}: ${t.finalVerification.layers.incomplete.join(", ")||"—"}
|
|
331
|
+
`:"";return`---
|
|
332
|
+
generated_from_state_version: ${e.state_version}
|
|
333
|
+
---
|
|
334
|
+
|
|
335
|
+
# ${n("verification")}
|
|
336
|
+
|
|
337
|
+
## ${n("currentResult")}
|
|
338
|
+
|
|
339
|
+
- ${i("Result","结果")}: **${zK(e)}**
|
|
340
|
+
- ${i("Verification status","验证情况")}: **${KK(e)}**
|
|
341
|
+
- ${i("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
342
|
+
- ${i("Iteration","迭代")}: ${e.verification.iteration}
|
|
343
|
+
- ${i("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
344
|
+
- ${i("Completed","完成时间")}: ${e.verification.completed_at}
|
|
345
|
+
- ${i("Summary","摘要")}: ${Gr(e.verification.summary)}
|
|
346
|
+
|
|
347
|
+
## ${n("acceptance")}
|
|
348
|
+
|
|
349
|
+
| ${i("ID","编号")} | ${i("Result","结果")} | ${i("Source","来源")} | ${i("Criterion","验收项")} | ${i("Reason","原因")} |
|
|
350
|
+
| --- | --- | --- | --- | --- |
|
|
351
|
+
${o}
|
|
352
|
+
|
|
353
|
+
## ${n("checks")}
|
|
354
|
+
|
|
355
|
+
${a}
|
|
356
|
+
|
|
357
|
+
${s}
|
|
358
|
+
|
|
359
|
+
## ${n("blockers")}
|
|
360
|
+
|
|
361
|
+
${c}
|
|
362
|
+
|
|
363
|
+
## ${n("risks")}
|
|
364
|
+
|
|
365
|
+
${l}
|
|
366
|
+
|
|
367
|
+
## ${n("previousIterations")}
|
|
368
|
+
|
|
369
|
+
${u}
|
|
370
|
+
|
|
371
|
+
${f}
|
|
372
|
+
|
|
373
|
+
${e.history_overflow.dropped_entries>0?`${i("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
|
|
374
|
+
|
|
375
|
+
`:""}## ${n("conclusion")}
|
|
376
|
+
|
|
377
|
+
${Gr(e.verification.summary)}
|
|
378
|
+
`}function GK(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 fu(e){let t;try{t=await UK.readFile(e.file,"utf8")}catch(n){if(n.code==="ENOENT")return"missing";throw n}let r=GK(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function rm(e){await Ue(e.file,du(e.state,e.supervisor),{beforeCommit:e.beforeCommit})}var Ls=I(()=>{"use strict";Te();Cs();jt();Tk();va()});import{randomUUID as YK}from"node:crypto";import{promises as XK}from"node:fs";import bA from"node:path";function RA(e){return"native/preserved-verification/"+encodeURIComponent(e)}function nm(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:bA.posix.join(t.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt}}async function pu(e){let{state:t,paths:r,file:n}=e,i=bA.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=du(t);if(o?.bytes.equals(Buffer.from(a)))return{};let s;if(o){await ci(r.projectRoot);let c=RA(e.runId);await yt(r.workspaceRuntimeRoot,c,{label:"Native preserved report"}),s=c+"/"+YK()+".md",await XK.writeFile(bA.join(r.workspaceRuntimeRoot,...s.split("/")),o.bytes,{flag:"wx"})}return await Ue(n,a,{containedRoot:r.projectRoot}),s?{preservedReportRef:s}:{}}var ka=I(()=>{"use strict";ot();Lr();jt();Ye();Te();Ls()});import{promises as im}from"node:fs";import om from"node:path";function n0(e,t){let r=e.map(({code:n,message:i,path:o})=>`- ${n}${o?` (${o})`:""}: ${i}`).join(`
|
|
379
|
+
`);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(`
|
|
380
|
+
`)}async function am(e){let t=Mt(e.paths,e.state.name),r=e.state.document_constraints_version,n=r===2||r===3,i=r===3,o=[...(await mO(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 m=`specs/${d.capability}/spec.md`;if(d.source!==m){o.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${m}.`,path:d.source??m});continue}try{let h=(await Je({root:t,ref:m,maxBytes:null,includeHash:!1})).text;o.push(...pO(h,m).findings)}catch(h){o.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${h.message}. Restore the complete file at ${m}.`,path:m})}}return{valid:o.length===0,findings:o}}async function NA(e){let t=await am(e);if(!t.valid)throw new Ts(n0(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}async function sm(e){let t=Mt(e.paths,e.state.name),r=om.join(t,"specs"),n=new Map(e.state.spec_changes.filter(({operation:a})=>a==="remove").map(a=>[a.capability,a])),i;try{i=await im.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(!Up.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=om.join(t,...s.split("/")),l=await im.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=om.join(e.paths.specsDir,a.name,"spec.md"),f="create";try{let p=await im.lstat(u);if(!p.isFile()||p.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${a.name}`);f="modify"}catch(p){if(p.code!=="ENOENT")throw p}let d=`specs/${a.name}/${lT}`,m=om.join(t,...d.split("/")),h={};try{let p=await im.lstat(m);if(!p.isFile()||p.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${d}`);let g=await Je({root:t,ref:d,maxBytes:null,includeHash:!1}),v=Or(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(p){if(p.code!=="ENOENT")throw p}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 cm(e){let t=Mt(e.paths,e.state.name),r=async o=>{let a=e.artifactTexts?.get(o);return a!==void 0?a:(await Je({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:ET({briefMarkdown:n,specs:i,legacyBriefBoundaries:e.legacyBriefBoundaries,resolveBriefReferences:e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1})}}var iG,Ro=I(()=>{"use strict";pr();Cs();Uk();jt();tn();Yl();Ds();_t();xs();ya();Vt();Ye();$p();Te();Kt();Ri();AA();Ao();ka();iG=Ql("en",{compact:!0})});var i0=I(()=>{"use strict";Ds();Kt()});var a0=I(()=>{"use strict";wt();Ds();_t();ya();Vt();Ro();Te();Kt();Ri();uu();_i();Ao();yr()});var lm=I(()=>{"use strict";Te();Ri();Kt()});var s0=I(()=>{"use strict";uu();Ao();ya();Vt();Ro();Kt();va();Ls();ka();yp();ru()});var l0=I(()=>{"use strict";ya();Vt();Ro();Kt();lm();uu();Ao();ka()});var u0=I(()=>{"use strict";jt();tn();Ds();xs();Vt();$p();Ro();Kt();lm()});var d0=I(()=>{"use strict";i0();Ro();a0();Kt();lm();s0();l0();u0()});var Jce,f0=I(()=>{"use strict";po();pr();Yl();_t();Vt();Te();d0();Ze();bs();Jce=Number.MAX_SAFE_INTEGER});import{createHash as aG,randomUUID as sG}from"node:crypto";import{promises as Nt}from"node:fs";import Yr from"node:path";function SA(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Ms(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=Yr.join(e.archiveDir,t);if(!qr(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function ii(e){try{return await Nt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hu(e,t){let r=await Ei(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function mu(e,t){await Nt.mkdir(e.transactionsDir,{recursive:!0}),await pi(Bp(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function _A(e,t){let r=Yr.join(e.specsDir,t),n=Yr.join(r,"spec.md");if(!qr(e.specsDir,n))throw new Error("Native canonical spec path escaped");let i;try{i=await Nt.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 Nt.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([Nt.realpath(e.specsDir),Nt.realpath(r)]);if(!qr(a,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let c;try{c=await Nt.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(!qr(s,await Nt.realpath(n)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{return{text:(await Je({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 cG(e){let t=Yr.join(e.paths.specsDir,e.change.capability),r=Yr.join(t,"spec.md");if(!qr(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let s;try{s=await Nt.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 Nt.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([Nt.realpath(e.paths.specsDir),Nt.realpath(t)]);if(!qr(l,u))throw new Error("Native canonical capability path escaped");try{let f=await Nt.lstat(r);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Nt.unlink(r)}catch(f){if(f.code!=="ENOENT")throw f}await Nt.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 _A(e.paths,e.change.capability),i=e.change.delta_content?Jl({currentMarkdown:n.text,delta:Or(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=Yr.join(Mt(e.paths,e.state.name),e.change.source);await Ue(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),!o&&(await Nt.mkdir(t,{recursive:!0}),await Ue(r,i,{containedRoot:e.paths.nativeRoot}))}function CA(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 lG(e,t){let r=Mt(e,t.name),n=[];for(let i of t.spec_changes){if(i.source===null){n.push({...i,content:null});continue}let o=await Je({root:r,ref:i.source,maxBytes:null,includeHash:!1});if(i.delta_source){let a=await Je({root:r,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=Or(a.text);if(s.capability!==i.capability)throw new Error(`Native delta capability ${s.capability} does not match ${i.capability}`);let c=await _A(e,i.capability),l=Jl({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 IA(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(CA(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function uG(e){let t=[],r=[];for(let n of e.state.spec_changes)try{let i=Mt(e.paths,e.state.name);n.source&&await Je({root:i,ref:n.source,maxBytes:null,includeHash:!1});let o;if(n.delta_source){let a=await Je({root:i,ref:n.delta_source,maxBytes:null,includeHash:!1}),s=Or(a.text);if(s.capability!==n.capability)throw new Error("Native delta capability does not match its target");let c=await _A(e.paths,n.capability);o=[...Jl({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 xA(e){let t=e.state??await ti(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 UO(e.paths,t);s&&!js(s)&&lu(s)}catch(s){r.push(s.message)}let n=!1,i;if(t.document_constraints_version===1){let s=await am({paths:e.paths,state:t});r.push(...s.findings.map(({message:c})=>c))}try{CA(t)}catch(s){r.push(s.message)}let o=await hu(e.paths,e.name);if(o===null){let s=Ms(e.paths,SA(t));await ii(s)&&r.push(`Native Archive target already exists: ${s}`);let c=await uG({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:Or(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 fu({file:Yr.join(Mt(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:Ms(e.paths,SA(t)),stateVersion:t.state_version}}async function p0(e){let{paths:t,state:r}=e;return Qe(t,async()=>{CA(r);let n=await hu(t,r.name);if(n)IA(n,r);else{let i=await xA({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:jp,id:sG(),change:r.name,start_state_version:r.state_version,archive_ref:SA(r),status:"prepared",next_spec_index:0,spec_changes:await lG(t,r),created_at:new Date().toISOString()},await mu(t,n)}if(n.status==="prepared"){for(let i=n.next_spec_index;i<n.spec_changes.length;i+=1)await cG({paths:t,state:r,change:n.spec_changes[i]}),n={...n,next_spec_index:i+1},await mu(t,n);n={...n,status:"specs-applied"},await mu(t,n)}return n},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function PA(e){let t=await hu(e.paths,e.state.name);if(!t||t.status!=="specs-applied")throw new Error("Native SDK Archive Specs have not been applied");if(IA(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 dG(e,t,r){let n=Yr.join(Ms(e,t),"comet-state.yaml"),i;try{i=await Nt.readFile(n,"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}if(!ma(i))return;let o=(0,EA.parseDocument)(i,{uniqueKeys:!0});if(o.errors.length>0)throw new Error("Native SDK Archive state is invalid");o.set(m0,r),await Ue(n,o.toString(),{containedRoot:e.nativeRoot})}async function fG(e,t){let r=Yr.join(Ms(e,t),"comet-state.yaml"),n=await Je({root:e.nativeRoot,ref:Yr.relative(e.nativeRoot,r).replaceAll("\\","/"),maxBytes:null});if(!ma(n.text))throw new Error("Native SDK Archive portable receipt has no managed Run");let i=(0,EA.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error("Native SDK Archive state is invalid");return i.toJS()[m0]}function h0(e,t){if(!t.trim())throw new Error("Native SDK Archive Run ID is missing");let r=aG("sha256").update(t).digest("hex");return Yr.join(e.runtimeDir,"sdk-archive-receipts",`${r}.json`)}async function g0(e){let{paths:t,state:r,runId:n}=e;return Qe(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 hu(t,r.name);if(!i){let l=await gu({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(IA(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=Mt(t,r.name),a=Ms(t,i.archive_ref);if(i.status==="specs-applied"){if(!await ii(o)||await ii(a))throw new Error("Native Archive layout contradicts its transaction");let l=Yr.join(o,"verification.md");if(!await ii(l))try{e.derivedReport?await e.derivedReport.write(l):await rm({file:l,state:r})}catch(u){if(!e.derivedReport?.optionalView)throw u}i={...i,status:"report-aligned"},await mu(t,i)}if(i.status==="report-aligned"){let l=await ii(o),u=await ii(a);if(l===u)throw new Error("Native Archive layout contradicts its transaction");l&&(await Nt.mkdir(t.archiveDir,{recursive:!0}),await $o(o,a)),i={...i,status:"moved"},await mu(t,i)}if(i.status!=="moved"||await ii(o)||!await ii(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 dG(t,i.archive_ref,s);let c=h0(t,n);return await Nt.mkdir(Yr.dirname(c),{recursive:!0}),await pi(c,s,{containedRoot:t.runtimeDir}),await Nt.rm(Bp(t,{kind:"archive",change:r.name}),{force:!0}),s},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function gu(e){let{paths:t,state:r,runId:n}=e,i;try{i=JSON.parse(await Nt.readFile(h0(t,n),"utf8"))}catch(o){if(o.code!=="ENOENT"||!e.archiveRef)throw o;i=await fG(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 hu(t,r.name)||await ii(Mt(t,r.name)))throw new Error("Native SDK Archive completion record does not match its Run or transaction");if(!await ii(Ms(t,i.archiveRef)))throw new Error("Native SDK Archive destination is missing");return i}async function v0(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o,actionId:a,state:s}=e,c=await Ne(t,o.input.artifactRootRef);return Qe(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 Ei(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 EA,m0,um=I(()=>{"use strict";yr();Kt();f0();EA=or(Vr(),1);Dd();Ml();jt();tn();xs();Vt();Ye();Ro();Kt();Te();Gl();Ls();m0="archive_receipt"});import dm from"node:path";import{isDeepStrictEqual as pG}from"node:util";async function mG(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 We(r);if(!a||a.native.artifact_root!==i.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let s=await Ne(r,i.artifactRootRef,{readOnly:!0}),c=dm.join(s.changesDir,n.name,"verification.md"),l=dm.relative(r,c).replaceAll("\\","/");return{state:n,paths:s,reportFile:c,reportRef:l,reportStateVersion:n.state_version-1}}async function hG(e,t,r){let n=await mG(e,t,r),i=await xA({paths:n.paths,name:n.state.name,state:n.state,requireCurrentAcceptance:!1,verificationReportStateVersion:n.reportStateVersion,derivedReport:!0}),o=dm.relative(r,i.archiveDir).replaceAll("\\","/");if(o.startsWith("../")||dm.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 w0(e,t,r){return hG(e,t,r)}function y0(e,t,r){return JSON.stringify([r,e.runId,e.revision,t.id,t.attempt,t.claim?.token])}async function OA(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 We(r);if(!s||s.native.artifact_root!==o.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let c=await Ne(r,o.artifactRootRef,{readOnly:!0});if(n){let l=await Ei(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 PA({paths:c,state:i})}return{state:i,paths:c,verificationReportStateVersion:a.reportStateVersion,derivedReport:!0}}function gG(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 k0(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 Ne(r,i.artifactRootRef,{readOnly:!0});return{state:n,paths:a,applied:o}}async function vG(e,t,r,n=!1){return k0(e,t,r)}function wG(e,t){return{optionalView:!0,preservedReportsRef:RA(e.runId),write:r=>pu({state:t.state,paths:t.paths,runId:e.runId,file:r})}}var TA,$A,fm,jA,pm,DA,mm,A0=I(()=>{"use strict";Hl();ka();Ze();_t();Ye();um();Te();Gl();TA=new Map;$A={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 w0(r,e,t.projectRoot);return TA.set(y0(r,e,t.projectRoot),n),{status:n.ready?"succeeded":"failed",output:n}}},fm={id:"comet-native-archive-preflight-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==$A.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=y0(e,t,n.projectRoot),a=TA.get(o);TA.delete(o);let s=a??await w0(e,t,n.projectRoot);return T(r.output)!==T(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)}}}};jA={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 OA(r,e,t.projectRoot),i=await p0(n);return{status:"succeeded",output:{transactionId:i.id,archiveRef:i.archive_ref,stateVersion:i.start_state_version,specCount:i.spec_changes.length}}}};pm={id:"comet-native-archive-apply-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==jA.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=gG(t);if(!c||!pG(r.output,c))return{accepted:!1,reason:"Native Archive lacks a matching rejected prewrite failure"};let{state:l,paths:u}=await OA(e,t,n.projectRoot);return await Ei(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 OA(e,t,n.projectRoot,i);if(r.status!=="succeeded")return{accepted:!1,reason:"Unexpected Native Archive apply event"};let s={...await PA({paths:a,state:o})};return T(r.output)===T(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)}}}};DA={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 k0(r,e,t.projectRoot),{state:i,paths:o,applied:a}=n,s=await g0({paths:o,state:i,runId:r.runId,transactionId:a.transactionId,archiveRef:a.archiveRef,derivedReport:wG(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}}},mm={id:"comet-native-archive-finalize-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==DA.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 vG(e,t,n.projectRoot,r.status==="succeeded");if(r.status!=="succeeded")return{accepted:!1,reason:"Native Archive finalization did not succeed"};let s=await gu({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||T(r.output)!==T(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===T(fn(e))}var BA=I(()=>{"use strict";Ze()});import{promises as yG}from"node:fs";import b0 from"node:path";async function gm(e,t){let r=M(e.state),n=e.input,i=await We(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 Ne(t,n.artifactRootRef),a=b0.join(o.changesDir,r.name,"capability-association.yaml"),s=b0.relative(t,a),c=await ce(t,s,{label:"Native capability association",expected:"file"});return{paths:o,file:a,inspected:c}}var R0,vm,wm,N0=I(()=>{"use strict";ot();_t();Vt();Ye();Te();R0={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 gm(r,t.projectRoot);return await Qe(o.paths,async()=>{let a=await gm(r,t.projectRoot);a.inspected.exists&&await yG.rm(a.file)}),{status:"succeeded",output:{removed:!0}}}},vm={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 gm(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)}}}},wm={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 gm(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 ym from"node:path";async function WA(e,t,r){xk(r);let n=M(e.state),i=e.input,o=await We(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 Ne(t,i.artifactRootRef);if(!(await ce(t,ym.relative(t,ym.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 ce(t,ym.relative(t,ym.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,S0,Am,E0=I(()=>{"use strict";ot();zl();_t();Ye();Te();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 WA(e,n.projectRoot,r.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},S0={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 WA(r,t.projectRoot,n.capability),{status:"succeeded",output:{capability:n.capability}}}},Am={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 WA(e,n.projectRoot,i.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}}});function qs(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 bm=I(()=>{"use strict"});function LA(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=pt(t,r.name),s=bt(r.name);if(typeof o?.integrationWorktree!="string"||!me(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=Rt(t,r.name,a),c=`comet/supervisor/${r.name}/${a}`;if(typeof o.worktree!="string"||!me(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=Ae(i.worktree),a=he(i.worktree,i.branch);if(o.currentBranch!==i.branch||!o.primaryWorktreeRoot||!me(o.primaryWorktreeRoot,t)||!a)throw new Error("Native 需求修订的 Git 工作区身份已变化");return{...i,head:a}})}function Aa(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"&&me(a.worktree,t)&&a.branch===r);if(!o)return null;if(he(t,r)!==o.head)throw new Error("Native 修订后保留的工作区提交已变化,请核对原现场");return o}var VA=I(()=>{"use strict";wt();Te();yr()});function MA(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 _0(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 kG(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 AG(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=bG(e);if(n)return r===n;let i=kG(e);return i!==void 0&&i.proposalHash===r}function bG(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 T({actionId:n,attempt:i,inputHash:o})}var Rm,qA,Nm,Sm,C0,Em,I0=I(()=>{"use strict";Ze();Te();VA();Rm={id:"comet-native-implementation-revision-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state),o=MA(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}}};qA={id:"comet-native-revise-implementation",capabilities:[],supports:e=>e.stepId==="repair.implementation"&&e.ref==="native-revise-implementation",async execute(e,t,r){let n=MA(e.input.activation);if(!r||!n||!t?.projectRoot)throw new Error("Native implementation revision lacks its input");return{status:"succeeded",output:await _0(r,n,t.projectRoot)}}},Nm={id:"comet-native-implementation-revision-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=MA(t.input.activation);if(!i||!n?.projectRoot||r.status!=="succeeded"||t.claim?.executorId!==qA.id)return{accepted:!1,reason:"Native implementation revision has no matching read-only result"};let o=await _0(e,i,n.projectRoot);return{accepted:T(r.output)===T(o),reason:"Native candidate changed during revision"}}};Sm={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(","))||!AG(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}}},C0={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?LA(r,t.projectRoot):void 0;return{status:"succeeded",output:{reason:n.reason.trim(),...o?{workspaces:o}:{}}}}},Em={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&&T(r.output?.workspaces??null)===T(LA(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 Gt(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 FA(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 ba=I(()=>{"use strict"});async function Fs(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 We(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 Xr(e,t){let r=await Fs(e,t),n=he(t,r.targetBranch);if(!n)throw new Error("Native SDK Supervisor target branch has no commit");return{...r,targetCommit:n}}function RG(e){let t=e.input.activation;if(!t||typeof t.child!="string"||typeof He(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:He(t)}}async function HA(e,t,r){let n=await Xr(e,r),i=RG(t);if(!n.contract.children.some(({name:a})=>a===i.child)||He(i,e)!==n.state.children_contract_ref||i.integrationBranch!==bt(n.state.name)||!me(i.integrationWorktree,pt(r,n.state.name))||he(r,i.integrationBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor child preparation no longer matches its parent plan");if(Ae(i.integrationWorktree).currentBranch!==i.integrationBranch)throw new Error("Native SDK Supervisor integration worktree changed before child preparation");return{...n,input:i}}var QA,_m,UA,Cm,Ra=I(()=>{"use strict";Pr();wt();_t();Te();VA();yr();QA={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 Xr(r,t.projectRoot);Aa(r,pt(t.projectRoot,n.state.name),bt(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 Xr(r,t.projectRoot),i=Aa(r,pt(t.projectRoot,n.state.name),bt(n.state.name)),o=await em({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??qc}}}},_m={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||!QA.supports(t))return{accepted:!1,reason:"Native SDK Supervisor preparation lacks its project"};try{let i=await Xr(e,n.projectRoot),o=r.output,a=pt(n.projectRoot,i.state.name),s=bt(i.state.name),c=Aa(e,a,s);if(!o||He(o,e,t)!==i.state.children_contract_ref||o.integrationBranch!==s||typeof o.integrationWorktree!="string"||!me(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(Ae(a).currentBranch!==s)throw new Error("Native SDK Supervisor integration worktree has a different branch");if(he(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)}}}},UA={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 HA(r,e,t.projectRoot);Aa(r,Rt(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 HA(r,e,t.projectRoot);Aa(r,Rt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`);let i=await tm({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}}}},Cm={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||!UA.supports(t))return{accepted:!1,reason:"Native SDK Supervisor child preparation lacks its project"};try{let i=await HA(e,t,n.projectRoot),o=r.output,a=Rt(n.projectRoot,i.state.name,i.input.child),s=`comet/supervisor/${i.state.name}/${i.input.child}`;if(!o||o.child!==i.input.child||He(o,e)!==He(i.input,e)||typeof o.worktree!="string"||!me(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=Ae(a),l=Aa(e,a,s);if(c.currentBranch!==s||he(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 P0}from"node:fs";import Br from"node:path";function Hs(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 He(t)!="string")throw new Error("Native Supervisor child archive lacks its activation");return{...t,contractRef:He(t)}}function JA(e,t,r,n){for(let i of[...Gt(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 T0(e,t,r,n=!1){let i=await Xr(e,r),o=i.state,a=Hs(t.input);if(o.phase!=="build"||o.status!=="active"||!o.children_contract_ref||He(a,e)!==o.children_contract_ref||!i.contract.children.some(({name:U})=>U===a.child)||!Na.test(a.candidateCommit)||!Na.test(a.integrationCommit))throw new Error("Native Supervisor child archive does not match the confirmed plan");let s=a.checksActionId?e.actions.find(U=>U.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(U=>U.id===l),f=u?.outcome?.output,d=a.repairActionId??s?.input?.activation?.repairActionId,m=d?e.actions.find(U=>U.id===d):void 0,h=m?.outcome?.output;if(u?.stepId!=="supervisor.child.integrate"||u.status!=="succeeded"||f?.child!==a.child||(m?m.stepId!=="supervisor.child.integration-repair"||m.status!=="succeeded"||m.input.activation?.mergeActionId!==u.id||m.input.activation.child!==a.child||m.input.activation.candidateCommit!==a.candidateCommit||He(m.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 p=c?.completedAt??de((e.outputs["supervisor.prepare"]?.value).integrationWorktree,["show","-s","--format=%cI",a.integrationCommit]).trim(),g=JA(e,"supervisor.child.verifier",a.child,U=>{let pe=U.evidence;return U.verdict==="pass"&&U.candidateCommit===a.candidateCommit&&typeof pe?.summary=="string"&&!!pe.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=JA(e,"supervisor.child.builder",a.child,U=>U.candidateCommit===a.candidateCommit),A=["1","2","3"].includes(g.action.executionOrigin?.workflow.version??""),b=A?JA(e,"supervisor.child.checks",a.child,U=>U.candidateId===a.candidateCommit):null;if(A&&!b)throw new Error("Legacy Child archive lacks its original accepted checks");let R=b?.output,_=e.outputs["supervisor.prepare"]?.value;if(typeof _?.integrationWorktree!="string"||typeof _.integrationBranch!="string")throw new Error("Native Supervisor child archive lacks its integration workspace");let W=Rt(r,o.name,a.child),O=`comet/supervisor/${o.name}/${a.child}`;if(Ae(W).currentBranch!==O)throw new Error("Native Supervisor child worktree moved before the child archive");if(Ae(_.integrationWorktree).currentBranch!==_.integrationBranch)throw new Error("Native Supervisor integration worktree moved before the child archive");let G=de(W,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(U=>U&&U!==".comet/config.yaml").map(U=>U.replaceAll("\\","/"));if(!n&&(!bo(W,G)||!bo(_.integrationWorktree)))throw new Error("Native Supervisor child archive requires clean worktrees");let Z=new Map;if(Array.isArray(v.acceptance))for(let U of v.acceptance)typeof U?.id!="string"||typeof U?.result!="string"||Z.set(U.id,typeof U.reason=="string"?U.reason:"");let J=yo(i.contract,a.child);for(let{id:U}of J)if(!Z.has(U))throw new Error(`Native Supervisor child archive evidence does not cover acceptance ${U}`);let F=(R?.checks??[]).map(U=>{if(typeof U.id!="string"||typeof U.name!="string"||!Array.isArray(U.argvDisplay)||typeof U.cwdRef!="string"||U.status!=="passed"||!Number.isSafeInteger(U.durationMs))throw new Error("Native Supervisor child archive requires passed Child checks");return{id:U.id,name:U.name,argvDisplay:U.argvDisplay,cwdRef:U.cwdRef,status:U.status,exitCode:typeof U.exitCode=="number"?U.exitCode:null,durationMs:U.durationMs}}),X=Array.isArray(v.risks)?v.risks.filter(U=>typeof U=="string"):[];return{parent:o.name,maxParallelChildren:i.state.coordination_mode==="single-session"?1:i.config.native.max_parallel_children??qc,child:a.child,language:o.language,targetBranch:i.targetBranch,worktree:W,branch:O,candidateCommit:a.candidateCommit,integrationBranch:_.integrationBranch,integrationWorktree:_.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:X,verifierAcceptance:Z,childChecks:F,...A?{}:{reportedChecks:ei(v.checks??[])},childChecksCompletedAt:R?.completedAt??p,integrationChecksCompletedAt:p,scopedAcceptance:J}}async function SG(e,t,r,n){let i=await Xr(e,r),o=await Ne(r,i.config.native.artifact_root),a=Br.join(o.changesDir,n.parent),s=await Je({root:a,ref:i.state.brief,includeHash:!1}),c=await Promise.all(i.state.spec_changes.flatMap(d=>d.source?[Je({root:a,ref:d.source,includeHash:!1})]:[])),l=n.language==="zh-CN"?"子任务归档":"Archived Child",u=n.scopedAcceptance.map(d=>`- ${d.id}: ${d.text}`).join(`
|
|
381
|
+
`),f=[s,...c].map(d=>`- ${d.ref}`).join(`
|
|
382
|
+
`);return{"brief.md":`# ${n.child}
|
|
383
|
+
|
|
384
|
+
${l}: ${n.parent}
|
|
385
|
+
|
|
386
|
+
${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."}
|
|
387
|
+
|
|
388
|
+
${u}
|
|
389
|
+
|
|
390
|
+
[Parent Spec](spec.md) · [${n.language==="zh-CN"?"来源与原始简报":"Sources and original brief"}](archive-source.md) · [${n.language==="zh-CN"?"验收记录":"Verification"}](verification.md)
|
|
391
|
+
`,"spec.md":c.length===0?`# Parent Spec
|
|
392
|
+
|
|
393
|
+
No Spec change was declared by the confirmed Parent.
|
|
394
|
+
`:c.length===1?c[0].text:c.map(d=>`# ${d.ref}
|
|
395
|
+
|
|
396
|
+
${d.text}`).join(`
|
|
397
|
+
|
|
398
|
+
`),"archive-source.md":`# ${n.language==="zh-CN"?"归档材料来源":"Archive material sources"}
|
|
399
|
+
|
|
400
|
+
- Parent Run: ${e.runId}
|
|
401
|
+
- Archive Action: ${t.id}
|
|
402
|
+
- Contract: ${He(Hs(t.input),e)}
|
|
403
|
+
- Candidate: ${n.candidateCommit}
|
|
404
|
+
- Verifier: ${n.verifierSessionId}
|
|
405
|
+
- Integration Action: ${Hs(t.input).mergeActionId??Hs(t.input).checksActionId}
|
|
406
|
+
|
|
407
|
+
${f}
|
|
408
|
+
|
|
409
|
+
## ${n.language==="zh-CN"?"Parent 原始简报":"Original Parent brief"}
|
|
410
|
+
|
|
411
|
+
${s.text}`}}async function EG(e,t,r){let n=[];for(let i of Object.keys(t))await Je({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 Ue(Br.join(e,i),t[i],{containedRoot:e});return n}function _G(e){let t=e.scopedAcceptance.filter(({id:n})=>NG.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?Tt(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:Tt(e.builderSummary??e.verifierSummary),addressed_acceptance_ids:t.map(({id:n})=>n),checks:e.childChecks.map(n=>({name:Tt(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:Tt(n.name),argv_display:n.argvDisplay.map(i=>Tt(i)),argv_truncated:!1,cwd_ref:n.cwdRef,status:"passed",exit_code:n.exitCode,duration_ms:n.durationMs})),summary:Tt(e.verifierSummary),risks:e.verifierRisks.map(n=>Tt(n)),risks_truncated:!1,completed_at:e.integrationChecksCompletedAt},verification_result:"pass",verification_report:"verification.md",history:[]})}async function O0(e,t){let r=await We(e.worktree);if(!r)throw new Error("Native Supervisor child worktree has no project config");let n=await Ne(e.worktree,r.native.artifact_root),i=Br.join(n.archiveDir,t),o=Br.resolve(i),a=Br.resolve(n.archiveDir);if(!o.toLowerCase().startsWith(`${a.toLowerCase()}${Br.sep}`)&&o.toLowerCase()!==a.toLowerCase())throw new Error("Native Supervisor child archive path escaped the archive root");return{target:o,relative:Br.relative(e.worktree,o).replaceAll("\\","/"),changesDir:n.changesDir,nativeRoot:n.nativeRoot}}function KA(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 Im(e,t,r){let n=de(e,["show","--name-only","--format=",t]).split(`
|
|
412
|
+
`).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 CG(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!==xm.id||a?.child!==r.child||a.archiveRef!==KA(r)||a.candidateCommit!==Hs(o.input).candidateCommit||a?.baseCommit!==Hs(o.input).integrationCommit||typeof a.archiveCommit!="string"||!Na.test(a.archiveCommit))throw new Error("Native Supervisor child archive lacks its accepted predecessor receipt");Im(r.worktree,a.archiveCommit,n.relative);for(let[s,c]of[[r.worktree,r.candidateCommit],[r.integrationWorktree,r.integrationCommit]])de(s,["merge-base","--is-ancestor",a.archiveCommit,c])}async function x0(e){try{return await P0.access(e),!0}catch{return!1}}var zA,Na,NG,xm,Pm,$0=I(()=>{"use strict";Pr();zA=or(Vr(),1);wt();zr();jt();tn();_t();Ye();Te();Ri();va();ba();Ra();_i();yr();Ls();au();Na=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,NG=/^A[1-9][0-9]*$/u;xm={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 T0(r,e,t.projectRoot);if(he(n.worktree,n.branch)!==n.candidateCommit)throw new Error("Native Supervisor child worktree moved before the child archive");if(he(n.integrationWorktree,n.integrationBranch)!==n.integrationCommit)throw new Error("Native Supervisor integration head moved before the child archive");let i=KA(n),o=await O0(n,i),a=null;if(await x0(o.target)&&(a=await yn(Br.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=he(n.worktree,n.branch);if(!u||!Na.test(u))throw new Error("Native Supervisor child worktree has no archive commit");Im(n.worktree,u,o.relative),s=u}else{if(await x0(Br.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=_G(n),f=await SG(r,e,t.projectRoot,n);if(a&&await CG(r,e,n,o),await P0.mkdir(o.target,{recursive:!0}),a){let g={...f,"comet-state.yaml":(0,zA.stringify)(u),"verification.md":du(u)};for(let[v,w]of Object.entries(g))await Ue(Br.join(o.target,v),w,{containedRoot:o.nativeRoot})}else await EG(o.target,f,!1),await Ue(Br.join(o.target,"comet-state.yaml"),(0,zA.stringify)(u),{containedRoot:o.nativeRoot}),await rm({file:Br.join(o.target,"verification.md"),state:u});if(await fu({file:Br.join(o.target,"verification.md"),stateVersion:u.state_version})!=="aligned")throw new Error("Native Supervisor child archive report is not aligned");de(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 m=de(n.worktree,["diff","--cached","--name-only","--",o.relative]).split(`
|
|
413
|
+
`).filter(Boolean);if(m.length===0)throw new Error("Native Supervisor child archive produced no committable content");let h=m.filter(g=>!g.startsWith(`${o.relative}/`));if(h.length>0)throw new Error(`Native Supervisor child archive staging left unrelated paths: ${h.join(", ")}`);de(n.worktree,["commit","-m",`chore(native): archive ${n.child}`]);let p=he(n.worktree,n.branch);if(!p||!Na.test(p))throw new Error("Native Supervisor child archive commit is missing");Im(n.worktree,p,o.relative),s=p}let c=he(n.integrationWorktree,n.integrationBranch);if(!c||!Na.test(c))throw new Error("Native Supervisor integration branch has no head");let l=c;try{de(n.integrationWorktree,["merge-base","--is-ancestor",s,c])}catch{de(n.integrationWorktree,["merge","--no-ff","--no-edit",n.branch]);let u=he(n.integrationWorktree,n.integrationBranch);if(!u||!Na.test(u))throw new Error("Native Supervisor child archive merge produced no head");l=u;let f=de(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(he(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}}}},Pm={id:"native-supervisor-child-archive-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==xm.id||r.status!=="succeeded")return{accepted:!1,reason:"Native Supervisor child archive was not executed by Runtime"};try{let i=await T0(e,t,n.projectRoot),o=r.output,a=KA(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 O0(i,a),c=await yn(Br.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(Im(i.worktree,o.archiveCommit,s.relative),he(i.worktree,i.branch)!==o.archiveCommit)throw new Error("Native Supervisor child branch is not at its archive commit");let l=de(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(he(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 j0,Tm,Om,D0=I(()=>{"use strict";wt();zr();Pr();Te();bm();Ra();_i();yr();ru();j0=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Tm={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 Fs(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)||He(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!me(a.worktree,Rt(n.projectRoot,i.name,a.child))||a.branch!==`comet/supervisor/${i.name}/${a.child}`||typeof a.baseCommit!="string"||!j0.test(a.baseCommit)||!s||typeof s.candidateCommit!="string"||!j0.test(s.candidateCommit))throw new Error("Native SDK Supervisor Builder result lacks a claimed child candidate");if(Ae(a.worktree).currentBranch!==a.branch||he(a.worktree,a.branch)!==s.candidateCommit)throw new Error("Native SDK Supervisor Builder candidate does not match its worktree");return ei(s.checks??[]),de(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)}}}},Om={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 Fs(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)||He(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!me(a.worktree,Rt(n.projectRoot,i.name,a.child))||typeof a.candidateCommit!="string"||typeof a.builderSessionId!="string"||qs(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=ei(c.checks),u=Kp(c.acceptance);return Gp({verdict:s.verdict,acceptance:u},{acceptanceIds:yo(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 GA(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 B0(e,t,r){let n=GA(e,"supervisor.prepare"),i=pt(t,r.name),o=bt(r.name);if(!n||He(n,e)!==r.children_contract_ref||typeof n.integrationWorktree!="string"||!me(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 Gt(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"||He(l,e)!==r.children_contract_ref||!me(l.worktree,Rt(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 W0(e,t,r){let n=M(e.state),i=GA(e,"supervisor.parent.deliver");if(t.stepId!=="supervisor.cleanup"||n.status!=="done"||!n.archived||!n.children_contract_ref||!GA(e,"archive.finalize")||!i||typeof i.targetRoot!="string"||typeof i.targetBranch!="string"||typeof i.targetCommit!="string"||i.targetCommit!==i.integrationCommit||!qt(r).some(o=>me(o,i.targetRoot))||Ae(i.targetRoot).currentBranch!==i.targetBranch||he(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:B0(e,r,n)}}function L0(e,t,r,n){lu({projectRoot:t,targetRoot:pt(t,n.name),targetBranch:bt(n.name),targetCommit:r,candidates:B0(e,t,n)})}function IG(e){return{targetBranch:e.targetBranch,targetCommit:e.targetCommit}}var YA,$m,XA=I(()=>{"use strict";Pr();wt();Te();ba();yr();YA={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=W0(r,e,t.projectRoot);return await dA(n),{status:"succeeded",output:IG(n)}}},$m={id:"native-supervisor-cleanup-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==YA.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor cleanup was not executed by Runtime"};try{let i=W0(e,t,n.projectRoot),o=r.output;if(!o||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||!js(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 Qs(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"||!V0.test(r.integrationCommit)||typeof i!="string"||!V0.test(i))throw new Error("Native Supervisor parent candidate has no valid Git commit");return i}var V0,ZA=I(()=>{"use strict";V0=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});import M0 from"node:path";async function q0(e,t,r){let n=await Xr(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?Qs(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=bt(i.name),d=pt(r,i.name);if(i.phase!=="archive"||i.verification_result!=="pass"||!i.verification||!i.builder_handoff||!l||!u||!o||He(o,e)!==i.children_contract_ref||o.candidateId!==i.builder_handoff.candidate_id||o.integrationBranch!==f||typeof o.integrationWorktree!="string"||!me(o.integrationWorktree,d)||typeof o.integrationCommit!="string"||c!==o.integrationCommit||a?.targetBranch!==n.targetBranch||typeof a.targetCommit!="string"||Ae(d).currentBranch!==f||he(d,f)!==o.integrationCommit)throw new Error("Native SDK Supervisor delivery lacks the approved integration candidate");let m=qt(r).find(v=>Ae(v).currentBranch===n.targetBranch);if(!m)throw new Error("Native SDK Supervisor target branch worktree is unavailable");let h=he(m,n.targetBranch),g=[...Gt(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 de(d,["merge-base","--is-ancestor",a.targetCommit,o.integrationCommit]),L0(e,r,o.integrationCommit,i),{state:i,input:o,targetRoot:m,targetBranch:n.targetBranch,targetCommit:h,integrationBranch:f,integrationCommit:o.integrationCommit}}function xG(e){return{contractRef:e.state.children_contract_ref,integrationCommit:e.integrationCommit,targetBranch:e.targetBranch,targetRoot:e.targetRoot,targetCommit:e.integrationCommit}}function PG(e,t){try{let r=e.targetRoot;de(r,["diff","--cached","--quiet",e.integrationCommit]),de(r,["diff","--quiet"]);let n=de(r,["diff","--name-only","--no-renames","-z",e.targetCommit,e.integrationCommit]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/"));return de(r,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/")).some(o=>n.includes(o))?!1:bo(r,[...t,...n])}catch{return!1}}async function TG(e,t,r,n){let i=await Ne(n,t.input.artifactRootRef),o=me(e.targetRoot,n)?M0.relative(e.targetRoot,M0.join(i.changesDir,e.state.name)).replaceAll("\\","/"):null,a=[...o?[o]:[],".comet/current-change.json",".comet/runtime"];if(!bo(e.targetRoot,a)&&!(e.targetCommit!==e.integrationCommit&&r.reconciliations.some(s=>s.attempt===r.attempt-1)&&PG(e,a)))throw new Error("Native SDK Supervisor target worktree has unrelated changes")}var eb,jm,F0=I(()=>{"use strict";XA();Pr();wt();zr();Ye();Te();ZA();ba();Ra();yr();au();eb={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 q0(r,e,t.projectRoot);if(await TG(n,r,e,t.projectRoot),n.targetCommit!==n.integrationCommit&&de(n.targetRoot,["merge","--ff-only",n.integrationBranch]),he(n.targetRoot,n.targetBranch)!==n.integrationCommit)throw new Error("Native SDK Supervisor target did not receive the verified integration");return{status:"succeeded",output:xG(n)}}},jm={id:"native-supervisor-parent-deliver-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==eb.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor delivery was not executed by Runtime"};try{let i=await q0(e,t,n.projectRoot),o=r.output;if(!o||He(o,e)!==i.state.children_contract_ref||o.integrationCommit!==i.integrationCommit||o.targetBranch!==i.targetBranch||typeof o.targetRoot!="string"||!me(o.targetRoot,i.targetRoot)||o.targetCommit!==i.integrationCommit||he(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 Q0(e,t,r){let n=await Xr(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)||He(o,e)!==i.children_contract_ref||typeof o.worktree!="string"||!me(o.worktree,Rt(r,i.name,o.child))||o.branch!==`comet/supervisor/${i.name}/${o.child}`||typeof o.candidateCommit!="string"||he(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=bt(i.name),l=pt(r,i.name);if(Ae(l).currentBranch!==c)throw new Error("Native SDK Supervisor integration worktree changed");let u=e.actions.findIndex(h=>h.id===t.id),f=Gt(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,m=f?f.outcome?.output?.integrationCommit:d?.integrationCommit??d?.targetCommit;if(typeof m!="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:m}}function U0(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 H0(e,t,r){let n=await Q0(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(!ga(n.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree must be clean before merge");let i=he(n.integrationWorktree,n.integrationBranch);if(!i||i!==n.expectedBaseCommit&&!U0(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 de(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,i]),de(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,n.plan.targetCommit]),{...n,baseCommit:i}}var Dm,tb,Bm,J0=I(()=>{"use strict";wt();zr();Pr();Te();Te();ba();Ra();yr();Dm={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 Xr(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),m=d?.outcome?.output,h=d?.status==="succeeded"&&d.stepId==="supervisor.child.integration-repair"&&d.input.activation?.mergeActionId===s?.id?m?.integrationCommit:c?.integrationCommit,p=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=pt(n.projectRoot,i.state.name),w=bt(i.state.name);if(!o||!p&&!g||He(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"||!me(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||Ae(v).currentBranch!==w||he(v,w)!==a.integrationCommit||!ga(v))throw new Error("Integration repair does not match its original merge, failure and workspace");if(de(v,["merge-base","--is-ancestor",o.integrationCommit,a.integrationCommit]),ei(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)}}}};tb={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 H0(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 H0(r,e,t.projectRoot),{baseCommit:i}=n;de(n.integrationWorktree,["merge-base",n.plan.targetCommit,i])===n.plan.targetCommit||de(n.integrationWorktree,["merge","--no-ff","--no-edit",n.plan.targetCommit]);let a=he(n.integrationWorktree,n.integrationBranch);if(!a)throw new Error("Native SDK Supervisor target sync produced no commit");de(n.integrationWorktree,["merge-base",n.input.candidateCommit,a])===n.input.candidateCommit||de(n.integrationWorktree,["merge","--no-ff","--no-edit",n.input.candidateCommit]);let c=he(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}}}},Bm={id:"native-supervisor-integrate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==tb.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor integration was not executed by Runtime"};try{let i=await Q0(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"||!U0(e,i.expectedBaseCommit,o.baseCommit))||typeof o.integrationCommit!="string"||o.integrationBranch!==i.integrationBranch||typeof o.integrationWorktree!="string"||!me(o.integrationWorktree,i.integrationWorktree)||he(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native SDK Supervisor integration outcome does not match the worktree");if(!ga(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=de(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(de(i.integrationWorktree,["merge-base","--is-ancestor",s,c]),o.integrationCommit===c)de(i.integrationWorktree,["merge-base","--is-ancestor",o.candidateCommit,o.integrationCommit]);else{let l=de(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 rb(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||He(n,e)!==r.children_contract_ref||typeof n.child!="string"||typeof n.candidateCommit!="string"||typeof n.builderSessionId!="string"||!Gt(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 z0(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 K0=I(()=>{"use strict";Ze();Pr();Te();ba();Ra()});var r$={};Fm(r$,{assertNativeSdkStartAvailable:()=>db,collectNativeSdkShapeProposal:()=>$G,defineNativeWorkflowApplication:()=>No,nativeSdkApplicationForRun:()=>ub,registerNativeSdkStartOwner:()=>OG});import e$ from"node:path";function ub(e,t=No()){if(e&&(e.workflow.version!=="4"||!hm(t.workflow,e)))throw new Error("Native Run 尚未完成业务数据适配,请通过原 change 的当前入口继续;原记录与批准保留。");return t}async function db(e){let t=await Ne(e.projectRoot,e.artifactRootRef,{change:e.name});if((await ce(e.projectRoot,e$.relative(e.projectRoot,vr(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 OG(e){let t=await Ne(e.projectRoot,e.artifactRootRef,{change:e.name});await Qe(t,async()=>{await db(e),await Xn(e.projectRoot,{schema:Hr,workflow:"native",change:e.name,format:"sdk",application:"native",runId:e.name})})}function t$(e){return e.phase==="shape"&&e.status==="active"&&e.loop.next_action==="prepare-shape-confirmation"?3:e.document_constraints_version??2}async function $G(e){let t=M({...e.state,document_constraints_version:t$(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=e$.join(e.paths.changesDir,t.name),n=await sm({paths:e.paths,state:t});e.materializeTargets===!0&&t.status==="active"&&t.shape_confirmation_hash===void 0&&n.some(s=>s.delta_source)&&await Qe(e.paths,()=>kA({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 NA({paths:e.paths,state:i?{...t,spec_changes:n}:t,specChanges:n});let o=e.acceptance===void 0?(await cm({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=Yi(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:Ni({...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 nb(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 jG(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:ql(),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 G0(e,t){let n={...Ur(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Tt(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 Sa(e){if(e===null||typeof e!="object")throw new Error("Native Shape proposal missing");return e}function Y0(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 DG(e){let t=Gt(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 ib(e,t,r){let n=t.input.activation,o=Gt(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 Wm(e,t){let r=[...Gt(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:Qs(r),...t}}function X0(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=nA().captureExecutionIdentity({identityProvider:wr,executionRef:i});return mA({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 BG(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||qs(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??Tc;if(!Number.isSafeInteger(c)||c<1)throw new Error("Native Verify failure budget is invalid");let l=nA(),u=l.captureExecutionIdentity({identityProvider:wr,executionRef:i}),f=hA({state:o,requireIndependentSession:!1,envelope:l.envelopeVerifierResponse({candidateId:a.candidate_id,identity:u,payload:n.response}),reportedChecks:ei(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 WG(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 wA({state:i,summary:n.summary})}function No(e="4"){if(e!=="4")throw new Error("旧 Native 受管检查定义不再支持;普通检查请使用 Agent 平台工具。");return VG()}function Z0(e,t){let r=[...e.actions].reverse().find(o=>o.stepId==="shape.prepare"&&o.status==="succeeded"),n=Sa(r.outcome.output),i=fA({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 LG(e,t){let r=gA(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:Qs(n),candidateId:r.builder_handoff?.candidate_id??null}}]}}function VG(){return{workflow:{id:"comet-native",version:"4",entry:"shape.prepare",commands:{"revise-implementation":{stepId:"repair.implementation",validator:{id:Rm.id,version:Rm.version}},"revise-requirements":{stepId:"shape.revise",validator:{id:Sm.id,version:Sm.version}},"remove-capability":{stepId:"shape.remove",validator:{id:km.id,version:km.version}},"disassociate-capability":{stepId:"shape.disassociate",validator:{id:vm.id,version:vm.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:lb.id,version:lb.version},steps:{"repair.implementation":{type:"call_tool",ref:"native-revise-implementation",validator:{id:Nm.id,version:Nm.version}},"shape.revise":{type:"call_tool",ref:"native-revise-requirements",validator:{id:Em.id,version:Em.version}},"shape.remove":{type:"call_tool",ref:"native-remove",validator:{id:Am.id,version:Am.version}},"shape.disassociate":{type:"call_tool",ref:"native-disassociate",validator:{id:wm.id,version:wm.version}},"shape.prepare":{type:"call_tool",ref:"native-shape-prepare",validator:{id:ob.id,version:ob.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:ab.id,version:ab.version}},"build.resume":{type:"ask_user",proposalFrom:"build.builder",choices:["continue"]},"supervisor.prepare":{type:"call_tool",ref:"native-supervisor-prepare",validator:{id:_m.id,version:_m.version}},"supervisor.child.prepare":{type:"call_tool",ref:"native-supervisor-child-prepare",validator:{id:Cm.id,version:Cm.version}},"supervisor.child.builder":{type:"handoff",ref:"native-supervisor-builder",validator:{id:Tm.id,version:Tm.version}},"supervisor.child.resume":{type:"ask_user",proposalFrom:"supervisor.child.builder",choices:["continue"]},"supervisor.child.verifier":{type:"handoff",ref:"native-supervisor-verifier",validator:{id:Om.id,version:Om.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:Bm.id,version:Bm.version}},"supervisor.child.integration-repair":{type:"handoff",ref:"native-supervisor-integration-repair",validator:{id:Dm.id,version:Dm.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:Pm.id,version:Pm.version}},"supervisor.parent.builder":{type:"handoff",ref:"native-supervisor-parent-builder",validator:{id:sb.id,version:sb.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:jm.id,version:jm.version}},"supervisor.cleanup":{type:"call_tool",ref:"native-supervisor-cleanup",validator:{id:$m.id,version:$m.version}},"verify.verifier":{type:"handoff",ref:"native-verifier",validator:{id:cb.id,version:cb.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:fm.id,version:fm.version}},"archive.execute":{type:"call_tool",ref:"native-archive",validator:{id:pm.id,version:pm.version}},"archive.finalize":{type:"call_tool",ref:"native-archive-finalize",validator:{id:mm.id,version:mm.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:G0(n,i.reason),next:["shape.prepare"]};let o=Ws({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:Wm(t,{failedVerifierActionId:a.id})}]:[{stepId:"build.builder",input:{repairContext:tu(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:G0(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:jG(n,o),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.disassociate")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:nb(n),next:["shape.prepare"]};if(r.kind==="action-outcome"&&r.stepId==="shape.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Sa(r.outcome.output);return{state:pA({state:{...n,document_constraints_version:t$(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"?Z0(t,n):{state:nb(n),next:["shape.prepare"]};if(r.kind==="wait-resolved"&&r.stepId==="supervisor.shape.confirm"){if(r.choice==="rejected")return{state:nb(n),next:["shape.prepare"]};let i=Sa(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 Z0(t,a)}if(r.kind==="action-outcome"&&r.stepId==="supervisor.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Sa(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=FA({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=Sa(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:yo(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&&z0(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}:ib(t,a,"failedCheckActionId")}]}}let s=t.actions.find(c=>c.id===o?.failedVerifierActionId);if(!s||!o||T(rb(t,s))!==T(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:ib(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:rb(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:ib(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:Y0(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=Sa(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(Gt(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=DG(t);if(c)return{state:n,next:[{stepId:"supervisor.child.integrate",input:Y0(c,c.outcome?.output,t.workflow.version==="4")}]};let l=new Set(Gt(t).filter(d=>d.stepId==="supervisor.child.prepare").map(d=>d.input.activation.child).filter(d=>!a.has(d))),u=FA({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:m,text:h})=>({id:d,source:m,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=X0(t,i,r.outcome);return{state:ni(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=X0(t,i,r.outcome);return{state:ni(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=WG(t,i,r.outcome);return a.status==="blocked"?{state:a,next:["verify.retry"]}:{state:ni(a),next:["verify.verifier"]}}let o=BG(t,i,r.outcome);return{state:o.state,next:o.state.verification_result==="pass"?[{stepId:"verify.confirm",input:{report:nm(o.state,t.input.artifactRootRef)}}]:o.state.phase==="build"?n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:Wm(t,{failedVerifierActionId:i.id})}]:[{stepId:"build.builder",input:{repairContext:tu(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||!eA(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:ni(vA(n,{reason:i.decision?.reason})),next:[{stepId:"verify.verifier",input:{recoveryWaitId:i.id,...i.decision?.reason===void 0?{}:{reason:i.decision.reason}}}]};let o=Ws({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:Wm(t,a?{failedVerifierActionId:a.id}:{failedCheckActionId:s.id})}]:[{stepId:"build.builder",input:{repairContext:tu(o,t)}}]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.retry")return{state:ni(yA(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||!eA(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:ni(a),next:["verify.verifier"]}}if(r.choice==="approved")return LG(t,n);let o=Ws({state:n,reason:"The user rejected the Skill-coordinated Verifier pass."});return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:Wm(t,{rejectedDecisionId:r.decisionId})}]:[{stepId:"build.builder",input:{repairContext:tu(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:Tt("归档候选已变化;由 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:[Nm,Em,Am,wm,ob,ab,cb,fm,pm,mm,_m,Cm,Tm,Om,Bm,Dm,sb,jm,$m,Pm],stateValidators:[lb],commandValidators:[Rm,Sm,km,vm],executors:[qA,C0,S0,R0,$A,jA,DA,QA,UA,tb,eb,xm,YA]}}var ob,ab,sb,cb,lb,Us=I(()=>{"use strict";ot();Pr();Ye();Kt();EO();wt();zr();Ze();pr();di();Pr();Ds();_t();ya();Vt();Ro();Te();Ri();kp();va();A0();BA();N0();E0();ka();bm();I0();$0();D0();XA();F0();J0();ZA();ba();Ra();K0();AA();_i();yr();tA();ob={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=Sa(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)}}}},ab={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 We(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)}}}},sb={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 Fs(e,n.projectRoot),o=t.input.activation,a=i.state,s=pt(n.projectRoot,a.name),c=bt(a.name),l=Qs(t,r),u=new Set(Gt(e).filter(f=>f.stepId==="supervisor.child.archive"&&f.status==="succeeded").map(f=>f.input.activation.child));if(a.phase!=="build"||!o||He(o,e)!==a.children_contract_ref||o.integrationBranch!==c||typeof o.integrationWorktree!="string"||!me(o.integrationWorktree,s)||typeof o.integrationCommit!="string"||Ae(s).currentBranch!==c||he(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 de(s,["merge-base","--is-ancestor",o.integrationCommit,l]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},cb={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 We(r.projectRoot);if(!i||i.native.artifact_root!==n.artifactRootRef||(n.maxVerifyFailures??Tc)!==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)}}}},lb={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 n$={};Fm(n$,{upgradeNativeRun:()=>oi});function oi(e,t,r){let n=fn(t),i=T(n);if(e.workflow.hash===i&&e.workflow.version===n.version)return e;if(e.workflow.version==="4"&&e.workflow.hash!==MG)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=Ry(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),m=[...a.actions].reverse().find(h=>h.stepId===d);!s(d)&&m&&c.push({step:d,results:a.actionContexts[m.id].results})}if(o.children_contract_ref&&!a.actions.some(d=>d.id===o.children_contract_ref)){let d=[...a.waits].reverse().find(p=>["shape.confirm","supervisor.shape.confirm"].includes(p.stepId)&&p.status==="resolved"&&["approved","single-session","multi-session"].includes(p.decision?.choice??"")),m=a.actions.find(p=>p.stepId==="shape.prepare"&&p.status==="succeeded"&&a.actionContexts[p.id].sequence===d?.results["shape.prepare"]?.sequence),h=m?.outcome?.output?.children?.contract;if(!m||!h)throw new Error("旧 Supervisor 缺少原已批准的子任务方案");a.state={...o,children_contract_hash:o.children_contract_ref,children_contract_ref:m.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"]:[],p=[...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(p){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:p.stepId,choice:p.decision.choice,proposalHash:p.proposalHash,decisionId:p.decision.id}})}if(v.next.length!==1)throw new Error("旧批准没有唯一的当前业务续行");a.state=v.state;let w=v.next[0];g={from:p.stepId,to:typeof w=="string"?w:w.stepId,results:{...p.results,[p.stepId]:{sequence:p.sequence,value:{choice:p.decision.choice,proposal:p.proposal}}},...typeof w=="string"?{}:{activation:w.input}}}else{let v=[...a.actions].reverse().find(R=>s(R.stepId)&&R.status==="succeeded"&&["build.builder","supervisor.parent.builder","supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair","verify.verifier"].includes(R.stepId)&&d.results[R.stepId]?.sequence===a.actionContexts[R.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,b;if(["supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair"].includes(v.stepId)){if(!r)throw new Error("旧 Child 需要当前业务转移器完成数据转换");let R=r.apply({run:a,event:{kind:"action-outcome",stepId:v.stepId,outcome:v.outcome}});if(R.next.length!==1)throw new Error("旧 Child 没有唯一的当前业务续行");a.state=R.state;let _=R.next[0];A=typeof _=="string"?_:_.stepId,b=typeof _=="string"?void 0:_.input,b&&typeof b=="object"&&!Array.isArray(b)&&(b={...b,contractRef:M(a.state).children_contract_ref},delete b.contractHash)}else{let R=M(a.state),_=v.stepId==="verify.verifier"&&R.verification_result==="pass";A=_?"verify.confirm":"verify.verifier",!_&&R.phase==="verify"&&R.loop.stage==="verify-ready"&&R.loop.next_action!=="await-verifier-result"&&(a.state=ni(R))}g={from:v.stepId,to:A,results:{...w.results,[v.stepId]:{sequence:w.sequence,value:v.outcome.output}},...b===void 0?{}:{activation:b}}}g.to==="verify.confirm"&&(g.activation={report:nm(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 MG,vu=I(()=>{"use strict";ya();ka();Ze();Te();MG="26c4e50c65dcb5e1280529642a73b650400e3109ba6fa2efded90e03ad790443"});_a();ji();Qm();wt();import Xl from"path";import{realpathSync as aK}from"fs";function $b(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:`'${t.replace(/'/gu,`'"'"'`)}'`).join(" ")}function jb(e,t){let r=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)?p:{},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,...m}=c,h=d===void 0?c:{...m,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 Vn={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Db(e){return e?e.command?`${Vn.next} ${e.command}`:e.ask_user?`${Vn.next} ${e.ask_user}`:e.instruction?`${Vn.next} ${e.instruction}`:null:null}function Bb(e,t){let r=[e.summary],n=Db(e.next);return n&&r.push(n),e.user_message&&r.push("",Vn.relay,e.user_message),t!==void 0&&r.push("",Vn.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
414
|
+
`)}
|
|
415
|
+
`}function Wb(e,t,r){let n=[e.summary],i=Db(e.next);return i&&n.push(i),e.user_message&&n.push("",Vn.relay,e.user_message),n.push("",`${Vn.detail} ${t}`),r!==void 0&&n.push("",Vn.details,JSON.stringify(r,null,2)),n.join(`
|
|
416
|
+
`)}Ye();_t();function Ee(e,t,r){return e==="zh-CN"?r:t}var rv={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function aE(e,t){return typeof e=="string"&&rv[e]?Ee(t,rv[e].en,rv[e].zh):typeof e=="string"?e:""}function nv(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 EV(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 sE(e,t){let r=[];e.failed>0&&r.push(Ee(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(Ee(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(Ee(t,`${e.pending} pending`,`${e.pending} 项待验`));let n=Ee(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${n} (${r.join(", ")})`:n}function cE(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 iv(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function _V(e,t,r){return e==="done"?Ee(r,"complete","已完成"):e==="await-user"?Ee(r,"waiting for a user decision","等待用户决定"):e==="blocked"?Ee(r,"paused: needs attention","已暂停,需要处理"):t?Ee(r,"waiting for a user decision","等待用户决定"):Ee(r,"ready to continue","可继续推进")}function CV(e,t,r){let n=iv(e),i=[];r&&i.push(r);let o=Ee(n,`Change ${e.change}`,`需求 ${e.change}`),a=aE(e.phase,n),s=e.mode==="wait"?Ee(n,"waiting for the original task","等待原任务完成"):_V(e.disposition,e.userCommunication.required,n);i.push([o,a||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&i.push(sE(t,n));let c=e.userCommunication,l=lE(e,n);return{summary:i.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function lE(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:Ee(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:$b(e.commandArgs)}:e.disposition==="done"?{ask_user:Ee(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")}:e.disposition==="blocked"?{ask_user:r.required&&r.message?r.agentInstruction:Ee(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}:{instruction:r.agentInstruction}}function IV(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function xV(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",n=aE(e.phase,t),i=e.status==="await-user"?Ee(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?Ee(t,"paused","已暂停"):e.status==="done"?Ee(t,"complete","已完成"):Ee(t,"in progress","进行中"),o=nv(e.acceptance)?`${Ee(t,", ",",")}${sE(e.acceptance,t)}`:"";return` ${r} · ${n||String(e.phase??"?")} · ${i}${o}`}function PV(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 TV(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 OV(e){if(e.healthy){let n=e.repaired?Ee("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):Ee("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),i=$V(e.continuation);return i?{summary:n,next:i}:{summary:n}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:Ee("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:Ee("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function $V(e){return cE(e)?lE(e,iv(e)):void 0}function uE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(TV(t))return OV(t);if(IV(t)){let n=PV(t.items);return{summary:[t.total===t.items.length?Ee(n,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):Ee(n,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(o=>xV(o,n))].join(`
|
|
417
|
+
`)}}let r=t.continuation;if(cE(r)){let n=iv(r),i=CV(r,jV(t),BV(t,n));return DV(t)==="unconfirmed"?{...i,summary:`${i.summary}${Ee(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:Ee(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 jV(e){if(nv(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(nv(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return EV(r.acceptance)}return null}function DV(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 BV(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return Ee(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?Ee(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function dE(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)?Ee("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:Ee("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:Ee("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:Ee("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:Ee("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:Ee("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:Ee("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:Ee("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:Ee("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Fd=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Hd();Uk();mp();var hO=["--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."],Jk=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:hO,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
|
|
418
|
+
comet native spec remove <change-name> <capability>
|
|
419
|
+
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]
|
|
420
|
+
comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
421
|
+
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>]
|
|
422
|
+
comet native next <sdk-change> --confirmed --coordination-mode multi-session|single-session --summary <text> --expected-state-version <n> --expected-action confirm-shape
|
|
423
|
+
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>
|
|
424
|
+
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>]
|
|
425
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]
|
|
426
|
+
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
|
|
427
|
+
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 Qp(e,t){return`${e}:
|
|
428
|
+
${t.map(r=>` ${r}`).join(`
|
|
429
|
+
`)}`}function nK(e){let t=e.filter(n=>n!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Jk[r]||t.length>1&&Jk[t[0]]?.subcommands?r:t[0]}function iK(e=[]){let t=nK(e),r=Jk[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let n=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&n.push("",Qp("Agent Quick Start",r.agentQuickStart)),r.subcommands&&n.push("",Qp("Commands",r.subcommands));let i=t===""?r.options:[...r.options??[],...hO];return i&&i.length>0&&n.push("",Qp("Options",i)),n.push("",`Output:
|
|
430
|
+
${r.output}`),r.examples&&n.push("",Qp("Examples",r.examples)),t===""&&n.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${n.join(`
|
|
431
|
+
`)}
|
|
432
|
+
`}}var oK=iK().usage;var $r=class extends Error{};function Os(e,t){let r=e.flatMap((n,i)=>n===t?[i]:[]);if(r.length>1)throw new $r(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Zl(e,t){let r=e.flatMap((o,a)=>o===t?[a]:[]);if(r.length>1)throw new $r(`${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 $r(`${t} requires a value`);return e.splice(n,2),i}function Kk(e){if(e.length>0)throw new $r(`Unexpected argument: ${e[0]}`)}function Gk(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new $r(`${t} is required`);return r}function zk(e,t){let r=Xl.normalize(gO(e)),n=Xl.normalize(gO(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function gO(e){let t=Xl.resolve(e);try{return aK.native(t)}catch{return t}}function sK(e,t){let r=Xl.resolve(t,e),n=Ae(t);if(!n.isSecondaryWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null)return r;let i=Ae(r);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!zk(n.primaryWorktreeRoot,i.primaryWorktreeRoot)||zk(n.currentWorktreeRoot,i.currentWorktreeRoot)?r:zk(t,n.currentWorktreeRoot)?Xl.resolve(t):n.currentWorktreeRoot}async function vO(e,t=process.cwd()){return e?sK(e,t):Vg(t)}function wO(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function yO(e){return JSON.stringify(e,null,2)+`
|
|
433
|
+
`}function Yk(e,t,r){return{command:e,exitCode:0,data:t,text:r??yO(t)}}function cK(e,t){if(t instanceof Ts)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof vo)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 Fc)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof $r)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Nu)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 Ea)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 Eo)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 Ln)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Fd)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 kO(e,t){let r=cK(e,t),n=r.error;if(!n)return r;let i=dE({code:n.code,message:n.message,data:r.data});return i?{...r,envelope:i}:r}function lK(e,t,r=!1){let n=e.envelope??uE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:jb(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}})+`
|
|
434
|
+
`}:e.error?{exitCode:e.exitCode,stderr:n?Wb(n,e.error.message,r?e.data:void 0):e.error.message}:n?{exitCode:e.exitCode,stdout:Bb(n,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==yO(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
435
|
+
${Vn.details}
|
|
436
|
+
${JSON.stringify(e.data,null,2)}
|
|
437
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function uK(e,t,r=!1){let n=lK(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 AO(e,t,r=!1){return uK(e,t,r).output}var Nb=or(Vr(),1);Lr();wt();Ze();bs();pr();Nn();ot();_t();Ye();Te();Kt();import{execFileSync as oY}from"node:child_process";import{createHash as aY}from"node:crypto";import{promises as we}from"node:fs";import ue from"node:path";ji();qn();Ml();Ze();bs();pr();ot();_t();Vt();Ye();Te();Kt();Us();vu();import{promises as R$}from"node:fs";import bu from"node:path";Ze();pr();jt();Cs();Yl();_t();Vt();Us();Kt();Te();Ye();import ZG from"node:path";um();Ze();Lr();import{AsyncLocalStorage as FG}from"node:async_hooks";vy();import{createHash as HG,randomUUID as hfe}from"node:crypto";import a$ from"node:path";Zm();import{promises as Lm}from"node:fs";import fb from"node:path";async function i$(e,t){let r=Xm(e),n=fb.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let a of["","workspaces",r.workspaceId,"observability"]){i=fb.join(i,a);let s;try{s=await Lm.lstat(i)}catch(c){if(!t||c.code!=="ENOENT")throw c;await Lm.mkdir(i,{recursive:a===""}).catch(l=>{if(l.code!=="EEXIST")throw l}),s=await Lm.lstat(i)}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let o=fb.join(n,"performance.sqlite");for(let a of["","-wal","-shm"])try{let s=await Lm.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 qG}from"node:util";function o$(e,t=process.env){let r=qG(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 QG=864e5,UG=1e4,s$=new FG;function pb(e){let t=s$.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function wu(e,t){return o$(e).slice(0,t)}async function c$(e,t){if(!t.length)return;let r=s$.getStore();if(r){let i=o=>process.platform==="win32"?a$.resolve(o).toLowerCase():a$.resolve(o);if(i(e)===i(await r.projectRoot())){r.spans.push(...t);return}}let n=Jf(await i$(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
438
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
439
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
440
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
441
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
442
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
443
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
444
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
445
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
446
|
+
BEGIN IMMEDIATE;`);let i=n.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
447
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
448
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
449
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
450
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
451
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
452
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
453
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
454
|
+
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:wu(a.name,240),summary:a.summary?wu(a.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(a.attributes??{}).slice(0,20).map(([u,f])=>[wu(u,80),Array.isArray(f)?f.slice(0,30).map(d=>wu(d,240)):typeof f=="string"?wu(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=HG("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*QG).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(UG),n.exec("COMMIT")}finally{n.close()}}var JG=(e,t)=>`workflow:${e}:${t}`,l$=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},u$=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}))}),d$=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function zG(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:o}=e,a=JG(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 m=u.get(`${d.id}:${d.attempt}`);if(m&&m.status===d.status&&m.outcome?.outcomeId===d.outcome?.outcomeId&&m.reason===d.reason&&m.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"&&(m?.status==="pending"||i)?o:null,endedAt:h&&(i||r!==null)?o:null,summary:d.outcome?.summary??d.reason,attributes:{phase:l$(d.stepId,t),actionId:d.id,actionType:d.type,ref:d.ref??null,executor:d.claim?.executorId??null,inputFields:d$(d.input),outputFields:d.outcome?d$(d.outcome.output):[],artifacts:(d.outcome?.artifacts??[]).map(p=>p.uri)}})}for(let d of["wait","evidence"]){let m=d==="wait"?n.waits:n.evidenceWaits??[],h=d==="wait"?r?.waits:r?.evidenceWaits,p=new Map(h?.map(g=>[g.id,g]));for(let g of m){let v=p.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:l$(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return f}function f$(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?u$(o):null}catch{n=null}return o&&pb({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){pb({workflow:t,change:i,runId:i});try{await c$(e,zG({workflow:t,previous:s,next:a,initial:o===null,observedAt:new Date().toISOString()}))}catch{}try{n=u$(a)}catch{n=null}}return c}}}Lr();var v$=or(Vr(),1);Ml();import{promises as vb}from"node:fs";import{isDeepStrictEqual as hb}from"node:util";import Ci from"node:path";Gl();Us();BA();vu();Ze();pr();po();Lr();Hl();Vt();Ye();um();Ls();Te();import p$ from"node:path";async function yu(e){let t=e.run.input;if(typeof t?.artifactRootRef!="string"||!Number.isSafeInteger(e.run.revision)||(await tt(e.projectRoot,"native",e.run.runId,{readOnly:!0}))?.application!=="native")return!1;if(await Pt({singleWriter:!0,rootDir:p$.join(it(e.projectRoot),"sdk-runs","native")}).readDisposition(e.run.runId)==="closed")return mb(e);let i=await Ne(e.projectRoot,t.artifactRootRef,{readOnly:!0});return Qe(i,()=>mb(e))}async function mb(e){let{projectRoot:t}=e,r=await tt(t,"native",e.run.runId,{readOnly:!0});if(!r||r.application!=="native")return!1;let n=Pt({singleWriter:!0,rootDir:p$.join(it(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=ub(null),a=oi(i,o.workflow,o.transitionHandler),s=oi(e.run,o.workflow,o.transitionHandler);if(T(a)!==T(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 Bt({...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 _y(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 Sp({projectRoot:t,run:c}))?.status!=="cancelled")return!1}else{if(!l.archived||l.phase!=="archive"||l.status!=="done"||!(await Np({projectRoot:t,run:c})).quiescent)return!1;let f=await Qr(t);if(f.status==="selected"&&f.selection.workflow==="native"&&f.selection.change===c.runId)return!1;let d=c.outputs["archive.execute"]?.value,m=c.outputs["archive.finalize"]?.value;if(!d||typeof d.archiveRef!="string"||typeof d.transactionId!="string"||d.stateVersion!==l.state_version-1||!m)return!1;let h=await Ne(t,u.artifactRootRef,{readOnly:!0}),p=await gu({paths:h,state:l,runId:c.runId,archiveRef:d.archiveRef,history:!0,allowMissingReport:["3","4"].includes(c.workflow.version),verificationResultHash:c.workflow.version!=="1"?r0(l):void 0});if(p.transactionId!==d.transactionId||T(m)!==T(p))throw new Error("Native history Archive receipt does not match its committed outcome")}return e.recover&&await n.readDisposition(c.runId)==="reopening"?(await Rx(t,"native",c.runId),await n.reopenRun(c.runId,c.revision)?mb({projectRoot:t,run:c}):!1):!await n.closeRun(c.runId,c.revision)||await n.readDisposition(c.runId)!=="closed"?!1:(await _y(t,r),!0)}pr();po();Vt();Ye();Hl();async function m$(e){if(e.run.status!=="cancelled")return;let t=e.run.input?.artifactRootRef;if(typeof t=="string"){let o=await Ne(e.projectRoot,t);if(await Ei(o,{kind:"archive",change:e.run.runId}))return}let r=await Sp(e);if(!r?.quiescent)return;if(!r.cleanupRequired){await yu(e);return}let n=e.run.input;if(typeof n?.artifactRootRef!="string")return;let i=await Ne(e.projectRoot,n.artifactRootRef);await Qe(i,async()=>{let o=await Qr(e.projectRoot);if(o.status!=="selected"||o.selection.change!==e.run.runId)return;let a=await tt(e.projectRoot,"native",e.run.runId);a&&(a.application==="native"?o.selection.workflow==="native":o.selection.workflow==="application"&&o.selection.applicationId===a.application)&&await ps(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 yu(e)}async function h$(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 Ne(t,a.artifactRootRef);return Qe(s,async()=>{let c=await r.read(n);if(c&&c.status!=="cancelled"){if(await Ei(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();po();Vt();Ye();async function g$(e){if(e.run.status!=="completed")return;let t=e.run.input;if(typeof t?.artifactRootRef!="string")return;let r=await Ne(e.projectRoot,t.artifactRootRef);await Qe(r,async()=>{let n=await Qr(e.projectRoot);if(n.status!=="selected"||n.selection.change!==e.run.runId)return;let i=await tt(e.projectRoot,"native",e.run.runId);i&&(i.application==="native"?n.selection.workflow==="native":n.selection.workflow==="application"&&n.selection.applicationId===i.application)&&await ps(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 yu(e)}tn();wt();Ze();pr();ot();_t();jt();Ye();Te();Kt();Kt();yr();bm();Ze();var gb=class extends Error{constructor(r,n,i=!1,o){let a=o?["runtime","dispatch","--application-file",Ci.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.
|
|
455
|
+
Recovery argv: ${JSON.stringify(a)}
|
|
456
|
+
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 KG(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 GG(e,t){return JSON.stringify(e)===JSON.stringify(t)}function YG(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=qt(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"?Rt(r,t.name,u):pt(r,t.name),d=typeof u=="string"?l.worktree:l.integrationWorktree,m=typeof u=="string"?l.branch:l.integrationBranch;if(typeof d!="string"||!me(d,f)||typeof m!="string"||a&&(!o.some(h=>me(h,f))||Ae(f).currentBranch!==m))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 ku(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 ce(e.projectRoot,Ci.relative(e.projectRoot,e.archiveDir),{label:"Native SDK Archive directory",expected:"directory"});if(!r.exists)return null;let n=(await vb.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?Ci.join(r.target,n[0],"comet-state.yaml"):null}async function w$(e,t){return Pt({singleWriter:!0,rootDir:Ci.join(await Wi(e),"sdk-runs","native")}).read(t)}async function Au(e){let{text:t}=await kE({root:Ci.dirname(e),ref:Ci.basename(e),maxBytes:Buffer.byteLength(Vl)+1});return ma(t)}async function y$(e,t){let r=await vb.readFile(e,"utf8");if(!ma(r))return!1;let n=wo(r,"Native state file");return oa(n[mn],t)!==null}async function wb(e,t,r,n,i,o){return XG(e,t,r,n?Xf(ia(n)):void 0,i,o)}function k$(e,t,r,n){return Vl+(0,v$.stringify)({...M(e),...r===void 0?{}:{archive_receipt:r},...n?{application_checkpoint:n}:{}})+(t?`${mn}: ${JSON.stringify(t)}
|
|
457
|
+
`:"")}async function XG(e,t,r,n,i,o){await Ue(e,k$(t,n,i,o),{containedRoot:r})}function Ii(e,t={},r=!1){let n=it(e),i=f$(e,"native",t.store??Pt({singleWriter:!0,rootDir:Ci.join(n,"sdk-runs","native")}));function o(){if(it(e)!==n)throw new Error("Native SDK workspace identity changed; recreate the store in the current workspace")}function a(f,d){return wo(d,"Native portable state")}async function s(f){return(await qe(e,Ci.relative(e,f),Number.MAX_SAFE_INTEGER,{label:"Native portable state"})).bytes.toString("utf8")}async function c(f,d,m=t.readOnly){let h=await We(e);if(!h)return null;let p=await Ne(e,h.native.artifact_root,{...t,readOnly:m,change:f}),g=vr(p,f),v=g,w;try{w=await s(v)}catch(J){if(J.code!=="ENOENT")throw J;let F=await ku(p,f);if(!F)return null;v=F,w=await s(v)}if(!ma(w))return null;let A=wo(w,"Native state file"),b=oa(A[mn],f,{preserveSourceRevision:!0});if(!b)return null;if(T(A.application_checkpoint??null)!==T(t.identity??null))throw new Error("Native portable checkpoint requires its original fixed Application package");let R=M(A),_=b.input;if(!GG(M(b.state),R)||_?.name!==f||_.artifactRootRef!==p.artifactRootRef||b.workflow.id!=="comet-native"||v!==g&&!R.archived)throw new Error(`Native portable Run checkpoint for ${f} does not match its state`);if(!t.identity){let[{nativeSdkApplicationForRun:J},{upgradeNativeRun:F}]=await Promise.all([Promise.resolve().then(()=>(Us(),r$)),Promise.resolve().then(()=>(vu(),n$))]);if(t.rootRunId===f&&b.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let X=J(null);F(b,X.workflow,X.transitionHandler)}!t.allowBranchRebind&&b.status!=="cancelled"&&!(R.archived&&b.status==="completed")&&eu(e,{isolation:R.workspace.isolation,changeBranch:R.workspace.change_branch,targetBranch:R.workspace.target_branch}),YG(b,R,e);let W=b.revision,O={...b,revision:W};if(d&&T(d)!==T({...O,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(m)return O;if((W>1||d)&&!i.restoreCheckpoint)throw new Error(`Native RuntimeStore cannot restore checkpoint revision ${W}; use a store with restoreCheckpoint support or restore the original Run history`);let G=t.identity?.id??"native",Z=R.archived&&b.status==="completed"?await tt(e,"native",f,{readOnly:!0}):null;return(Z?.application!==G||Z.runId!==f)&&await Xn(e,{schema:Hr,workflow:"native",change:f,format:"sdk",application:G,runId:f}),W===1&&!d?await i.compareAndSwap(f,null,O):await i.restoreCheckpoint(f,d?1:null,O),i.read(f)}async function l(f,d){let m=M(f.state),h=f.input;if(m.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 p=await We(e);if(p&&p.native.artifact_root!==h.artifactRootRef)throw new Error("Native artifact root changed after Run creation");if(!d||!KG(f))return f;let g=f,v=m,w=await Ne(e,h.artifactRootRef,{change:f.runId}),A=vr(w,f.runId);try{await vb.access(Ci.dirname(A))}catch(O){if(O.code!=="ENOENT")throw O;if(!v.archived)return g;let G=await ku(w,f.runId);if(!G)throw new Error(`Native SDK Archive ${f.runId} is ambiguous`,{cause:O});A=G}let b=null;try{b=await s(A)}catch(O){if(O.code!=="ENOENT")throw O}let R=b&&g.actions.some(O=>O.stepId==="archive.finalize")?a(A,b).archive_receipt:void 0,_=Xf(ia(g)),W=k$(v,_,R,t.identity);return b!==W&&await Ue(A,W,{containedRoot:w.nativeRoot}),g}async function u(f,d=!1){let m;if(r)try{m=(await qo(i,f)).record}catch(p){if(p.code!=="RUN_NOT_FOUND")throw p;m=null}else m=await i.read(f);let h=m?.revision===1&&m.actions.some(p=>p.status!=="pending")?m:void 0;if(!m||h){let p=await c(f,h,!0);if(!p)return m;if(!m||p.revision>m.revision){if(t.readOnly)throw new gb(e,f,!!h,t.identity);o(),await ci(e),m=await c(f,h,!1)}}return m?l(m,d&&!t.readOnly):null}return{queryScope:i.queryScope,read:u,readProjection:f=>Ii(e,{...t,store:i,readOnly:!0},!0).read(f),async compareAndSwap(f,d,m){if(t.readOnly)throw new Error("Native SDK diagnostic store is read-only");o();let h=M(m.state);for(let R of m.actions){if(R.status!=="running"||!["verify.verifier","supervisor.child.verifier"].includes(R.stepId)||!qs(m,R))continue;let W=R.input.activation?.builderSessionId??h.builder_handoff?.builder_execution_ref;if(!W||R.claim?.sessionId!==W)continue;let O=await i.read(f),G=O?.actions.find(Z=>Z.id===R.id);if(O?.revision===d&&(G?.status!=="running"||!hb(G.claim,R.claim)))throw new k("VERIFIER_SESSION_NOT_INDEPENDENT","Native Verifier requires an independent session; use a different sessionId from the Builder.")}let p=h.workspace;try{eu(e,{isolation:p.isolation,changeBranch:p.change_branch,targetBranch:p.target_branch})}catch(R){let _=await i.read(f),W=m.actions.some(G=>G.status==="running"&&!_?.actions.some(Z=>Z.id===G.id&&Z.status==="running"&&Z.attempt===G.attempt&&hb(Z.claim,G.claim))),O=_?.actions.some(G=>["running","unknown"].includes(G.status)&&m.actions.some(Z=>Z.id===G.id&&Z.attempt===G.attempt&&hb(Z.claim,G.claim)));if(W||m.status!=="cancelled"&&!O)throw R}let g=()=>i.compareAndSwap(f,d,m),v=[...m.actions].reverse().find(R=>R.stepId==="archive.execute"&&R.status==="failed"),A=(v?await i.read(f):null)?.actions.some(R=>R.id===v?.id&&R.status==="unknown"),b=m.status==="cancelled"?await h$({projectRoot:e,store:i,runId:f,expectedRevision:d,next:m}):A?await v0({projectRoot:e,store:i,runId:f,expectedRevision:d,next:m,actionId:v.id,state:h}):await g();return b&&(await l(m,!0),m.status==="cancelled"&&await m$({projectRoot:e,run:m}),m.status==="completed"&&await g$({projectRoot:e,run:m})),b}}}async function eY(e){let t=No(),r=Ii(e.paths.projectRoot);return Bt({store:{async read(o){let a=await r.read(o);if(a&&!await tt(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 Xn(e.paths.projectRoot,{schema:Hr,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 A$(e,t){let r=ZG.join(Mt(e,t),"comet-state.yaml");if(!await Au(r))return null;let n=await yn(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 b$(e,t){let r=await A$(e,t);return r?eY({paths:e,name:t,initialState:r}):null}async function N$(e,t,r){if(r.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let n=S$(),i=oi(r,n.workflow,n.transitionHandler);return await Bt({...n,workflows:[n.workflow],transitionHandlers:[n.transitionHandler],store:{read:async()=>i,compareAndSwap:async()=>!1}}).inspect(t),Xn(e,{schema:Hr,workflow:"native",change:t,format:"sdk",application:"native",runId:t},{canonical:!0})}async function tY(e,t){let r=await Tn(e.projectRoot,"native",t);return r||Qe(e,async()=>{let n=await Tn(e.projectRoot,"native",t);if(n)return n;let i=bu.relative(e.projectRoot,vr(e,t));if(!(await ce(e.projectRoot,i,{label:"Native legacy change state",expected:"file"})).exists){let c=await ku(e,t);if(!c)return null;let l=bu.relative(e.projectRoot,c),u=await ce(e.projectRoot,l,{label:"Native archived change state",expected:"file"});if(!u.exists||!await Au(u.target))return null;if(await yb(e.projectRoot,t))return await(await kb(e.projectRoot,t)).runtime.inspect(t),tt(e.projectRoot,"native",t);let f=await Ii(e.projectRoot,{rootRunId:t}).read(t);if(f){let d=await tt(e.projectRoot,"native",t);return d||N$(e.projectRoot,t,f)}throw new Error(`Native archived change ${t} has a managed state file but lost its Run checkpoint`)}if(await yb(e.projectRoot,t))return await(await kb(e.projectRoot,t)).runtime.inspect(t),tt(e.projectRoot,"native",t);let s=await Ii(e.projectRoot,{rootRunId:t}).read(t);if(s){let c=await tt(e.projectRoot,"native",t);return c||N$(e.projectRoot,t,s)}if(await b$(e,t)){let c=await tt(e.projectRoot,"native",t);if(!c)throw new Error(`Recovered Native change ${t} has no Run ownership`);return c}return await rY(e,t),Cy(e.projectRoot,{schema:Hr,workflow:"native",change:t,format:"compat"})})}async function rY(e,t){let r=vr(e,t);if(await Au(r)&&!await y$(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 yb(e,t){let r=await We(e);if(!r)return null;let n=await Ne(e,r.native.artifact_root,{readOnly:!0}),i=vr(n,t);try{await R$.access(i)}catch(a){if(a.code!=="ENOENT")throw a;let s=await ku(n,t);if(!s)return null;i=s}return wo(await R$.readFile(i,"utf8"),"Native application checkpoint").application_checkpoint??null}var nY=si("nativeBuiltinDefinition",()=>No());function S$(){return nY()}async function kb(e,t,r={}){let n=r.owner??await tt(e,"native",t,r),i=n?.application==="native"?null:await yb(e,t),o=n?.application??i?.id??"native";if(o==="native"){let c=Ii(e,{...r,rootRunId:t}),l=await c.read(t),u=S$();if(l){let f=oi(l,u.workflow,u.transitionHandler);f!==l&&(await Bt({...u,workflows:[u.workflow],transitionHandlers:[u.transitionHandler],store:{read:async()=>f,compareAndSwap:async()=>!1}}).inspect(t),l=f)}return{runtime:Bt({...u,executors:r.readOnly?[]:u.executors,store:{...c,async read(f){if(l&&f===t){let m=l;return l=null,Promise.resolve(m)}let d=await c.read(f);return d&&oi(d,u.workflow,u.transitionHandler)}},workflows:[u.workflow],transitionHandlers:[u.transitionHandler]}),executors:u.executors,application:null}}let a=i?.packageRoot?bu.join(i.packageRoot,"application.json"):await fk(e,o,t),s=await As({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:Bt({...s.implementation,...r.readOnly?{executors:[]}:{},store:s.store}),executors:s.implementation.executors??[],application:s}}async function Vm(e,t,r={}){let n=await tt(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 kb(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 iY(e,t,r={}){let n=bu.resolve(e);return await tt(n,"native",t,r)?{projectRoot:n,...await Vm(n,t,r)}:null}async function E$(e,t,r={}){let n=bu.resolve(e),i=await Tn(n,"native",t,r);if(!i&&!r.readOnly){let o=await We(n);if(o){let a=await Ne(n,o.native.artifact_root,{change:t});i=await tY(a,t)}}return i?n:(await iY(n,t,r))?.projectRoot??n}Us();vu();yr();var bb="comet.native.supervisor-transfer.v1",sY=Number.MAX_SAFE_INTEGER;function Wr(e,t){return oY("git",t,{cwd:e,timeout:3e4,killSignal:"SIGKILL",maxBuffer:sY,stdio:["ignore","pipe","pipe"]})}function Wn(e){return aY("sha256").update(e).digest("hex")}function So(e){if(!e||e.includes("\\")||ue.posix.isAbsolute(e)||ue.posix.normalize(e)!==e||e.split("/").some(t=>t==="."||t===".."||t===".git"))throw new Error(`Native Supervisor transfer has an unsafe file path: ${e}`);return e}function Rb(e,t,r){return r.kind==="integration"?pt(e,t):Rt(e,t,r.child)}function cY(e,t){let r=ue.relative(e,t);return r===""||!r.startsWith(`..${ue.sep}`)&&r!==".."&&!ue.isAbsolute(r)}function _$(e,t){let r=M(e.state);if(r.phase!=="build"||r.archived||!r.children_contract_ref)throw new Error("Native Supervisor transfer requires an active SDK Build");if(e.actions.some(a=>["supervisor.child.verifier","supervisor.child.integrate","supervisor.parent.builder"].includes(a.stepId)))throw new Error("Native Supervisor transfer supports Child Builder and candidate review before independent Verify/integration");let i=[...e.actions].reverse().find(a=>a.stepId==="supervisor.prepare"&&a.status==="succeeded")?.outcome?.output;if(!i||typeof i.integrationWorktree!="string"||typeof i.integrationBranch!="string"||i.integrationBranch!==`comet/supervisor/${r.name}/integration`||typeof i.targetBranch!="string"||typeof i.targetCommit!="string")throw new Error("Native Supervisor transfer requires a prepared integration worktree");let o=[{kind:"integration",child:null,sourcePath:i.integrationWorktree,branch:i.integrationBranch,head:"",patchSha256:"",tracked:[],untracked:[]}];for(let a of e.actions){if(a.stepId!=="supervisor.child.prepare"||a.status!=="succeeded")continue;let s=a.outcome?.output;if(!s||typeof s.child!="string"||typeof s.worktree!="string"||typeof s.branch!="string"||s.branch!==`comet/supervisor/${r.name}/${s.child}`)throw new Error("Native Supervisor transfer has an invalid Child receipt");let c=o.find(l=>l.branch===s.branch||me(l.sourcePath,s.worktree));if(c){if(c.kind!=="child"||c.child!==s.child||c.branch!==s.branch||!me(c.sourcePath,s.worktree))throw new Error("Native Supervisor transfer has conflicting workspace identities");continue}o.push({kind:"child",child:s.child,sourcePath:s.worktree,branch:s.branch,head:"",patchSha256:"",tracked:[],untracked:[]})}if(o.length<2)throw new Error("Native Supervisor transfer has no prepared Child");if(t){let a=qt(t);for(let s of o){let c=Rb(t,r.name,s);if(!me(s.sourcePath,c)||!a.some(l=>me(l,c))||Ae(c).currentBranch!==s.branch)throw new Error(`Native Supervisor transfer worktree is unavailable: ${c}`);if(s.head=he(c,s.branch)??"",!s.head)throw new Error(`Native Supervisor transfer branch is missing: ${s.branch}`)}if(he(t,i.targetBranch)!==i.targetCommit)throw new Error("Native Supervisor target branch changed before transfer")}return{targetBranch:i.targetBranch,targetCommit:i.targetCommit,workspaces:o}}async function C$(e,t,r="",n=!1){let i=[];for(let o of await we.readdir(e,{withFileTypes:!0})){let a=So(r?`${r}/${o.name}`:o.name),s=ue.join(e,o.name);if(n&&!r&&o.name==="runtime"&&await th(s))continue;let c=ue.join(t,o.name);if(o.isSymbolicLink())throw new Error(`Native Supervisor transfer cannot copy a symlink: ${a}`);if(o.isDirectory())await we.mkdir(c,{recursive:!0}),i.push(...await C$(s,c,a));else if(o.isFile()){let l=await we.readFile(s);await we.mkdir(ue.dirname(c),{recursive:!0}),await we.writeFile(c,l,{flag:"wx"}),i.push({path:a,sha256:Wn(l)})}else throw new Error(`Native Supervisor transfer cannot copy a special file: ${a}`)}return i.sort((o,a)=>o.path.localeCompare(a.path))}async function Ab(e,t){if(t.some(i=>i.executable!==void 0&&i.executable!==!0))throw new Error("Native Supervisor transfer file mode is invalid");let r=[];async function n(i,o=""){for(let a of await we.readdir(i,{withFileTypes:!0})){let s=So(o?`${o}/${a.name}`:a.name),c=ue.join(i,a.name);if(a.isDirectory())await n(c,s);else if(a.isFile())r.push({path:s,sha256:Wn(await we.readFile(c))});else throw new Error(`Native Supervisor transfer contains a symlink or special file: ${s}`)}}if(await n(e),r.sort((i,o)=>i.path.localeCompare(o.path)),JSON.stringify(r)!==JSON.stringify(t.map(({path:i,sha256:o})=>({path:i,sha256:o}))))throw new Error("Native Supervisor transfer files differ from their manifest")}function lY(e,t){function r(a){return typeof a=="string"?t.get(a)??a:Array.isArray(a)?a.map(r):a&&typeof a=="object"?Object.fromEntries(Object.entries(a).map(([s,c])=>[s,r(c)])):a}let n=r(e),i=new Map;for(let a of n.actions){o(a.input);let s=a.input.activation?.reviewSource;if(s){let c=e.actions.find(u=>u.id===a.id).input.activation.reviewSource,l=n.actions.find(u=>u.id===s.actionId);if(!l)throw new Error("Native 扩展转移缺少原候选检查");s.inputHash=l.inputHash,i.set(T(c),T(s))}a.inputHash=T(a.input),a.outcome&&o(a.outcome.output)}function o(a){if(!a||typeof a!="object")return;let s=a;typeof s.bindingHash=="string"&&i.has(s.bindingHash)&&(s.bindingHash=i.get(s.bindingHash));let c=s.reviewSource;c?.actionId&&(c.inputHash=n.actions.find(l=>l.id===c.actionId).inputHash);for(let l of Object.values(s))o(l)}o(n);for(let a of n.actions)if(a.inputHash=T(a.input),a.outcome){a.outcome.inputHash=a.inputHash;let s=a.receipts.find(c=>c.outcomeId===a.outcome.outcomeId);if(!s)throw new Error("Native Supervisor transfer has a missing Action receipt");s.hash=T(a.outcome)}for(let a of n.waits)a.proposalHash=T(a.proposal),a.decision&&(a.decision.proposalHash=a.proposalHash);return ia(n).run}async function I$(e){if(!e.confirmedStopped)throw new Error("Stop the original Supervisor agents before exporting their worktrees");let t=ue.resolve(e.projectRoot),r=ue.resolve(e.outputDir),{run:n,artifactRootRef:i}=await Vm(t,e.name),{targetBranch:o,targetCommit:a,workspaces:s}=_$(n,t),c=await Ne(t,i),l=[ue.join(c.changesDir,e.name),...s.map(b=>b.sourcePath)],u=await we.realpath(ue.dirname(r)).catch(()=>ue.dirname(r)),f=ue.join(u,ue.basename(r));if(l.some(b=>cY(b,f)))throw new Error("Native Supervisor transfer package cannot be inside a source workspace");try{throw await we.access(r),new Error(`Native Supervisor transfer output already exists: ${r}`)}catch(b){if(b.code!=="ENOENT")throw b}let d=vr(c,e.name),m=await we.readFile(d,"utf8"),h=(0,Nb.parseDocument)(m,{uniqueKeys:!0});if(h.errors.length>0)throw new Error("Native Supervisor state file is invalid");let p=h.toJS()[mn],g=h.toJS().application_checkpoint,v=await Tn(t,"native",e.name);if(v?.format==="sdk"&&v.application!=="native"&&g?.id!==v.application)throw new Error("Native 转移缺少原固定应用的 checkpoint");if(typeof p?.hash!="string"||!oa(p,n.runId))throw new Error("Native Supervisor transfer requires a current portable Run checkpoint");let w=ue.dirname(r);await we.mkdir(w,{recursive:!0});let A=await we.mkdtemp(ue.join(w,".comet-supervisor-transfer-"));try{let b=await C$(ue.join(c.changesDir,e.name),ue.join(A,"change"),"",!0);for(let[W,O]of s.entries()){let G=ue.join(A,"workspaces",String(W));await we.mkdir(ue.join(G,"tracked"),{recursive:!0}),await we.mkdir(ue.join(G,"untracked"),{recursive:!0});let Z=Wr(O.sourcePath,["diff","--binary","--no-ext-diff","HEAD","--"]);O.patchSha256=Wn(Z),await we.writeFile(ue.join(G,"changes.patch"),Z,{flag:"wx"});let J=Wr(O.sourcePath,["diff","--name-only","--diff-filter=ACMRT","-z","HEAD","--"]).toString("utf8").split("\0").filter(Boolean);for(let X of n.actions){let U=X.input.activation;if(!(!X.stepId.startsWith("native.extension.")||!U?.workspaceRoot||!me(U.workspaceRoot,O.sourcePath)))for(let pe of U.artifactRefs??[])So(pe),J.includes(pe)||J.push(pe)}for(let X of J){So(X);let U=ue.join(O.sourcePath,X),pe=await we.lstat(U);if(!pe.isFile())throw new Error(`Native Supervisor transfer cannot copy a tracked symlink: ${X}`);let Le=await we.readFile(U),D=ue.join(G,"tracked",X);await we.mkdir(ue.dirname(D),{recursive:!0}),await we.writeFile(D,Le,{flag:"wx"}),O.tracked.push({path:X,sha256:Wn(Le),...pe.mode&73?{executable:!0}:{}})}O.tracked.sort((X,U)=>X.path.localeCompare(U.path));let F=Wr(O.sourcePath,["ls-files","--others","--exclude-standard","-z"]).toString("utf8").split("\0").filter(Boolean);for(let X of F){So(X);let U=ue.join(O.sourcePath,X),pe=await we.lstat(U);if(!pe.isFile())throw new Error(`Native Supervisor transfer cannot copy an untracked symlink: ${X}`);let Le=await we.readFile(U),D=ue.join(G,"untracked",X);await we.mkdir(ue.dirname(D),{recursive:!0}),await we.writeFile(D,Le,{flag:"wx"}),O.untracked.push({path:X,sha256:Wn(Le),...pe.mode&73?{executable:!0}:{}})}O.untracked.sort((X,U)=>X.path.localeCompare(U.path))}let R=ue.join(A,"branches.bundle");Wr(t,["bundle","create",R,...s.map(W=>`refs/heads/${W.branch}`)]);let _={schema:bb,name:e.name,artifactRootRef:i,sourceRoot:t,targetBranch:o,targetCommit:a,checkpointHash:p.hash,bundleSha256:Wn(await we.readFile(R)),changeFiles:b,workspaces:s,...g?{application:g}:{}};if(await we.writeFile(ue.join(A,"manifest.json"),JSON.stringify(_,null,2)+`
|
|
458
|
+
`,{flag:"wx"}),(await Vm(t,e.name)).run.revision!==n.revision)throw new Error("Native Supervisor Run changed during transfer export");return await we.rename(A,r),{packageDir:r,checkpointHash:_.checkpointHash}}catch(b){throw await we.rm(A,{recursive:!0,force:!0}),b}}async function x$(e){let t=ue.resolve(e.projectRoot),r=ue.resolve(e.inputDir),n=JSON.parse(await we.readFile(ue.join(r,"manifest.json"),"utf8"));if(n.schema!==bb||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(n.name)||!Array.isArray(n.changeFiles)||!Array.isArray(n.workspaces)||n.workspaces.length<2||typeof n.sourceRoot!="string"||typeof n.artifactRootRef!="string"||typeof n.targetBranch!="string"||typeof n.targetCommit!="string"||typeof n.checkpointHash!="string"||typeof n.bundleSha256!="string")throw new Error("Native Supervisor transfer manifest is invalid");let i=await We(t);if(!i||i.native.artifact_root!==n.artifactRootRef)throw new Error("Native Supervisor transfer project configuration does not match");if(he(t,n.targetBranch)!==n.targetCommit)throw new Error("Native Supervisor transfer target branch has a different commit");if(await Tn(t,"native",n.name)||await w$(t,n.name))throw new Error("Native Supervisor transfer target already owns this change");await Ab(ue.join(r,"change"),n.changeFiles);let o=ue.join(r,"change","comet-state.yaml"),a=(0,Nb.parseDocument)(await we.readFile(o,"utf8"),{uniqueKeys:!0});if(a.errors.length>0)throw new Error("Native Supervisor transfer state file is invalid");let s=a.toJS()[mn];if(s?.hash!==n.checkpointHash)throw new Error("Native Supervisor transfer checkpoint differs from its manifest");let c=oa(s,n.name);if(!c)throw new Error("Native Supervisor transfer checkpoint is missing");let l=a.toJS().application_checkpoint;if(T(n.application??null)!==T(l??null))throw new Error("Native 转移固定应用与 manifest 不一致");if(l&&(l.base!=="native"||!me(l.projectRoot,n.sourceRoot)))throw new Error("Native 转移的固定应用归属不一致");let u=l?await As({file:ue.join(l.packageRoot,"application.json"),projectRoot:t,expectedIdentity:{...l,projectRoot:await we.realpath(t)}}):null;if(u&&u.identity.id!==l.id)throw new Error("Native 转移需要原固定应用包");let f=No(),d=u?.implementation??{...f,workflows:[f.workflow],transitionHandlers:[f.transitionHandler]},m=d.workflows.find(J=>J.id===c.workflow.id),h=d.transitionHandlers?.find(J=>J.id===m?.transitionHandler?.id&&J.version===m.transitionHandler.version);if(!m||!h)throw new Error("转移需要原业务应用的当前定义");let p=Gf();await p.restoreCheckpoint(c.runId,null,c),await Bt({store:p,workflows:[]}).inspect(c.runId),c=oi(c,m,h);let g=Gf();await g.restoreCheckpoint(c.runId,null,c),await Bt({...d,store:g}).inspect(c.runId);let v=await Ne(t,n.artifactRootRef);if(M(c.state).name!==n.name)throw new Error("Native Supervisor transfer change name differs");let A=_$(c);if(A.targetBranch!==n.targetBranch||A.targetCommit!==n.targetCommit||A.workspaces.length!==n.workspaces.length)throw new Error("Native Supervisor transfer workspaces differ from the checkpoint");let b=ue.join(r,"branches.bundle");if(Wn(await we.readFile(b))!==n.bundleSha256)throw new Error("Native Supervisor transfer Git bundle differs from its manifest");Wr(t,["bundle","verify",b]);let R=new Map(Wr(t,["bundle","list-heads",b]).toString("utf8").trim().split(`
|
|
459
|
+
`).map(J=>{let F=/^([a-f0-9]{40,64}) (refs\/heads\/.+)$/u.exec(J.trim());if(!F)throw new Error("Native Supervisor transfer Git bundle has an invalid ref");return[F[2],F[1]]}));if(R.size!==n.workspaces.length||n.workspaces.some(J=>R.get(`refs/heads/${J.branch}`)!==J.head))throw new Error("Native Supervisor transfer Git bundle heads differ from its manifest");let _=new Map([[n.sourceRoot,t]]);for(let[J,F]of n.workspaces.entries()){let X=A.workspaces[J];if(!X||X.kind!==F.kind||X.child!==F.child||X.sourcePath!==F.sourcePath||X.branch!==F.branch||typeof F.head!="string"||typeof F.patchSha256!="string"||!Array.isArray(F.tracked)||!Array.isArray(F.untracked))throw new Error("Native Supervisor transfer workspace manifest is invalid");let U=await we.readFile(ue.join(r,"workspaces",String(J),"changes.patch"));if(Wn(U)!==F.patchSha256)throw new Error("Native Supervisor transfer patch differs from its manifest");await Ab(ue.join(r,"workspaces",String(J),"tracked"),F.tracked),await Ab(ue.join(r,"workspaces",String(J),"untracked"),F.untracked);let pe=Rb(t,n.name,F);if(_.set(F.sourcePath,pe),await we.stat(pe).catch(()=>null)!==null){if(!qt(t).some(re=>me(re,pe))||Ae(pe).currentBranch!==F.branch||he(pe,F.branch)!==F.head)throw new Error(`Native Supervisor transfer worktree path already exists: ${pe}`);let D=Wr(pe,["diff","--binary","--no-ext-diff","HEAD","--"]);if(D.length>0&&Wn(D)!==F.patchSha256)throw new Error(`Native Supervisor transfer worktree has different changes: ${pe}`)}let Le=he(t,F.branch);if(Le&&Le!==F.head)throw new Error(`Native Supervisor transfer branch changed: ${F.branch}`)}let W=lY(c,_),O=ue.join(v.changesDir,n.name);for(let J of n.changeFiles){So(J.path);let F=ue.join(O,J.path),X=await we.readFile(F).catch(U=>{if(U.code==="ENOENT")return null;throw U});if(X&&Wn(X)!==J.sha256){let U=ue.relative(t,F).replaceAll("\\","/"),pe=!1;try{Wr(t,["ls-files","--error-unmatch","--",U]),pe=Wr(t,["status","--porcelain=v1","--",U]).length===0}catch{}if(!pe)throw new Error(`Native Supervisor transfer would replace an existing file: ${F}`)}}for(let J of n.workspaces)if(he(t,J.branch)||Wr(t,["fetch","--no-tags",b,`refs/heads/${J.branch}:refs/heads/${J.branch}`]),he(t,J.branch)!==J.head)throw new Error(`Native Supervisor transfer branch could not be restored: ${J.branch}`);let G=[];for(let[J,F]of n.workspaces.entries()){let X=Rb(t,n.name,F);if(await we.mkdir(ue.dirname(X),{recursive:!0}),qt(t).some(S=>me(S,X))||Wr(t,["worktree","add",X,F.branch]),Ae(X).currentBranch!==F.branch||he(X,F.branch)!==F.head)throw new Error(`Native Supervisor transfer worktree changed: ${X}`);await yt(X,".comet",{label:"Native Supervisor worktree configuration directory"});let U=ue.join(X,".comet","config.yaml"),pe=await we.readFile(ue.join(t,".comet","config.yaml")),Le=await we.lstat(U).catch(S=>{if(S.code==="ENOENT")return null;throw S});if(Le&&(!Le.isFile()||Le.isSymbolicLink()))throw new Error(`Native Supervisor transfer worktree configuration is not a file: ${U}`);let D=await we.readFile(U).catch(S=>{if(S.code==="ENOENT")return null;throw S});if(D&&!D.equals(pe)&&JSON.stringify(await We(X))!==JSON.stringify(i))throw new Error(`Native Supervisor transfer worktree configuration changed: ${U}`);D||await Ua(U,pe,{containedRoot:X,exclusive:!0,requireAtomicPublication:!0});let re=ue.join(r,"workspaces",String(J)),ge=ue.join(re,"changes.patch"),mt=Wr(X,["diff","--binary","--no-ext-diff","HEAD","--"]);(await we.stat(ge)).size>0&&mt.length===0&&(Wr(X,["apply","--check",ge]),Wr(X,["apply",ge]));for(let S of F.tracked){let N=ue.join(X,So(S.path)),C=await we.readFile(ue.join(re,"tracked",S.path)),B=await we.lstat(N).catch(Q=>{if(Q.code==="ENOENT")return null;throw Q});if(B&&(!B.isFile()||B.isSymbolicLink()))throw new Error(`Native Supervisor transfer tracked path is not a file: ${N}`);let L=await we.readFile(N).catch(Q=>{if(Q.code==="ENOENT")return null;throw Q}),q=B?.mode;if(L?.equals(C)){S.executable&&q!==void 0&&!(q&73)&&await we.chmod(N,q&511|73);continue}await Ua(N,C,{containedRoot:X}),(q!==void 0||S.executable)&&await we.chmod(N,(q??420)&511|(S.executable?73:0))}for(let S of F.untracked){let N=ue.join(X,So(S.path)),C=await we.lstat(N).catch(L=>{if(L.code==="ENOENT")return null;throw L});if(C&&(!C.isFile()||C.isSymbolicLink()))throw new Error(`Native Supervisor transfer untracked path is not a file: ${N}`);let B=await we.readFile(N).catch(L=>{if(L.code==="ENOENT")return null;throw L});if(B&&Wn(B)!==S.sha256)throw new Error(`Native Supervisor transfer untracked file already exists: ${N}`);await Ua(N,await we.readFile(ue.join(re,"untracked",S.path)),{containedRoot:X}),S.executable&&await we.chmod(N,493)}G.push(X)}for(let J of n.changeFiles){let F=ue.join(O,J.path);await Ua(F,await we.readFile(ue.join(r,"change",J.path)),{containedRoot:t})}if(await wb(vr(v,n.name),M(W.state),t,W,void 0,u?.identity),u){if(!await u.store.read(n.name))throw new Error("Native 定制应用转移未恢复原 Run")}else{if(!await Pt({singleWriter:!0,rootDir:ue.join(v.workspaceRuntimeRoot,"sdk-runs/native")}).compareAndSwap(n.name,null,W))throw new Error("Native Supervisor transfer Run was created by another process");await Ii(t).read(n.name)}let Z=`transfers/native/${n.name}.json`;return await yt(v.workspaceRuntimeRoot,"transfers/native",{label:"Native Supervisor transfer receipt directory"}),await Et(ue.join(v.workspaceRuntimeRoot,...Z.split("/")),`${JSON.stringify({schema:bb,change:n.name,sourceCheckpointHash:n.checkpointHash,importedCheckpointHash:ia(W).hash,actionBindings:W.actions.filter(J=>J.stepId.startsWith("native.extension.")).map(J=>({actionId:J.id,attempt:J.attempt,inputHash:J.inputHash,sourceInputHash:c.actions.find(F=>F.id===J.id).inputHash,sourceBindingHash:T(c.actions.find(F=>F.id===J.id).input.activation.reviewSource),bindingHash:T(J.input.activation.reviewSource)}))})}
|
|
460
|
+
`,{containedRoot:v.workspaceRuntimeRoot,exclusive:!0,requireAtomicPublication:!0}),await Xn(t,{schema:Hr,workflow:"native",change:n.name,format:"sdk",application:u?.identity.id??"native",runId:n.name}),{change:n.name,worktrees:G}}async function P$(e,t){let r=Gk(e,"transfer action");if(r==="export"){let n=Gk(e,"change name"),i=Zl(e,"--output"),o=Os(e,"--confirmed-stopped");if(Kk(e),!i)throw new $r("transfer export requires --output <directory>");let a=await I$({projectRoot:t,name:n,outputDir:i,confirmedStopped:o});return Yk("transfer export",a,`Exported Supervisor work to ${a.packageDir}. Keep this package private; it contains source files.
|
|
461
|
+
`)}if(r==="import"){let n=Zl(e,"--input");if(Kk(e),!n)throw new $r("transfer import requires --input <directory>");let i=await x$({projectRoot:t,inputDir:n});return Yk("transfer import",i,`Imported Supervisor ${i.change}. Reconcile any Action whose outcome is unknown before continuing.
|
|
462
|
+
`)}throw new $r(`Unknown transfer action: ${r}`)}import{Buffer as T$}from"node:buffer";var uY=new Set(["continuation","input","commandArgs","userCommunication","current","pendingAction","changedPaths","artifactRefs","artifacts"]);function dY(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(([m,h])=>o(m,h)||a(h));return n.set(u,d),d},s=(u,f,d,m)=>{if(o(d,u)||/(?:hash|revision|attempt|claim|token|blockers|workspace)$/iu.test(d))return u;if(m&&(typeof u=="string"&&u.length>=160||uY.has(d)&&u!==null&&typeof u=="object"&&!a(u))){let p=JSON.stringify(u);if(p.length>=160){let g=r.get(p);if(g!==void 0&&g.length+f.length+8<p.length){t[f]=g;return}return r.set(p,f),u}}return Array.isArray(u)?u.map((p,g)=>s(p,`${f}/${g}`,"",!1)):u!==null&&typeof u=="object"?Object.fromEntries(Object.entries(u).flatMap(([p,g])=>{let v=s(g,`${f}/${i(p)}`,p,!0);return v===void 0?[]:[[p,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 O$(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=dY(r),i=n.outputView;if(!i?.references||Object.keys(i.references).length===0)return e;let o=`${JSON.stringify(n)}
|
|
463
|
+
`;return T$.byteLength(o)<T$.byteLength(e)?o:e}zr();import Mm from"node:path";function $$(e,t){return[...e,...t&&!e.includes("--project-root")?["--project-root",t]:[],...e.includes("--json")?[]:["--json"]]}function ai(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function j$(e,t){if(e.error?.code==="usage"||e.command==="hook-guard")return e;let r=ai(e.data),n=ai(r.continuation);if(ai(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??Mm.resolve(t.projectRoot);o&&e.exitCode!==0&&!e.executionCwd&&(a=await E$(a,o,{readOnly:!0}).catch(()=>a));let s=w=>$$(w,a),c=s(["comet","native","doctor",...o?[o]:[]]),l=ai(r.state),u=ai(r.workspaceFinishResult),f=typeof u.message=="string"?u.message:e.error?.message??"",d=f.toLowerCase(),m=d.split(`
|
|
464
|
+
`),h=m.some(w=>{let A=w.indexOf("worktree");return A!==-1&&w.indexOf("locked",A+8+1)!==-1}),p=d.includes("index.lock")||d.includes("cannot lock ref")||h||m.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 ai(r.recovery).reason=="string"?ai(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:ai(l.builder_handoff).candidate_id??r.candidateId??null,shapeConfirmationHash:l.shape_confirmation_hash??r.shapeConfirmationHash??null}},v=ai(r.recovery).schema?r.recovery:ai(n.recovery).schema?n.recovery:void 0;if(p){let w=typeof u.targetRoot=="string"?u.targetRoot:a,A=[];try{/index\.lock/iu.test(f)?A.push(Mm.resolve(w,de(w,["rev-parse","--git-path","index.lock"]))):h&&A.push(Mm.join(Mm.resolve(w,de(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}wt();async function D$(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(Os(i,"--json"),Os(i,"--compact"),c&&!a)throw new $r("--compact requires --json");Os(i,"--verbose"),l=Zl(i,"--project-root");let h=[...i,...o];u=h[0]?.startsWith("--")?void 0:h[0];let p=async()=>{let g=await vO(l);return{executionCwd:g,...await t(h,g)}};d=wO(e,h)?await Tb(p):await p()}catch(h){f=h,d=kO(e,h)}d=await j$(d,{projectRoot:d.executionCwd??l??process.cwd(),name:u,error:f});let m=AO(d,a,s);return m.stdout&&process.stdout.write(O$(m.stdout,c&&a)),m.stderr&&process.stderr.write(m.stderr+(m.stderr.endsWith(`
|
|
465
|
+
`)?"":`
|
|
466
|
+
`)),m.exitCode}process.exitCode=await D$("transfer",P$);
|