@aviaratech/ai-delivery 0.3.31 → 0.3.32

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.
@@ -281,31 +281,31 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
281
281
  }
282
282
  }
283
283
  `,{owner:e.repo.owner,name:e.repo.repo,number:t}),i=P({repository:P({issue:P({number:j().int().positive().safe(),repository:n,state:I([`OPEN`,`CLOSED`]),stateReason:I([`COMPLETED`,`NOT_PLANNED`,`DUPLICATE`,`REOPENED`]).nullable(),duplicateOf:P({number:j().int().positive().safe(),repository:n}).nullable()})})}).parse(r).repository.issue;if(i.number!==t||i.repository.nameWithOwner.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Native closure readback returned a foreign issue identity.`);if(i.state===`OPEN`&&i.stateReason!==null&&i.stateReason!==`REOPENED`||i.state===`CLOSED`&&i.stateReason===`REOPENED`||i.duplicateOf!==null&&i.stateReason!==`DUPLICATE`)throw new D(`Native closure readback has contradictory state evidence.`);return{state:i.state===`OPEN`?`open`:`closed`,closeReason:i.stateReason===null||i.stateReason===`REOPENED`?null:i.stateReason.toLowerCase(),duplicateOf:i.duplicateOf===null?null:{number:i.duplicateOf.number,repository:i.duplicateOf.repository.nameWithOwner}}}async function Uv(e,t){if(e.clients.role!==`author`)throw new D(`Issue writes require the configured author role.`);if(t.closeReason!==void 0&&![`completed`,`not_planned`,`duplicate`].includes(t.closeReason)||(t.closeReason!==void 0||t.supersededBy!==void 0)&&t.state!==`closed`)throw new D(`Closure details require state closed and a supported close reason.`);if(t.supersededBy!==void 0&&(!Number.isSafeInteger(t.supersededBy)||t.supersededBy<=0||t.supersededBy===t.issueNumber))throw new D(`A superseding issue must be a different positive issue number.`);let{clients:n,config:r,repo:i}=e,a=await Gv(e,t.issueNumber),o=Mv(t,a);t={...t,title:o.issue.title,body:o.body,...o.issue.issueType===void 0?{}:{issueType:o.issue.issueType},...o.issue.points===void 0?{}:{points:o.issue.points},...o.conversion===void 0?{}:{preserveHistory:!0},...o.issue.draft?{park:!0}:{}};let s=t.labels===void 0?void 0:await jv(e,t.labels);if(t.issueType!==void 0&&!r.native.issueTypes.includes(t.issueType))throw new D(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!r.native.points.values.includes(String(t.points)))throw new D(`Unsupported configured Points value.`);if(t.priority!==void 0&&!r.native.priority.values.includes(t.priority))throw new D(`Unsupported configured Priority value.`);if(t.parentIssueNumber!==void 0||t.blockedBy!==void 0){let e=await D_({graphql:n.graphql,issueNumber:t.issueNumber,repo:i});await N_({blockers:e.blockers.map(e=>e.number),...e.parentNumber===null?{}:{parentIssueNumber:e.parentNumber},repo:i,rest:n.rest}),await N_({blockers:t.blockedBy??[],...t.parentIssueNumber===void 0||t.parentIssueNumber===null?{}:{parentIssueNumber:t.parentIssueNumber},repo:i,rest:n.rest})}let c=t.blockedBy!==void 0||t.blocks!==void 0?await V_(e,[...t.blockedBy===void 0?[]:[{dependent:t.issueNumber,blockers:t.blockedBy}],...(t.blocks??[]).map(e=>({dependent:e,blockers:[t.issueNumber]}))],t.overrideReason):void 0,l=t.closeReason??(t.supersededBy===void 0?void 0:`completed`),u;if(t.supersededBy!==void 0){let e=(await n.rest.issues.get({...i,issue_number:t.supersededBy})).data;if(e.number!==t.supersededBy||`pull_request`in e||!Number.isSafeInteger(e.id)||e.id<=0||new URL(e.html_url).pathname.toLowerCase()!==`/${i.owner}/${i.repo}/issues/${String(t.supersededBy)}`.toLowerCase())throw new D(`Superseding issue readback is not the requested repository issue.`);u=e.id}let d=e=>{if(e.state!==`closed`||e.closeReason!==l||l===`duplicate`&&t.supersededBy!==void 0&&(e.duplicateOf?.number!==t.supersededBy||e.duplicateOf.repository.toLowerCase()!==`${i.owner}/${i.repo}`.toLowerCase()))throw new D(`Native closure readback disagrees with the requested reason or superseding issue.`)};if(l!==void 0){let n=await Hv(e,t.issueNumber);if(n.state===`closed`)try{d(n)}catch{throw new D(`Issue is already closed with different closure evidence; reopen it explicitly first.`)}}let f,p;if(t.preserveHistory===!0&&(t.title!==void 0||t.body!==void 0)){let r=(await n.rest.issues.get({...i,issue_number:t.issueNumber})).data;if(r.number!==t.issueNumber||`pull_request`in r)throw new D(`History target is not the requested issue.`);let a={title:r.title,body:r.body??``};if(t.title!==void 0&&t.title!==a.title||t.body!==void 0&&t.body!==a.body){let n=Vv(a.title,a.body),r=lv({title:a.title,legacyBody:a.body,draft:!0},!1);if(r.failures.length)throw new uv(r.failures);if(n.length>65536)throw new D(`Complete issue history exceeds the supported comment body limit; issue was not rewritten.`);p=a,f=await Ov(e,{issueNumber:t.issueNumber,body:n})}}let m;if(l!==void 0&&(m=await Ov(e,{issueNumber:t.issueNumber,body:`Requested closure reason: ${l}.${t.supersededBy===void 0?``:`\nSuperseded by ${i.owner}/${i.repo}#${String(t.supersededBy)}.`}`})),p!==void 0){let e=(await n.rest.issues.get({...i,issue_number:t.issueNumber})).data;if(e.number!==t.issueNumber||`pull_request`in e||e.title!==p.title||(e.body??``)!==p.body)throw new D(`Issue content changed after history readback; retry against the current title and body.`)}await n.rest.issues.update({issue_number:t.issueNumber,owner:i.owner,repo:i.repo,...t.body===void 0?{}:{body:t.body},...t.issueType===void 0?{}:{type:t.issueType},...s===void 0?{}:{labels:s},...t.milestone===void 0?{}:{milestone:t.milestone},...t.state===void 0?{}:{state:t.state},...l===void 0?{}:{state_reason:l,headers:{"X-GitHub-Api-Version":vg}},...l!==`duplicate`||u===void 0?{}:{duplicate_issue_id:u},...t.title===void 0?{}:{title:t.title}});let h=l===void 0?void 0:await Hv(e,t.issueNumber);h!==void 0&&d(h),(t.points!==void 0||t.priority!==void 0)&&await Eg({issueNumber:t.issueNumber,metadata:{...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority}},org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:yg(r)}),t.parentIssueNumber!==void 0&&await M_({graphql:n.graphql,issueNumber:t.issueNumber,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&t.parentIssueNumber!==null&&await xg({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:yg(r)});try{t.blockedBy!==void 0&&await j_({...c===void 0?{}:{beforeAdd:c},blockers:t.blockedBy,graphql:n.graphql,issueNumber:t.issueNumber,repo:i,rest:n.rest});for(let e of new Set(t.blocks??[]))await k_({...c===void 0?{}:{beforeAdd:c},blockers:[t.issueNumber],graphql:n.graphql,issueNumber:e,repo:i,rest:n.rest})}catch(e){throw new D(`Issue #${t.issueNumber} content or metadata may have changed, but dependency tracking did not complete: ${e instanceof Error?e.message:String(e)}. Inspect native state and resume this existing issue.`)}let g=await Gv(e,t.issueNumber),_=g.state===`closed`||g.projectStatus===`Done`?`Done`:g.blockedBy.length>0?`Blocked`:t.park===!0||t.blockedBy!==void 0||g.projectStatus===null?`Todo`:g.projectStatus===`In Progress`||g.projectStatus===`Blocked`&&t.state===void 0?g.projectStatus:`Todo`,v=(await n.rest.issues.get({issue_number:t.issueNumber,...i})).data;await Fu({graphql:n.graphql,issueNodeId:v.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Nu(r),status:_});let y=await Gv(e,t.issueNumber);if(t.title!==void 0&&y.title!==t.title||t.body!==void 0&&y.body!==t.body||t.state!==void 0&&y.state!==t.state||t.points!==void 0&&y.points!==t.points||t.issueType!==void 0&&y.issueType!==t.issueType)throw new D(`Issue update readback disagrees with the requested content or state.`);return{...y,warnings:o.warnings,...o.conversion===void 0?{}:{conversion:o.conversion},...f===void 0?{}:{historyComment:f},...h===void 0||m===void 0?{}:{closure:{...h,supersededBy:t.supersededBy??null,comment:m}}}}async function Wv(e,t){return Uv(e,t)}async function Gv(e,t){let{clients:n,config:r,repo:i}=e,a=(await n.rest.issues.get({issue_number:t,owner:i.owner,repo:i.repo})).data;if(`pull_request`in a)throw new D(`Requested issue number is a pull request.`);let[o,s,c]=await Promise.all([Cg({issueNumber:t,owner:i.owner,repo:i.repo,rest:n.rest,settings:yg(r)}),D_({graphql:n.graphql,issueNumber:t,repo:i}),Au({graphql:n.graphql,issueNodeId:a.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Nu(r)})]);return{...e.configuration?{routing:e.configuration.routing}:{},blockedBy:s.blockers.filter(e=>e.state===`OPEN`).map(e=>e.number),body:a.body??``,issueNumber:t,issueType:a.type?.name??null,labels:(a.labels??[]).flatMap(e=>typeof e==`string`?[e]:e.name===void 0?[]:[e.name]),milestone:a.milestone?.number??null,parentIssueNumber:s.parentNumber,...o.points===void 0?{}:{points:o.points},...o.priority===void 0?{}:{priority:o.priority},projectStatus:c?.status??null,state:a.state,title:a.title,url:a.html_url,worktree:null}}async function Kv(e,t){if(`pull_request`in(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data)throw new D(`Requested issue number is a pull request.`);return(await e.clients.rest.paginate(e.clients.rest.issues.listSubIssues,{...e.repo,issue_number:t,per_page:100})).map(e=>e.number).sort((e,t)=>e-t)}async function qv(e,t){let n=await Gv(e,t),r=await O_({issueNumber:t,repo:e.repo,rest:e.clients.rest});return _v({blockedBy:n.blockedBy,body:n.body,...n.points===void 0?{}:{points:n.points},repoRoot:void 0,title:n.title,...n.issueType===null?{}:{issueType:n.issueType},trackingParent:r})}async function Jv(e,t){let n=[],r=new Set,i=null;for(let a=0;a<20;a++){let a=(await e.clients.graphql(`query DeliveryIssueBranches($owner:String!,$repo:String!,$issue:Int!,$cursor:String){repository(owner:$owner,name:$repo){issue(number:$issue){linkedBranches(first:100,after:$cursor){nodes{ref{name target{oid} repository{nameWithOwner}}} pageInfo{hasNextPage endCursor}}}}}`,{owner:e.repo.owner,repo:e.repo.repo,issue:t,cursor:i})).repository?.issue?.linkedBranches;if(!a||!Array.isArray(a.nodes)||typeof a.pageInfo?.hasNextPage!=`boolean`)throw new D(`Incomplete GitHub linked issue branch readback.`);for(let t of a.nodes){let r=t?.ref;if(!r||!r.name||!/^[a-f0-9]{40}$/u.test(r.target.oid)||!r.repository.nameWithOwner)throw new D(`Incomplete GitHub linked branch identity.`);r.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()&&n.push({name:r.name,sha:r.target.oid,repository:r.repository.nameWithOwner})}if(!a.pageInfo.hasNextPage)return n;let o=a.pageInfo.endCursor;if(!o||r.has(o))throw new D(`GitHub linked branch pagination did not advance.`);r.add(o),i=o}throw new D(`GitHub linked issue branches exceed the bounded readback window.`)}async function Yv(e,t,n){let r=(await Jv(e,t)).filter(e=>n===void 0||e.name===n);if(r.length!==1)throw new D(`Select exactly one GitHub-linked issue branch; no local worktree or receipt fallback is available.`);return r[0].name}async function Xv(e,t,n){let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(r.number!==t||`pull_request`in r||r.state!==`open`)throw new D(`Start requires the requested open GitHub issue.`);let i=await Jv(e,t),a=n??(i.length===1?i[0].name:`issue/${t}`);if(!/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u.test(a)||a.startsWith(`/`)||a.endsWith(`/`)||a.endsWith(`.lock`))throw new D(`Invalid issue branch name.`);let o=i.filter(e=>e.name===a);if(i.length>0&&o.length!==1)throw new D(`Select exactly one existing GitHub-linked issue branch before start.`);if(o.length>1)throw new D(`GitHub issue branch has conflicting linked matches.`);if(o.length===1)return{issueNumber:t,issueUrl:r.html_url,branch:a,headSha:o[0].sha,reused:!0};let s=(await e.clients.rest.repos.get({...e.repo})).data,c=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${s.default_branch}`})).data.object.sha;if(!/^[a-f0-9]{40}$/u.test(c)||!s.node_id)throw new D(`GitHub repository default branch identity is incomplete.`);await e.clients.graphql(`mutation DeliveryStartBranch($input:CreateLinkedBranchInput!){createLinkedBranch(input:$input){linkedBranch{ref{name target{oid}}}}}`,{input:{issueId:r.node_id,repositoryId:s.node_id,oid:c,name:a,clientMutationId:B({repository:e.config.repository,issueNumber:t,name:a,base:c})}});let l=(await Jv(e,t)).filter(e=>e.name===a);if(l.length!==1||l[0].sha!==c)throw new D(`Started GitHub branch/link readback disagrees; resume this issue without creating another.`);return{issueNumber:t,issueUrl:r.html_url,branch:a,headSha:c,reused:!1}}async function Zv(e,t){let n=await qv(e,t);if(!n.ready)throw new uv(n.failures);let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(r.number!==t||`pull_request`in r||r.state!==`open`||!r.node_id)throw new D(`Start requires the requested open GitHub issue before Project synchronization.`);return Fu({graphql:e.clients.graphql,issueNodeId:r.node_id,org:e.config.native.organization,...e.projectConfiguration===void 0?{}:{configuration:e.projectConfiguration},settings:Nu(e.config),status:`In Progress`})}function Qv(e){ty(e,448)}function $v(e,t){ry({directoryMode:511,mode:438,path:e,value:t})}function ey(e,t){ry({directoryMode:448,mode:384,path:e,value:t})}function ty(e,t){let n=[],r=e;for(;!i(r);){n.push(r);let e=C(r);if(e===r)break;r=e}for(let e of n.reverse()){try{l(e,{mode:t})}catch(n){if(n.code!==`EEXIST`)throw n;let r=c(e);if(!r.isDirectory()||r.isSymbolicLink()||t===448&&r.mode&63)throw Error(`Concurrent directory creation did not publish a safe directory.`)}ny(C(e))}}function ny(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function ry({directoryMode:e,mode:t,path:r,value:i}){let a=C(r);ty(a,e);let s=w(a,`.${String(process.pid)}.${he()}.tmp`),c,l,d;try{c=u(s,`wx`,t),n(c),c=void 0,ee(s,`${JSON.stringify(i,null,2)}\n`,`utf8`),l=u(s,`r`),o(l),n(l),l=void 0,g(s,r),d=u(a,`r`),o(d),n(d),d=void 0}catch(e){c!==void 0&&n(c),l!==void 0&&n(l),d!==void 0&&n(d);try{x(s)}catch{}throw e}}var iy=A().regex(/^sha256:[a-f0-9]{64}$/u),ay=2,oy=P({admissionId:iy,capability:P({cli:j().int().positive(),mcp:j().int().positive()}).strict(),cliPath:A().min(1),cliSha256:iy,configDigest:iy,mcpLauncherPath:A().min(1),mcpLauncherSha256:iy,packageDistSha256:iy,packageManifestSha256:iy,packageVersion:A().min(1),pluginManifestPath:A().min(1),pluginManifestSha256:iy,repository:A().min(1),schemaVersion:L(`ai-delivery.runtime-admission@2`),sourceArchiveSha256:iy,sourceCommit:A().regex(/^[a-f0-9]{40}$/u)}).strict().superRefine((e,t)=>{let{admissionId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Runtime admission identity is invalid.`})});function sy(e){return`sha256:${pe(`sha256`).update(d(e)).digest(`hex`)}`}function cy(e){let t=[],n=(e,r)=>{for(let i of p(e,{withFileTypes:!0}).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))){let a=w(e,i.name),o=r?`${r}/${i.name}`:i.name;if(i.isDirectory())n(a,o);else if(i.isFile())t.push({path:o,sha256:sy(a)});else throw new D(`Runtime distribution contains an unsupported link or file type.`)}};if(n(e,``),t.length===0)throw new D(`Runtime distribution is empty.`);return B(t)}function ly(e){let t=JSON.parse(d(e,`utf8`));if(typeof t!=`object`||!t||Array.isArray(t))throw new D(`Runtime package or plugin manifest is invalid.`);return t}async function uy(e){let t=fd(e.repoRoot),n=e.configuration??await qh(t,e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}),r=w(pd(t),`ai-delivery`,`runtime-admission.json`),i;try{i=oy.parse(JSON.parse(H(r).toString(`utf8`)))}catch{throw new D(`Missing or invalid private ai-delivery runtime admission; refresh the installed binding before lifecycle mutation.`)}return dy(i,n,e.runtimeEntryPath)}function dy(e,t,n){let r=n??process.argv[1];if(!r)throw new D(`Running ai-delivery entry path is unavailable.`);try{let n=h(r),i=h(e.mcpLauncherPath),a=h(e.pluginManifestPath),o=C(n),s=w(C(o),`package.json`),c=ly(s),l=ly(a),u=n!==e.cliPath&&`cliPath`||i!==e.mcpLauncherPath&&`mcpLauncherPath`||a!==e.pluginManifestPath&&`pluginManifestPath`||h(w(C(C(i)),`.claude-plugin`,`plugin.json`))!==a&&`launcherPluginManifestPath`||sy(n)!==e.cliSha256&&`cliSha256`||sy(i)!==e.mcpLauncherSha256&&`mcpLauncherSha256`||sy(a)!==e.pluginManifestSha256&&`pluginManifestSha256`||sy(s)!==e.packageManifestSha256&&`packageManifestSha256`||cy(o)!==e.packageDistSha256&&`packageDistSha256`||e.configDigest!==t.configDigest&&`configDigest`||e.repository!==t.config.repository&&`repository`||e.capability.cli!==ay&&`cliCapability`||e.capability.mcp!==ay&&`mcpCapability`||c.name!==`@aviaratech/ai-delivery`&&`packageName`||c.version!==e.packageVersion&&`packageVersion`||l.name!==`ai-delivery`&&`pluginName`||l.packageVersion!==e.packageVersion&&`pluginPackageVersion`||l.deliveryCapabilityVersion!==ay&&`pluginCapability`;if(u)throw new D(`Installed CLI/MCP source, capability or repository admission disagrees with the running delivery contract. Failed predicate: ${u}.`)}catch(e){throw e instanceof D?e:new D(`Installed CLI/MCP source or capability readback is unavailable.`)}return e}function fy(e){for(let t of[e.cliPath,e.mcpLauncherPath,e.pluginManifestPath])if(h(t)!==t)throw new D(`Installed runtime paths must be canonical regular files.`);let t=C(e.cliPath),n=w(C(t),`package.json`),r=ly(n).bin;if(typeof r!=`object`||!r||!(`ai-delivery`in r)||r[`ai-delivery`]!==`./dist/cli.js`)throw new D(`Installed package CLI entry is not the supported ai-delivery executable.`);let i={capability:{cli:ay,mcp:ay},cliPath:e.cliPath,cliSha256:sy(e.cliPath),configDigest:e.configuration.configDigest,mcpLauncherPath:e.mcpLauncherPath,mcpLauncherSha256:sy(e.mcpLauncherPath),packageDistSha256:cy(t),packageManifestSha256:sy(n),packageVersion:e.packageVersion,pluginManifestPath:e.pluginManifestPath,pluginManifestSha256:sy(e.pluginManifestPath),repository:e.configuration.config.repository,schemaVersion:`ai-delivery.runtime-admission@2`,sourceArchiveSha256:e.sourceArchiveSha256,sourceCommit:e.sourceCommit};return dy(oy.parse({...i,admissionId:B(i)}),e.configuration,e.cliPath)}var py=E(((e,t)=>{var n=Ne(`constants`),r=process.cwd,i=null,a=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return i||=r.call(process),i};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var o=process.chdir;process.chdir=function(e){i=null,o.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,o)}t.exports=s;function s(e){n.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),a===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,r,i){e.open(t,n.O_WRONLY|n.O_SYMLINK,r,function(t,n){if(t){i&&i(t);return}e.fchmod(n,r,function(t){e.close(n,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,r){var i=e.openSync(t,n.O_WRONLY|n.O_SYMLINK,r),a=!0,o;try{o=e.fchmodSync(i,r),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function r(e){n.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,r,i,a){e.open(t,n.O_SYMLINK,function(t,n){if(t){a&&a(t);return}e.futimes(n,r,i,function(t){e.close(n,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,r,i){var a=e.openSync(t,n.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,r,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function o(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!(e&&e.code!==`ENOSYS`&&(process.getuid&&process.getuid()===0||e.code!==`EINVAL`&&e.code!==`EPERM`))}}})),my=E(((e,t)=>{var n=Ne(`stream`).Stream;t.exports=r;function r(e){return{ReadStream:t,WriteStream:r};function t(r,i){if(!(this instanceof t))return new t(r,i);n.call(this);var a=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function r(t,i){if(!(this instanceof r))return new r(t,i);n.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),hy=E(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),gy=E(((e,t)=>{var n=Ne(`fs`),r=py(),i=my(),a=hy(),o=Ne(`util`),s,c;typeof Symbol==`function`&&typeof Symbol.for==`function`?(s=Symbol.for(`graceful-fs.queue`),c=Symbol.for(`graceful-fs.previous`)):(s=`___graceful-fs.queue`,c=`___graceful-fs.previous`);function l(){}function u(e,t){Object.defineProperty(e,s,{get:function(){return t}})}var d=l;o.debuglog?d=o.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(d=function(){var e=o.format.apply(o,arguments);e=`GFS4: `+e.split(/\n/).join(`
284
- GFS4: `),console.error(e)}),n[s]||(u(n,global[s]||[]),n.close=(function(e){function t(t,r){return e.call(n,t,function(e){e||h(),typeof r==`function`&&r.apply(this,arguments)})}return Object.defineProperty(t,c,{value:e}),t})(n.close),n.closeSync=(function(e){function t(t){e.apply(n,arguments),h()}return Object.defineProperty(t,c,{value:e}),t})(n.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){d(n[s]),Ne(`assert`).equal(n[s].length,0)})),global[s]||u(global,n[s]),t.exports=f(a(n)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!n.__patched&&(t.exports=f(n),n.__patched=!0);function f(e){r(e),e.gracefulify=f,e.createReadStream=ne,e.createWriteStream=re;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?p([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var a=e.writeFile;e.writeFile=o;function o(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,o){return a(e,t,n,function(a){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([i,[e,t,n,r],a,o||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var m=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=m.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=i(e);x=g.ReadStream,S=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=ee);var v=e.WriteStream;v&&(S.prototype=Object.create(v.prototype),S.prototype.open=te),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return S},set:function(e){S=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=S;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function ee(){var e=this;ae(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function S(e,t){return this instanceof S?(v.apply(this,arguments),this):S.apply(Object.create(S.prototype),arguments)}function te(){var e=this;ae(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ne(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var ie=e.open;e.open=ae;function ae(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return ie(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function p(e){d(`ENQUEUE`,e[0].name,e[1]),n[s].push(e),g()}var m;function h(){for(var e=Date.now(),t=0;t<n[s].length;++t)n[s][t].length>2&&(n[s][t][3]=e,n[s][t][4]=e);g()}function g(){if(clearTimeout(m),m=void 0,n[s].length!==0){var e=n[s].shift(),t=e[0],r=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)d(`RETRY`,t.name,r),t.apply(null,r);else if(Date.now()-a>=6e4){d(`TIMEOUT`,t.name,r);var c=r.pop();typeof c==`function`&&c.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(d(`RETRY`,t.name,r),t.apply(null,r.concat([a]))):n[s].push(e)}m===void 0&&(m=setTimeout(g,0))}}})),_y=E(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),vy=E((e=>{var t=_y();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),yy=E(((e,t)=>{t.exports=vy()})),by=E(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),xy=E(((e,t)=>{var n=global.process,r=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!r(n))t.exports=function(){return function(){}};else{var i=Ne(`assert`),a=by(),o=/^win/i.test(n.platform),s=Ne(`events`);typeof s!=`function`&&(s=s.EventEmitter);var c;n.__signal_exit_emitter__?c=n.__signal_exit_emitter__:(c=n.__signal_exit_emitter__=new s,c.count=0,c.emitted={}),c.infinite||(c.setMaxListeners(1/0),c.infinite=!0),t.exports=function(e,t){if(!r(global.process))return function(){};i.equal(typeof e,`function`,`a callback must be provided for exit handler`),f===!1&&p();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),c.on(n,e),function(){c.removeListener(n,e),c.listeners(`exit`).length===0&&c.listeners(`afterexit`).length===0&&l()}};var l=function(){f&&r(global.process)&&(f=!1,a.forEach(function(e){try{n.removeListener(e,d[e])}catch{}}),n.emit=g,n.reallyExit=m,--c.count)};t.exports.unload=l;var u=function(e,t,n){c.emitted[e]||(c.emitted[e]=!0,c.emit(e,t,n))},d={};a.forEach(function(e){d[e]=function(){r(global.process)&&n.listeners(e).length===c.count&&(l(),u(`exit`,null,e),u(`afterexit`,null,e),o&&e===`SIGHUP`&&(e=`SIGINT`),n.kill(n.pid,e))}}),t.exports.signals=function(){return a};var f=!1,p=function(){!f&&r(global.process)&&(f=!0,c.count+=1,a=a.filter(function(e){try{return n.on(e,d[e]),!0}catch{return!1}}),n.emit=_,n.reallyExit=h)};t.exports.load=p;var m=n.reallyExit,h=function(e){r(global.process)&&(n.exitCode=e||0,u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),m.call(n,n.exitCode))},g=n.emit,_=function(e,t){if(e===`exit`&&r(global.process)){t!==void 0&&(n.exitCode=t);var i=g.apply(this,arguments);return u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),i}return g.apply(this,arguments)}}})),Sy=E(((e,t)=>{var n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Cy=E(((e,t)=>{var n=Ne(`path`),r=gy(),i=yy(),a=xy(),o=Sy(),s={};function c(e,t){return t.lockfilePath||`${e}.lock`}function l(e,t,r){if(!t.realpath)return r(null,n.resolve(e));t.fs.realpath(e,r)}function u(e,t,n){let r=c(e,t);t.fs.mkdir(r,i=>{if(!i)return o.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?u(e,{...t,stale:0},n):n(r);if(!d(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));f(e,t,r=>{if(r)return n(r);u(e,{...t,stale:0},n)})})})}function d(e,t){return e.mtime.getTime()<Date.now()-t.stale}function f(e,t,n){t.fs.rmdir(c(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function p(e,t){let n=s[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return m(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let s=o.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,s,s,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));n.mtime=s,n.lastUpdate=Date.now(),n.updateDelay=null,p(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function m(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),s[e]===t&&delete s[e],t.options.onCompromised(n)}function h(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:r,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),l(e,t,(e,r)=>{if(e)return n(e);let a=i.operation(t.retries);a.attempt(()=>{u(r,t,(e,i,o)=>{if(a.retry(e))return;if(e)return n(a.mainError());let l=s[r]={lockfilePath:c(r,t),mtime:i,mtimePrecision:o,options:t,lastUpdate:Date.now()};p(r,t),n(null,e=>{if(l.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));g(r,{...t,realpath:!1},e)})})})})}function g(e,t,n){t={fs:r,realpath:!0,...t},l(e,t,(e,r)=>{if(e)return n(e);let i=s[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete s[r],f(r,t,n)})}function _(e,t,n){t={stale:1e4,realpath:!0,fs:r,...t},t.stale=Math.max(t.stale||0,2e3),l(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(c(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!d(r,t)))})}function v(){return s}a(()=>{for(let e in s){let t=s[e].options;try{t.fs.rmdirSync(c(e,t))}catch{}}}),t.exports.lock=h,t.exports.unlock=g,t.exports.check=_,t.exports.getLocks=v})),wy=E(((e,t)=>{var n=gy();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),Ty=je(E(((e,t)=>{var n=Cy(),{toPromise:r,toSync:i,toSyncOptions:a}=wy();async function o(e,t){return r(await r(n.lock)(e,t))}function s(e,t){return i(i(n.lock)(e,a(t)))}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1),Ey={realpath:!1,retries:0,stale:1e4},Dy=200;async function Oy(e,{onCompromised:t,onReleaseError:n,onTimeout:r,operation:i,projectRoot:a,timeout:o}){let s=a??process.cwd(),c=T(s,e),l=null,u=typeof o==`number`&&o>0?o:null,d=u===null?null:Math.ceil(u/Dy),f=0,p=u===null?null:Date.now()+u,m=!1;try{for(;;){if(d!==null&&f>=d)throw Error(`Lock acquisition timeout after ${u===null?`unknown`:String(u)}ms on ${c}. Another process may be holding the lock.`);f+=1,b_(`Acquiring lock on ${c}... (attempt ${d===null?String(f):`${String(f)}/${String(d)}`})`);try{l=await Ty.lock(c,{...Ey,...t===void 0?{}:{onCompromised:t}}),b_(`Lock acquired on ${c}`);break}catch(e){if(!Ay(e))throw e;m||=(S_(`Unable to acquire lock on ${c} - another agent is modifying it. Retrying...`),!0),p!==null&&u!==null&&Date.now()>=p&&(r?.(),p=Date.now()+u),await ky(Dy)}}return await i()}finally{if(l!==null)try{await l(),b_(`Lock released on ${c}`)}catch(e){n?.(e),b_(`Failed to release lock on ${c}: ${e instanceof Error?e.message:String(e)}`)}}}function ky(e){return new Promise(t=>setTimeout(t,e))}function Ay(e){return typeof e!=`object`||!e?!1:e.code===`ELOCKED`}var jy=F({bounds:F({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe().optional(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:N(A().min(1)).min(1).optional()}),maxSampledAggregateRssBytes:j().int().nonnegative().safe().nullable(),maxSampledNewOutputBytes:j().int().nonnegative().safe().nullable(),minSampledFreeDiskBytes:j().int().nonnegative().safe().nullable(),observation:L(`sampled`),outputBaselineId:A().regex(/^sha256:[a-f0-9]{64}$/u).optional(),processCoverage:L(`observed-processes-only`),sampleCount:j().int().nonnegative().safe()}).superRefine((e,t)=>{(e.maxSampledAggregateRssBytes!==null&&e.maxSampledAggregateRssBytes>e.bounds.maxAggregateRssBytes||e.maxSampledNewOutputBytes!==null&&e.bounds.maxNewOutputBytes!==void 0&&e.maxSampledNewOutputBytes>e.bounds.maxNewOutputBytes||e.minSampledFreeDiskBytes!==null&&e.minSampledFreeDiskBytes<e.bounds.minFreeDiskBytes||e.sampleCount>0&&(e.maxSampledAggregateRssBytes===null||e.minSampledFreeDiskBytes===null)||e.bounds.maxNewOutputBytes!==void 0&&e.sampleCount>0&&e.maxSampledNewOutputBytes===null||e.bounds.maxNewOutputBytes!==void 0!=(e.outputBaselineId!==void 0))&&t.addIssue({code:`custom`,message:`Resource samples do not satisfy their declared bounds.`})});function My(e){let t=[[`maxAggregateRssBytes`,e.maxAggregateRssBytes],[`minFreeDiskBytes`,e.minFreeDiskBytes]];e.maxNewOutputBytes!==void 0&&t.push([`maxNewOutputBytes`,e.maxNewOutputBytes]);for(let[e,n]of t)if(!Number.isSafeInteger(n)||n<=0)throw new D(`Invalid ${e} resource bound.`);if(e.maxNewOutputBytes===void 0!=(e.outputRoots===void 0))throw new D(`Filesystem output limit and output roots must be supplied together.`);if(e.outputRoots!==void 0&&(e.outputRoots.length===0||e.outputRoots.some(e=>!e)))throw new D(`Filesystem output roots must be nonempty paths.`);if(process.platform===`win32`)throw new D(`Resource observation requires POSIX process support.`)}var Ny=`AI_DELIVERY_OUTPUT_OBSERVATION_GATE`,Py=F({pid:j().int().positive(),identity:A().min(1)}),Fy=F({directory:A().min(1),id:fl(),owner:Py}),Iy=F({gateId:fl(),id:fl(),kind:I([`scan`,`fixture`]),owner:Py});function Ly(e=nb()){let t=e.get(process.pid);if(!t)throw new D(`Filesystem observation gate owner is unavailable.`);return{pid:t.pid,identity:t.identity}}function Ry(e){let t=c(e);if(!t.isDirectory()||t.mode&63||h(e)!==e)throw new D(`Filesystem observation gate directory is invalid.`)}function zy(e){try{let t=Fy.parse(JSON.parse(e));return Vy(t),t}catch(e){throw new D(`Filesystem observation gate capability is invalid or stale: `+(e instanceof Error?e.message:String(e)))}}function By(e,t=nb()){let n=t.get(e.pid);return n?.identity===e.identity&&!n.status.startsWith(`Z`)}function Vy(e,t=!1){Ry(e.directory);let n=Fy.parse(JSON.parse(H(w(e.directory,`gate.json`)).toString(`utf8`))),r=nb(),i=r.get(process.pid),a=new Set;for(;i&&i.pid!==e.owner.pid&&!a.has(i.pid);)a.add(i.pid),i=r.get(i.ppid);if(B(n)!==B(e)||(t?By(e.owner,r):!By(e.owner,r)||i?.identity!==e.owner.identity))throw new D(`Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.`);return r}function Hy(e,t){let n=Iy.parse(JSON.parse(H(t).toString(`utf8`)));if(n.gateId!==e.id)throw new D(`Filesystem observation gate claim belongs to another run.`);return n}function Uy(e,t){let n=w(e.directory,`requests`);Ry(n);let r=p(n);if(r.length>1024||r.some(e=>!/^[a-f0-9-]{36}\.json$/u.test(e)))throw new D(`Filesystem observation gate scan requests are invalid.`);let i=[],a=t??nb();for(let t of r){let r;try{r=Hy(e,w(n,t))}catch(e){if(e.code===`ENOENT`)continue;throw e}if(r.kind!==`scan`||t!==r.id+`.json`||!By(r.owner,a))throw new D(`Filesystem observation gate scan request was abandoned.`);i.push(t)}return i}function Wy(e,t,n){if(B(Hy(e,t))!==B(n))throw new D(`Filesystem observation gate claim changed before release.`);x(t)}async function Gy(e,t,n,r){if(!e)return n();let a=Vy(e),o={gateId:e.id,id:he(),kind:t,owner:Ly(a)},s=t===`scan`?w(e.directory,`requests`,o.id+`.json`):void 0,u=w(e.directory,`held`),d=w(u,`owner.json`);if(s){let t=w(e.directory,o.id+`.pending`);ey(t,o),g(t,s)}let f,m,h,_=()=>{if(!f)return;let t=c(u);if(!t.isDirectory()||t.dev!==f.dev||t.ino!==f.ino)throw new D(`Filesystem observation gate lock changed before release.`);if(p(u).join(`,`)!==`owner.json`)throw new D(`Filesystem observation gate lock has unrelated metadata.`);Wy(e,d,o),v(u),f=void 0};try{for(;;){if(r?.aborted)throw new D(`Filesystem observation gate wait cancelled.`);let a=Uy(e,Vy(e));if(t===`scan`||a.length===0){let r=!1;try{l(u,{mode:448}),r=!0}catch(e){if(e.code!==`EEXIST`)throw e}if(r){let r=c(u);if(f={dev:r.dev,ino:r.ino},ey(d,o),t===`scan`||Uy(e).length===0)return await n();_()}}if(i(u))try{Ry(u);let n=Hy(e,d);if(m=void 0,!By(n.owner))throw new D(`Filesystem observation gate fixture or scanner was abandoned.`);if(t===`scan`&&n.kind===`fixture`){if(h?.claimId!==n.id&&(h={claimId:n.id,since:Date.now()}),Date.now()-h.since>5e3)throw new D(`Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled.`)}else h=void 0}catch(e){if(e.code!==`ENOENT`)throw e;if(m??=Date.now(),Date.now()-m>2e3)throw new D(`Filesystem observation gate owner publication is incomplete.`)}await new Promise(e=>setTimeout(e,100))}}finally{try{_()}finally{s&&Wy(e,s,o)}}}function Ky(e,t=!1){Vy(e,t);let n=w(e.directory,`requests`),r=w(e.directory,`held`);if(p(e.directory).some(e=>![`gate.json`,`requests`,`held`].includes(e)))throw new D(`Filesystem observation gate has unrelated or incomplete metadata.`);if(i(r)){if(Ry(r),p(r).join(`,`)!==`owner.json`)throw new D(`Filesystem observation gate lock has unrelated metadata.`);let t=Hy(e,w(r,`owner.json`));if(By(t.owner))throw new D(`Filesystem observation gate still has a live holder.`);Wy(e,w(r,`owner.json`),t),v(r)}for(let t of p(n)){if(!/^[a-f0-9-]{36}\.json$/u.test(t))throw new D(`Filesystem observation gate has unrelated metadata.`);let r=w(n,t),i=Hy(e,r);if(i.kind!==`scan`||t!==i.id+`.json`)throw new D(`Filesystem observation gate has unrelated scan metadata.`);if(By(i.owner))throw new D(`Filesystem observation gate still has a live scan request.`);Wy(e,r,i)}if(v(n),B(JSON.parse(H(w(e.directory,`gate.json`)).toString(`utf8`)))!==B(e))throw new D(`Filesystem observation gate changed before retirement.`);x(w(e.directory,`gate.json`)),v(e.directory)}function qy(e,t){try{Ky(e)}catch(e){throw e instanceof tb&&(e.message+=` Output-gate retirement: wrappedOperation=${t?`completed`:`failed`}.`),e}}async function Jy(e,t,n){let r=process.env[Ny];if(r!==void 0)return n(zy(r));if(!t)return n(void 0);let i=he(),a=w(pd(e),`ai-delivery`,`output-observation`,mb(e).slice(7));Qv(a);for(let e of p(a)){fl().parse(e);let t=w(a,e);Ry(t);let n=Fy.parse(JSON.parse(H(w(t,`gate.json`)).toString(`utf8`)));if(n.id!==e||n.directory!==t||By(n.owner))throw new D(`Prior filesystem observation gate is live or has conflicting ownership.`);Ky(n,!0)}let o=w(a,i);Qv(w(o,`requests`));let s={directory:o,id:i,owner:Ly()};ey(w(o,`gate.json`),s);let c=!1;try{let e=await n(s);return c=!0,e}finally{qy(s,c)}}var Yy=class extends D{cause;code;constructor(e,t,n){let r=n.code;super(`${e} Path ${JSON.stringify(t)} (${r??`unknown errno`}): ${n instanceof Error?n.message:String(n)}`),this.code=r,this.cause=n}};function Xy(e,t,n=!1,r){let a=new Map,o=new Map,s=i=>{let l;try{l=c(i)}catch(e){if(e.code===`ENOENT`)return;throw new Yy(`Filesystem output lstat failed.`,i,e)}if(l.isSymbolicLink()){let a;try{a=m(i)}catch(e){throw new Yy(`Filesystem output readlink failed.`,i,e)}let s=B({device:l.dev,inode:l.ino,changed:l.ctimeMs,modified:l.mtimeMs,link:a}),u,d=!1;try{u=h(i)}catch(e){let o=new Yy(`Filesystem output observation encountered a broken or cyclic symbolic link.`,i,e),l=t.get(i);if(l!==void 0&&l.identity!==s)throw new D(`Filesystem output alias identity changed. Path ${JSON.stringify(i)}.`);if(!n||o.code!==`ENOENT`||l?.identity!==s)throw o;let f=T(C(i),a),p=f,g=new Set([i]);for(;;)try{u=w(h(p),f.slice(p.length));break}catch(e){if(e.code!==`ENOENT`||C(p)===p)throw new Yy(`Filesystem output ancestor resolution failed.`,p,e);let n;try{n=c(p)}catch(e){if(e.code!==`ENOENT`)throw new Yy(`Filesystem output ancestor lstat failed.`,p,e)}if(n?.isSymbolicLink()){let e,r;try{e=m(p),r=c(p)}catch(e){throw new Yy(`Filesystem output ancestor alias read failed.`,p,e)}let i=B({device:n.dev,inode:n.ino,changed:n.ctimeMs,modified:n.mtimeMs,link:e}),a=t.get(p);if(a===void 0)throw o;if(g.has(p)||a.identity!==i||!r.isSymbolicLink()||r.dev!==n.dev||r.ino!==n.ino||r.ctimeMs!==n.ctimeMs||r.mtimeMs!==n.mtimeMs)throw new D(`Filesystem output ancestor alias identity changed. Path ${JSON.stringify(p)}.`);g.add(p),f=w(T(C(p),e),f.slice(p.length)),p=f;continue}p=C(p)}if(u!==l.target)throw new D(`Filesystem output alias target identity changed. Path ${JSON.stringify(i)}.`);d=!0,r?.(o.message)}let f=t.get(i);if(f?.missing&&(f.identity!==s||f.target!==u))throw new D(`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(i)}.`);if(!e.some(e=>u===e||u.startsWith(`${e}${ce}`)))throw new D(`Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(i)} resolves to ${JSON.stringify(u)}.`);let p;try{p=c(i)}catch(e){if(n&&e.code===`ENOENT`&&f?.identity===s)return;throw new Yy(`Filesystem output alias identity readback failed.`,i,e)}if(!p.isSymbolicLink()||p.dev!==l.dev||p.ino!==l.ino||p.ctimeMs!==l.ctimeMs||p.mtimeMs!==l.mtimeMs)throw new D(`Filesystem output alias identity changed during observation. Path ${JSON.stringify(i)}.`);o.set(i,{identity:s,target:u,missing:d});return}if(l.isDirectory()){let e;try{e=p(i)}catch(e){if(e.code===`ENOENT`)return;throw new Yy(`Filesystem output readdir failed.`,i,e)}for(let t of e)s(w(i,t));return}if(!l.isFile()&&!l.isSocket()||!Number.isSafeInteger(l.size))throw new D(`Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(i)}.`);if(a.set(i,l.isSocket()?0:l.size),a.size>1e6)throw new D(`Filesystem output observation exceeded its file limit.`)};for(let t of e){if(i(t)&&h(t)!==t)throw new D(`Filesystem output roots must not be symbolic links.`);s(t)}t.clear();for(let[e,n]of o)t.set(e,n);return a}async function Zy(e,t,n=!1,r){let i,a,o,s,c=()=>{if(s!==void 0&&Date.now()-s>=1e3)throw new D(`Filesystem output observation remained unavailable for 1 second. First observation: ${a.message} Last observation: ${o.message}`)};for(;;){if(t?.aborted)throw new D(`Filesystem output observation cancelled.`);c();try{i=await Gy(e.gate,`scan`,()=>Xy(e.roots,e.links,n,r),t),c();break}catch(e){if(!n||!(e instanceof Yy)||e.code!==`ENOENT`)throw e;o=e,a===void 0&&(s=Date.now(),a=e,r?.(e.message)),c(),await new Promise(e=>setTimeout(e,25))}}let l=0;for(let[t,n]of i)if(l+=Math.max(0,n-(e.files.get(t)??0)),!Number.isSafeInteger(l))throw new D(`Filesystem output observation overflowed.`);return l}function Qy(e){let t=e;for(;;)try{let e=b(t,{bigint:!0});return e.bavail*e.bsize}catch(e){if(e.code!==`ENOENT`||C(t)===t)throw e;t=C(t)}}function $y(e,t){let n=(t===void 0?[e]:[e,...t.roots]).reduce((e,t)=>{let n=Qy(t);return n<e?n:e},BigInt(2**53-1));if(n>BigInt(2**53-1))throw new D(`Free disk observation overflowed.`);return Number(n)}function eb(e,t,n){if($y(e,n)<t.minFreeDiskBytes)throw new D(`Free disk fell below limit ${t.minFreeDiskBytes}.`)}var tb=class extends D{};function nb(){let e=i(`/usr/bin/ps`)?`/usr/bin/ps`:`/bin/ps`,t=re(e,[`-A`,`-o`,`pid=,ppid=,pgid=,rss=,stat=,lstart=`],{encoding:`utf8`,env:{...process.env,LC_ALL:`C`},maxBuffer:4194304,timeout:1e3});if(t.status!==0||t.error||t.signal||!t.stdout.endsWith(`
284
+ GFS4: `),console.error(e)}),n[s]||(u(n,global[s]||[]),n.close=(function(e){function t(t,r){return e.call(n,t,function(e){e||h(),typeof r==`function`&&r.apply(this,arguments)})}return Object.defineProperty(t,c,{value:e}),t})(n.close),n.closeSync=(function(e){function t(t){e.apply(n,arguments),h()}return Object.defineProperty(t,c,{value:e}),t})(n.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){d(n[s]),Ne(`assert`).equal(n[s].length,0)})),global[s]||u(global,n[s]),t.exports=f(a(n)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!n.__patched&&(t.exports=f(n),n.__patched=!0);function f(e){r(e),e.gracefulify=f,e.createReadStream=ne,e.createWriteStream=re;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?p([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var a=e.writeFile;e.writeFile=o;function o(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,o){return a(e,t,n,function(a){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([i,[e,t,n,r],a,o||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var m=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=m.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=i(e);x=g.ReadStream,S=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=ee);var v=e.WriteStream;v&&(S.prototype=Object.create(v.prototype),S.prototype.open=te),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return S},set:function(e){S=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=S;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function ee(){var e=this;ae(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function S(e,t){return this instanceof S?(v.apply(this,arguments),this):S.apply(Object.create(S.prototype),arguments)}function te(){var e=this;ae(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ne(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var ie=e.open;e.open=ae;function ae(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return ie(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function p(e){d(`ENQUEUE`,e[0].name,e[1]),n[s].push(e),g()}var m;function h(){for(var e=Date.now(),t=0;t<n[s].length;++t)n[s][t].length>2&&(n[s][t][3]=e,n[s][t][4]=e);g()}function g(){if(clearTimeout(m),m=void 0,n[s].length!==0){var e=n[s].shift(),t=e[0],r=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)d(`RETRY`,t.name,r),t.apply(null,r);else if(Date.now()-a>=6e4){d(`TIMEOUT`,t.name,r);var c=r.pop();typeof c==`function`&&c.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(d(`RETRY`,t.name,r),t.apply(null,r.concat([a]))):n[s].push(e)}m===void 0&&(m=setTimeout(g,0))}}})),_y=E(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),vy=E((e=>{var t=_y();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),yy=E(((e,t)=>{t.exports=vy()})),by=E(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),xy=E(((e,t)=>{var n=global.process,r=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!r(n))t.exports=function(){return function(){}};else{var i=Ne(`assert`),a=by(),o=/^win/i.test(n.platform),s=Ne(`events`);typeof s!=`function`&&(s=s.EventEmitter);var c;n.__signal_exit_emitter__?c=n.__signal_exit_emitter__:(c=n.__signal_exit_emitter__=new s,c.count=0,c.emitted={}),c.infinite||(c.setMaxListeners(1/0),c.infinite=!0),t.exports=function(e,t){if(!r(global.process))return function(){};i.equal(typeof e,`function`,`a callback must be provided for exit handler`),f===!1&&p();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),c.on(n,e),function(){c.removeListener(n,e),c.listeners(`exit`).length===0&&c.listeners(`afterexit`).length===0&&l()}};var l=function(){f&&r(global.process)&&(f=!1,a.forEach(function(e){try{n.removeListener(e,d[e])}catch{}}),n.emit=g,n.reallyExit=m,--c.count)};t.exports.unload=l;var u=function(e,t,n){c.emitted[e]||(c.emitted[e]=!0,c.emit(e,t,n))},d={};a.forEach(function(e){d[e]=function(){r(global.process)&&n.listeners(e).length===c.count&&(l(),u(`exit`,null,e),u(`afterexit`,null,e),o&&e===`SIGHUP`&&(e=`SIGINT`),n.kill(n.pid,e))}}),t.exports.signals=function(){return a};var f=!1,p=function(){!f&&r(global.process)&&(f=!0,c.count+=1,a=a.filter(function(e){try{return n.on(e,d[e]),!0}catch{return!1}}),n.emit=_,n.reallyExit=h)};t.exports.load=p;var m=n.reallyExit,h=function(e){r(global.process)&&(n.exitCode=e||0,u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),m.call(n,n.exitCode))},g=n.emit,_=function(e,t){if(e===`exit`&&r(global.process)){t!==void 0&&(n.exitCode=t);var i=g.apply(this,arguments);return u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),i}return g.apply(this,arguments)}}})),Sy=E(((e,t)=>{var n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Cy=E(((e,t)=>{var n=Ne(`path`),r=gy(),i=yy(),a=xy(),o=Sy(),s={};function c(e,t){return t.lockfilePath||`${e}.lock`}function l(e,t,r){if(!t.realpath)return r(null,n.resolve(e));t.fs.realpath(e,r)}function u(e,t,n){let r=c(e,t);t.fs.mkdir(r,i=>{if(!i)return o.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?u(e,{...t,stale:0},n):n(r);if(!d(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));f(e,t,r=>{if(r)return n(r);u(e,{...t,stale:0},n)})})})}function d(e,t){return e.mtime.getTime()<Date.now()-t.stale}function f(e,t,n){t.fs.rmdir(c(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function p(e,t){let n=s[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return m(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let s=o.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,s,s,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));n.mtime=s,n.lastUpdate=Date.now(),n.updateDelay=null,p(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function m(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),s[e]===t&&delete s[e],t.options.onCompromised(n)}function h(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:r,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),l(e,t,(e,r)=>{if(e)return n(e);let a=i.operation(t.retries);a.attempt(()=>{u(r,t,(e,i,o)=>{if(a.retry(e))return;if(e)return n(a.mainError());let l=s[r]={lockfilePath:c(r,t),mtime:i,mtimePrecision:o,options:t,lastUpdate:Date.now()};p(r,t),n(null,e=>{if(l.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));g(r,{...t,realpath:!1},e)})})})})}function g(e,t,n){t={fs:r,realpath:!0,...t},l(e,t,(e,r)=>{if(e)return n(e);let i=s[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete s[r],f(r,t,n)})}function _(e,t,n){t={stale:1e4,realpath:!0,fs:r,...t},t.stale=Math.max(t.stale||0,2e3),l(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(c(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!d(r,t)))})}function v(){return s}a(()=>{for(let e in s){let t=s[e].options;try{t.fs.rmdirSync(c(e,t))}catch{}}}),t.exports.lock=h,t.exports.unlock=g,t.exports.check=_,t.exports.getLocks=v})),wy=E(((e,t)=>{var n=gy();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),Ty=je(E(((e,t)=>{var n=Cy(),{toPromise:r,toSync:i,toSyncOptions:a}=wy();async function o(e,t){return r(await r(n.lock)(e,t))}function s(e,t){return i(i(n.lock)(e,a(t)))}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1),Ey={realpath:!1,retries:0,stale:1e4},Dy=200;async function Oy(e,{onCompromised:t,onReleaseError:n,onTimeout:r,operation:i,projectRoot:a,timeout:o}){let s=a??process.cwd(),c=T(s,e),l=null,u=typeof o==`number`&&o>0?o:null,d=u===null?null:Math.ceil(u/Dy),f=0,p=u===null?null:Date.now()+u,m=!1;try{for(;;){if(d!==null&&f>=d)throw Error(`Lock acquisition timeout after ${u===null?`unknown`:String(u)}ms on ${c}. Another process may be holding the lock.`);f+=1,b_(`Acquiring lock on ${c}... (attempt ${d===null?String(f):`${String(f)}/${String(d)}`})`);try{l=await Ty.lock(c,{...Ey,...t===void 0?{}:{onCompromised:t}}),b_(`Lock acquired on ${c}`);break}catch(e){if(!Ay(e))throw e;m||=(S_(`Unable to acquire lock on ${c} - another agent is modifying it. Retrying...`),!0),p!==null&&u!==null&&Date.now()>=p&&(r?.(),p=Date.now()+u),await ky(Dy)}}return await i()}finally{if(l!==null)try{await l(),b_(`Lock released on ${c}`)}catch(e){n?.(e),b_(`Failed to release lock on ${c}: ${e instanceof Error?e.message:String(e)}`)}}}function ky(e){return new Promise(t=>setTimeout(t,e))}function Ay(e){return typeof e!=`object`||!e?!1:e.code===`ELOCKED`}var jy=F({bounds:F({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe().optional(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:N(A().min(1)).min(1).optional()}),maxSampledAggregateRssBytes:j().int().nonnegative().safe().nullable(),maxSampledNewOutputBytes:j().int().nonnegative().safe().nullable(),minSampledFreeDiskBytes:j().int().nonnegative().safe().nullable(),observation:L(`sampled`),outputBaselineId:A().regex(/^sha256:[a-f0-9]{64}$/u).optional(),processCoverage:L(`observed-processes-only`),sampleCount:j().int().nonnegative().safe()}).superRefine((e,t)=>{(e.maxSampledAggregateRssBytes!==null&&e.maxSampledAggregateRssBytes>e.bounds.maxAggregateRssBytes||e.maxSampledNewOutputBytes!==null&&e.bounds.maxNewOutputBytes!==void 0&&e.maxSampledNewOutputBytes>e.bounds.maxNewOutputBytes||e.minSampledFreeDiskBytes!==null&&e.minSampledFreeDiskBytes<e.bounds.minFreeDiskBytes||e.sampleCount>0&&(e.maxSampledAggregateRssBytes===null||e.minSampledFreeDiskBytes===null)||e.bounds.maxNewOutputBytes!==void 0&&e.sampleCount>0&&e.maxSampledNewOutputBytes===null||e.bounds.maxNewOutputBytes!==void 0!=(e.outputBaselineId!==void 0))&&t.addIssue({code:`custom`,message:`Resource samples do not satisfy their declared bounds.`})});function My(e){let t=[[`maxAggregateRssBytes`,e.maxAggregateRssBytes],[`minFreeDiskBytes`,e.minFreeDiskBytes]];e.maxNewOutputBytes!==void 0&&t.push([`maxNewOutputBytes`,e.maxNewOutputBytes]);for(let[e,n]of t)if(!Number.isSafeInteger(n)||n<=0)throw new D(`Invalid ${e} resource bound.`);if(e.maxNewOutputBytes===void 0!=(e.outputRoots===void 0))throw new D(`Filesystem output limit and output roots must be supplied together.`);if(e.outputRoots!==void 0&&(e.outputRoots.length===0||e.outputRoots.some(e=>!e)))throw new D(`Filesystem output roots must be nonempty paths.`);if(process.platform===`win32`)throw new D(`Resource observation requires POSIX process support.`)}var Ny=`AI_DELIVERY_OUTPUT_OBSERVATION_GATE`,Py=F({pid:j().int().positive(),identity:A().min(1)}),Fy=F({directory:A().min(1),id:fl(),owner:Py}),Iy=F({gateId:fl(),id:fl(),kind:I([`scan`,`fixture`]),owner:Py});function Ly(e=rb()){let t=e.get(process.pid);if(!t)throw new D(`Filesystem observation gate owner is unavailable.`);return{pid:t.pid,identity:t.identity}}function Ry(e){let t=c(e);if(!t.isDirectory()||t.mode&63||h(e)!==e)throw new D(`Filesystem observation gate directory is invalid.`)}function zy(e){try{let t=Fy.parse(JSON.parse(e));return Vy(t),t}catch(e){throw new D(`Filesystem observation gate capability is invalid or stale: `+(e instanceof Error?e.message:String(e)))}}function By(e,t=rb()){let n=t.get(e.pid);return n?.identity===e.identity&&!n.status.startsWith(`Z`)}function Vy(e,t=!1){Ry(e.directory);let n=Fy.parse(JSON.parse(H(w(e.directory,`gate.json`)).toString(`utf8`))),r=rb(),i=r.get(process.pid),a=new Set;for(;i&&i.pid!==e.owner.pid&&!a.has(i.pid);)a.add(i.pid),i=r.get(i.ppid);if(B(n)!==B(e)||(t?By(e.owner,r):!By(e.owner,r)||i?.identity!==e.owner.identity))throw new D(`Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.`);return r}function Hy(e,t){let n=Iy.parse(JSON.parse(H(t).toString(`utf8`)));if(n.gateId!==e.id)throw new D(`Filesystem observation gate claim belongs to another run.`);return n}function Uy(e,t){let n=w(e.directory,`requests`);Ry(n);let r=p(n);if(r.length>1024||r.some(e=>!/^[a-f0-9-]{36}\.json$/u.test(e)))throw new D(`Filesystem observation gate scan requests are invalid.`);let i=[],a=t??rb();for(let t of r){let r;try{r=Hy(e,w(n,t))}catch(e){if(e.code===`ENOENT`)continue;throw e}if(r.kind!==`scan`||t!==r.id+`.json`||!By(r.owner,a))throw new D(`Filesystem observation gate scan request was abandoned.`);i.push(t)}return i}function Wy(e,t,n){if(B(Hy(e,t))!==B(n))throw new D(`Filesystem observation gate claim changed before release.`);x(t)}async function Gy(e,t,n,r){if(!e)return n();let a=Vy(e),o={gateId:e.id,id:he(),kind:t,owner:Ly(a)},s=t===`scan`?w(e.directory,`requests`,o.id+`.json`):void 0,u=w(e.directory,`held`),d=w(u,`owner.json`);if(s){let t=w(e.directory,o.id+`.pending`);ey(t,o),g(t,s)}let f,m,h,_=()=>{if(!f)return;let t=c(u);if(!t.isDirectory()||t.dev!==f.dev||t.ino!==f.ino)throw new D(`Filesystem observation gate lock changed before release.`);if(p(u).join(`,`)!==`owner.json`)throw new D(`Filesystem observation gate lock has unrelated metadata.`);Wy(e,d,o),v(u),f=void 0};try{for(;;){if(r?.aborted)throw new D(`Filesystem observation gate wait cancelled.`);let a=Uy(e,Vy(e));if(t===`scan`||a.length===0){let r=!1;try{l(u,{mode:448}),r=!0}catch(e){if(e.code!==`EEXIST`)throw e}if(r){let r=c(u);if(f={dev:r.dev,ino:r.ino},ey(d,o),t===`scan`||Uy(e).length===0)return await n();_()}}if(i(u))try{Ry(u);let n=Hy(e,d);if(m=void 0,!By(n.owner))throw new D(`Filesystem observation gate fixture or scanner was abandoned.`);if(t===`scan`&&n.kind===`fixture`){if(h?.claimId!==n.id&&(h={claimId:n.id,since:Date.now()}),Date.now()-h.since>5e3)throw new D(`Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled.`)}else h=void 0}catch(e){if(e.code!==`ENOENT`)throw e;if(m??=Date.now(),Date.now()-m>2e3)throw new D(`Filesystem observation gate owner publication is incomplete.`)}await new Promise(e=>setTimeout(e,100))}}finally{try{_()}finally{s&&Wy(e,s,o)}}}function Ky(e,t=!1){Vy(e,t);let n=w(e.directory,`requests`),r=w(e.directory,`held`);if(p(e.directory).some(e=>![`gate.json`,`requests`,`held`].includes(e)))throw new D(`Filesystem observation gate has unrelated or incomplete metadata.`);if(i(r)){if(Ry(r),p(r).join(`,`)!==`owner.json`)throw new D(`Filesystem observation gate lock has unrelated metadata.`);let t=Hy(e,w(r,`owner.json`));if(By(t.owner))throw new D(`Filesystem observation gate still has a live holder.`);Wy(e,w(r,`owner.json`),t),v(r)}for(let t of p(n)){if(!/^[a-f0-9-]{36}\.json$/u.test(t))throw new D(`Filesystem observation gate has unrelated metadata.`);let r=w(n,t),i=Hy(e,r);if(i.kind!==`scan`||t!==i.id+`.json`)throw new D(`Filesystem observation gate has unrelated scan metadata.`);if(By(i.owner))throw new D(`Filesystem observation gate still has a live scan request.`);Wy(e,r,i)}if(v(n),B(JSON.parse(H(w(e.directory,`gate.json`)).toString(`utf8`)))!==B(e))throw new D(`Filesystem observation gate changed before retirement.`);x(w(e.directory,`gate.json`)),v(e.directory)}function qy(e,t){let n=`kind=UNKNOWN`;if(!ue.isProxy(e)&&ue.isNativeError(e)){n=`kind=Error`;let t=Object.getOwnPropertyDescriptor(e,`message`),r=t&&`value`in t?t.value:void 0;if(typeof r==`string`&&r.length<=4096){n+=`; messageDigest=${V(Buffer.from(r))}`;let e=/^Selected policy stage command failed \(exit (\d{1,3})\)\. Command exit \1\./u.exec(r);if(e!==null&&Number(e[1])<=255&&(n+=`; exit=${Number(e[1])}`),r.startsWith(`Owned process resource observation failed. `)){let e=/"errorCode":"(ETIMEDOUT|EACCES|EPERM|ENOENT|ENOBUFS|EAGAIN|ENOMEM|EIO|EINVAL|other)"/u.exec(r);n+=`; observation=${e?.[1]??`UNKNOWN`}`}}}return Error(`Wrapped operation failed. ${n}`,t===void 0?void 0:{cause:t.value})}function Jy(e,t,n){try{Ky(e)}catch(e){if(e instanceof nb&&(e.message+=` Output-gate retirement: wrappedOperation=${t?`completed`:`failed`}.`),!t&&!ue.isProxy(e)&&ue.isNativeError(e)){let t=Object.getOwnPropertyDescriptor(e,`cause`);(t===void 0&&Object.isExtensible(e)||t!==void 0&&`value`in t&&(t.configurable||t.writable))&&Object.defineProperty(e,"cause",{configurable:t?.configurable??!0,enumerable:t?.enumerable??!1,writable:t?.writable??!0,value:qy(n,t)})}throw e}}async function Yy(e,t,n){let r=process.env[Ny];if(r!==void 0)return n(zy(r));if(!t)return n(void 0);let i=he(),a=w(pd(e),`ai-delivery`,`output-observation`,hb(e).slice(7));Qv(a);for(let e of p(a)){fl().parse(e);let t=w(a,e);Ry(t);let n=Fy.parse(JSON.parse(H(w(t,`gate.json`)).toString(`utf8`)));if(n.id!==e||n.directory!==t||By(n.owner))throw new D(`Prior filesystem observation gate is live or has conflicting ownership.`);Ky(n,!0)}let o=w(a,i);Qv(w(o,`requests`));let s={directory:o,id:i,owner:Ly()};ey(w(o,`gate.json`),s);let c=!1,l;try{let e=await n(s);return c=!0,e}catch(e){throw l=e,e}finally{Jy(s,c,l)}}var Xy=class extends D{cause;code;constructor(e,t,n){let r=n.code;super(`${e} Path ${JSON.stringify(t)} (${r??`unknown errno`}): ${n instanceof Error?n.message:String(n)}`),this.code=r,this.cause=n}};function Zy(e,t,n=!1,r){let a=new Map,o=new Map,s=i=>{let l;try{l=c(i)}catch(e){if(e.code===`ENOENT`)return;throw new Xy(`Filesystem output lstat failed.`,i,e)}if(l.isSymbolicLink()){let a;try{a=m(i)}catch(e){throw new Xy(`Filesystem output readlink failed.`,i,e)}let s=B({device:l.dev,inode:l.ino,changed:l.ctimeMs,modified:l.mtimeMs,link:a}),u,d=!1;try{u=h(i)}catch(e){let o=new Xy(`Filesystem output observation encountered a broken or cyclic symbolic link.`,i,e),l=t.get(i);if(l!==void 0&&l.identity!==s)throw new D(`Filesystem output alias identity changed. Path ${JSON.stringify(i)}.`);if(!n||o.code!==`ENOENT`||l?.identity!==s)throw o;let f=T(C(i),a),p=f,g=new Set([i]);for(;;)try{u=w(h(p),f.slice(p.length));break}catch(e){if(e.code!==`ENOENT`||C(p)===p)throw new Xy(`Filesystem output ancestor resolution failed.`,p,e);let n;try{n=c(p)}catch(e){if(e.code!==`ENOENT`)throw new Xy(`Filesystem output ancestor lstat failed.`,p,e)}if(n?.isSymbolicLink()){let e,r;try{e=m(p),r=c(p)}catch(e){throw new Xy(`Filesystem output ancestor alias read failed.`,p,e)}let i=B({device:n.dev,inode:n.ino,changed:n.ctimeMs,modified:n.mtimeMs,link:e}),a=t.get(p);if(a===void 0)throw o;if(g.has(p)||a.identity!==i||!r.isSymbolicLink()||r.dev!==n.dev||r.ino!==n.ino||r.ctimeMs!==n.ctimeMs||r.mtimeMs!==n.mtimeMs)throw new D(`Filesystem output ancestor alias identity changed. Path ${JSON.stringify(p)}.`);g.add(p),f=w(T(C(p),e),f.slice(p.length)),p=f;continue}p=C(p)}if(u!==l.target)throw new D(`Filesystem output alias target identity changed. Path ${JSON.stringify(i)}.`);d=!0,r?.(o.message)}let f=t.get(i);if(f?.missing&&(f.identity!==s||f.target!==u))throw new D(`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(i)}.`);if(!e.some(e=>u===e||u.startsWith(`${e}${ce}`)))throw new D(`Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(i)} resolves to ${JSON.stringify(u)}.`);let p;try{p=c(i)}catch(e){if(n&&e.code===`ENOENT`&&f?.identity===s)return;throw new Xy(`Filesystem output alias identity readback failed.`,i,e)}if(!p.isSymbolicLink()||p.dev!==l.dev||p.ino!==l.ino||p.ctimeMs!==l.ctimeMs||p.mtimeMs!==l.mtimeMs)throw new D(`Filesystem output alias identity changed during observation. Path ${JSON.stringify(i)}.`);o.set(i,{identity:s,target:u,missing:d});return}if(l.isDirectory()){let e;try{e=p(i)}catch(e){if(e.code===`ENOENT`)return;throw new Xy(`Filesystem output readdir failed.`,i,e)}for(let t of e)s(w(i,t));return}if(!l.isFile()&&!l.isSocket()||!Number.isSafeInteger(l.size))throw new D(`Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(i)}.`);if(a.set(i,l.isSocket()?0:l.size),a.size>1e6)throw new D(`Filesystem output observation exceeded its file limit.`)};for(let t of e){if(i(t)&&h(t)!==t)throw new D(`Filesystem output roots must not be symbolic links.`);s(t)}t.clear();for(let[e,n]of o)t.set(e,n);return a}async function Qy(e,t,n=!1,r){let i,a,o,s,c=()=>{if(s!==void 0&&Date.now()-s>=1e3)throw new D(`Filesystem output observation remained unavailable for 1 second. First observation: ${a.message} Last observation: ${o.message}`)};for(;;){if(t?.aborted)throw new D(`Filesystem output observation cancelled.`);c();try{i=await Gy(e.gate,`scan`,()=>Zy(e.roots,e.links,n,r),t),c();break}catch(e){if(!n||!(e instanceof Xy)||e.code!==`ENOENT`)throw e;o=e,a===void 0&&(s=Date.now(),a=e,r?.(e.message)),c(),await new Promise(e=>setTimeout(e,25))}}let l=0;for(let[t,n]of i)if(l+=Math.max(0,n-(e.files.get(t)??0)),!Number.isSafeInteger(l))throw new D(`Filesystem output observation overflowed.`);return l}function $y(e){let t=e;for(;;)try{let e=b(t,{bigint:!0});return e.bavail*e.bsize}catch(e){if(e.code!==`ENOENT`||C(t)===t)throw e;t=C(t)}}function eb(e,t){let n=(t===void 0?[e]:[e,...t.roots]).reduce((e,t)=>{let n=$y(t);return n<e?n:e},BigInt(2**53-1));if(n>BigInt(2**53-1))throw new D(`Free disk observation overflowed.`);return Number(n)}function tb(e,t,n){if(eb(e,n)<t.minFreeDiskBytes)throw new D(`Free disk fell below limit ${t.minFreeDiskBytes}.`)}var nb=class extends D{};function rb(){let e=i(`/usr/bin/ps`)?`/usr/bin/ps`:`/bin/ps`,t=re(e,[`-A`,`-o`,`pid=,ppid=,pgid=,rss=,stat=,lstart=`],{encoding:`utf8`,env:{...process.env,LC_ALL:`C`},maxBuffer:4194304,timeout:1e3});if(t.status!==0||t.error||t.signal||!t.stdout.endsWith(`
285
285
  `)){let e=t.error?.code,n=t.signal,r={status:Number.isSafeInteger(t.status)?t.status:null,errorCode:e===void 0?null:[`EACCES`,`EPERM`,`ETIMEDOUT`,`ENOENT`,`ENOBUFS`,`EAGAIN`,`ENOMEM`,`EIO`,`EINVAL`].includes(e)?e:`other`,signal:n===null?null:[`SIGTERM`,`SIGKILL`,`SIGINT`,`SIGABRT`,`SIGSEGV`,`SIGBUS`,`SIGHUP`,`SIGQUIT`,`SIGPIPE`].includes(n)?n:`other`,stdoutPresent:typeof t.stdout==`string`,stdoutTerminated:typeof t.stdout==`string`&&t.stdout.endsWith(`
286
- `)};throw new tb(`Owned process resource observation failed. ${JSON.stringify(r)}`)}let n=new Map;for(let e of t.stdout.trim().split(`
287
- `)){let t=/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(e.trim());if(!t)throw new D(`Owned process resource observation is ambiguous.`);let r={pid:Number(t[1]),ppid:Number(t[2]),pgid:Number(t[3]),rssBytes:Number(t[4])*1024,status:t[5],identity:t[6]};if(!Number.isSafeInteger(r.pid)||r.pid<=0||!Number.isSafeInteger(r.ppid)||!Number.isSafeInteger(r.pgid)||!Number.isSafeInteger(r.rssBytes)||n.has(r.pid))throw new D(`Owned process resource observation is ambiguous.`);n.set(r.pid,r)}return n}function rb(e,t){let n=t.get(e.rootPid);if(e.rootIdentity===void 0){if(n===void 0||n.status.startsWith(`Z`)||n.pgid!==e.rootPid)throw new D(`Owned process identity could not be established before the command exited.`);e.rootIdentity=n.identity,e.tracked.set(n.pid,n)}else if(n!==void 0&&n.identity!==e.rootIdentity)throw new D(`Owned process identity changed during verification.`);let r=new Map;for(let[n,i]of e.tracked){let a=t.get(n);if(a===void 0||a.status.startsWith(`Z`))e.tracked.delete(n);else if(a.identity!==i.identity)throw new D(`Tracked process identity changed during verification.`);else r.set(n,a)}for(let n of t.values())!n.status.startsWith(`Z`)&&n.pgid===e.rootPid&&r.set(n.pid,n);let i=new Map;for(let e of t.values()){let t=i.get(e.ppid)??[];t.push(e),i.set(e.ppid,t)}let a=[...r.values()];for(let e of a)for(let t of i.get(e.pid)??[])!t.status.startsWith(`Z`)&&!r.has(t.pid)&&(r.set(t.pid,t),a.push(t));for(let t of r.values())e.tracked.set(t.pid,t);return e.sampled=!0,[...r.values()]}function ib(e,t,n,r,i,a=0,o=!1){let s=nb(),c=rb(e,s),l=o?ab(s,new Set(c.map(e=>e.pid))):a,u=c.reduce((e,t)=>e+t.rssBytes,l);if(!Number.isSafeInteger(u))throw new D(`Owned aggregate RSS is outside the safe integer range.`);if(u>n.maxAggregateRssBytes)throw new D(`Owned aggregate RSS ${u} exceeded limit ${n.maxAggregateRssBytes}.`);let d=$y(t,r);if(d<n.minFreeDiskBytes)throw new D(`Free disk fell below limit ${n.minFreeDiskBytes}.`);if(i!==void 0&&!Number.isSafeInteger(i))throw new D(`Filesystem output observation overflowed.`);if(r!==void 0&&n.maxNewOutputBytes!==void 0&&i!==void 0&&i>n.maxNewOutputBytes)throw new D(`Positive new filesystem output ${i} exceeded limit ${n.maxNewOutputBytes}.`);return{aggregateRssBytes:u,freeDiskBytes:d,...i===void 0?{}:{newOutputBytes:i},ownedProcessCount:c.length}}function ab(e=nb(),t=new Set){let n=e.get(process.pid);if(n===void 0||n.status.startsWith(`Z`))throw new D(`Runtime setup controller resource observation is unavailable.`);let r=new Set([process.pid]),i=process.memoryUsage().rss;for(let n of r)for(let a of e.values())a.ppid===n&&!a.status.startsWith(`Z`)&&!r.has(a.pid)&&(r.add(a.pid),t.has(a.pid)||(i+=a.rssBytes));if(!Number.isSafeInteger(i))throw new D(`Controller aggregate RSS observation overflowed.`);return i}async function ob(e){if(!e.sampled||e.rootIdentity===void 0)throw new D(`Owned process cleanup cannot be verified without a root identity.`);let t=Date.now()+2e3;for(;;){let n=nb(),r=n.get(e.rootPid);if(r!==void 0&&r.identity!==e.rootIdentity)throw new D(`Owned process group identity changed before cleanup readback.`);let i=[...n.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)),a=[...e.tracked.values()].some(e=>{let t=n.get(e.pid);if(t===void 0||t.status.startsWith(`Z`))return!1;if(t.identity!==e.identity)throw new D(`Tracked process identity changed before cleanup readback.`);return!0});if(!i&&!a)return;if(Date.now()>=t)throw new D(`Owned process cleanup did not release every sampled process.`);await new Promise(e=>setTimeout(e,100))}}function sb(e){if(!e.sampled||e.rootIdentity===void 0)throw new D(`Owned process identity is unknown.`);let t=nb(),n=t.get(e.rootPid);if(n!==void 0&&n.identity!==e.rootIdentity)throw new D(`Owned process group identity changed before cleanup.`);let r=[...e.tracked.values()].flatMap(e=>{let n=t.get(e.pid);if(n===void 0||n.status.startsWith(`Z`))return[];if(n.identity!==e.identity)throw new D(`Tracked process identity changed before cleanup.`);return[n]}),i=[...t.values()].filter(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`));if(i.length>0&&!r.some(t=>t.pgid===e.rootPid))throw new D(`Owned process group has no surviving recorded identity; cleanup is ambiguous.`);let a=t=>{try{process.kill(t,`SIGKILL`)}catch(n){let r=n.code;if(r===`ESRCH`)return;if(r!==`EPERM`)throw n;let i=nb();if(t<0){let t=i.get(e.rootPid);if(t!==void 0&&t.identity!==e.rootIdentity)throw new D(`Owned process group identity changed during cleanup signal readback.`);if([...i.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)))throw n}else{let r=i.get(t);if(r!==void 0&&r.identity!==e.tracked.get(t)?.identity)throw new D(`Tracked process identity changed during cleanup signal readback.`);if(r!==void 0&&!r.status.startsWith(`Z`))throw n}}};i.length>0&&a(-e.rootPid);for(let e of r.reverse())a(e.pid)}var cb=F({pid:j().int().positive(),identity:A().min(1)}),lb=F({schemaVersion:L(`ai-delivery.verification-writer@1`),writerId:fl(),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),owner:cb,command:Wl([F({phase:L(`idle`)}),F({phase:L(`starting`)}),F({phase:L(`running`),root:cb,tracked:N(F({...cb.shape,pgid:j().int().positive()}))})]),stateId:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{stateId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Writer state is corrupt.`})});function ub(e,t){if(t===void 0)return;let n=lb.parse(JSON.parse(t.toString(`utf8`)));if(n.worktreeDigest!==mb(e))throw new D(`Verification writer belongs to another worktree.`);let r=nb(),i=r.get(n.owner.pid);if(i?.identity===n.owner.identity&&!i.status.startsWith(`Z`))throw new D(`A live verification writer still owns this worktree.`);if(n.command.phase===`starting`)throw new D(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(n.command.phase===`running`){let e=[n.command.root,...n.command.tracked],t=new Set([n.command.root.pid,...n.command.tracked.map(e=>e.pgid)]);if(e.some(e=>r.has(e.pid))||[...r.values()].some(e=>t.has(e.pgid)))throw new D(`Transition requires identity-bound command and process-group absence.`)}}async function db(e,t,r,a,s=!1){let l=mb(e),d=w(a??pd(e),`ai-delivery`,`writers@1`,`${l.slice(7)}.json`);return Qv(C(d)),Oy(d,{projectRoot:e,timeout:200,...r?.onLockReleaseError===void 0?{}:{onReleaseError:r.onLockReleaseError},...r?.onLockCompromised===void 0?{}:{onCompromised:r.onLockCompromised},operation:async()=>{await Ib(a??pd(e),l,s);let f=nb(),p=f.get(process.pid);if(p===void 0||p.status.startsWith(`Z`))throw new D(`Verification writer identity is unknown.`);let m;if(r)try{c(d),m=H(d)}catch(e){if(e.code!==`ENOENT`)throw e}else i(d)&&(m=H(d));if(r&&ub(e,m),m!==void 0&&!r){let e=lb.parse(JSON.parse(m.toString(`utf8`)));if(e.worktreeDigest!==l)throw new D(`Verification writer belongs to another worktree.`);let t=f.get(e.owner.pid);if(t?.identity===e.owner.identity&&!t.status.startsWith(`Z`))throw new D(`A live verification writer still owns this worktree.`);if(e.command.phase===`starting`)throw new D(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(e.command.phase===`running`){let t={rootPid:e.command.root.pid,rootIdentity:e.command.root.identity,sampled:!0,tracked:new Map(e.command.tracked.map(e=>[e.pid,{...e,ppid:0,rssBytes:0,status:``}]))};sb(t),await ob(t),xb({state:`recovered`,stageId:`writer`,completedStages:0,reusedStages:0,remainingStages:0,elapsedMs:0,reason:`Recorded interrupted command cleanup confirmed; compatible completed stages remain available.`})}}r&&await r.beforeClaim({previousBytes:m===void 0?void 0:Buffer.from(m),owner:{pid:p.pid,identity:p.identity}});let h={schemaVersion:`ai-delivery.verification-writer@1`,writerId:r?.writerId??he(),worktreeDigest:l,owner:{pid:p.pid,identity:p.identity},command:{phase:`idle`}},g=e=>{h={...h,command:e},ey(d,{...h,stateId:B(h)})};if(r){let e=Buffer.from(`${JSON.stringify({...h,stateId:B(h)},null,2)}\n`);await r.recordClaim(Buffer.from(e));let t;try{c(d),t=H(d)}catch(e){if(e.code!==`ENOENT`)throw e}if(t===void 0!=(m===void 0)||t!==void 0&&m!==void 0&&!t.equals(m))throw new D(`Writer changed after transition intent preservation.`)}g({phase:`idle`});let _={starting:()=>g({phase:`starting`}),observed:e=>{if(e.rootIdentity===void 0)throw new D(`Cannot persist an unknown command owner.`);g({phase:`running`,root:{pid:e.rootPid,identity:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,identity:t,pgid:n}))})},idle:()=>g({phase:`idle`}),assertQuiescent:()=>{let e=lb.parse(JSON.parse(H(d).toString(`utf8`)));if(e.writerId!==h.writerId||e.command.phase!==`idle`)throw new D(`Verification writer command quiescence is not confirmed.`)}},v=async()=>{let e=H(d),t=lb.parse(JSON.parse(e.toString(`utf8`)));if(t.writerId!==h.writerId)throw new D(`Verification writer ownership changed.`);if(t.command.phase===`idle`){if(r&&(await r.recordRelease(Buffer.from(e)),!H(d).equals(e)))throw new D(`Writer changed before recorded release.`);if(x(d),r){let e=u(C(d),`r`);try{o(e)}finally{n(e)}try{c(d)}catch(e){if(e.code!==`ENOENT`)throw e;await r.afterRelease?.();return}throw new D(`Writer absence is not confirmed after recorded release.`)}}};try{return await r?.afterClaim?.(Buffer.from(H(d))),await t(_)}finally{await v()}}})}async function fb(e,t,n){let r=w(pd(e),`ai-delivery`,`writers@1`,`${mb(t).slice(7)}.json`);return Oy(r,{projectRoot:e,timeout:200,operation:async()=>{await Ib(pd(e),mb(t));try{c(r)}catch(e){if(e.code!==`ENOENT`)throw e;return n()}throw new D(`Sealed transition writer absence postcondition drifted.`)}})}async function pb(e,t){fl().parse(e.writerId);let n=fd(e.repoRoot);return db(e.worktreePath===void 0?n:T(e.worktreePath),async e=>{e.assertQuiescent();let n=await t();return e.assertQuiescent(),n},e,pd(n))}function mb(e){return B(T(e))}function hb(t){let n=[],r=e=>{for(let i of p(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=w(e,i.name);i.isDirectory()?r(a):i.isFile()&&i.name.endsWith(`.js`)&&!i.name.endsWith(`.test.js`)&&n.push({path:a.slice(t.length+1),digest:V(d(a))})}};r(t);let a=new Map,o=t=>{if(a.has(t))return;let n=d(t),r=P({dependencies:Ql(A(),A()).optional()}).parse(JSON.parse(n.toString(`utf8`)));a.set(t,V(n));let s=e(t);for(let e of Object.keys(r.dependencies??{}).sort()){let t;try{t=s.resolve(`${e}/package.json`)}catch{t=s.resolve(e)}let n=C(t);for(;;){let t=w(n,`package.json`);if(i(t)&&P({name:A().optional()}).parse(JSON.parse(d(t,`utf8`))).name===e){o(t);break}let r=C(n);if(r===n)throw new D(`Producer dependency identity is unavailable for ${e}.`);n=r}}};return o(w(C(t),`package.json`)),{code:n,dependencies:[...a].sort(([e],[t])=>e.localeCompare(t))}}function gb(e=C(be(import.meta.url))){return B(hb(e))}function _b(e){return gb(h(e))}function vb(e){return hb(h(e)).dependencies.map(([e,t])=>({source:e,digest:t}))}function yb(e){return bb(JSON.parse(e.toString(`utf8`)))}function bb(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new D(`Invalid run manifest.`);let t=e,n=ng.parse(t.classification),r=lg.parse(t.aggregate),i=cg.array().parse(t.stageReceipts);if(![`ai-delivery.run@1`,`ai-delivery.run@2`,`ai-delivery.run@3`].includes(String(t.schemaVersion)))throw new D(`Run manifest schema version is unsupported.`);if(t.schemaVersion===`ai-delivery.run@1`&&t.resources!==void 0)throw new D(`Historical run manifest has unexpected resource evidence.`);let a=t.resources===void 0?void 0:jy.parse(t.resources);if(t.schemaVersion===`ai-delivery.run@2`&&a===void 0)throw new D(`Historical bounded run lacks resource evidence.`);let o=t.schemaVersion===`ai-delivery.run@3`?F({worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).parse(t.writer):void 0,s={aggregate:r,classification:n,completedAt:t.completedAt,...a===void 0?{}:{resources:a},...o===void 0?{}:{writer:o},schemaVersion:t.schemaVersion,stageReceipts:i};if(typeof t.completedAt!=`string`||t.manifestId!==B(s)||fg({classification:n,receipts:i}).aggregateId!==r.aggregateId)throw new D(`Run manifest identity or aggregate is invalid.`);return{...s,completedAt:t.completedAt,manifestId:t.manifestId}}function xb(e){process.stderr.write(`ai-delivery.verify ${JSON.stringify(e)}\n`)}function Sb(e,t,n,r,i,a,o,s,c){let[l,...u]=t;if(!l)throw new D(`Policy selected an empty stage command.`);if(n?.aborted)throw new D(`Selected policy stage command cancelled.`);return s?.starting(),new Promise((t,d)=>{let f=ne(`/bin/sh`,[`-c`,`IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null`,`ai-delivery-command`,l,...u],{cwd:c?.cwd??e,detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`],...a?.gate===void 0&&c===void 0?{}:{env:{...c?.environment??process.env,...a?.gate===void 0?{}:{[Ny]:JSON.stringify(a.gate)}}}}),p=[],m=[],h=process.platform===`win32`||f.pid===void 0?void 0:{rootPid:f.pid,sampled:!1,tracked:new Map},g=0,_=0,v=c?.maxCapturedOutputBytes??8388608,y=0,b,x,ee,S=!1,te=!1,re=!1,ie,ae,C,oe=new AbortController,w=()=>{let t=ie===void 0?``:` First filesystem observation: ${ie} Last filesystem observation: ${ae}`;try{let n=Buffer.concat([...p,...m]);return c?.failedOutput?c.failedOutput(n):` Command output ${hg({bytes:n,gitCommonDir:pd(e)})}.${t}`}catch(e){return` Command output persistence failed (${e instanceof Error?e.message:String(e)}).${t}`}},se,T,ce,le=()=>{clearInterval(pe),ce!==void 0&&clearInterval(ce),se!==void 0&&clearTimeout(se),T!==void 0&&clearTimeout(T),n?.removeEventListener(`abort`,me),process.removeListener(`SIGINT`,he),process.removeListener(`SIGTERM`,ge)},ue=()=>{if(f.pid!==void 0){if(h?.sampled){try{rb(h,nb())}catch(e){x??=e instanceof Error?e.message:String(e)}try{s?.observed(h)}catch(e){ee??=e instanceof Error?e.message:String(e)}try{sb(h)}catch(e){x??=e instanceof Error?e.message:String(e)}}else try{f.exitCode===null&&f.signalCode===null&&f.kill(`SIGKILL`),re&&(x??=`owned process identity was not observed before cleanup`)}catch(e){x??=e instanceof Error?e.message:String(e)}}},de=e=>{b===void 0&&(b=e,oe.abort(),ue(),S||(se=setTimeout(()=>{te||S||(te=!0,le(),f.stdout.destroy(),f.stderr.destroy(),f.unref(),c?.onCleanupFailure?.(`Owned command pipes did not close; descendant cleanup could not be verified.`),d(new D(`Selected policy stage command failed (${b}).${w()}${ee===void 0?``:` Writer state persistence failed (${ee}).`} Owned process cleanup failed (owned command pipes did not close; descendant cleanup could not be verified).`)))},2e3)))},fe=(e,t)=>{if(g+=t.length,c?.onCaptured?.(g),c!==void 0&&i?.maxNewOutputBytes!==void 0&&g+y>i.maxNewOutputBytes){de(`source-phase captured output exceeded remaining cumulative allowance`);return}if(g>v){let n=v-_;n>0&&(e.push(Buffer.from(t.subarray(0,n))),_+=Math.min(n,t.length)),de(c?.maxCapturedOutputBytes===void 0?`captured output exceeded 8 MiB`:`captured output exceeded ${v} bytes`);return}e.push(t),_+=t.length};f.stdout.on(`data`,e=>fe(p,e)),f.stderr.on(`data`,e=>fe(m,e)),f.stdout.once(`error`,e=>de(e.message)),f.stderr.once(`error`,e=>de(e.message)),f.stdin.once(`error`,e=>de(e.message)),f.once(`error`,e=>{f.pid===void 0&&s?.idle(),de(e.message)}),f.once(`exit`,(e,t)=>{e!==0||t!==null?de(`exit ${String(e)}${t===null?``:` signal ${t}`}`):S||(T=setTimeout(()=>{S||de(`owned command pipes did not close after direct child exit`)},1e3))}),f.once(`spawn`,()=>{let t=()=>{if(b===void 0&&f.pid!==void 0)try{if(h===void 0)throw new D(`Owned process identity is unavailable on this platform.`);if(rb(h,nb()),s?.observed(h),i!==void 0){let t=ib(h,e,i,a,void 0,c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(S||C!==void 0)return;C=(async()=>{if(i!==void 0&&a!==void 0){let t=await Zy(a,oe.signal,re,e=>{ie??=e,ae=e,r?.(g,void 0,e)});if(b!==void 0)return;y=t;let n=ib(h,e,i,a,t+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(n),r?.(g,n)}b===void 0&&!re&&(re=!0,f.stdin.end(`run
288
- `))})().catch(e=>de(e instanceof Error?e.message:String(e))).finally(()=>{C=void 0})}catch(e){de(e instanceof Error?e.message:String(e))}};t(),ce=setInterval(t,1e3),ce.unref()});let pe=setInterval(()=>r?.(g),5e3);pe.unref();let me=()=>de(`cancelled`),he=()=>de(`cancelled by SIGINT`),ge=()=>de(`cancelled by SIGTERM`);n?.addEventListener(`abort`,me,{once:!0}),process.once(`SIGINT`,he),process.once(`SIGTERM`,ge),n?.aborted&&me();let _e=async(n,l)=>{if(S=!0,!te){if(await C,b===void 0&&h!==void 0)try{if(i!==void 0){let t=ib(h,e,i,a,a===void 0?void 0:await Zy(a,oe.signal)+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(!h.sampled)throw new D(`Owned process resource observation was unavailable.`);if(rb(h,nb()).length>0)throw new D(`A sampled owned descendant survived command exit.`)}catch(e){de(e instanceof Error?e.message:String(e))}if(b!==void 0||n!==0||l!==null){let e=b??`exit ${String(n)}${l===null?``:` signal ${l}`}`,t=f.pid===void 0||!re;if(h!==void 0&&h.sampled)try{await ob(h),t=!0}catch(e){x??=e instanceof Error?e.message:String(e)}if(t)try{s?.idle()}catch(e){ee??=e instanceof Error?e.message:String(e)}te=!0,x!==void 0&&c?.onCleanupFailure?.(x),d(new D(`Selected policy stage command failed (${e}). Command exit ${String(n)}${l===null?``:` signal ${l}`}.${w()}${ee===void 0?``:` Writer state persistence failed (${ee}).`}${x===void 0?``:` Owned process cleanup failed (${x}).`}`));return}s?.idle(),te=!0,t(c?.stdoutOnly?Buffer.concat(p):Buffer.concat([...p,...m],g))}};f.once(`close`,(e,t)=>{_e(e,t).catch(e=>{te=!0,d(e)}).finally(le)})})}var Cb=A().regex(/^sha256:[a-f0-9]{64}$/u),wb=A().regex(/^[a-f0-9]{40}$/u),Tb=F({path:A().min(1),digest:Cb}),Eb=Tb.extend({device:j().int().nonnegative().safe(),inode:j().int().nonnegative().safe(),uid:j().int().nonnegative().safe(),mode:j().int().nonnegative().safe()}),Db=F({argv:N(A()).min(1),cwd:A().min(1),executable:Eb}),Ob=F({head:wb,indexTree:wb,branch:A().min(1),configDigest:Cb,dirty:N(F({path:A().min(1),digest:Cb.nullable()}))}),kb=F({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:N(A().min(1)).min(1)}),Ab=F({phaseId:Cb,recordId:Cb,baselineId:Cb.optional(),authorizationDigest:Cb}),jb=F({repoRoot:A().min(1),issueNumber:j().int().positive().safe(),identity:A().min(1),rowDigest:Cb,controller:F({head:wb,configDigest:Cb,admissionId:Cb,runtimeEntryPath:A().min(1),packageVersion:A().min(1),archiveDigest:Cb}),source:Ob.extend({path:A().min(1),effect:Kl(`kind`,[F({kind:L(`preserve`)}),F({kind:L(`commitOnce`),parent:wb,tree:wb,configDigest:Cb.optional()})])}),caller:Tb,authorization:Tb,inputs:N(Tb),commands:N(Db).min(1),commandGraphDigest:Cb,environment:F({digest:Cb,overrides:Ql(A(),A().nullable())}),bounds:kb,completionArtifacts:N(A().min(1)),reconciliation:Ab.optional()}).omit({environment:!0}).extend({environmentDigest:Cb}),Mb=F({roots:N(A().min(1)).min(1),files:N(Xl([A(),j().int().nonnegative().safe()])),links:N(Xl([A(),F({identity:A(),target:A(),missing:M()})])),baselineId:Cb}),Nb=F({index:j().int().nonnegative().safe(),outputDigest:Cb.nullable(),outputBytes:j().int().nonnegative().safe(),status:I([`complete`,`failed`])}),Pb=F({source:Ob,artifacts:N(Eb),newOutputBytes:j().int().nonnegative().safe(),writerReleased:L(!0),lockReleased:L(!0)}),Fb=F({schemaVersion:L(`ai-delivery.source-phase@1`),phaseId:Cb,recordId:Cb,worktreeDigest:Cb,bindingDigest:Cb,authorizationDigest:Cb,status:I([`preparing`,`intent`,`complete`,`failed-quiescent`,`rejected-before-work`,`unresolved`]),writerId:fl(),binding:jb.optional(),baseline:Mb.optional(),allocation:kb.optional(),owner:F({pid:j().int().positive().safe(),identity:A().min(1)}),bootstrapFiles:N(Xl([A(),j().int().nonnegative().safe()])),bootstrapBytes:j().int().nonnegative().safe(),capturedBytes:j().int().nonnegative().safe(),nextCommandIndex:j().int().nonnegative().safe(),commands:N(Nb),claimDigest:Cb.optional(),releaseDigest:Cb.optional(),preparationArtifact:Eb.optional(),writerArtifact:Eb.optional(),producerDigest:Cb.optional(),actor:F({identity:A().min(1),actorLogin:A().min(1),credentialIdentity:A().min(1)}).optional(),retainedArtifacts:N(Eb).optional(),retainedPredecessors:N(F({phaseId:Cb,recordId:Cb})),reconciliation:Ab.optional(),result:Pb.optional(),failure:F({operation:A().optional(),accounting:A().optional(),cleanup:A().optional(),writerRelease:A().optional(),lockRelease:A().optional()}).optional()}).superRefine((e,t)=>{let{recordId:n,...r}=e;if((n!==B(r)||e.phaseId!==e.bindingDigest)&&t.addIssue({code:`custom`,message:`Source-phase record identity is invalid.`}),e.binding!==void 0&&B(e.binding)!==e.bindingDigest&&t.addIssue({code:`custom`,message:`Source-phase input binding is invalid.`}),e.baseline!==void 0){let{baselineId:n,...r}=e.baseline;n!==B(r)&&t.addIssue({code:`custom`,message:`Source-phase baseline is invalid.`})}e.status===`rejected-before-work`&&(e.commands.length!==0||e.nextCommandIndex!==0||e.capturedBytes!==0)&&t.addIssue({code:`custom`,message:`Rejected source-phase input cannot contain executed work.`}),e.status===`complete`&&(e.result===void 0||e.baseline===void 0||e.binding===void 0||e.failure!==void 0)&&t.addIssue({code:`custom`,message:`Source-phase completion is incomplete.`}),e.status===`complete`&&(e.commands.length!==e.binding?.commands.length||e.nextCommandIndex!==e.commands.length||e.commands.some((e,t)=>e.index!==t||e.status!==`complete`))&&t.addIssue({code:`custom`,message:`Source-phase completion does not contain its exact successful command graph.`})});async function Ib(e,t,n=!1){let r=w(e,`ai-delivery`,`receipts`,`source-phase@1`,t.slice(7)),i;try{let e=c(r);if(!e.isDirectory()||e.isSymbolicLink())throw new D(`Source-phase admission metadata is not a canonical directory.`);i=p(r)}catch(e){if(e.code===`ENOENT`)return;throw e}if(i.length>1e5)throw new D(`Source-phase admission exceeded its entry bound.`);for(let e of i){let i=Fb.parse(JSON.parse(H(w(r,e)).toString(`utf8`)));if(i.worktreeDigest!==t||e!==`${i.phaseId.slice(7)}.json`)throw new D(`Source-phase admission record belongs to another input or worktree.`);if(i.status===`preparing`||i.status===`intent`)throw new D(`An unsealed source phase still excludes another worktree writer.`);if(n&&i.status===`unresolved`)throw new D(`Unresolved source phase requires owning reconciliation before another attempt.`);await new Promise(e=>setImmediate(e))}}F({status:L(`complete`),phaseId:Cb,recordId:Cb,source:Ob,commands:N(Nb)});var Lb=F({schemaVersion:L(`ai-delivery.runtime-output@1`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),limit:j().int().positive().safe().max(8*1024**2),outputs:N(F({digest:A().regex(/^sha256:[a-f0-9]{64}$/u),bytes:j().int().nonnegative().safe().max(8*1024**2),status:I([`reserved`,`complete`])})).max(4096),contentDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{contentDigest:n,...r}=e;(n!==B(r)||new Set(e.outputs.map(e=>e.digest)).size!==e.outputs.length||e.outputs.reduce((e,t)=>e+t.bytes,0)>e.limit)&&t.addIssue({code:`custom`,message:`Runtime retained-output ledger is corrupt.`})});async function Rb(e,t,n){let r=new AbortController,i=n?.signal===void 0?r.signal:AbortSignal.any([n.signal,r.signal]),a,o,s=0,c=Date.now(),l=()=>{if(a!==void 0)throw a;if(i.aborted)throw new D(`Runtime setup cancelled.`);let t=n===void 0?0:ab();if(n!==void 0){if(t>n.bounds.maxAggregateRssBytes)throw new D(`Controller aggregate RSS ${t} exceeded limit ${n.bounds.maxAggregateRssBytes}.`);eb(e,n.bounds,o)}return t};if(n!==void 0){if(My(n.bounds),!Number.isSafeInteger(n.maxCapturedOutputBytes)||n.maxCapturedOutputBytes<=0||n.maxCapturedOutputBytes>8*1024**2)throw new D(`Invalid runtime setup captured-output bound; maximum is 8 MiB.`);l()}return e=fd(e),db(e,async u=>Jy(e,n!==void 0,async d=>{let f,p,m=pd(e),h=()=>{if(f===void 0||p===void 0)throw new D(`Runtime output allowance is unbound.`);let{contentDigest:e,...t}=f;if(f=Lb.parse({...t,contentDigest:B(t)}),Buffer.byteLength(JSON.stringify(f,null,2))>1024**2)throw new D(`Runtime retained-output ledger exceeds its evidence bound.`);ey(p,f)},g=e=>{try{if(gg({gitCommonDir:m,digest:e.digest,expectedBytes:e.bytes}).length!==e.bytes)throw new D(`Runtime retained-output evidence size changed.`);return!0}catch(t){if(e.status===`reserved`&&t.code===`ENOENT`)return!1;throw t}},_=t=>{if(n===void 0)return;if(f!==void 0)throw new D(`Runtime output allowance is already bound.`);let r={stageId:t,worktreeDigest:mb(e),producerDigest:gb(),limit:n.maxCapturedOutputBytes};p=w(m,`ai-delivery`,`verification@1`,`runtime-output`,r.worktreeDigest.slice(7),`${t.slice(7)}.json`);let i;try{i=H(p,{maxBytes:1024**2})}catch(e){if(e.code!==`ENOENT`)throw e}if(i!==void 0){if(f=Lb.parse(JSON.parse(i.toString(`utf8`))),f.stageId!==r.stageId||f.worktreeDigest!==r.worktreeDigest||f.producerDigest!==r.producerDigest||f.limit!==r.limit)throw new D(`Runtime retained-output ledger belongs to an incompatible stage or controller.`);let e=!1;for(let t of f.outputs)g(t)&&t.status===`reserved`&&(t.status=`complete`,e=!0);e&&h()}else{let e={schemaVersion:`ai-delivery.runtime-output@1`,...r,outputs:[]};f=Lb.parse({...e,contentDigest:B(e)}),h()}},v=()=>{if(n===void 0)return 8*1024**2;if(f===void 0)throw new D(`Runtime output allowance is unbound.`);return f.limit-f.outputs.reduce((e,t)=>e+t.bytes,0)},y=e=>{if(f===void 0)throw new D(`Runtime output allowance is unbound.`);let t=V(e),n=f.outputs.find(e=>e.digest===t);if(n!==void 0){if(n.bytes!==e.length||!g(n))throw new D(`Runtime retained-output reservation is unresolved; identical output cannot be rewritten.`);return` Command output ${t}.`}if(e.length>v())throw new D(`Runtime retained-output allowance exceeded.`);let r={digest:t,bytes:e.length,status:`reserved`};if(f.outputs.push(r),h(),hg({bytes:e,gitCommonDir:m}),!g(r))throw new D(`Runtime retained-output publication is unresolved.`);return f.outputs[f.outputs.length-1].status=`complete`,h(),` Command output ${t}.`};if(n!==void 0){let t=[...n.bounds.outputRoots??[],w(pd(e),`ai-delivery`)].map(t=>T(e,t)).sort(),r=t.filter((e,n)=>!t.slice(0,n).some(t=>e===t||e.startsWith(`${t}${ce}`))),a=new Map,s=await Gy(d,`scan`,()=>Xy(r,a),i);o={roots:r,links:a,files:s,baselineId:B([...s]),...d===void 0?{}:{gate:d}}}let b=async()=>{let t=l();if(n===void 0||o===void 0)return;let r=s+await Zy(o,i);if(l(),r>n.bounds.maxNewOutputBytes)throw new D(`Runtime setup output ${r} exceeded limit ${n.bounds.maxNewOutputBytes}.`);xb({state:`running`,stageId:`runtime-setup`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:s,sampledAggregateRssBytes:t,sampledFreeDiskBytes:$y(e,o),sampledNewOutputBytes:r})};await b();let x=n===void 0?void 0:setInterval(()=>{try{l()}catch(e){a??=e instanceof Error?e:new D(String(e)),r.abort()}},1e3);x?.unref();try{let r=await t({assertQuiescent:()=>u.assertQuiescent(),bindCapturedOutput:_,checkResources:b,signal:i,run:async(t,r,a,o,l)=>{await b(),My(r);let f=r.outputRoots?.map(t=>T(e,t)).sort();if(f!==void 0){for(let e=1;e<f.length;e++)if(f[e]===f[e-1]||f[e].startsWith(`${f[e-1]}${ce}`))throw new D(`Filesystem output roots must not overlap.`)}let p=async d=>{let p=v();if(p<=0)throw new D(`Runtime retained-output allowance is exhausted; installer was not started.`);let m=new Map,h=f===void 0?void 0:await Gy(d,`scan`,()=>Xy(f,m),i),g=f===void 0||h===void 0?void 0:{roots:f,files:h,links:m,baselineId:B([...h]),...d===void 0?{}:{gate:d}};eb(e,r,g);let _=0,x=await Sb(e,t,a===void 0?i:AbortSignal.any([i,a]),(e,t,n)=>xb({state:`running`,stageId:`runtime-setup:install`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:e,...n===void 0?{}:{reason:n},...t===void 0?{}:{sampledAggregateRssBytes:t.aggregateRssBytes,sampledFreeDiskBytes:t.freeDiskBytes,sampledNewOutputBytes:t.newOutputBytes}}),r,g,void 0,u,n===void 0&&o===void 0&&l===void 0?void 0:{environment:o??process.env,...l===void 0?{}:{cwd:l},...n===void 0?{}:{maxCapturedOutputBytes:p,includeControllerTree:!0,failedOutput:y},onCaptured:e=>{s+=e-_,_=e}});return await b(),x};return n===void 0?Jy(e,f!==void 0,p):p(d)}});return await b(),xb({state:`completed`,stageId:`runtime-setup`,completedStages:1,reusedStages:0,remainingStages:0,elapsedMs:Date.now()-c}),r}catch(e){throw a===void 0?i.aborted?new D(`Runtime setup cancelled. ${e instanceof Error?e.message:String(e)}`):e:new D(`${a.message} Runtime setup operation failed (${e instanceof Error?e.message:String(e)}).`)}finally{x!==void 0&&clearInterval(x)}}))}var zb=`.issue-cli`;function Bb(e){let t=e??process.cwd(),n=T(t,zb);return i(n)||l(n,{recursive:!0}),n}var Vb=`${zb}/worktrees.json`,Hb=F({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:I([`active`,`error`,`merged`,`pr-published`,`stale`]),type:L(`issue`),updatedAt:A().min(1)}).transform(({prNumber:e,...t})=>({...t,...e===void 0?{}:{prNumber:e}})),Ub=F({schemaVersion:L(`ai-delivery.committed-continuation-plan@1`),planId:R,repository:A().min(1),repoRoot:A().min(1),configDigest:R,currentRuntime:oy,row:Hb,replacement:Hb,head:xd,terminalHead:xd,terminalMergeId:R,operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1),preserved:N(F({path:A().min(1),digest:R})).min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e,{prNumber:i,identity:a,status:o,updatedAt:s,...c}=e.row,{identity:l,status:u,updatedAt:d,...f}=e.replacement;(n!==B(r)||e.row.status!==`merged`||!e.row.prNumber||e.replacement.status!==`active`||e.replacement.prNumber!==void 0||z(c)!==z(f)||e.head.sha===e.terminalHead.sha||new Set(e.preserved.map(e=>e.path)).size!==e.preserved.length)&&t.addIssue({code:`custom`,message:`Committed continuation plan identity or disposition is invalid.`})}),Wb=F({schemaVersion:L(`ai-delivery.committed-continuation-intent@1`),intentId:R,plan:Ub,authorityCommentId:j().int().positive(),acceptanceCommentId:j().int().positive()}).superRefine(({intentId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Continuation intent identity is invalid.`})}),Gb=F({schemaVersion:L(`ai-delivery.committed-continuation-completion@1`),completionId:R,intentId:R,planId:R,row:Hb,head:xd,completed:L(!0)}).superRefine(({completionId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Continuation completion identity is invalid.`})});function Kb(e,t,n){return w(pd(e),`ai-delivery`,`continuations`,String(t),`${n}.plan.json`)}function qb(e){return Kb(e.repoRoot,e.row.issueNumber,e.head.sha).replace(/\.plan\.json$/u,`.intent.json`)}function Jb(e){return qb(e).replace(/\.intent\.json$/u,`.completion.json`)}function Yb(e,t){return w(pd(e.repoRoot),`ai-delivery`,`continuations`,`evidence`,`${t.slice(7)}.bin`)}function Xb(e,t=!1){for(let n of e.preserved)if(V(H(n.path))!==n.digest||t&&V(H(Yb(e,n.digest)))!==n.digest)throw Error(`Committed continuation original evidence changed.`);if(t){let t=Buffer.from(z(e.row));if(!H(Yb(e,V(t))).equals(t))throw Error(`Committed continuation original row beforeimage changed.`)}}function Zb(e,t){let n=w(pd(t),`ai-delivery`,`continuations`,String(e));if(!i(n))return;let r;for(let a of p(n).filter(e=>e.endsWith(`.intent.json`)).sort()){let o=Wb.parse(JSON.parse(H(w(n,a)).toString(`utf8`))),s=o.plan;if(s.repoRoot!==T(t)||s.row.issueNumber!==e||w(n,a)!==qb(s))throw Error(`Committed continuation checkpoint identity disagrees.`);Xb(s,!0);let c=Jb(s);if(i(c)){let e=Gb.parse(JSON.parse(H(c).toString(`utf8`)));if(e.intentId!==o.intentId||e.planId!==s.planId||z(e.row)!==z(s.replacement)||z(e.head)!==z(s.head))throw Error(`Committed continuation completion disagrees with its intent.`);nx(s.replacement,t),ox(t,n,!1),ox(t,C(Yb(s,s.preserved[0].digest)),!1),ax(c)}else{if(r)throw Error(`Issue has multiple incomplete committed continuations.`);r=o}}return r}function Qb(e){if(!e.identity)throw Error(`ai-delivery worktree ownership requires the preparing identity.`);return{branch:e.branch,identity:e.identity,...e.issueNumber===void 0?{}:{issueNumber:e.issueNumber},path:e.path,...e.prNumber===void 0||e.type===`issue`?{}:{prNumber:e.prNumber},schemaVersion:`ai-delivery.worktree-owner@1`,type:e.type}}function $b(e,t){let n=B(Qb(t)).slice(7);return w(pd(e),`ai-delivery`,`worktree-owners`,`${n}.json`)}function ex(e,t){if(e.type!==`issue`||e.issueNumber===void 0)return;let n=w(pd(t),`ai-delivery`,`worktree-owners`,`issue-${String(e.issueNumber)}.transition.json`);try{c(n)}catch(e){if(e.code===`ENOENT`)return;throw Error(`Worktree transition is incomplete or unreadable.`)}try{let r=JSON.parse(H(n).toString(`utf8`)),{intentId:i,...a}=r,{planId:o,...s}=r.plan;if(r.schemaVersion!==`ai-delivery.worktree-transition-intent@1`||i!==B(a)||o!==B(s)||r.plan.repoRoot!==T(t)||r.plan.row.issueNumber!==e.issueNumber)throw Error(`Invalid transition intent.`);if(r.plan.purpose===`merged-cleanup`)throw Error(`Worktree transition is terminal and cannot authorize ordinary source operations.`);let c=w(`${n}.evidence`,`completion.json`),l=JSON.parse(H(c).toString(`utf8`)),{completionId:u,...d}=l;if(l.schemaVersion!==`ai-delivery.worktree-transition-completion@1`||l.planId!==o||l.intentId!==i||l.completed!==!0||u!==B(d)||JSON.stringify(Qb(e))!==JSON.stringify(Qb(r.plan.row)))throw Error(`Invalid transition completion.`);return}catch(e){throw e instanceof Error&&e.message.includes(`transition is terminal`)?e:Error(`Worktree transition is incomplete or unreadable; resume its exact approved plan.`)}}function tx(e,t){if(e.issueNumber!==void 0&&Tx(e.issueNumber,t),ex(e,t),e.issueNumber!==void 0&&Zb(e.issueNumber,t))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);nx(e,t)}function nx(e,t){let n=Qb(e),r=$b(t,e),i;try{i=JSON.parse(H(r).toString(`utf8`))}catch{throw Error(`Worktree lacks its exact ai-delivery ownership witness.`)}if(JSON.stringify(i)!==JSON.stringify({...n,ownerId:B(n)}))throw Error(`Worktree ownership witness disagrees with the canonical registry identity.`)}function rx(e,t,n=!1){if(Tx(e,t),Zb(e,t)&&!n)throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);let r=w(pd(t),`ai-delivery`,`worktree-owners`,`issue-${String(e)}.transition.json`);try{c(r)}catch(e){if(e.code===`ENOENT`)return;throw Error(`Worktree transition is incomplete or unreadable.`)}let i;try{if(i=JSON.parse(H(r).toString(`utf8`)).plan.row,i.type!==`issue`||i.issueNumber!==e)throw Error(`Transition embedded issue identity disagrees.`)}catch{throw Error(`Worktree transition is incomplete or unreadable.`)}ex(i,t)}function ix(e,t,n=!1){let r=Qb(e);wd($b(t,e),Buffer.from(JSON.stringify({...r,ownerId:B(r)}))),n||tx(e,t)}function ax(e){let t=u(C(e),`r`);try{o(t)}finally{n(t)}}function ox(e,t,n=!0){let r=w(pd(e),`ai-delivery`),i=[r,w(r,`continuations`),t],a=(e,t)=>{let n;try{n=c(e)}catch(e){if(t&&e.code===`ENOENT`)return;throw e}if(!n.isDirectory()||n.isSymbolicLink()||e!==r&&n.mode&63)throw Error(`Committed continuation evidence requires a private directory.`)};for(let e of i)a(e,n&&e!==r);n&&Qv(t);for(let e of i)a(e,!1),ax(e)}async function sx(e,t){let n=e.repoRoot;if(Zb(e.row.issueNumber,n))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);return ux(n),Oy(Vb,{projectRoot:n,timeout:5e3,operation:async()=>{let r=fx(n),i=r.worktrees.filter(t=>t.type===`issue`&&t.issueNumber===e.row.issueNumber);if(i.length>1)throw Error(`Transition has duplicate canonical issue rows.`);if(r.worktrees.some(t=>!i.includes(t)&&gx(t,e.row)))throw Error(`Transition conflicts with another canonical registry path, branch or PR identity.`);let a=i[0],o={...e.row,...e.row.prNumber===void 0?{}:{prNumber:e.row.prNumber}},s=e.purpose===`active-resume`?o:{...o,prNumber:e.terminalPrNumber,status:`merged`};if(a!==void 0&&![o,s].some(e=>z(a)===z(e)))throw Error(`Transition canonical row drifted.`);let c=w(pd(n),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`),l=()=>{if(JSON.parse(H(c).toString(`utf8`)).plan?.planId!==e.planId)throw Error(`Transition lacks its exact durable intent.`)};return t({current:a,writeOwner:()=>{l(),ix(s,n,!0)},commitRow:()=>{if(l(),a===void 0)throw Error(`Transition cannot recreate a removed canonical row.`);return r.worktrees.splice(r.worktrees.indexOf(a),1,s),a=s,bx(n,r),s},removeRow:()=>{if(l(),e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw Error(`Transition lacks explicit unheld terminal source disposition.`);a!==void 0&&(r.worktrees.splice(r.worktrees.indexOf(a),1),bx(n,r),a=void 0)}})}})}function cx(e){let t=e.row,n=Qb(t);if(z(JSON.parse(H($b(e.repoRoot,t)).toString(`utf8`)))!==z({...n,ownerId:B(n)}))throw Error(`Sealed transition owner witness drifted.`)}function lx(e){return fx(e??process.cwd()).worktrees}function ux(e){Bb(e)}function dx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fx(e){let t=T(e,Vb);if(!i(t))return{worktrees:[]};try{let e=d(t,`utf8`),n=JSON.parse(e);if(!dx(n)||Object.keys(n).length!==1||!Array.isArray(n.worktrees))throw Error(`Registry must be an object with a worktrees array.`);return{worktrees:n.worktrees.map((e,t)=>px(e,t))}}catch(e){throw Error(`Unable to read worktree registry: ${e instanceof Error?e.message:String(e)}`)}}function px(e,t){if(!dx(e))throw Error(`worktrees[${String(t)}] must be an object.`);let n=new Set([`branch`,`createdAt`,`identity`,`issueNumber`,`path`,`prNumber`,`status`,`type`,`updatedAt`]),r=Object.keys(e).filter(e=>!n.has(e));if(r.length>0)throw Error(`worktrees[${String(t)}] has unsupported fields: ${r.join(`, `)}.`);let i=_x(e.branch,`worktrees[${String(t)}].branch`),a=_x(e.createdAt,`worktrees[${String(t)}].createdAt`),o=_x(e.path,`worktrees[${String(t)}].path`),s=yx(e.type,`worktrees[${String(t)}].type`),c=vx(e.status,`worktrees[${String(t)}].status`),l=hx(e.identity,`worktrees[${String(t)}].identity`),u=mx(e.issueNumber,`worktrees[${String(t)}].issueNumber`),d=mx(e.prNumber,`worktrees[${String(t)}].prNumber`),f=_x(e.updatedAt,`worktrees[${String(t)}].updatedAt`);if(s===`issue`&&u===void 0)throw Error(`worktrees[${String(t)}].issueNumber is required for issue worktrees.`);return{branch:i,createdAt:a,...l===void 0?{}:{identity:l},...u===void 0?{}:{issueNumber:u},path:o,...d===void 0?{}:{prNumber:d},status:c,type:s,updatedAt:f}}function mx(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer.`);return e}}function hx(e,t){if(e!==void 0)return _x(e,t)}function gx(e,t){return e.path===t.path||e.branch===t.branch||e.issueNumber!==void 0&&t.issueNumber!==void 0&&e.issueNumber===t.issueNumber||e.prNumber!==void 0&&t.prNumber!==void 0&&e.prNumber===t.prNumber}function _x(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string.`);return e}function vx(e,t){if(e===`merged`||e===`pr-published`||e===`active`||e===`error`||e===`stale`)return e;throw Error(`${t} is invalid.`)}function yx(e,t){if(e===`issue`||e===`pr`||e===`standalone`)return e;throw Error(`${t} is invalid.`)}function bx(e,t){ux(e);let n=T(e,Vb);try{$v(n,t)}catch(e){throw Error(`Unable to save worktree registry: ${e instanceof Error?e.message:String(e)}`)}}var xx=F({schemaVersion:L(`ai-delivery.investigation-preparation@1`),preparationId:R,repository:yd,repoRoot:A().min(1),row:Hb,head:xd,physical:F({device:j().int().nonnegative().safe(),inode:j().int().nonnegative().safe(),gitDirectory:A().min(1),gitDevice:j().int().nonnegative().safe(),gitInode:j().int().nonnegative().safe()}),operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1)}).superRefine(({preparationId:e,...t},n)=>{(e!==B(t)||t.row.status!==`active`||t.row.prNumber!==void 0||t.row.branch!==`issue/${String(t.row.issueNumber)}`||t.row.path!==w(t.repoRoot,`.worktrees`,`issue-${String(t.row.issueNumber)}`)||t.operator.actorLogin.toLowerCase()===t.reviewerActor.toLowerCase())&&n.addIssue({code:`custom`,message:`Investigation preparation identity is invalid.`})}),Sx=F({schemaVersion:L(`ai-delivery.investigation-completion-intent@1`),intentId:R,preparationId:R,resultDigest:R,authorityCommentId:j().int().positive().safe(),acceptanceCommentId:j().int().positive().safe(),registryBeforeimage:R,authorityDigest:R}).superRefine(({intentId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Investigation intent is corrupt.`})}),Cx=F({schemaVersion:L(`ai-delivery.investigation-completion@1`),completionId:R,intentId:R,preparationId:R,completed:L(!0)}).superRefine(({completionId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Investigation completion is corrupt.`})});function wx(e,t){return w(pd(e),`ai-delivery`,`investigations`,String(t))}function Tx(e,t){let n=w(wx(t,e),`intent.json`);try{c(n)}catch(e){if(e.code===`ENOENT`)return;throw e}throw Error(`Investigation completion is pending or terminal; resume only its exact completion.`)}function Ex(e){return JSON.parse(H(e,{maxBytes:1048576}).toString(`utf8`))}function Dx(e,t){let n=w(wx(e,t),`preparation.json`);try{c(n)}catch(e){if(e.code===`ENOENT`)return;throw e}let r=xx.parse(Ex(n));if(r.repoRoot!==e||r.row.issueNumber!==t)throw Error(`Investigation preparation belongs to another repository or issue.`);return r}function Ox(e,t){return F({commentId:j().int().positive().safe(),url:ml(),body:A().min(1)}).parse(Ex(w(wx(e,t),`acknowledgement.json`)))}function kx(e,t){let n=wx(e,t),r=pd(e);for(let e of[w(r,`ai-delivery`),w(r,`ai-delivery`,`investigations`),n])try{let t=c(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`Investigation custody directory is unsafe.`)}catch(e){if(e.code!==`ENOENT`)throw e}return Qv(n),n}function Ax(e){let t=w(e,zb),n=c(t);if(!n.isDirectory()||n.isSymbolicLink())throw Error(`Canonical registry directory is unsafe.`);let r=w(e,Vb);if(i(r)){let e=c(r);if(!e.isFile()||e.isSymbolicLink()||e.nlink!==1)throw Error(`Canonical registry file is unsafe.`)}}function jx(e,t){let n=e.worktrees.filter(e=>gx(e,t.row));if(n.length>1||n[0]!==void 0&&z(n[0])!==z(t.row))throw Error(`Investigation conflicts with canonical registry custody.`);return n[0]}async function Mx(e,t){let n=xx.parse(e),r=n.repoRoot,i=n.row.issueNumber;rx(i,r),ux(r),Ax(r),await Oy(Vb,{projectRoot:r,timeout:5e3,operation:async()=>{rx(i,r);let e=fx(r),a=Dx(r,i);if(a===void 0&&e.worktrees.some(e=>gx(e,n.row)))throw Error(`Legacy custody cannot be adopted as a current investigation.`);let o=jx(e,n);if(a!==void 0&&z(a)!==z(n))throw Error(`Investigation baseline cannot be replaced.`);let s=kx(r,i);wd(w(s,`preparation.json`),Buffer.from(z(n)));let c=await t();if(wd(w(s,`acknowledgement.json`),Buffer.from(z(c))),ix(n.row,r),o===void 0&&(e.worktrees.push(n.row),bx(r,e)),jx(fx(r),n)===void 0)throw Error(`Investigation registration readback is missing.`)}})}async function Nx(e){let t=xx.parse(e.preparation),n=t.repoRoot,r=t.row.issueNumber;return ux(n),Ax(n),Oy(Vb,{projectRoot:n,timeout:5e3,operation:async()=>{if(z(Dx(n,r))!==z(t))throw Error(`Investigation preparation drifted.`);if(ex(t.row,n),Zb(r,n))throw Error(`Committed continuation is incomplete.`);nx(t.row,n);let a=wx(n,r),o=w(a,`intent.json`),s=w(a,`completion.json`),c=i(o)?Sx.parse(Ex(o)):void 0,l=i(s)?Cx.parse(Ex(s)):void 0,u=fx(n),f=jx(u,t);if(f===void 0&&c===void 0)throw Error(`Investigation row disappeared without a removal intent.`);if(l!==void 0&&(c===void 0||f!==void 0||l.intentId!==c.intentId||l.preparationId!==t.preparationId))throw Error(`Investigation completion custody is inconsistent.`);let p=V(e.result);if(c!==void 0&&(c.preparationId!==t.preparationId||c.resultDigest!==p||c.authorityCommentId!==e.authorityCommentId||c.acceptanceCommentId!==e.acceptanceCommentId))throw Error(`Resume requires the same exact investigation intent and evidence.`);if(c!==void 0){for(let e of[c.resultDigest,c.registryBeforeimage,c.authorityDigest])if(V(H(w(a,`${e.slice(7)}.bin`)))!==e)throw Error(`Preserved investigation evidence changed.`)}e.assertSource(c!==void 0);let m=await e.authorize();if(e.assertSource(c!==void 0),e.dryRun)return{completed:!1,replayed:c!==void 0};if(l!==void 0)return{completed:!0,replayed:!0,receiptPath:s};let h=c;if(h===void 0){let r=d(w(n,Vb)),i=Buffer.from(z(m));for(let t of[e.result,r,i]){let e=V(t);wd(w(a,`${e.slice(7)}.bin`),t,e)}let s={schemaVersion:`ai-delivery.investigation-completion-intent@1`,preparationId:t.preparationId,resultDigest:p,authorityCommentId:e.authorityCommentId,acceptanceCommentId:e.acceptanceCommentId,registryBeforeimage:V(r),authorityDigest:V(i)};h=Sx.parse({...s,intentId:B(s)}),wd(o,Buffer.from(z(h)))}if(e.assertSource(c!==void 0),e.removeSource(),e.assertSource(!0),f!==void 0&&(u.worktrees.splice(u.worktrees.indexOf(f),1),bx(n,u)),jx(fx(n),t)!==void 0)throw Error(`Investigation registry removal readback failed.`);let g={schemaVersion:`ai-delivery.investigation-completion@1`,intentId:h.intentId,preparationId:t.preparationId,completed:!0};return wd(s,Buffer.from(z({...g,completionId:B(g)}))),{completed:!0,replayed:c!==void 0,receiptPath:s}}})}function Px(e,t){let n=se(w(e,`.worktrees`),t);if(n===``||n.startsWith(`..`)||n.startsWith(`/`))throw new D(`Worktree path must be inside the repository .worktrees directory.`)}function Fx(e){if(!Number.isSafeInteger(e)||e<=0)throw new D(`Issue number must be positive.`)}function Ix(e,t){Fx(e.issueNumber??0);let n=`issue/${String(e.issueNumber)}`,r=w(t,`.worktrees`,`issue-${String(e.issueNumber)}`);if(e.type!==`issue`||e.path!==r||e.branch!==n||!i(r)||fd(r)!==h(r)||pd(r)!==pd(t))throw new D(`Registered worktree disagrees with its exact repository, path or branch.`);if(ud(r,`branch`,`--show-current`)!==n)throw new D(`Registered branch drifted.`)}function Lx(e){return ud(e,`worktree`,`list`,`--porcelain`).split(`
286
+ `)};throw new nb(`Owned process resource observation failed. ${JSON.stringify(r)}`)}let n=new Map;for(let e of t.stdout.trim().split(`
287
+ `)){let t=/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(e.trim());if(!t)throw new D(`Owned process resource observation is ambiguous.`);let r={pid:Number(t[1]),ppid:Number(t[2]),pgid:Number(t[3]),rssBytes:Number(t[4])*1024,status:t[5],identity:t[6]};if(!Number.isSafeInteger(r.pid)||r.pid<=0||!Number.isSafeInteger(r.ppid)||!Number.isSafeInteger(r.pgid)||!Number.isSafeInteger(r.rssBytes)||n.has(r.pid))throw new D(`Owned process resource observation is ambiguous.`);n.set(r.pid,r)}return n}function ib(e,t){let n=t.get(e.rootPid);if(e.rootIdentity===void 0){if(n===void 0||n.status.startsWith(`Z`)||n.pgid!==e.rootPid)throw new D(`Owned process identity could not be established before the command exited.`);e.rootIdentity=n.identity,e.tracked.set(n.pid,n)}else if(n!==void 0&&n.identity!==e.rootIdentity)throw new D(`Owned process identity changed during verification.`);let r=new Map;for(let[n,i]of e.tracked){let a=t.get(n);if(a===void 0||a.status.startsWith(`Z`))e.tracked.delete(n);else if(a.identity!==i.identity)throw new D(`Tracked process identity changed during verification.`);else r.set(n,a)}for(let n of t.values())!n.status.startsWith(`Z`)&&n.pgid===e.rootPid&&r.set(n.pid,n);let i=new Map;for(let e of t.values()){let t=i.get(e.ppid)??[];t.push(e),i.set(e.ppid,t)}let a=[...r.values()];for(let e of a)for(let t of i.get(e.pid)??[])!t.status.startsWith(`Z`)&&!r.has(t.pid)&&(r.set(t.pid,t),a.push(t));for(let t of r.values())e.tracked.set(t.pid,t);return e.sampled=!0,[...r.values()]}function ab(e,t,n,r,i,a=0,o=!1){let s=rb(),c=ib(e,s),l=o?ob(s,new Set(c.map(e=>e.pid))):a,u=c.reduce((e,t)=>e+t.rssBytes,l);if(!Number.isSafeInteger(u))throw new D(`Owned aggregate RSS is outside the safe integer range.`);if(u>n.maxAggregateRssBytes)throw new D(`Owned aggregate RSS ${u} exceeded limit ${n.maxAggregateRssBytes}.`);let d=eb(t,r);if(d<n.minFreeDiskBytes)throw new D(`Free disk fell below limit ${n.minFreeDiskBytes}.`);if(i!==void 0&&!Number.isSafeInteger(i))throw new D(`Filesystem output observation overflowed.`);if(r!==void 0&&n.maxNewOutputBytes!==void 0&&i!==void 0&&i>n.maxNewOutputBytes)throw new D(`Positive new filesystem output ${i} exceeded limit ${n.maxNewOutputBytes}.`);return{aggregateRssBytes:u,freeDiskBytes:d,...i===void 0?{}:{newOutputBytes:i},ownedProcessCount:c.length}}function ob(e=rb(),t=new Set){let n=e.get(process.pid);if(n===void 0||n.status.startsWith(`Z`))throw new D(`Runtime setup controller resource observation is unavailable.`);let r=new Set([process.pid]),i=process.memoryUsage().rss;for(let n of r)for(let a of e.values())a.ppid===n&&!a.status.startsWith(`Z`)&&!r.has(a.pid)&&(r.add(a.pid),t.has(a.pid)||(i+=a.rssBytes));if(!Number.isSafeInteger(i))throw new D(`Controller aggregate RSS observation overflowed.`);return i}async function sb(e){if(!e.sampled||e.rootIdentity===void 0)throw new D(`Owned process cleanup cannot be verified without a root identity.`);let t=Date.now()+2e3;for(;;){let n=rb(),r=n.get(e.rootPid);if(r!==void 0&&r.identity!==e.rootIdentity)throw new D(`Owned process group identity changed before cleanup readback.`);let i=[...n.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)),a=[...e.tracked.values()].some(e=>{let t=n.get(e.pid);if(t===void 0||t.status.startsWith(`Z`))return!1;if(t.identity!==e.identity)throw new D(`Tracked process identity changed before cleanup readback.`);return!0});if(!i&&!a)return;if(Date.now()>=t)throw new D(`Owned process cleanup did not release every sampled process.`);await new Promise(e=>setTimeout(e,100))}}function cb(e){if(!e.sampled||e.rootIdentity===void 0)throw new D(`Owned process identity is unknown.`);let t=rb(),n=t.get(e.rootPid);if(n!==void 0&&n.identity!==e.rootIdentity)throw new D(`Owned process group identity changed before cleanup.`);let r=[...e.tracked.values()].flatMap(e=>{let n=t.get(e.pid);if(n===void 0||n.status.startsWith(`Z`))return[];if(n.identity!==e.identity)throw new D(`Tracked process identity changed before cleanup.`);return[n]}),i=[...t.values()].filter(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`));if(i.length>0&&!r.some(t=>t.pgid===e.rootPid))throw new D(`Owned process group has no surviving recorded identity; cleanup is ambiguous.`);let a=t=>{try{process.kill(t,`SIGKILL`)}catch(n){let r=n.code;if(r===`ESRCH`)return;if(r!==`EPERM`)throw n;let i=rb();if(t<0){let t=i.get(e.rootPid);if(t!==void 0&&t.identity!==e.rootIdentity)throw new D(`Owned process group identity changed during cleanup signal readback.`);if([...i.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)))throw n}else{let r=i.get(t);if(r!==void 0&&r.identity!==e.tracked.get(t)?.identity)throw new D(`Tracked process identity changed during cleanup signal readback.`);if(r!==void 0&&!r.status.startsWith(`Z`))throw n}}};i.length>0&&a(-e.rootPid);for(let e of r.reverse())a(e.pid)}var lb=F({pid:j().int().positive(),identity:A().min(1)}),ub=F({schemaVersion:L(`ai-delivery.verification-writer@1`),writerId:fl(),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),owner:lb,command:Wl([F({phase:L(`idle`)}),F({phase:L(`starting`)}),F({phase:L(`running`),root:lb,tracked:N(F({...lb.shape,pgid:j().int().positive()}))})]),stateId:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{stateId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Writer state is corrupt.`})});function db(e,t){if(t===void 0)return;let n=ub.parse(JSON.parse(t.toString(`utf8`)));if(n.worktreeDigest!==hb(e))throw new D(`Verification writer belongs to another worktree.`);let r=rb(),i=r.get(n.owner.pid);if(i?.identity===n.owner.identity&&!i.status.startsWith(`Z`))throw new D(`A live verification writer still owns this worktree.`);if(n.command.phase===`starting`)throw new D(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(n.command.phase===`running`){let e=[n.command.root,...n.command.tracked],t=new Set([n.command.root.pid,...n.command.tracked.map(e=>e.pgid)]);if(e.some(e=>r.has(e.pid))||[...r.values()].some(e=>t.has(e.pgid)))throw new D(`Transition requires identity-bound command and process-group absence.`)}}async function fb(e,t,r,a,s=!1){let l=hb(e),d=w(a??pd(e),`ai-delivery`,`writers@1`,`${l.slice(7)}.json`);return Qv(C(d)),Oy(d,{projectRoot:e,timeout:200,...r?.onLockReleaseError===void 0?{}:{onReleaseError:r.onLockReleaseError},...r?.onLockCompromised===void 0?{}:{onCompromised:r.onLockCompromised},operation:async()=>{await Lb(a??pd(e),l,s);let f=rb(),p=f.get(process.pid);if(p===void 0||p.status.startsWith(`Z`))throw new D(`Verification writer identity is unknown.`);let m;if(r)try{c(d),m=H(d)}catch(e){if(e.code!==`ENOENT`)throw e}else i(d)&&(m=H(d));if(r&&db(e,m),m!==void 0&&!r){let e=ub.parse(JSON.parse(m.toString(`utf8`)));if(e.worktreeDigest!==l)throw new D(`Verification writer belongs to another worktree.`);let t=f.get(e.owner.pid);if(t?.identity===e.owner.identity&&!t.status.startsWith(`Z`))throw new D(`A live verification writer still owns this worktree.`);if(e.command.phase===`starting`)throw new D(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(e.command.phase===`running`){let t={rootPid:e.command.root.pid,rootIdentity:e.command.root.identity,sampled:!0,tracked:new Map(e.command.tracked.map(e=>[e.pid,{...e,ppid:0,rssBytes:0,status:``}]))};cb(t),await sb(t),Sb({state:`recovered`,stageId:`writer`,completedStages:0,reusedStages:0,remainingStages:0,elapsedMs:0,reason:`Recorded interrupted command cleanup confirmed; compatible completed stages remain available.`})}}r&&await r.beforeClaim({previousBytes:m===void 0?void 0:Buffer.from(m),owner:{pid:p.pid,identity:p.identity}});let h={schemaVersion:`ai-delivery.verification-writer@1`,writerId:r?.writerId??he(),worktreeDigest:l,owner:{pid:p.pid,identity:p.identity},command:{phase:`idle`}},g=e=>{h={...h,command:e},ey(d,{...h,stateId:B(h)})};if(r){let e=Buffer.from(`${JSON.stringify({...h,stateId:B(h)},null,2)}\n`);await r.recordClaim(Buffer.from(e));let t;try{c(d),t=H(d)}catch(e){if(e.code!==`ENOENT`)throw e}if(t===void 0!=(m===void 0)||t!==void 0&&m!==void 0&&!t.equals(m))throw new D(`Writer changed after transition intent preservation.`)}g({phase:`idle`});let _={starting:()=>g({phase:`starting`}),observed:e=>{if(e.rootIdentity===void 0)throw new D(`Cannot persist an unknown command owner.`);g({phase:`running`,root:{pid:e.rootPid,identity:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,identity:t,pgid:n}))})},idle:()=>g({phase:`idle`}),assertQuiescent:()=>{let e=ub.parse(JSON.parse(H(d).toString(`utf8`)));if(e.writerId!==h.writerId||e.command.phase!==`idle`)throw new D(`Verification writer command quiescence is not confirmed.`)}},v=async()=>{let e=H(d),t=ub.parse(JSON.parse(e.toString(`utf8`)));if(t.writerId!==h.writerId)throw new D(`Verification writer ownership changed.`);if(t.command.phase===`idle`){if(r&&(await r.recordRelease(Buffer.from(e)),!H(d).equals(e)))throw new D(`Writer changed before recorded release.`);if(x(d),r){let e=u(C(d),`r`);try{o(e)}finally{n(e)}try{c(d)}catch(e){if(e.code!==`ENOENT`)throw e;await r.afterRelease?.();return}throw new D(`Writer absence is not confirmed after recorded release.`)}}};try{return await r?.afterClaim?.(Buffer.from(H(d))),await t(_)}finally{await v()}}})}async function pb(e,t,n){let r=w(pd(e),`ai-delivery`,`writers@1`,`${hb(t).slice(7)}.json`);return Oy(r,{projectRoot:e,timeout:200,operation:async()=>{await Lb(pd(e),hb(t));try{c(r)}catch(e){if(e.code!==`ENOENT`)throw e;return n()}throw new D(`Sealed transition writer absence postcondition drifted.`)}})}async function mb(e,t){fl().parse(e.writerId);let n=fd(e.repoRoot);return fb(e.worktreePath===void 0?n:T(e.worktreePath),async e=>{e.assertQuiescent();let n=await t();return e.assertQuiescent(),n},e,pd(n))}function hb(e){return B(T(e))}function gb(t){let n=[],r=e=>{for(let i of p(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=w(e,i.name);i.isDirectory()?r(a):i.isFile()&&i.name.endsWith(`.js`)&&!i.name.endsWith(`.test.js`)&&n.push({path:a.slice(t.length+1),digest:V(d(a))})}};r(t);let a=new Map,o=t=>{if(a.has(t))return;let n=d(t),r=P({dependencies:Ql(A(),A()).optional()}).parse(JSON.parse(n.toString(`utf8`)));a.set(t,V(n));let s=e(t);for(let e of Object.keys(r.dependencies??{}).sort()){let t;try{t=s.resolve(`${e}/package.json`)}catch{t=s.resolve(e)}let n=C(t);for(;;){let t=w(n,`package.json`);if(i(t)&&P({name:A().optional()}).parse(JSON.parse(d(t,`utf8`))).name===e){o(t);break}let r=C(n);if(r===n)throw new D(`Producer dependency identity is unavailable for ${e}.`);n=r}}};return o(w(C(t),`package.json`)),{code:n,dependencies:[...a].sort(([e],[t])=>e.localeCompare(t))}}function _b(e=C(be(import.meta.url))){return B(gb(e))}function vb(e){return _b(h(e))}function yb(e){return gb(h(e)).dependencies.map(([e,t])=>({source:e,digest:t}))}function bb(e){return xb(JSON.parse(e.toString(`utf8`)))}function xb(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new D(`Invalid run manifest.`);let t=e,n=ng.parse(t.classification),r=lg.parse(t.aggregate),i=cg.array().parse(t.stageReceipts);if(![`ai-delivery.run@1`,`ai-delivery.run@2`,`ai-delivery.run@3`].includes(String(t.schemaVersion)))throw new D(`Run manifest schema version is unsupported.`);if(t.schemaVersion===`ai-delivery.run@1`&&t.resources!==void 0)throw new D(`Historical run manifest has unexpected resource evidence.`);let a=t.resources===void 0?void 0:jy.parse(t.resources);if(t.schemaVersion===`ai-delivery.run@2`&&a===void 0)throw new D(`Historical bounded run lacks resource evidence.`);let o=t.schemaVersion===`ai-delivery.run@3`?F({worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).parse(t.writer):void 0,s={aggregate:r,classification:n,completedAt:t.completedAt,...a===void 0?{}:{resources:a},...o===void 0?{}:{writer:o},schemaVersion:t.schemaVersion,stageReceipts:i};if(typeof t.completedAt!=`string`||t.manifestId!==B(s)||fg({classification:n,receipts:i}).aggregateId!==r.aggregateId)throw new D(`Run manifest identity or aggregate is invalid.`);return{...s,completedAt:t.completedAt,manifestId:t.manifestId}}function Sb(e){process.stderr.write(`ai-delivery.verify ${JSON.stringify(e)}\n`)}function Cb(e,t,n,r,i,a,o,s,c){let[l,...u]=t;if(!l)throw new D(`Policy selected an empty stage command.`);if(n?.aborted)throw new D(`Selected policy stage command cancelled.`);return s?.starting(),new Promise((t,d)=>{let f=ne(`/bin/sh`,[`-c`,`IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null`,`ai-delivery-command`,l,...u],{cwd:c?.cwd??e,detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`],...a?.gate===void 0&&c===void 0?{}:{env:{...c?.environment??process.env,...a?.gate===void 0?{}:{[Ny]:JSON.stringify(a.gate)}}}}),p=[],m=[],h=process.platform===`win32`||f.pid===void 0?void 0:{rootPid:f.pid,sampled:!1,tracked:new Map},g=0,_=0,v=c?.maxCapturedOutputBytes??8388608,y=0,b,x,ee,S=!1,te=!1,re=!1,ie,ae,C,oe=new AbortController,w=()=>{let t=ie===void 0?``:` First filesystem observation: ${ie} Last filesystem observation: ${ae}`;try{let n=Buffer.concat([...p,...m]);return c?.failedOutput?c.failedOutput(n):` Command output ${hg({bytes:n,gitCommonDir:pd(e)})}.${t}`}catch(e){return` Command output persistence failed (${e instanceof Error?e.message:String(e)}).${t}`}},se,T,ce,le=()=>{clearInterval(pe),ce!==void 0&&clearInterval(ce),se!==void 0&&clearTimeout(se),T!==void 0&&clearTimeout(T),n?.removeEventListener(`abort`,me),process.removeListener(`SIGINT`,he),process.removeListener(`SIGTERM`,ge)},ue=()=>{if(f.pid!==void 0){if(h?.sampled){try{ib(h,rb())}catch(e){x??=e instanceof Error?e.message:String(e)}try{s?.observed(h)}catch(e){ee??=e instanceof Error?e.message:String(e)}try{cb(h)}catch(e){x??=e instanceof Error?e.message:String(e)}}else try{f.exitCode===null&&f.signalCode===null&&f.kill(`SIGKILL`),re&&(x??=`owned process identity was not observed before cleanup`)}catch(e){x??=e instanceof Error?e.message:String(e)}}},de=e=>{b===void 0&&(b=e,oe.abort(),ue(),S||(se=setTimeout(()=>{te||S||(te=!0,le(),f.stdout.destroy(),f.stderr.destroy(),f.unref(),c?.onCleanupFailure?.(`Owned command pipes did not close; descendant cleanup could not be verified.`),d(new D(`Selected policy stage command failed (${b}).${w()}${ee===void 0?``:` Writer state persistence failed (${ee}).`} Owned process cleanup failed (owned command pipes did not close; descendant cleanup could not be verified).`)))},2e3)))},fe=(e,t)=>{if(g+=t.length,c?.onCaptured?.(g),c!==void 0&&i?.maxNewOutputBytes!==void 0&&g+y>i.maxNewOutputBytes){de(`source-phase captured output exceeded remaining cumulative allowance`);return}if(g>v){let n=v-_;n>0&&(e.push(Buffer.from(t.subarray(0,n))),_+=Math.min(n,t.length)),de(c?.maxCapturedOutputBytes===void 0?`captured output exceeded 8 MiB`:`captured output exceeded ${v} bytes`);return}e.push(t),_+=t.length};f.stdout.on(`data`,e=>fe(p,e)),f.stderr.on(`data`,e=>fe(m,e)),f.stdout.once(`error`,e=>de(e.message)),f.stderr.once(`error`,e=>de(e.message)),f.stdin.once(`error`,e=>de(e.message)),f.once(`error`,e=>{f.pid===void 0&&s?.idle(),de(e.message)}),f.once(`exit`,(e,t)=>{e!==0||t!==null?de(`exit ${String(e)}${t===null?``:` signal ${t}`}`):S||(T=setTimeout(()=>{S||de(`owned command pipes did not close after direct child exit`)},1e3))}),f.once(`spawn`,()=>{let t=()=>{if(b===void 0&&f.pid!==void 0)try{if(h===void 0)throw new D(`Owned process identity is unavailable on this platform.`);if(ib(h,rb()),s?.observed(h),i!==void 0){let t=ab(h,e,i,a,void 0,c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(S||C!==void 0)return;C=(async()=>{if(i!==void 0&&a!==void 0){let t=await Qy(a,oe.signal,re,e=>{ie??=e,ae=e,r?.(g,void 0,e)});if(b!==void 0)return;y=t;let n=ab(h,e,i,a,t+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(n),r?.(g,n)}b===void 0&&!re&&(re=!0,f.stdin.end(`run
288
+ `))})().catch(e=>de(e instanceof Error?e.message:String(e))).finally(()=>{C=void 0})}catch(e){de(e instanceof Error?e.message:String(e))}};t(),ce=setInterval(t,1e3),ce.unref()});let pe=setInterval(()=>r?.(g),5e3);pe.unref();let me=()=>de(`cancelled`),he=()=>de(`cancelled by SIGINT`),ge=()=>de(`cancelled by SIGTERM`);n?.addEventListener(`abort`,me,{once:!0}),process.once(`SIGINT`,he),process.once(`SIGTERM`,ge),n?.aborted&&me();let _e=async(n,l)=>{if(S=!0,!te){if(await C,b===void 0&&h!==void 0)try{if(i!==void 0){let t=ab(h,e,i,a,a===void 0?void 0:await Qy(a,oe.signal)+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(!h.sampled)throw new D(`Owned process resource observation was unavailable.`);if(ib(h,rb()).length>0)throw new D(`A sampled owned descendant survived command exit.`)}catch(e){de(e instanceof Error?e.message:String(e))}if(b!==void 0||n!==0||l!==null){let e=b??`exit ${String(n)}${l===null?``:` signal ${l}`}`,t=f.pid===void 0||!re;if(h!==void 0&&h.sampled)try{await sb(h),t=!0}catch(e){x??=e instanceof Error?e.message:String(e)}if(t)try{s?.idle()}catch(e){ee??=e instanceof Error?e.message:String(e)}te=!0,x!==void 0&&c?.onCleanupFailure?.(x),d(new D(`Selected policy stage command failed (${e}). Command exit ${String(n)}${l===null?``:` signal ${l}`}.${w()}${ee===void 0?``:` Writer state persistence failed (${ee}).`}${x===void 0?``:` Owned process cleanup failed (${x}).`}`));return}s?.idle(),te=!0,t(c?.stdoutOnly?Buffer.concat(p):Buffer.concat([...p,...m],g))}};f.once(`close`,(e,t)=>{_e(e,t).catch(e=>{te=!0,d(e)}).finally(le)})})}var wb=A().regex(/^sha256:[a-f0-9]{64}$/u),Tb=A().regex(/^[a-f0-9]{40}$/u),Eb=F({path:A().min(1),digest:wb}),Db=Eb.extend({device:j().int().nonnegative().safe(),inode:j().int().nonnegative().safe(),uid:j().int().nonnegative().safe(),mode:j().int().nonnegative().safe()}),Ob=F({argv:N(A()).min(1),cwd:A().min(1),executable:Db}),kb=F({head:Tb,indexTree:Tb,branch:A().min(1),configDigest:wb,dirty:N(F({path:A().min(1),digest:wb.nullable()}))}),Ab=F({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:N(A().min(1)).min(1)}),jb=F({phaseId:wb,recordId:wb,baselineId:wb.optional(),authorizationDigest:wb}),Mb=F({repoRoot:A().min(1),issueNumber:j().int().positive().safe(),identity:A().min(1),rowDigest:wb,controller:F({head:Tb,configDigest:wb,admissionId:wb,runtimeEntryPath:A().min(1),packageVersion:A().min(1),archiveDigest:wb}),source:kb.extend({path:A().min(1),effect:Kl(`kind`,[F({kind:L(`preserve`)}),F({kind:L(`commitOnce`),parent:Tb,tree:Tb,configDigest:wb.optional()})])}),caller:Eb,authorization:Eb,inputs:N(Eb),commands:N(Ob).min(1),commandGraphDigest:wb,environment:F({digest:wb,overrides:Ql(A(),A().nullable())}),bounds:Ab,completionArtifacts:N(A().min(1)),reconciliation:jb.optional()}).omit({environment:!0}).extend({environmentDigest:wb}),Nb=F({roots:N(A().min(1)).min(1),files:N(Xl([A(),j().int().nonnegative().safe()])),links:N(Xl([A(),F({identity:A(),target:A(),missing:M()})])),baselineId:wb}),Pb=F({index:j().int().nonnegative().safe(),outputDigest:wb.nullable(),outputBytes:j().int().nonnegative().safe(),status:I([`complete`,`failed`])}),Fb=F({source:kb,artifacts:N(Db),newOutputBytes:j().int().nonnegative().safe(),writerReleased:L(!0),lockReleased:L(!0)}),Ib=F({schemaVersion:L(`ai-delivery.source-phase@1`),phaseId:wb,recordId:wb,worktreeDigest:wb,bindingDigest:wb,authorizationDigest:wb,status:I([`preparing`,`intent`,`complete`,`failed-quiescent`,`rejected-before-work`,`unresolved`]),writerId:fl(),binding:Mb.optional(),baseline:Nb.optional(),allocation:Ab.optional(),owner:F({pid:j().int().positive().safe(),identity:A().min(1)}),bootstrapFiles:N(Xl([A(),j().int().nonnegative().safe()])),bootstrapBytes:j().int().nonnegative().safe(),capturedBytes:j().int().nonnegative().safe(),nextCommandIndex:j().int().nonnegative().safe(),commands:N(Pb),claimDigest:wb.optional(),releaseDigest:wb.optional(),preparationArtifact:Db.optional(),writerArtifact:Db.optional(),producerDigest:wb.optional(),actor:F({identity:A().min(1),actorLogin:A().min(1),credentialIdentity:A().min(1)}).optional(),retainedArtifacts:N(Db).optional(),retainedPredecessors:N(F({phaseId:wb,recordId:wb})),reconciliation:jb.optional(),result:Fb.optional(),failure:F({operation:A().optional(),accounting:A().optional(),cleanup:A().optional(),writerRelease:A().optional(),lockRelease:A().optional()}).optional()}).superRefine((e,t)=>{let{recordId:n,...r}=e;if((n!==B(r)||e.phaseId!==e.bindingDigest)&&t.addIssue({code:`custom`,message:`Source-phase record identity is invalid.`}),e.binding!==void 0&&B(e.binding)!==e.bindingDigest&&t.addIssue({code:`custom`,message:`Source-phase input binding is invalid.`}),e.baseline!==void 0){let{baselineId:n,...r}=e.baseline;n!==B(r)&&t.addIssue({code:`custom`,message:`Source-phase baseline is invalid.`})}e.status===`rejected-before-work`&&(e.commands.length!==0||e.nextCommandIndex!==0||e.capturedBytes!==0)&&t.addIssue({code:`custom`,message:`Rejected source-phase input cannot contain executed work.`}),e.status===`complete`&&(e.result===void 0||e.baseline===void 0||e.binding===void 0||e.failure!==void 0)&&t.addIssue({code:`custom`,message:`Source-phase completion is incomplete.`}),e.status===`complete`&&(e.commands.length!==e.binding?.commands.length||e.nextCommandIndex!==e.commands.length||e.commands.some((e,t)=>e.index!==t||e.status!==`complete`))&&t.addIssue({code:`custom`,message:`Source-phase completion does not contain its exact successful command graph.`})});async function Lb(e,t,n=!1){let r=w(e,`ai-delivery`,`receipts`,`source-phase@1`,t.slice(7)),i;try{let e=c(r);if(!e.isDirectory()||e.isSymbolicLink())throw new D(`Source-phase admission metadata is not a canonical directory.`);i=p(r)}catch(e){if(e.code===`ENOENT`)return;throw e}if(i.length>1e5)throw new D(`Source-phase admission exceeded its entry bound.`);for(let e of i){let i=Ib.parse(JSON.parse(H(w(r,e)).toString(`utf8`)));if(i.worktreeDigest!==t||e!==`${i.phaseId.slice(7)}.json`)throw new D(`Source-phase admission record belongs to another input or worktree.`);if(i.status===`preparing`||i.status===`intent`)throw new D(`An unsealed source phase still excludes another worktree writer.`);if(n&&i.status===`unresolved`)throw new D(`Unresolved source phase requires owning reconciliation before another attempt.`);await new Promise(e=>setImmediate(e))}}F({status:L(`complete`),phaseId:wb,recordId:wb,source:kb,commands:N(Pb)});var Rb=F({schemaVersion:L(`ai-delivery.runtime-output@1`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),limit:j().int().positive().safe().max(8*1024**2),outputs:N(F({digest:A().regex(/^sha256:[a-f0-9]{64}$/u),bytes:j().int().nonnegative().safe().max(8*1024**2),status:I([`reserved`,`complete`])})).max(4096),contentDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{contentDigest:n,...r}=e;(n!==B(r)||new Set(e.outputs.map(e=>e.digest)).size!==e.outputs.length||e.outputs.reduce((e,t)=>e+t.bytes,0)>e.limit)&&t.addIssue({code:`custom`,message:`Runtime retained-output ledger is corrupt.`})});async function zb(e,t,n){let r=new AbortController,i=n?.signal===void 0?r.signal:AbortSignal.any([n.signal,r.signal]),a,o,s=0,c=Date.now(),l=()=>{if(a!==void 0)throw a;if(i.aborted)throw new D(`Runtime setup cancelled.`);let t=n===void 0?0:ob();if(n!==void 0){if(t>n.bounds.maxAggregateRssBytes)throw new D(`Controller aggregate RSS ${t} exceeded limit ${n.bounds.maxAggregateRssBytes}.`);tb(e,n.bounds,o)}return t};if(n!==void 0){if(My(n.bounds),!Number.isSafeInteger(n.maxCapturedOutputBytes)||n.maxCapturedOutputBytes<=0||n.maxCapturedOutputBytes>8*1024**2)throw new D(`Invalid runtime setup captured-output bound; maximum is 8 MiB.`);l()}return e=fd(e),fb(e,async u=>Yy(e,n!==void 0,async d=>{let f,p,m=pd(e),h=()=>{if(f===void 0||p===void 0)throw new D(`Runtime output allowance is unbound.`);let{contentDigest:e,...t}=f;if(f=Rb.parse({...t,contentDigest:B(t)}),Buffer.byteLength(JSON.stringify(f,null,2))>1024**2)throw new D(`Runtime retained-output ledger exceeds its evidence bound.`);ey(p,f)},g=e=>{try{if(gg({gitCommonDir:m,digest:e.digest,expectedBytes:e.bytes}).length!==e.bytes)throw new D(`Runtime retained-output evidence size changed.`);return!0}catch(t){if(e.status===`reserved`&&t.code===`ENOENT`)return!1;throw t}},_=t=>{if(n===void 0)return;if(f!==void 0)throw new D(`Runtime output allowance is already bound.`);let r={stageId:t,worktreeDigest:hb(e),producerDigest:_b(),limit:n.maxCapturedOutputBytes};p=w(m,`ai-delivery`,`verification@1`,`runtime-output`,r.worktreeDigest.slice(7),`${t.slice(7)}.json`);let i;try{i=H(p,{maxBytes:1024**2})}catch(e){if(e.code!==`ENOENT`)throw e}if(i!==void 0){if(f=Rb.parse(JSON.parse(i.toString(`utf8`))),f.stageId!==r.stageId||f.worktreeDigest!==r.worktreeDigest||f.producerDigest!==r.producerDigest||f.limit!==r.limit)throw new D(`Runtime retained-output ledger belongs to an incompatible stage or controller.`);let e=!1;for(let t of f.outputs)g(t)&&t.status===`reserved`&&(t.status=`complete`,e=!0);e&&h()}else{let e={schemaVersion:`ai-delivery.runtime-output@1`,...r,outputs:[]};f=Rb.parse({...e,contentDigest:B(e)}),h()}},v=()=>{if(n===void 0)return 8*1024**2;if(f===void 0)throw new D(`Runtime output allowance is unbound.`);return f.limit-f.outputs.reduce((e,t)=>e+t.bytes,0)},y=e=>{if(f===void 0)throw new D(`Runtime output allowance is unbound.`);let t=V(e),n=f.outputs.find(e=>e.digest===t);if(n!==void 0){if(n.bytes!==e.length||!g(n))throw new D(`Runtime retained-output reservation is unresolved; identical output cannot be rewritten.`);return` Command output ${t}.`}if(e.length>v())throw new D(`Runtime retained-output allowance exceeded.`);let r={digest:t,bytes:e.length,status:`reserved`};if(f.outputs.push(r),h(),hg({bytes:e,gitCommonDir:m}),!g(r))throw new D(`Runtime retained-output publication is unresolved.`);return f.outputs[f.outputs.length-1].status=`complete`,h(),` Command output ${t}.`};if(n!==void 0){let t=[...n.bounds.outputRoots??[],w(pd(e),`ai-delivery`)].map(t=>T(e,t)).sort(),r=t.filter((e,n)=>!t.slice(0,n).some(t=>e===t||e.startsWith(`${t}${ce}`))),a=new Map,s=await Gy(d,`scan`,()=>Zy(r,a),i);o={roots:r,links:a,files:s,baselineId:B([...s]),...d===void 0?{}:{gate:d}}}let b=async()=>{let t=l();if(n===void 0||o===void 0)return;let r=s+await Qy(o,i);if(l(),r>n.bounds.maxNewOutputBytes)throw new D(`Runtime setup output ${r} exceeded limit ${n.bounds.maxNewOutputBytes}.`);Sb({state:`running`,stageId:`runtime-setup`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:s,sampledAggregateRssBytes:t,sampledFreeDiskBytes:eb(e,o),sampledNewOutputBytes:r})};await b();let x=n===void 0?void 0:setInterval(()=>{try{l()}catch(e){a??=e instanceof Error?e:new D(String(e)),r.abort()}},1e3);x?.unref();try{let r=await t({assertQuiescent:()=>u.assertQuiescent(),bindCapturedOutput:_,checkResources:b,signal:i,run:async(t,r,a,o,l)=>{await b(),My(r);let f=r.outputRoots?.map(t=>T(e,t)).sort();if(f!==void 0){for(let e=1;e<f.length;e++)if(f[e]===f[e-1]||f[e].startsWith(`${f[e-1]}${ce}`))throw new D(`Filesystem output roots must not overlap.`)}let p=async d=>{let p=v();if(p<=0)throw new D(`Runtime retained-output allowance is exhausted; installer was not started.`);let m=new Map,h=f===void 0?void 0:await Gy(d,`scan`,()=>Zy(f,m),i),g=f===void 0||h===void 0?void 0:{roots:f,files:h,links:m,baselineId:B([...h]),...d===void 0?{}:{gate:d}};tb(e,r,g);let _=0,x=await Cb(e,t,a===void 0?i:AbortSignal.any([i,a]),(e,t,n)=>Sb({state:`running`,stageId:`runtime-setup:install`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:e,...n===void 0?{}:{reason:n},...t===void 0?{}:{sampledAggregateRssBytes:t.aggregateRssBytes,sampledFreeDiskBytes:t.freeDiskBytes,sampledNewOutputBytes:t.newOutputBytes}}),r,g,void 0,u,n===void 0&&o===void 0&&l===void 0?void 0:{environment:o??process.env,...l===void 0?{}:{cwd:l},...n===void 0?{}:{maxCapturedOutputBytes:p,includeControllerTree:!0,failedOutput:y},onCaptured:e=>{s+=e-_,_=e}});return await b(),x};return n===void 0?Yy(e,f!==void 0,p):p(d)}});return await b(),Sb({state:`completed`,stageId:`runtime-setup`,completedStages:1,reusedStages:0,remainingStages:0,elapsedMs:Date.now()-c}),r}catch(e){throw a===void 0?i.aborted?new D(`Runtime setup cancelled. ${e instanceof Error?e.message:String(e)}`):e:new D(`${a.message} Runtime setup operation failed (${e instanceof Error?e.message:String(e)}).`)}finally{x!==void 0&&clearInterval(x)}}))}var Bb=`.issue-cli`;function Vb(e){let t=e??process.cwd(),n=T(t,Bb);return i(n)||l(n,{recursive:!0}),n}var Hb=`${Bb}/worktrees.json`,Ub=F({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:I([`active`,`error`,`merged`,`pr-published`,`stale`]),type:L(`issue`),updatedAt:A().min(1)}).transform(({prNumber:e,...t})=>({...t,...e===void 0?{}:{prNumber:e}})),Wb=F({schemaVersion:L(`ai-delivery.committed-continuation-plan@1`),planId:R,repository:A().min(1),repoRoot:A().min(1),configDigest:R,currentRuntime:oy,row:Ub,replacement:Ub,head:xd,terminalHead:xd,terminalMergeId:R,operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1),preserved:N(F({path:A().min(1),digest:R})).min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e,{prNumber:i,identity:a,status:o,updatedAt:s,...c}=e.row,{identity:l,status:u,updatedAt:d,...f}=e.replacement;(n!==B(r)||e.row.status!==`merged`||!e.row.prNumber||e.replacement.status!==`active`||e.replacement.prNumber!==void 0||z(c)!==z(f)||e.head.sha===e.terminalHead.sha||new Set(e.preserved.map(e=>e.path)).size!==e.preserved.length)&&t.addIssue({code:`custom`,message:`Committed continuation plan identity or disposition is invalid.`})}),Gb=F({schemaVersion:L(`ai-delivery.committed-continuation-intent@1`),intentId:R,plan:Wb,authorityCommentId:j().int().positive(),acceptanceCommentId:j().int().positive()}).superRefine(({intentId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Continuation intent identity is invalid.`})}),Kb=F({schemaVersion:L(`ai-delivery.committed-continuation-completion@1`),completionId:R,intentId:R,planId:R,row:Ub,head:xd,completed:L(!0)}).superRefine(({completionId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Continuation completion identity is invalid.`})});function qb(e,t,n){return w(pd(e),`ai-delivery`,`continuations`,String(t),`${n}.plan.json`)}function Jb(e){return qb(e.repoRoot,e.row.issueNumber,e.head.sha).replace(/\.plan\.json$/u,`.intent.json`)}function Yb(e){return Jb(e).replace(/\.intent\.json$/u,`.completion.json`)}function Xb(e,t){return w(pd(e.repoRoot),`ai-delivery`,`continuations`,`evidence`,`${t.slice(7)}.bin`)}function Zb(e,t=!1){for(let n of e.preserved)if(V(H(n.path))!==n.digest||t&&V(H(Xb(e,n.digest)))!==n.digest)throw Error(`Committed continuation original evidence changed.`);if(t){let t=Buffer.from(z(e.row));if(!H(Xb(e,V(t))).equals(t))throw Error(`Committed continuation original row beforeimage changed.`)}}function Qb(e,t){let n=w(pd(t),`ai-delivery`,`continuations`,String(e));if(!i(n))return;let r;for(let a of p(n).filter(e=>e.endsWith(`.intent.json`)).sort()){let o=Gb.parse(JSON.parse(H(w(n,a)).toString(`utf8`))),s=o.plan;if(s.repoRoot!==T(t)||s.row.issueNumber!==e||w(n,a)!==Jb(s))throw Error(`Committed continuation checkpoint identity disagrees.`);Zb(s,!0);let c=Yb(s);if(i(c)){let e=Kb.parse(JSON.parse(H(c).toString(`utf8`)));if(e.intentId!==o.intentId||e.planId!==s.planId||z(e.row)!==z(s.replacement)||z(e.head)!==z(s.head))throw Error(`Committed continuation completion disagrees with its intent.`);rx(s.replacement,t),sx(t,n,!1),sx(t,C(Xb(s,s.preserved[0].digest)),!1),ox(c)}else{if(r)throw Error(`Issue has multiple incomplete committed continuations.`);r=o}}return r}function $b(e){if(!e.identity)throw Error(`ai-delivery worktree ownership requires the preparing identity.`);return{branch:e.branch,identity:e.identity,...e.issueNumber===void 0?{}:{issueNumber:e.issueNumber},path:e.path,...e.prNumber===void 0||e.type===`issue`?{}:{prNumber:e.prNumber},schemaVersion:`ai-delivery.worktree-owner@1`,type:e.type}}function ex(e,t){let n=B($b(t)).slice(7);return w(pd(e),`ai-delivery`,`worktree-owners`,`${n}.json`)}function tx(e,t){if(e.type!==`issue`||e.issueNumber===void 0)return;let n=w(pd(t),`ai-delivery`,`worktree-owners`,`issue-${String(e.issueNumber)}.transition.json`);try{c(n)}catch(e){if(e.code===`ENOENT`)return;throw Error(`Worktree transition is incomplete or unreadable.`)}try{let r=JSON.parse(H(n).toString(`utf8`)),{intentId:i,...a}=r,{planId:o,...s}=r.plan;if(r.schemaVersion!==`ai-delivery.worktree-transition-intent@1`||i!==B(a)||o!==B(s)||r.plan.repoRoot!==T(t)||r.plan.row.issueNumber!==e.issueNumber)throw Error(`Invalid transition intent.`);if(r.plan.purpose===`merged-cleanup`)throw Error(`Worktree transition is terminal and cannot authorize ordinary source operations.`);let c=w(`${n}.evidence`,`completion.json`),l=JSON.parse(H(c).toString(`utf8`)),{completionId:u,...d}=l;if(l.schemaVersion!==`ai-delivery.worktree-transition-completion@1`||l.planId!==o||l.intentId!==i||l.completed!==!0||u!==B(d)||JSON.stringify($b(e))!==JSON.stringify($b(r.plan.row)))throw Error(`Invalid transition completion.`);return}catch(e){throw e instanceof Error&&e.message.includes(`transition is terminal`)?e:Error(`Worktree transition is incomplete or unreadable; resume its exact approved plan.`)}}function nx(e,t){if(e.issueNumber!==void 0&&Ex(e.issueNumber,t),tx(e,t),e.issueNumber!==void 0&&Qb(e.issueNumber,t))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);rx(e,t)}function rx(e,t){let n=$b(e),r=ex(t,e),i;try{i=JSON.parse(H(r).toString(`utf8`))}catch{throw Error(`Worktree lacks its exact ai-delivery ownership witness.`)}if(JSON.stringify(i)!==JSON.stringify({...n,ownerId:B(n)}))throw Error(`Worktree ownership witness disagrees with the canonical registry identity.`)}function ix(e,t,n=!1){if(Ex(e,t),Qb(e,t)&&!n)throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);let r=w(pd(t),`ai-delivery`,`worktree-owners`,`issue-${String(e)}.transition.json`);try{c(r)}catch(e){if(e.code===`ENOENT`)return;throw Error(`Worktree transition is incomplete or unreadable.`)}let i;try{if(i=JSON.parse(H(r).toString(`utf8`)).plan.row,i.type!==`issue`||i.issueNumber!==e)throw Error(`Transition embedded issue identity disagrees.`)}catch{throw Error(`Worktree transition is incomplete or unreadable.`)}tx(i,t)}function ax(e,t,n=!1){let r=$b(e);wd(ex(t,e),Buffer.from(JSON.stringify({...r,ownerId:B(r)}))),n||nx(e,t)}function ox(e){let t=u(C(e),`r`);try{o(t)}finally{n(t)}}function sx(e,t,n=!0){let r=w(pd(e),`ai-delivery`),i=[r,w(r,`continuations`),t],a=(e,t)=>{let n;try{n=c(e)}catch(e){if(t&&e.code===`ENOENT`)return;throw e}if(!n.isDirectory()||n.isSymbolicLink()||e!==r&&n.mode&63)throw Error(`Committed continuation evidence requires a private directory.`)};for(let e of i)a(e,n&&e!==r);n&&Qv(t);for(let e of i)a(e,!1),ox(e)}async function cx(e,t){let n=e.repoRoot;if(Qb(e.row.issueNumber,n))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);return dx(n),Oy(Hb,{projectRoot:n,timeout:5e3,operation:async()=>{let r=px(n),i=r.worktrees.filter(t=>t.type===`issue`&&t.issueNumber===e.row.issueNumber);if(i.length>1)throw Error(`Transition has duplicate canonical issue rows.`);if(r.worktrees.some(t=>!i.includes(t)&&_x(t,e.row)))throw Error(`Transition conflicts with another canonical registry path, branch or PR identity.`);let a=i[0],o={...e.row,...e.row.prNumber===void 0?{}:{prNumber:e.row.prNumber}},s=e.purpose===`active-resume`?o:{...o,prNumber:e.terminalPrNumber,status:`merged`};if(a!==void 0&&![o,s].some(e=>z(a)===z(e)))throw Error(`Transition canonical row drifted.`);let c=w(pd(n),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`),l=()=>{if(JSON.parse(H(c).toString(`utf8`)).plan?.planId!==e.planId)throw Error(`Transition lacks its exact durable intent.`)};return t({current:a,writeOwner:()=>{l(),ax(s,n,!0)},commitRow:()=>{if(l(),a===void 0)throw Error(`Transition cannot recreate a removed canonical row.`);return r.worktrees.splice(r.worktrees.indexOf(a),1,s),a=s,xx(n,r),s},removeRow:()=>{if(l(),e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw Error(`Transition lacks explicit unheld terminal source disposition.`);a!==void 0&&(r.worktrees.splice(r.worktrees.indexOf(a),1),xx(n,r),a=void 0)}})}})}function lx(e){let t=e.row,n=$b(t);if(z(JSON.parse(H(ex(e.repoRoot,t)).toString(`utf8`)))!==z({...n,ownerId:B(n)}))throw Error(`Sealed transition owner witness drifted.`)}function ux(e){return px(e??process.cwd()).worktrees}function dx(e){Vb(e)}function fx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function px(e){let t=T(e,Hb);if(!i(t))return{worktrees:[]};try{let e=d(t,`utf8`),n=JSON.parse(e);if(!fx(n)||Object.keys(n).length!==1||!Array.isArray(n.worktrees))throw Error(`Registry must be an object with a worktrees array.`);return{worktrees:n.worktrees.map((e,t)=>mx(e,t))}}catch(e){throw Error(`Unable to read worktree registry: ${e instanceof Error?e.message:String(e)}`)}}function mx(e,t){if(!fx(e))throw Error(`worktrees[${String(t)}] must be an object.`);let n=new Set([`branch`,`createdAt`,`identity`,`issueNumber`,`path`,`prNumber`,`status`,`type`,`updatedAt`]),r=Object.keys(e).filter(e=>!n.has(e));if(r.length>0)throw Error(`worktrees[${String(t)}] has unsupported fields: ${r.join(`, `)}.`);let i=vx(e.branch,`worktrees[${String(t)}].branch`),a=vx(e.createdAt,`worktrees[${String(t)}].createdAt`),o=vx(e.path,`worktrees[${String(t)}].path`),s=bx(e.type,`worktrees[${String(t)}].type`),c=yx(e.status,`worktrees[${String(t)}].status`),l=gx(e.identity,`worktrees[${String(t)}].identity`),u=hx(e.issueNumber,`worktrees[${String(t)}].issueNumber`),d=hx(e.prNumber,`worktrees[${String(t)}].prNumber`),f=vx(e.updatedAt,`worktrees[${String(t)}].updatedAt`);if(s===`issue`&&u===void 0)throw Error(`worktrees[${String(t)}].issueNumber is required for issue worktrees.`);return{branch:i,createdAt:a,...l===void 0?{}:{identity:l},...u===void 0?{}:{issueNumber:u},path:o,...d===void 0?{}:{prNumber:d},status:c,type:s,updatedAt:f}}function hx(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer.`);return e}}function gx(e,t){if(e!==void 0)return vx(e,t)}function _x(e,t){return e.path===t.path||e.branch===t.branch||e.issueNumber!==void 0&&t.issueNumber!==void 0&&e.issueNumber===t.issueNumber||e.prNumber!==void 0&&t.prNumber!==void 0&&e.prNumber===t.prNumber}function vx(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string.`);return e}function yx(e,t){if(e===`merged`||e===`pr-published`||e===`active`||e===`error`||e===`stale`)return e;throw Error(`${t} is invalid.`)}function bx(e,t){if(e===`issue`||e===`pr`||e===`standalone`)return e;throw Error(`${t} is invalid.`)}function xx(e,t){dx(e);let n=T(e,Hb);try{$v(n,t)}catch(e){throw Error(`Unable to save worktree registry: ${e instanceof Error?e.message:String(e)}`)}}var Sx=F({schemaVersion:L(`ai-delivery.investigation-preparation@1`),preparationId:R,repository:yd,repoRoot:A().min(1),row:Ub,head:xd,physical:F({device:j().int().nonnegative().safe(),inode:j().int().nonnegative().safe(),gitDirectory:A().min(1),gitDevice:j().int().nonnegative().safe(),gitInode:j().int().nonnegative().safe()}),operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1)}).superRefine(({preparationId:e,...t},n)=>{(e!==B(t)||t.row.status!==`active`||t.row.prNumber!==void 0||t.row.branch!==`issue/${String(t.row.issueNumber)}`||t.row.path!==w(t.repoRoot,`.worktrees`,`issue-${String(t.row.issueNumber)}`)||t.operator.actorLogin.toLowerCase()===t.reviewerActor.toLowerCase())&&n.addIssue({code:`custom`,message:`Investigation preparation identity is invalid.`})}),Cx=F({schemaVersion:L(`ai-delivery.investigation-completion-intent@1`),intentId:R,preparationId:R,resultDigest:R,authorityCommentId:j().int().positive().safe(),acceptanceCommentId:j().int().positive().safe(),registryBeforeimage:R,authorityDigest:R}).superRefine(({intentId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Investigation intent is corrupt.`})}),wx=F({schemaVersion:L(`ai-delivery.investigation-completion@1`),completionId:R,intentId:R,preparationId:R,completed:L(!0)}).superRefine(({completionId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Investigation completion is corrupt.`})});function Tx(e,t){return w(pd(e),`ai-delivery`,`investigations`,String(t))}function Ex(e,t){let n=w(Tx(t,e),`intent.json`);try{c(n)}catch(e){if(e.code===`ENOENT`)return;throw e}throw Error(`Investigation completion is pending or terminal; resume only its exact completion.`)}function Dx(e){return JSON.parse(H(e,{maxBytes:1048576}).toString(`utf8`))}function Ox(e,t){let n=w(Tx(e,t),`preparation.json`);try{c(n)}catch(e){if(e.code===`ENOENT`)return;throw e}let r=Sx.parse(Dx(n));if(r.repoRoot!==e||r.row.issueNumber!==t)throw Error(`Investigation preparation belongs to another repository or issue.`);return r}function kx(e,t){return F({commentId:j().int().positive().safe(),url:ml(),body:A().min(1)}).parse(Dx(w(Tx(e,t),`acknowledgement.json`)))}function Ax(e,t){let n=Tx(e,t),r=pd(e);for(let e of[w(r,`ai-delivery`),w(r,`ai-delivery`,`investigations`),n])try{let t=c(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`Investigation custody directory is unsafe.`)}catch(e){if(e.code!==`ENOENT`)throw e}return Qv(n),n}function jx(e){let t=w(e,Bb),n=c(t);if(!n.isDirectory()||n.isSymbolicLink())throw Error(`Canonical registry directory is unsafe.`);let r=w(e,Hb);if(i(r)){let e=c(r);if(!e.isFile()||e.isSymbolicLink()||e.nlink!==1)throw Error(`Canonical registry file is unsafe.`)}}function Mx(e,t){let n=e.worktrees.filter(e=>_x(e,t.row));if(n.length>1||n[0]!==void 0&&z(n[0])!==z(t.row))throw Error(`Investigation conflicts with canonical registry custody.`);return n[0]}async function Nx(e,t){let n=Sx.parse(e),r=n.repoRoot,i=n.row.issueNumber;ix(i,r),dx(r),jx(r),await Oy(Hb,{projectRoot:r,timeout:5e3,operation:async()=>{ix(i,r);let e=px(r),a=Ox(r,i);if(a===void 0&&e.worktrees.some(e=>_x(e,n.row)))throw Error(`Legacy custody cannot be adopted as a current investigation.`);let o=Mx(e,n);if(a!==void 0&&z(a)!==z(n))throw Error(`Investigation baseline cannot be replaced.`);let s=Ax(r,i);wd(w(s,`preparation.json`),Buffer.from(z(n)));let c=await t();if(wd(w(s,`acknowledgement.json`),Buffer.from(z(c))),ax(n.row,r),o===void 0&&(e.worktrees.push(n.row),xx(r,e)),Mx(px(r),n)===void 0)throw Error(`Investigation registration readback is missing.`)}})}async function Px(e){let t=Sx.parse(e.preparation),n=t.repoRoot,r=t.row.issueNumber;return dx(n),jx(n),Oy(Hb,{projectRoot:n,timeout:5e3,operation:async()=>{if(z(Ox(n,r))!==z(t))throw Error(`Investigation preparation drifted.`);if(tx(t.row,n),Qb(r,n))throw Error(`Committed continuation is incomplete.`);rx(t.row,n);let a=Tx(n,r),o=w(a,`intent.json`),s=w(a,`completion.json`),c=i(o)?Cx.parse(Dx(o)):void 0,l=i(s)?wx.parse(Dx(s)):void 0,u=px(n),f=Mx(u,t);if(f===void 0&&c===void 0)throw Error(`Investigation row disappeared without a removal intent.`);if(l!==void 0&&(c===void 0||f!==void 0||l.intentId!==c.intentId||l.preparationId!==t.preparationId))throw Error(`Investigation completion custody is inconsistent.`);let p=V(e.result);if(c!==void 0&&(c.preparationId!==t.preparationId||c.resultDigest!==p||c.authorityCommentId!==e.authorityCommentId||c.acceptanceCommentId!==e.acceptanceCommentId))throw Error(`Resume requires the same exact investigation intent and evidence.`);if(c!==void 0){for(let e of[c.resultDigest,c.registryBeforeimage,c.authorityDigest])if(V(H(w(a,`${e.slice(7)}.bin`)))!==e)throw Error(`Preserved investigation evidence changed.`)}e.assertSource(c!==void 0);let m=await e.authorize();if(e.assertSource(c!==void 0),e.dryRun)return{completed:!1,replayed:c!==void 0};if(l!==void 0)return{completed:!0,replayed:!0,receiptPath:s};let h=c;if(h===void 0){let r=d(w(n,Hb)),i=Buffer.from(z(m));for(let t of[e.result,r,i]){let e=V(t);wd(w(a,`${e.slice(7)}.bin`),t,e)}let s={schemaVersion:`ai-delivery.investigation-completion-intent@1`,preparationId:t.preparationId,resultDigest:p,authorityCommentId:e.authorityCommentId,acceptanceCommentId:e.acceptanceCommentId,registryBeforeimage:V(r),authorityDigest:V(i)};h=Cx.parse({...s,intentId:B(s)}),wd(o,Buffer.from(z(h)))}if(e.assertSource(c!==void 0),e.removeSource(),e.assertSource(!0),f!==void 0&&(u.worktrees.splice(u.worktrees.indexOf(f),1),xx(n,u)),Mx(px(n),t)!==void 0)throw Error(`Investigation registry removal readback failed.`);let g={schemaVersion:`ai-delivery.investigation-completion@1`,intentId:h.intentId,preparationId:t.preparationId,completed:!0};return wd(s,Buffer.from(z({...g,completionId:B(g)}))),{completed:!0,replayed:c!==void 0,receiptPath:s}}})}function Fx(e,t){let n=se(w(e,`.worktrees`),t);if(n===``||n.startsWith(`..`)||n.startsWith(`/`))throw new D(`Worktree path must be inside the repository .worktrees directory.`)}function Ix(e){if(!Number.isSafeInteger(e)||e<=0)throw new D(`Issue number must be positive.`)}function Lx(e,t){Ix(e.issueNumber??0);let n=`issue/${String(e.issueNumber)}`,r=w(t,`.worktrees`,`issue-${String(e.issueNumber)}`);if(e.type!==`issue`||e.path!==r||e.branch!==n||!i(r)||fd(r)!==h(r)||pd(r)!==pd(t))throw new D(`Registered worktree disagrees with its exact repository, path or branch.`);if(ud(r,`branch`,`--show-current`)!==n)throw new D(`Registered branch drifted.`)}function Rx(e){return ud(e,`worktree`,`list`,`--porcelain`).split(`
289
289
 
290
290
  `).filter(Boolean).map(e=>e.split(`
291
- `))}function Rx(e){try{return c(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function zx(e,t){Fx(t);let n=w(e,`.worktrees`,`issue-${String(t)}`),r=`issue/${String(t)}`;if(Ix({path:n,branch:r,issueNumber:t,type:`issue`,status:`active`,createdAt:``,updatedAt:``},e),ud(n,`ls-files`,`-v`,`-z`).split(`\0`).some(e=>/^(?:[a-z]|S) /u.test(e)))throw new D(`Investigation source has assume-unchanged or skip-worktree index entries; preserve hidden local data.`);if(gd(n),ud(n,`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`-z`)!==``)throw new D(`Investigation source contains ignored files; preserve them before completion.`);let i=Lx(e).filter(e=>e.includes(`worktree ${n}`)||e.includes(`branch refs/heads/${r}`));if(i.length!==1||i[0].some(e=>/^(?:locked|prunable)(?: |$)/u.test(e)))throw new D(`Investigation Git worktree custody is ambiguous or locked.`);let a=h(T(n,ud(n,`rev-parse`,`--git-dir`))),o=c(n),s=c(a);return{head:{sha:ud(n,`rev-parse`,`HEAD`),tree:ud(n,`rev-parse`,`HEAD^{tree}`)},physical:{device:o.dev,inode:o.ino,gitDirectory:a,gitDevice:s.dev,gitInode:s.ino}}}function Bx(e,t,n=!1){let{repoRoot:r,row:i,head:a}=e;if(Px(r,i.path),i.path!==w(r,`.worktrees`,`issue-${String(i.issueNumber)}`)||i.branch!==`issue/${String(i.issueNumber)}`)throw new D(`Investigation path or branch disagrees.`);if(i.path===md(r)||i.path===fd(t))throw new D(`Investigation completion refuses the primary or current worktree.`);let o=se(i.path,h(process.cwd()));if(!(o===`..`||o.startsWith(`..${ce}`)||oe(o)))throw new D(`Investigation completion refuses the current worktree.`);if(ud(r,`rev-parse`,`refs/heads/${i.branch}`)!==a.sha)throw new D(`Investigation retaining branch has new or unpushed commits.`);let s=Lx(r).filter(e=>e.includes(`worktree ${i.path}`)||e.includes(`branch refs/heads/${i.branch}`));if(!Rx(i.path)){if(!n||s.length!==0||Rx(e.physical.gitDirectory))throw new D(`Investigation source is missing without exact completed Git removal.`);return}let c=zx(r,i.issueNumber);if(JSON.stringify(c.head)!==JSON.stringify(a)||JSON.stringify(c.physical)!==JSON.stringify(e.physical))throw new D(`Investigation source commit, tree or physical identity changed.`)}function Vx(e,t){if(Bx(e,t,!0),Rx(e.row.path)&&ud(e.repoRoot,`worktree`,`remove`,e.row.path),Rx(e.row.path)||Rx(e.physical.gitDirectory)||Lx(e.repoRoot).some(t=>t.includes(`worktree ${e.row.path}`)))throw new D(`Investigation removal disk/Git readback is incomplete.`);Bx(e,t,!0)}function Hx(e,t,n,r,a){if(Px(t,e.path),e.status!==`merged`||e.path!==w(t,`.worktrees`,`issue-${String(e.issueNumber)}`))throw new D(`Only the exact registered merged issue worktree can be cleaned.`);let o=i(e.path);if(o&&fd(e.path)!==h(e.path))throw new D(`Registered worktree points elsewhere.`);if(!o&&!a)throw new D(`Registered worktree is missing.`);o&&gd(e.path);let s=_d(t,n),c=dd(t,`merge-base`,`--is-ancestor`,e.branch,s)===0;if(r){if(r.headBranch!==e.branch||r.headSha!==ud(o?e.path:t,`rev-parse`,o?`HEAD`:e.branch)||r.remoteHeadSha!==null&&r.remoteHeadSha!==r.headSha||r.baseBranch!==s.slice(`refs/remotes/${sd(t,n)}/`.length)||r.remoteBaseSha!==ud(t,`rev-parse`,s)||dd(t,`merge-base`,`--is-ancestor`,r.baseSha,r.mergeSha)!==0||dd(t,`merge-base`,`--is-ancestor`,r.mergeSha,s)!==0||ud(t,`rev-parse`,`${r.mergeSha}^{tree}`)!==r.mergeTree||!c&&r.strategy===`merge`)throw new D(`Exact merged-result cleanup attestation disagrees with Git or remote readback.`)}else if(!c)throw new D(`Branch is not included in the current base and exact merged-result attestation is absent.`);o&&ud(t,`worktree`,`remove`,e.path)}function Ux(e,t){if(e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw new D(`Transition cannot remove held or nonterminal source.`);let n=e.lineage.find(t=>t.prNumber===e.terminalPrNumber);if(!n?.merged||!n.mergeSha)throw new D(`Transition lacks exact native terminal merge lineage.`);let r=ud(e.repoRoot,`rev-parse`,`${n.mergeSha}^{tree}`),i=dd(e.repoRoot,`merge-base`,`--is-ancestor`,e.head.sha,n.mergeSha)===0?`merge`:`squash`;if(i===`squash`&&r!==e.head.tree)throw new D(`Transition lacks exact retained tree proof for non-merge source removal.`);if(!e.remoteRefs||e.remoteRefs.headSha!==null&&e.remoteRefs.headSha!==e.head.sha)throw new D(`Transition lacks exact authenticated remote branch readback.`);Hx({...e.row,status:`merged`,prNumber:n.prNumber},e.repoRoot,t,{baseBranch:n.baseBranch,baseSha:n.baseSha,headBranch:e.row.branch,headSha:e.head.sha,mergeSha:n.mergeSha,mergeTree:r,remoteBaseSha:e.remoteRefs.baseSha,remoteHeadSha:e.remoteRefs.headSha,strategy:i},!0)}var Wx=F({path:A().min(1),source:A().min(1),digest:R,size:j().int().nonnegative().safe()}),Gx=F({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:I([`active`,`error`,`merged`,`pr-published`,`stale`]),type:L(`issue`),updatedAt:A().min(1)}),Kx=F({prNumber:j().int().positive(),headSha:vd,headBranch:A().min(1),baseSha:vd,baseBranch:A().min(1),mergeSha:vd.nullable(),merged:M(),authorLogin:A().min(1)}),qx=F({schemaVersion:L(`ai-delivery.worktree-transition-plan@1`),planId:R,repository:A().min(1),repoRoot:A().min(1),row:Gx,purpose:I([`active-resume`,`merged-cleanup`]),disposition:I([`retain`,`remove`]),head:F({sha:vd,tree:vd}),terminalPrNumber:j().int().positive().nullable(),lineage:N(Kx),retainedHoldCommentIds:N(j().int().positive()),remoteRefs:F({headSha:vd.nullable(),baseSha:vd}).nullable(),holdEvidence:N(F({commentId:j().int().positive(),digest:R})),inventory:N(Wx),inventoryId:R,historicalProducer:L(`UNKNOWN`),closure:F({family:L(`public-ai-delivery-0.3.5-posix@1`),admissionPath:A().min(1),archivePath:A().min(1),admission:oy,admissionBytesDigest:R,producerDigest:R,runManifestIds:N(R).min(1)}),currentRuntime:oy,policyDigest:R,operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e;(n!==B(r)||e.inventoryId!==B(e.inventory)||e.disposition===`remove`&&(e.purpose!==`merged-cleanup`||e.retainedHoldCommentIds.length!==0)||e.purpose===`active-resume`&&e.terminalPrNumber!==null||e.purpose===`merged-cleanup`&&e.terminalPrNumber===null||e.disposition===`remove`&&e.remoteRefs===null)&&t.addIssue({code:`custom`,message:`Transition plan identity or disposition is invalid.`})}),Jx=`sha256:c561a94b7727ad5dfc520cbdcad803b9eaddfd49d334ccbc9253edeede26994e`;function Yx(e,t,n){if(!e.configuration)throw new D(`Transition requires the current repository configuration.`);let r=H(t),i=oy.parse(JSON.parse(r.toString(`utf8`)));if(i.packageVersion!==`0.3.5`||i.sourceArchiveSha256!==Jx)throw new D(`Retained operational producer is outside the supported public 0.3.5 family.`);dy(i,{...e.configuration,configDigest:i.configDigest},i.cliPath);let a=Qx(n);if(V(a)!==Jx)throw new D(`Retained official public archive bytes disagree.`);let o=ye(a,{maxOutputLength:8388608}),s=C(C(i.cliPath)),c=[],l=(e,t)=>{let n=Qx(e);c.push({source:e,path:t,digest:V(n),size:n.length})},u=0;for(let e=0;e+512<=o.length;){let t=o.subarray(e,e+512);if(t.every(e=>e===0))break;let n=t.subarray(0,100).toString(`utf8`).replace(/\0.*$/su,``),r=Number.parseInt(t.subarray(124,136).toString(`ascii`).replace(/\0.*$/su,``).trim(),8);if(t[156]!==48||!/^package\/(?!.*(?:^|\/)\.\.\/)[A-Za-z0-9_./-]+$/u.test(n)||!Number.isSafeInteger(r)||r<0)throw new D(`Retained public archive inventory is unsupported.`);let i=o.subarray(e+512,e+512+r),a=T(s,n.slice(8)),c=Qx(a);if(i.length!==r||!c.equals(i))throw new D(`Retained producer bytes drifted: ${n}`);u+=1,l(a,`retained/${n}`),e+=512+Math.ceil(r/512)*512}if(u!==155)throw new D(`Retained public producer inventory is incomplete.`);l(t,`retained/admission.json`),l(n,`retained/public-archive.tar.gz`);let d=vb(C(i.cliPath));for(let e of d)l(e.source,`retained/dependency-manifests/${B(e.source).slice(7)}.json`);return c.sort((e,t)=>e.path.localeCompare(t.path)),{admissionPath:t,archivePath:n,admission:i,admissionBytesDigest:V(r),producerDigest:_b(C(i.cliPath)),inventory:c}}function Xx(e,t,n,r,i){let a=n.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).map(e=>yb(Qx(e.source)));if(a.length===0||!a.some(e=>e.classification.head.sha===i.sha&&e.classification.head.tree===i.tree)||a.some(e=>e.schemaVersion!==`ai-delivery.run@3`||e.writer?.worktreeDigest!==B(t.path)||e.writer.producerDigest!==r||e.classification.repository===``||e.classification.requiredStages.some(e=>![`source_only`,`focused_node`,`canonical_verify`].includes(e.resourceClass))||e.classification.requiredStages.some(e=>e.commands.length>0)&&e.resources===void 0))throw new D(`Complete operational run inventory lacks supported producer-bound closure for the exact retained source head/tree.`);for(let t of a)for(let n of t.stageReceipts){let t=n.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,r=w(pd(e),`ai-delivery`,`verification@${String(t)}`,`stages`,n.input.stageId,`${n.input.inputId.slice(7)}.json`);if(z(JSON.parse(H(r).toString(`utf8`)))!==z(n))throw new D(`Operational run inventory has a missing or conflicting stage checkpoint.`)}return a.map(e=>e.manifestId).sort()}function Zx(e){try{return c(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Qx(e){let t=c(e);if(!t.isFile()||t.isSymbolicLink()||t.nlink!==1||h(e)!==e)throw new D(`Historical evidence requires canonical regular files without links.`);return d(e)}function $x(e,t,n=!1){let r=pd(e),i=new Map,a=new Set;Zx(t.path)?a.add(ud(t.path,`rev-parse`,`HEAD`)):n&&a.add(ud(e,`rev-parse`,t.branch));let o=(e,s)=>{if(!Zx(e))return;let l=c(e);if(l.isSymbolicLink()||h(e)!==e)throw new D(`Historical evidence inventory contains a noncanonical path.`);if(l.isDirectory()){for(let t of p(e).sort())o(w(e,t),`${s}/${t}`);return}let u=Qx(e);if(i.set(s,{path:s,source:e,digest:V(u),size:u.length}),s.endsWith(`.json`)){let i;try{i=JSON.parse(u.toString(`utf8`))}catch{return}if(i&&typeof i.headSha==`string`&&/^[a-f0-9]{40}$/u.test(i.headSha)&&a.add(i.headSha),i?.schemaVersion===`issue-cli.terminal-evidence@1`){if(!Array.isArray(i.files))throw new D(`Historical terminal evidence manifest is incomplete.`);for(let t of i.files){if(typeof t.name!=`string`||!/^[A-Za-z0-9_.-]+$/u.test(t.name)||typeof t.sha256!=`string`)throw new D(`Historical terminal evidence inventory is invalid.`);let n=Qx(w(C(e),t.name));if(n.length!==t.size||V(n)!==`sha256:${t.sha256}`)throw new D(`Historical terminal evidence manifest disagrees with original bytes.`)}}if(s.startsWith(`git/ai-delivery/runs@2/`)&&i?.schemaVersion===`ai-delivery.run@3`){let e=yb(u),i=e.classification.head.sha;a.add(i);for(let i of e.stageReceipts){let e=i.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,a=`ai-delivery/verification@${String(e)}/stages/${i.input.stageId}/${i.input.inputId.slice(7)}.json`;o(w(r,a),`git/${a}`);let s=`ai-delivery/resource-stages@1/${i.input.inputId.slice(7)}.json`;o(w(r,s),`git/${s}`);for(let e of i.commands){let t=`ai-delivery/verification@1/command-output/${e.outputDigest.slice(7)}.bin`;if(V(Qx(w(r,t)))!==e.outputDigest)throw new D(`Historical command output is corrupt.`);o(w(r,t),`git/${t}`)}for(let e of i.artifacts){if(n)continue;let r=T(t.path,e.path);if(se(t.path,r).startsWith(`..`)||V(Qx(r))!==e.digest)throw new D(`Historical stage artifact is missing or corrupt.`);o(r,`worktree/${e.path}`)}}if(e.resources?.outputBaselineId){let t=`ai-delivery/output-baselines@1/${e.resources.outputBaselineId.slice(7)}`;o(w(r,`${t}.json`),`git/${t}.json`),o(w(r,`${t}.state.json`),`git/${t}.state.json`)}}}};o(w(e,`.issue-cli`,`issues`,String(t.issueNumber)),`repository/.issue-cli/issues/${String(t.issueNumber)}`),n||o(w(t.path,`.issue-cli`),`worktree/.issue-cli`);let s=B(T(t.path)).slice(7);o(w(r,`ai-delivery`,`runs@2`,s),`git/ai-delivery/runs@2/${s}`),o(w(r,`ai-delivery`,`writers@1`,`${s}.json`),`git/ai-delivery/writers@1/${s}.json`);let l=w(e,`.issue-cli`,`receipts`),u=t=>{if(!Zx(t))return;let n=c(t);if(n.isSymbolicLink())throw new D(`Historical receipt inventory contains a link.`);if(n.isDirectory())for(let e of p(t).sort())u(w(t,e));else[...a].some(e=>t.includes(e))&&o(t,`repository/${se(e,t)}`)};u(l);for(let e of[`publications`,`reviews`,`merges`,`merge-intents`,`merge-attempts`,`merge-results`])o(w(r,`ai-delivery`,e,String(t.issueNumber)),`git/ai-delivery/${e}/${String(t.issueNumber)}`);for(let e of[...a].sort())o(w(r,`ai-delivery`,`runs`,`${e}.json`),`git/ai-delivery/runs/${e}.json`);return[...i.values()].sort((e,t)=>e.path.localeCompare(t.path))}var eS=F({schemaVersion:L(`ai-delivery.worktree-transition-intent@1`),intentId:R,plan:qx,relinquishmentCommentId:j().int().positive(),acceptanceCommentId:j().int().positive(),originalRegistryDigest:R,originalWriterDigest:R.nullable()}).superRefine((e,t)=>{let{intentId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Transition intent is corrupt.`})}),tS=F({schemaVersion:L(`ai-delivery.worktree-transition-step@1`),planId:R,intentId:R,attemptId:fl(),event:I([`authority`,`claim`,`claimed`,`release`,`released`,`row`,`owner`,`removal-intent`,`removed`]),sequence:j().int().positive().safe(),predecessorId:R.nullable(),data:Ql(A(),Ll()),stepId:R}),nS=F({schemaVersion:L(`ai-delivery.worktree-transition-completion@1`),completionId:R,planId:R,intentId:R,completed:L(!0),writerReleased:L(!0),result:I([`active-resumed`,`retained`,`removed`]),rowAfter:Gx.nullable(),inventoryId:R,attempts:N(R).min(1),completedAt:Du()}).superRefine((e,t)=>{let{completionId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Transition completion is corrupt.`})});function rS(e){let t=w(pd(e.repoRoot),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`);return{intent:t,directory:`${t}.evidence`,blobs:w(`${t}.evidence`,`bytes`)}}function iS(e,t){wd(e,Buffer.from(z(t)))}function aS(e,t){let n=V(t);return wd(w(e,`${n.slice(7)}.bin`),t,n),n}function oS(e,t){let n=H(w(e,`${R.parse(t).slice(7)}.bin`));if(V(n)!==t)throw new D(`Preserved transition evidence is corrupt.`);return n}function sS(e){let t=B({planId:e.planId,purpose:`transition-writer`}).slice(7);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`}function cS(e,t){if(!Zx(e))return[];let n=null;return p(e).sort((e,t)=>Number(e.split(`.`)[0])-Number(t.split(`.`)[0])).map((r,i)=>{if(!/^[1-9]\d*\.[a-f0-9-]{36}\.(?:authority|claim|claimed|release|released|row|owner|removal-intent|removed)\.json$/u.test(r))throw new D(`Transition attempt inventory contains an unsupported record.`);let a=tS.parse(JSON.parse(H(w(e,r)).toString(`utf8`))),{stepId:o,...s}=a;if(o!==B(s)||a.intentId!==t.intentId||a.planId!==t.plan.planId||a.sequence!==i+1||a.predecessorId!==n||r!==`${String(a.sequence)}.${a.attemptId}.${a.event}.json`)throw new D(`Transition attempt record is corrupt or belongs to another intent.`);return n=o,a})}function lS(e,t){let n=[e.originalWriterDigest],r,i;for(let e of t)if(e.event===`claim`){let t=R.parse(e.data.bytesDigest),a=e.data.previousBytesDigest===null?null:R.parse(e.data.previousBytesDigest);if(!n.includes(a))throw new D(`Transition claim predecessor is outside its exact writer lineage.`);n=[a,t],r={attemptId:e.attemptId,bytesDigest:t},i=void 0}else if(e.event===`claimed`||e.event===`release`){if(!r||e.attemptId!==r.attemptId||e.data.bytesDigest!==r.bytesDigest)throw new D(`Transition claim/release acknowledgement belongs to another writer lineage.`);n=e.event===`claimed`?[r.bytesDigest]:[r.bytesDigest,null],e.event===`release`&&(i=e.attemptId)}else if(e.event===`released`){if(i!==e.attemptId||e.data.absent!==!0)throw new D(`Transition absence lacks its exact latest release intent.`);n=[null]}return n}function uS(e,t,n){t.originalWriterDigest!==null&&oS(e,t.originalWriterDigest);for(let t of n)[`authority`,`claim`,`claimed`,`release`].includes(t.event)&&oS(e,R.parse(t.data.bytesDigest))}async function dS(e,t,n,r,i){if(!e.configuration||e.root!==t.repoRoot||e.config.repository!==t.repository)throw new D(`Transition repository or current configuration drifted.`);if(z(await uy({repoRoot:t.repoRoot,configuration:e.configuration,...i===void 0?{}:{runtimeEntryPath:i}}))!==z(t.currentRuntime)||V(Qx(TS(e).policyModulePath))!==t.policyDigest)throw new D(`Transition current runtime/configuration/policy drifted.`);let{inventory:a,...o}=Yx(e,t.closure.admissionPath,t.closure.archivePath),{family:s,runManifestIds:c,...l}=t.closure;if(z(o)!==z(l))throw new D(`Retained operational producer drifted.`);for(let e of[`v1`,`v2`])if(Zx(w(pd(t.repoRoot),`issue-cli`,`verification-stages`,e)))throw new D(`Unsupported operative issue-cli verification-stages/${e}; supported closure is missing.`);let u=!Zx(t.row.path);if(u&&(!r||t.disposition!==`remove`))throw new D(`Transition source disappeared without recorded removal intent.`);if(!u){if(fd(t.row.path)!==t.row.path||pd(t.row.path)!==pd(t.repoRoot)||ud(t.row.path,`branch`,`--show-current`)!==t.row.branch)throw new D(`Transition worktree ownership or branch drifted.`);gd(t.row.path)}let d=u?t.repoRoot:t.row.path,f=u?t.row.branch:`HEAD`;if(ud(d,`rev-parse`,f)!==t.head.sha||ud(d,`rev-parse`,`${f}^{tree}`)!==t.head.tree)throw new D(`Transition exact source coordinates drifted.`);let p=await bS(e,t.row,t.terminalPrNumber);if(z(p)!==z(t.lineage))throw new D(`Transition authenticated native PR lineage or complete PR set drifted.`);if(t.disposition===`remove`){let n=t.lineage.find(e=>e.prNumber===t.terminalPrNumber);if(!n||z(await SS(e,t.row.branch,n.baseBranch))!==z(t.remoteRefs)||ud(t.repoRoot,`rev-parse`,_d(t.repoRoot,TS(e).remote))!==t.remoteRefs?.baseSha)throw new D(`Transition native remote branch readback or local retaining ref drifted.`);if(a.some(e=>{let n=se(t.row.path,e.source);return n===``||!n.startsWith(`..`)&&!n.startsWith(`/`)}))throw new D(`Retained operational producer must remain outside the source selected for removal.`)}let m=(await e.clients.rest.issues.get({...e.repo,issue_number:t.row.issueNumber})).data;if(m.state!==(t.purpose===`merged-cleanup`?`closed`:`open`))throw new D(`Transition native issue state drifted.`);for(let n of t.holdEvidence){let t=(await e.clients.rest.issues.getComment({...e.repo,comment_id:n.commentId})).data;if(V(Buffer.from(z(t)))!==n.digest)throw new D(`Retained native hold evidence drifted.`)}let h=[...$x(t.repoRoot,t.row,u),...a].sort((e,t)=>e.path.localeCompare(t.path));if(xS(t.repoRoot,t.row,t.purpose,t.terminalPrNumber,t.head,p,m.state,h),z(Xx(t.repoRoot,t.row,h,o.producerDigest,t.head))!==z(t.closure.runManifestIds))throw new D(`Operational run inventory IDs drifted.`);if(h.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(e=>yb(Qx(e.source)).classification.repository!==t.repository))throw new D(`Operational run inventory belongs to another repository.`);let g=e=>e.filter(e=>!e.path.startsWith(`git/ai-delivery/writers@1/`)&&!(u&&e.path.startsWith(`worktree/`)));if(z(g(h))!==z(g(t.inventory)))throw new D(`Transition complete historical writer/run/stage inventory drifted.`);if(n&&h.some(e=>e.path.startsWith(`git/ai-delivery/writers@1/`)&&!t.inventory.some(t=>z(t)===z(e))))throw new D(`Original transition writer evidence drifted.`)}async function fS(e,t){if(t.authority!==`worktree:transition`)throw new D(`Explicit exact-plan worktree transition authority is required.`);let n=qx.parse(JSON.parse(Qx(h(t.planPath)).toString(`utf8`)));if(n.planId!==t.expectedPlanId)throw new D(`Transition expected plan identity disagrees.`);let r=rS(n),i=w(r.directory,`completion.json`),a=w(r.directory,`attempts`),o;if(Zx(r.intent)&&(o=eS.parse(JSON.parse(H(r.intent).toString(`utf8`))),z(o.plan)!==z(n)||o.relinquishmentCommentId!==t.relinquishmentCommentId||o.acceptanceCommentId!==t.acceptanceCommentId))throw new D(`Pending transition requires its original exact plan and native authority IDs.`);let s=n.purpose===`active-resume`?`active-resumed`:n.disposition===`retain`?`retained`:`removed`;if(Zx(i)){if(!o)throw new D(`Transition completion lacks its durable intent.`);let c=nS.parse(JSON.parse(H(i).toString(`utf8`))),l=cS(a,o);if(c.planId!==n.planId||c.intentId!==o.intentId||c.result!==s||c.inventoryId!==n.inventoryId||z(c.attempts)!==z(l.map(e=>e.stepId))||z(lS(o,l))!==z([null]))throw new D(`Transition completion is corrupt.`);for(let e of n.inventory)oS(r.blobs,e.digest);oS(r.blobs,o.originalRegistryDigest),uS(r.blobs,o,l);for(let e of n.holdEvidence)oS(r.blobs,e.digest);return await dS(e,n,!1,cS(a,o).some(e=>e.event===`removal-intent`),t.runtimeEntryPath),await _S(e,n,t),await fb(n.repoRoot,n.row.path,()=>sx(n,async({current:e})=>{if(z(e??null)!==z(c.rowAfter))throw new D(`Sealed transition registry postcondition drifted.`);if(cx(n),s===`removed`){if(Zx(n.row.path)||e!==void 0)throw new D(`Removed transition source was recreated; terminal absence postcondition drifted.`)}else if(!e||!Zx(n.row.path))throw new D(`Sealed transition source or owner witness disappeared.`)})),{planId:n.planId,result:s,replayed:!0,receiptPath:i}}let c=he(),l=o===void 0?[]:cS(a,o),u=(e,t)=>{if(!o)throw new D(`Transition step lacks durable intent.`);let r={schemaVersion:`ai-delivery.worktree-transition-step@1`,planId:n.planId,intentId:o.intentId,attemptId:c,event:e,data:t,sequence:l.length+1,predecessorId:l.at(-1)?.stepId??null},i=tS.parse({...r,stepId:B(r)});lS(o,[...l,i]),iS(w(a,`${String(i.sequence)}.${c}.${e}.json`),i),l.push(i)},d=[...l],f=null,p,m=!1,g=null;return await pb({repoRoot:n.repoRoot,worktreePath:n.row.path,writerId:sS(n),beforeClaim:async({previousBytes:i})=>{await sx(n,async({current:s})=>{o!==void 0&&(l=cS(a,o));let c=d.some(e=>e.event===`removal-intent`);if(s===void 0&&!c)throw new D(`Transition row disappeared without recorded removal intent.`);await dS(e,n,o===void 0,c,t.runtimeEntryPath);let p=await _S(e,n,t);if(o===void 0){let e=n.inventory.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));if(i===void 0!=(e===void 0)||i!==void 0&&V(i)!==e?.digest)throw new D(`Original transition writer bytes or absence drifted.`);let a=aS(r.blobs,Qx(w(n.repoRoot,`.issue-cli`,`worktrees.json`))),s={schemaVersion:`ai-delivery.worktree-transition-intent@1`,plan:n,relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId,originalRegistryDigest:a,originalWriterDigest:i===void 0?null:V(i)};o=eS.parse({...s,intentId:B(s)}),iS(r.intent,o),wS(r.blobs,n.inventory)}else{for(let e of n.inventory){if(!Zx(w(r.blobs,`${e.digest.slice(7)}.bin`))){if(e.path.startsWith(`git/ai-delivery/writers@1/`)){if(i===void 0||V(i)!==e.digest)throw new D(`Original writer was lost before preservation.`);aS(r.blobs,i)}else wS(r.blobs,[e])}oS(r.blobs,e.digest)}let e=i===void 0?null:V(i);if(!lS(o,l).includes(e))throw new D(`Writer bytes/absence are outside the latest exact transition claim/release lineage.`);e!==null&&oS(r.blobs,e)}f=i===void 0?null:V(i),oS(r.blobs,o.originalRegistryDigest),uS(r.blobs,o,l),u(`authority`,{bytesDigest:aS(r.blobs,Buffer.from(z(p))),relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId});for(let t of n.holdEvidence){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.commentId})).data;if(aS(r.blobs,Buffer.from(z(n)))!==t.digest)throw new D(`Retained hold changed during preservation.`)}})},recordClaim:e=>{p=aS(r.blobs,e),u(`claim`,{bytesDigest:p,previousBytesDigest:f})},afterClaim:e=>{if(V(e)!==p)throw new D(`Actual writer claim bytes disagree with their recorded intent.`);u(`claimed`,{bytesDigest:p})},recordRelease:e=>{if(V(e)!==p)throw new D(`Writer changed before its exact recorded release.`);u(`release`,{bytesDigest:aS(r.blobs,e)})},afterRelease:async()=>{u(`released`,{absent:!0}),m&&o&&await sx(n,async({current:e})=>{if(z(e??null)!==z(g))throw new D(`Transition row changed before completion sealing.`);for(let e of n.inventory)oS(r.blobs,e.digest);let t=cS(a,o);uS(r.blobs,o,t);let c={schemaVersion:`ai-delivery.worktree-transition-completion@1`,planId:n.planId,intentId:o.intentId,completed:!0,writerReleased:!0,result:s,rowAfter:g,inventoryId:n.inventoryId,attempts:t.map(e=>e.stepId),completedAt:new Date().toISOString()};iS(i,{...c,completionId:B(c)})})}},async()=>{await sx(n,async({current:r,writeOwner:i,commitRow:a,removeRow:o})=>{let s=d.some(e=>e.event===`removal-intent`);if(await dS(e,n,!1,s,t.runtimeEntryPath),await _S(e,n,t),r!==void 0&&(i(),u(`owner`,{exactWitness:!0}),g=a(),u(`row`,{rowDigest:B(g)})),n.disposition===`remove`){if(u(`removal-intent`,{head:n.head,path:n.row.path}),Ux(n,TS(e).remote),Zx(n.row.path))throw new D(`Terminal source removal readback is not absent.`);u(`removed`,{absent:!0}),o(),g=null}m=!0})}),{planId:n.planId,result:s,replayed:d.length>0,receiptPath:i}}async function pS(e){if(e.clients.authSource!==`personal`||e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new D(`Worktree relinquishment requires the configured authenticated personal operator.`);let t=await e.clients.authenticatedAuthor();if(!/^user:[1-9]\d*$/u.test(t.credentialIdentity))throw new D(`Operator user identity is unavailable.`);let n=await vh({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(n.authSource!==`app`||!n.appActorLogin)throw new D(`Configured reviewer App identity is unavailable.`);let r=await n.appActorLogin();if(r.toLowerCase()===t.actorLogin.toLowerCase())throw new D(`Transition acceptance requires a distinct configured reviewer App.`);return{operator:t,reviewerActor:r,reviewer:n}}function mS(e){return z({schemaVersion:`ai-delivery.worktree-relinquishment@1`,plan:gS(e),acceptedScope:`the-complete-content-addressed-plan-and-every-original-in-its-inventory`,authority:`relinquish-only-the-inventoried-public-posix-writers`,operationalClosure:`the-inventory-is-the-complete-remaining-launcher-writer-and-managed-process-set-all-are-quiescent-no-unknown-resources`,maintainedExclusion:`all-old-launchers-and-writers-remain-excluded-through-apply-including-interruption-and-exact-plan-replay`,historicalAuthority:`preservation-only-no-current-verification-review-or-retirement-authority`,sourceDisposition:e.disposition===`remove`?`no-outstanding-holds-remove-only-clean-merged-source`:`retain-source-and-all-outstanding-holds`,exclusions:[`private-adoption`,`hold-release`,`launcher-changes`,`shared-runtime-admission`,`legacy-protocol-retirement`]})}function hS(e,t){return z({schemaVersion:`ai-delivery.worktree-transition-acceptance@1`,plan:gS(e),acceptedScope:`independent-acceptance-of-the-complete-content-addressed-plan-and-inventory-including-complete-launcher-set-and-maintained-exclusion`,relinquishmentCommentId:t,relinquishmentDigest:V(Buffer.from(mS(e))),result:`approved`})}function gS(e){let t=qx.parse(e);return{planId:t.planId,inventoryId:t.inventoryId,repository:t.repository,repoRoot:t.repoRoot,row:t.row,head:t.head,purpose:t.purpose,disposition:t.disposition,terminalPrNumber:t.terminalPrNumber,lineage:t.lineage,remoteRefs:t.remoteRefs,holdEvidence:t.holdEvidence,closure:t.closure,currentRuntimeId:t.currentRuntime.admissionId,currentConfigDigest:t.currentRuntime.configDigest,policyDigest:t.policyDigest,operator:t.operator,reviewerActor:t.reviewerActor,historicalProducer:t.historicalProducer}}async function _S(e,t,n){let r=await pS(e);if(z(r.operator)!==z(t.operator)||r.reviewerActor!==t.reviewerActor)throw new D(`Configured transition authority identities drifted.`);if(t.lineage.some(e=>e.authorLogin.toLowerCase()===r.reviewerActor.toLowerCase()))throw new D(`Configured transition reviewer App is also the native PR author.`);let i=t.terminalPrNumber??t.row.issueNumber;return vS(e,{repository:t.repository,subject:i,operator:t.operator,reviewerActor:t.reviewerActor,authorityCommentId:n.relinquishmentCommentId,acceptanceCommentId:n.acceptanceCommentId,operatorBody:mS(t),reviewerBody:hS(t,n.relinquishmentCommentId),revokedBody:z({schemaVersion:`ai-delivery.worktree-relinquishment-revocation@1`,planId:t.planId,relinquishmentCommentId:n.relinquishmentCommentId})})}async function vS(e,t){let n=await pS(e);if(z(n.operator)!==z(t.operator)||n.reviewerActor!==t.reviewerActor)throw new D(`Configured transition authority identities drifted.`);let r=t.subject,i=`https://api.github.com/repos/${t.repository}/issues/${String(r)}`,a=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.authorityCommentId})).data,o=(await n.reviewer.rest.issues.getComment({...e.repo,comment_id:t.acceptanceCommentId})).data;if(a?.id!==t.authorityCommentId||a.issue_url?.toLowerCase()!==i.toLowerCase()||a.user?.type!==`User`||a.user?.login.toLowerCase()!==n.operator.actorLogin.toLowerCase()||`user:${String(a.user?.id)}`!==n.operator.credentialIdentity||a.body!==t.operatorBody)throw new D(`Native operator relinquishment is missing, changed or belongs to another subject.`);if(o?.id!==t.acceptanceCommentId||o.issue_url?.toLowerCase()!==i.toLowerCase()||o.user?.type!==`Bot`||o.user.login.toLowerCase()!==n.reviewerActor.toLowerCase()||o.body!==t.reviewerBody)throw new D(`Native configured reviewer-App exact-plan acceptance is missing or changed.`);for(let i=1;;i+=1){let a=(await e.clients.rest.issues.listComments({...e.repo,issue_number:r,per_page:100,page:i})).data;if(a.some(e=>e.body===t.revokedBody&&e.user?.login.toLowerCase()===n.operator.actorLogin.toLowerCase()&&`user:${String(e.user.id)}`===n.operator.credentialIdentity))throw new D(`Native operator relinquishment has been revoked.`);if(a.length<100)break}return{relinquishment:a,acceptance:o}}async function yS(e,t,n){let r=(await e.clients.rest.pulls.get({...e.repo,pull_number:n})).data,i=(await e.clients.graphql(`query WorktreeTransitionLineage($owner: String!, $repo: String!, $number: Int!) {
291
+ `))}function zx(e){try{return c(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Bx(e,t){Ix(t);let n=w(e,`.worktrees`,`issue-${String(t)}`),r=`issue/${String(t)}`;if(Lx({path:n,branch:r,issueNumber:t,type:`issue`,status:`active`,createdAt:``,updatedAt:``},e),ud(n,`ls-files`,`-v`,`-z`).split(`\0`).some(e=>/^(?:[a-z]|S) /u.test(e)))throw new D(`Investigation source has assume-unchanged or skip-worktree index entries; preserve hidden local data.`);if(gd(n),ud(n,`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`-z`)!==``)throw new D(`Investigation source contains ignored files; preserve them before completion.`);let i=Rx(e).filter(e=>e.includes(`worktree ${n}`)||e.includes(`branch refs/heads/${r}`));if(i.length!==1||i[0].some(e=>/^(?:locked|prunable)(?: |$)/u.test(e)))throw new D(`Investigation Git worktree custody is ambiguous or locked.`);let a=h(T(n,ud(n,`rev-parse`,`--git-dir`))),o=c(n),s=c(a);return{head:{sha:ud(n,`rev-parse`,`HEAD`),tree:ud(n,`rev-parse`,`HEAD^{tree}`)},physical:{device:o.dev,inode:o.ino,gitDirectory:a,gitDevice:s.dev,gitInode:s.ino}}}function Vx(e,t,n=!1){let{repoRoot:r,row:i,head:a}=e;if(Fx(r,i.path),i.path!==w(r,`.worktrees`,`issue-${String(i.issueNumber)}`)||i.branch!==`issue/${String(i.issueNumber)}`)throw new D(`Investigation path or branch disagrees.`);if(i.path===md(r)||i.path===fd(t))throw new D(`Investigation completion refuses the primary or current worktree.`);let o=se(i.path,h(process.cwd()));if(!(o===`..`||o.startsWith(`..${ce}`)||oe(o)))throw new D(`Investigation completion refuses the current worktree.`);if(ud(r,`rev-parse`,`refs/heads/${i.branch}`)!==a.sha)throw new D(`Investigation retaining branch has new or unpushed commits.`);let s=Rx(r).filter(e=>e.includes(`worktree ${i.path}`)||e.includes(`branch refs/heads/${i.branch}`));if(!zx(i.path)){if(!n||s.length!==0||zx(e.physical.gitDirectory))throw new D(`Investigation source is missing without exact completed Git removal.`);return}let c=Bx(r,i.issueNumber);if(JSON.stringify(c.head)!==JSON.stringify(a)||JSON.stringify(c.physical)!==JSON.stringify(e.physical))throw new D(`Investigation source commit, tree or physical identity changed.`)}function Hx(e,t){if(Vx(e,t,!0),zx(e.row.path)&&ud(e.repoRoot,`worktree`,`remove`,e.row.path),zx(e.row.path)||zx(e.physical.gitDirectory)||Rx(e.repoRoot).some(t=>t.includes(`worktree ${e.row.path}`)))throw new D(`Investigation removal disk/Git readback is incomplete.`);Vx(e,t,!0)}function Ux(e,t,n,r,a){if(Fx(t,e.path),e.status!==`merged`||e.path!==w(t,`.worktrees`,`issue-${String(e.issueNumber)}`))throw new D(`Only the exact registered merged issue worktree can be cleaned.`);let o=i(e.path);if(o&&fd(e.path)!==h(e.path))throw new D(`Registered worktree points elsewhere.`);if(!o&&!a)throw new D(`Registered worktree is missing.`);o&&gd(e.path);let s=_d(t,n),c=dd(t,`merge-base`,`--is-ancestor`,e.branch,s)===0;if(r){if(r.headBranch!==e.branch||r.headSha!==ud(o?e.path:t,`rev-parse`,o?`HEAD`:e.branch)||r.remoteHeadSha!==null&&r.remoteHeadSha!==r.headSha||r.baseBranch!==s.slice(`refs/remotes/${sd(t,n)}/`.length)||r.remoteBaseSha!==ud(t,`rev-parse`,s)||dd(t,`merge-base`,`--is-ancestor`,r.baseSha,r.mergeSha)!==0||dd(t,`merge-base`,`--is-ancestor`,r.mergeSha,s)!==0||ud(t,`rev-parse`,`${r.mergeSha}^{tree}`)!==r.mergeTree||!c&&r.strategy===`merge`)throw new D(`Exact merged-result cleanup attestation disagrees with Git or remote readback.`)}else if(!c)throw new D(`Branch is not included in the current base and exact merged-result attestation is absent.`);o&&ud(t,`worktree`,`remove`,e.path)}function Wx(e,t){if(e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw new D(`Transition cannot remove held or nonterminal source.`);let n=e.lineage.find(t=>t.prNumber===e.terminalPrNumber);if(!n?.merged||!n.mergeSha)throw new D(`Transition lacks exact native terminal merge lineage.`);let r=ud(e.repoRoot,`rev-parse`,`${n.mergeSha}^{tree}`),i=dd(e.repoRoot,`merge-base`,`--is-ancestor`,e.head.sha,n.mergeSha)===0?`merge`:`squash`;if(i===`squash`&&r!==e.head.tree)throw new D(`Transition lacks exact retained tree proof for non-merge source removal.`);if(!e.remoteRefs||e.remoteRefs.headSha!==null&&e.remoteRefs.headSha!==e.head.sha)throw new D(`Transition lacks exact authenticated remote branch readback.`);Ux({...e.row,status:`merged`,prNumber:n.prNumber},e.repoRoot,t,{baseBranch:n.baseBranch,baseSha:n.baseSha,headBranch:e.row.branch,headSha:e.head.sha,mergeSha:n.mergeSha,mergeTree:r,remoteBaseSha:e.remoteRefs.baseSha,remoteHeadSha:e.remoteRefs.headSha,strategy:i},!0)}var Gx=F({path:A().min(1),source:A().min(1),digest:R,size:j().int().nonnegative().safe()}),Kx=F({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:I([`active`,`error`,`merged`,`pr-published`,`stale`]),type:L(`issue`),updatedAt:A().min(1)}),qx=F({prNumber:j().int().positive(),headSha:vd,headBranch:A().min(1),baseSha:vd,baseBranch:A().min(1),mergeSha:vd.nullable(),merged:M(),authorLogin:A().min(1)}),Jx=F({schemaVersion:L(`ai-delivery.worktree-transition-plan@1`),planId:R,repository:A().min(1),repoRoot:A().min(1),row:Kx,purpose:I([`active-resume`,`merged-cleanup`]),disposition:I([`retain`,`remove`]),head:F({sha:vd,tree:vd}),terminalPrNumber:j().int().positive().nullable(),lineage:N(qx),retainedHoldCommentIds:N(j().int().positive()),remoteRefs:F({headSha:vd.nullable(),baseSha:vd}).nullable(),holdEvidence:N(F({commentId:j().int().positive(),digest:R})),inventory:N(Gx),inventoryId:R,historicalProducer:L(`UNKNOWN`),closure:F({family:L(`public-ai-delivery-0.3.5-posix@1`),admissionPath:A().min(1),archivePath:A().min(1),admission:oy,admissionBytesDigest:R,producerDigest:R,runManifestIds:N(R).min(1)}),currentRuntime:oy,policyDigest:R,operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e;(n!==B(r)||e.inventoryId!==B(e.inventory)||e.disposition===`remove`&&(e.purpose!==`merged-cleanup`||e.retainedHoldCommentIds.length!==0)||e.purpose===`active-resume`&&e.terminalPrNumber!==null||e.purpose===`merged-cleanup`&&e.terminalPrNumber===null||e.disposition===`remove`&&e.remoteRefs===null)&&t.addIssue({code:`custom`,message:`Transition plan identity or disposition is invalid.`})}),Yx=`sha256:c561a94b7727ad5dfc520cbdcad803b9eaddfd49d334ccbc9253edeede26994e`;function Xx(e,t,n){if(!e.configuration)throw new D(`Transition requires the current repository configuration.`);let r=H(t),i=oy.parse(JSON.parse(r.toString(`utf8`)));if(i.packageVersion!==`0.3.5`||i.sourceArchiveSha256!==Yx)throw new D(`Retained operational producer is outside the supported public 0.3.5 family.`);dy(i,{...e.configuration,configDigest:i.configDigest},i.cliPath);let a=$x(n);if(V(a)!==Yx)throw new D(`Retained official public archive bytes disagree.`);let o=ye(a,{maxOutputLength:8388608}),s=C(C(i.cliPath)),c=[],l=(e,t)=>{let n=$x(e);c.push({source:e,path:t,digest:V(n),size:n.length})},u=0;for(let e=0;e+512<=o.length;){let t=o.subarray(e,e+512);if(t.every(e=>e===0))break;let n=t.subarray(0,100).toString(`utf8`).replace(/\0.*$/su,``),r=Number.parseInt(t.subarray(124,136).toString(`ascii`).replace(/\0.*$/su,``).trim(),8);if(t[156]!==48||!/^package\/(?!.*(?:^|\/)\.\.\/)[A-Za-z0-9_./-]+$/u.test(n)||!Number.isSafeInteger(r)||r<0)throw new D(`Retained public archive inventory is unsupported.`);let i=o.subarray(e+512,e+512+r),a=T(s,n.slice(8)),c=$x(a);if(i.length!==r||!c.equals(i))throw new D(`Retained producer bytes drifted: ${n}`);u+=1,l(a,`retained/${n}`),e+=512+Math.ceil(r/512)*512}if(u!==155)throw new D(`Retained public producer inventory is incomplete.`);l(t,`retained/admission.json`),l(n,`retained/public-archive.tar.gz`);let d=yb(C(i.cliPath));for(let e of d)l(e.source,`retained/dependency-manifests/${B(e.source).slice(7)}.json`);return c.sort((e,t)=>e.path.localeCompare(t.path)),{admissionPath:t,archivePath:n,admission:i,admissionBytesDigest:V(r),producerDigest:vb(C(i.cliPath)),inventory:c}}function Zx(e,t,n,r,i){let a=n.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).map(e=>bb($x(e.source)));if(a.length===0||!a.some(e=>e.classification.head.sha===i.sha&&e.classification.head.tree===i.tree)||a.some(e=>e.schemaVersion!==`ai-delivery.run@3`||e.writer?.worktreeDigest!==B(t.path)||e.writer.producerDigest!==r||e.classification.repository===``||e.classification.requiredStages.some(e=>![`source_only`,`focused_node`,`canonical_verify`].includes(e.resourceClass))||e.classification.requiredStages.some(e=>e.commands.length>0)&&e.resources===void 0))throw new D(`Complete operational run inventory lacks supported producer-bound closure for the exact retained source head/tree.`);for(let t of a)for(let n of t.stageReceipts){let t=n.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,r=w(pd(e),`ai-delivery`,`verification@${String(t)}`,`stages`,n.input.stageId,`${n.input.inputId.slice(7)}.json`);if(z(JSON.parse(H(r).toString(`utf8`)))!==z(n))throw new D(`Operational run inventory has a missing or conflicting stage checkpoint.`)}return a.map(e=>e.manifestId).sort()}function Qx(e){try{return c(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function $x(e){let t=c(e);if(!t.isFile()||t.isSymbolicLink()||t.nlink!==1||h(e)!==e)throw new D(`Historical evidence requires canonical regular files without links.`);return d(e)}function eS(e,t,n=!1){let r=pd(e),i=new Map,a=new Set;Qx(t.path)?a.add(ud(t.path,`rev-parse`,`HEAD`)):n&&a.add(ud(e,`rev-parse`,t.branch));let o=(e,s)=>{if(!Qx(e))return;let l=c(e);if(l.isSymbolicLink()||h(e)!==e)throw new D(`Historical evidence inventory contains a noncanonical path.`);if(l.isDirectory()){for(let t of p(e).sort())o(w(e,t),`${s}/${t}`);return}let u=$x(e);if(i.set(s,{path:s,source:e,digest:V(u),size:u.length}),s.endsWith(`.json`)){let i;try{i=JSON.parse(u.toString(`utf8`))}catch{return}if(i&&typeof i.headSha==`string`&&/^[a-f0-9]{40}$/u.test(i.headSha)&&a.add(i.headSha),i?.schemaVersion===`issue-cli.terminal-evidence@1`){if(!Array.isArray(i.files))throw new D(`Historical terminal evidence manifest is incomplete.`);for(let t of i.files){if(typeof t.name!=`string`||!/^[A-Za-z0-9_.-]+$/u.test(t.name)||typeof t.sha256!=`string`)throw new D(`Historical terminal evidence inventory is invalid.`);let n=$x(w(C(e),t.name));if(n.length!==t.size||V(n)!==`sha256:${t.sha256}`)throw new D(`Historical terminal evidence manifest disagrees with original bytes.`)}}if(s.startsWith(`git/ai-delivery/runs@2/`)&&i?.schemaVersion===`ai-delivery.run@3`){let e=bb(u),i=e.classification.head.sha;a.add(i);for(let i of e.stageReceipts){let e=i.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,a=`ai-delivery/verification@${String(e)}/stages/${i.input.stageId}/${i.input.inputId.slice(7)}.json`;o(w(r,a),`git/${a}`);let s=`ai-delivery/resource-stages@1/${i.input.inputId.slice(7)}.json`;o(w(r,s),`git/${s}`);for(let e of i.commands){let t=`ai-delivery/verification@1/command-output/${e.outputDigest.slice(7)}.bin`;if(V($x(w(r,t)))!==e.outputDigest)throw new D(`Historical command output is corrupt.`);o(w(r,t),`git/${t}`)}for(let e of i.artifacts){if(n)continue;let r=T(t.path,e.path);if(se(t.path,r).startsWith(`..`)||V($x(r))!==e.digest)throw new D(`Historical stage artifact is missing or corrupt.`);o(r,`worktree/${e.path}`)}}if(e.resources?.outputBaselineId){let t=`ai-delivery/output-baselines@1/${e.resources.outputBaselineId.slice(7)}`;o(w(r,`${t}.json`),`git/${t}.json`),o(w(r,`${t}.state.json`),`git/${t}.state.json`)}}}};o(w(e,`.issue-cli`,`issues`,String(t.issueNumber)),`repository/.issue-cli/issues/${String(t.issueNumber)}`),n||o(w(t.path,`.issue-cli`),`worktree/.issue-cli`);let s=B(T(t.path)).slice(7);o(w(r,`ai-delivery`,`runs@2`,s),`git/ai-delivery/runs@2/${s}`),o(w(r,`ai-delivery`,`writers@1`,`${s}.json`),`git/ai-delivery/writers@1/${s}.json`);let l=w(e,`.issue-cli`,`receipts`),u=t=>{if(!Qx(t))return;let n=c(t);if(n.isSymbolicLink())throw new D(`Historical receipt inventory contains a link.`);if(n.isDirectory())for(let e of p(t).sort())u(w(t,e));else[...a].some(e=>t.includes(e))&&o(t,`repository/${se(e,t)}`)};u(l);for(let e of[`publications`,`reviews`,`merges`,`merge-intents`,`merge-attempts`,`merge-results`])o(w(r,`ai-delivery`,e,String(t.issueNumber)),`git/ai-delivery/${e}/${String(t.issueNumber)}`);for(let e of[...a].sort())o(w(r,`ai-delivery`,`runs`,`${e}.json`),`git/ai-delivery/runs/${e}.json`);return[...i.values()].sort((e,t)=>e.path.localeCompare(t.path))}var tS=F({schemaVersion:L(`ai-delivery.worktree-transition-intent@1`),intentId:R,plan:Jx,relinquishmentCommentId:j().int().positive(),acceptanceCommentId:j().int().positive(),originalRegistryDigest:R,originalWriterDigest:R.nullable()}).superRefine((e,t)=>{let{intentId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Transition intent is corrupt.`})}),nS=F({schemaVersion:L(`ai-delivery.worktree-transition-step@1`),planId:R,intentId:R,attemptId:fl(),event:I([`authority`,`claim`,`claimed`,`release`,`released`,`row`,`owner`,`removal-intent`,`removed`]),sequence:j().int().positive().safe(),predecessorId:R.nullable(),data:Ql(A(),Ll()),stepId:R}),rS=F({schemaVersion:L(`ai-delivery.worktree-transition-completion@1`),completionId:R,planId:R,intentId:R,completed:L(!0),writerReleased:L(!0),result:I([`active-resumed`,`retained`,`removed`]),rowAfter:Kx.nullable(),inventoryId:R,attempts:N(R).min(1),completedAt:Du()}).superRefine((e,t)=>{let{completionId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Transition completion is corrupt.`})});function iS(e){let t=w(pd(e.repoRoot),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`);return{intent:t,directory:`${t}.evidence`,blobs:w(`${t}.evidence`,`bytes`)}}function aS(e,t){wd(e,Buffer.from(z(t)))}function oS(e,t){let n=V(t);return wd(w(e,`${n.slice(7)}.bin`),t,n),n}function sS(e,t){let n=H(w(e,`${R.parse(t).slice(7)}.bin`));if(V(n)!==t)throw new D(`Preserved transition evidence is corrupt.`);return n}function cS(e){let t=B({planId:e.planId,purpose:`transition-writer`}).slice(7);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`}function lS(e,t){if(!Qx(e))return[];let n=null;return p(e).sort((e,t)=>Number(e.split(`.`)[0])-Number(t.split(`.`)[0])).map((r,i)=>{if(!/^[1-9]\d*\.[a-f0-9-]{36}\.(?:authority|claim|claimed|release|released|row|owner|removal-intent|removed)\.json$/u.test(r))throw new D(`Transition attempt inventory contains an unsupported record.`);let a=nS.parse(JSON.parse(H(w(e,r)).toString(`utf8`))),{stepId:o,...s}=a;if(o!==B(s)||a.intentId!==t.intentId||a.planId!==t.plan.planId||a.sequence!==i+1||a.predecessorId!==n||r!==`${String(a.sequence)}.${a.attemptId}.${a.event}.json`)throw new D(`Transition attempt record is corrupt or belongs to another intent.`);return n=o,a})}function uS(e,t){let n=[e.originalWriterDigest],r,i;for(let e of t)if(e.event===`claim`){let t=R.parse(e.data.bytesDigest),a=e.data.previousBytesDigest===null?null:R.parse(e.data.previousBytesDigest);if(!n.includes(a))throw new D(`Transition claim predecessor is outside its exact writer lineage.`);n=[a,t],r={attemptId:e.attemptId,bytesDigest:t},i=void 0}else if(e.event===`claimed`||e.event===`release`){if(!r||e.attemptId!==r.attemptId||e.data.bytesDigest!==r.bytesDigest)throw new D(`Transition claim/release acknowledgement belongs to another writer lineage.`);n=e.event===`claimed`?[r.bytesDigest]:[r.bytesDigest,null],e.event===`release`&&(i=e.attemptId)}else if(e.event===`released`){if(i!==e.attemptId||e.data.absent!==!0)throw new D(`Transition absence lacks its exact latest release intent.`);n=[null]}return n}function dS(e,t,n){t.originalWriterDigest!==null&&sS(e,t.originalWriterDigest);for(let t of n)[`authority`,`claim`,`claimed`,`release`].includes(t.event)&&sS(e,R.parse(t.data.bytesDigest))}async function fS(e,t,n,r,i){if(!e.configuration||e.root!==t.repoRoot||e.config.repository!==t.repository)throw new D(`Transition repository or current configuration drifted.`);if(z(await uy({repoRoot:t.repoRoot,configuration:e.configuration,...i===void 0?{}:{runtimeEntryPath:i}}))!==z(t.currentRuntime)||V($x(ES(e).policyModulePath))!==t.policyDigest)throw new D(`Transition current runtime/configuration/policy drifted.`);let{inventory:a,...o}=Xx(e,t.closure.admissionPath,t.closure.archivePath),{family:s,runManifestIds:c,...l}=t.closure;if(z(o)!==z(l))throw new D(`Retained operational producer drifted.`);for(let e of[`v1`,`v2`])if(Qx(w(pd(t.repoRoot),`issue-cli`,`verification-stages`,e)))throw new D(`Unsupported operative issue-cli verification-stages/${e}; supported closure is missing.`);let u=!Qx(t.row.path);if(u&&(!r||t.disposition!==`remove`))throw new D(`Transition source disappeared without recorded removal intent.`);if(!u){if(fd(t.row.path)!==t.row.path||pd(t.row.path)!==pd(t.repoRoot)||ud(t.row.path,`branch`,`--show-current`)!==t.row.branch)throw new D(`Transition worktree ownership or branch drifted.`);gd(t.row.path)}let d=u?t.repoRoot:t.row.path,f=u?t.row.branch:`HEAD`;if(ud(d,`rev-parse`,f)!==t.head.sha||ud(d,`rev-parse`,`${f}^{tree}`)!==t.head.tree)throw new D(`Transition exact source coordinates drifted.`);let p=await xS(e,t.row,t.terminalPrNumber);if(z(p)!==z(t.lineage))throw new D(`Transition authenticated native PR lineage or complete PR set drifted.`);if(t.disposition===`remove`){let n=t.lineage.find(e=>e.prNumber===t.terminalPrNumber);if(!n||z(await CS(e,t.row.branch,n.baseBranch))!==z(t.remoteRefs)||ud(t.repoRoot,`rev-parse`,_d(t.repoRoot,ES(e).remote))!==t.remoteRefs?.baseSha)throw new D(`Transition native remote branch readback or local retaining ref drifted.`);if(a.some(e=>{let n=se(t.row.path,e.source);return n===``||!n.startsWith(`..`)&&!n.startsWith(`/`)}))throw new D(`Retained operational producer must remain outside the source selected for removal.`)}let m=(await e.clients.rest.issues.get({...e.repo,issue_number:t.row.issueNumber})).data;if(m.state!==(t.purpose===`merged-cleanup`?`closed`:`open`))throw new D(`Transition native issue state drifted.`);for(let n of t.holdEvidence){let t=(await e.clients.rest.issues.getComment({...e.repo,comment_id:n.commentId})).data;if(V(Buffer.from(z(t)))!==n.digest)throw new D(`Retained native hold evidence drifted.`)}let h=[...eS(t.repoRoot,t.row,u),...a].sort((e,t)=>e.path.localeCompare(t.path));if(SS(t.repoRoot,t.row,t.purpose,t.terminalPrNumber,t.head,p,m.state,h),z(Zx(t.repoRoot,t.row,h,o.producerDigest,t.head))!==z(t.closure.runManifestIds))throw new D(`Operational run inventory IDs drifted.`);if(h.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(e=>bb($x(e.source)).classification.repository!==t.repository))throw new D(`Operational run inventory belongs to another repository.`);let g=e=>e.filter(e=>!e.path.startsWith(`git/ai-delivery/writers@1/`)&&!(u&&e.path.startsWith(`worktree/`)));if(z(g(h))!==z(g(t.inventory)))throw new D(`Transition complete historical writer/run/stage inventory drifted.`);if(n&&h.some(e=>e.path.startsWith(`git/ai-delivery/writers@1/`)&&!t.inventory.some(t=>z(t)===z(e))))throw new D(`Original transition writer evidence drifted.`)}async function pS(e,t){if(t.authority!==`worktree:transition`)throw new D(`Explicit exact-plan worktree transition authority is required.`);let n=Jx.parse(JSON.parse($x(h(t.planPath)).toString(`utf8`)));if(n.planId!==t.expectedPlanId)throw new D(`Transition expected plan identity disagrees.`);let r=iS(n),i=w(r.directory,`completion.json`),a=w(r.directory,`attempts`),o;if(Qx(r.intent)&&(o=tS.parse(JSON.parse(H(r.intent).toString(`utf8`))),z(o.plan)!==z(n)||o.relinquishmentCommentId!==t.relinquishmentCommentId||o.acceptanceCommentId!==t.acceptanceCommentId))throw new D(`Pending transition requires its original exact plan and native authority IDs.`);let s=n.purpose===`active-resume`?`active-resumed`:n.disposition===`retain`?`retained`:`removed`;if(Qx(i)){if(!o)throw new D(`Transition completion lacks its durable intent.`);let c=rS.parse(JSON.parse(H(i).toString(`utf8`))),l=lS(a,o);if(c.planId!==n.planId||c.intentId!==o.intentId||c.result!==s||c.inventoryId!==n.inventoryId||z(c.attempts)!==z(l.map(e=>e.stepId))||z(uS(o,l))!==z([null]))throw new D(`Transition completion is corrupt.`);for(let e of n.inventory)sS(r.blobs,e.digest);sS(r.blobs,o.originalRegistryDigest),dS(r.blobs,o,l);for(let e of n.holdEvidence)sS(r.blobs,e.digest);return await fS(e,n,!1,lS(a,o).some(e=>e.event===`removal-intent`),t.runtimeEntryPath),await vS(e,n,t),await pb(n.repoRoot,n.row.path,()=>cx(n,async({current:e})=>{if(z(e??null)!==z(c.rowAfter))throw new D(`Sealed transition registry postcondition drifted.`);if(lx(n),s===`removed`){if(Qx(n.row.path)||e!==void 0)throw new D(`Removed transition source was recreated; terminal absence postcondition drifted.`)}else if(!e||!Qx(n.row.path))throw new D(`Sealed transition source or owner witness disappeared.`)})),{planId:n.planId,result:s,replayed:!0,receiptPath:i}}let c=he(),l=o===void 0?[]:lS(a,o),u=(e,t)=>{if(!o)throw new D(`Transition step lacks durable intent.`);let r={schemaVersion:`ai-delivery.worktree-transition-step@1`,planId:n.planId,intentId:o.intentId,attemptId:c,event:e,data:t,sequence:l.length+1,predecessorId:l.at(-1)?.stepId??null},i=nS.parse({...r,stepId:B(r)});uS(o,[...l,i]),aS(w(a,`${String(i.sequence)}.${c}.${e}.json`),i),l.push(i)},d=[...l],f=null,p,m=!1,g=null;return await mb({repoRoot:n.repoRoot,worktreePath:n.row.path,writerId:cS(n),beforeClaim:async({previousBytes:i})=>{await cx(n,async({current:s})=>{o!==void 0&&(l=lS(a,o));let c=d.some(e=>e.event===`removal-intent`);if(s===void 0&&!c)throw new D(`Transition row disappeared without recorded removal intent.`);await fS(e,n,o===void 0,c,t.runtimeEntryPath);let p=await vS(e,n,t);if(o===void 0){let e=n.inventory.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));if(i===void 0!=(e===void 0)||i!==void 0&&V(i)!==e?.digest)throw new D(`Original transition writer bytes or absence drifted.`);let a=oS(r.blobs,$x(w(n.repoRoot,`.issue-cli`,`worktrees.json`))),s={schemaVersion:`ai-delivery.worktree-transition-intent@1`,plan:n,relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId,originalRegistryDigest:a,originalWriterDigest:i===void 0?null:V(i)};o=tS.parse({...s,intentId:B(s)}),aS(r.intent,o),TS(r.blobs,n.inventory)}else{for(let e of n.inventory){if(!Qx(w(r.blobs,`${e.digest.slice(7)}.bin`))){if(e.path.startsWith(`git/ai-delivery/writers@1/`)){if(i===void 0||V(i)!==e.digest)throw new D(`Original writer was lost before preservation.`);oS(r.blobs,i)}else TS(r.blobs,[e])}sS(r.blobs,e.digest)}let e=i===void 0?null:V(i);if(!uS(o,l).includes(e))throw new D(`Writer bytes/absence are outside the latest exact transition claim/release lineage.`);e!==null&&sS(r.blobs,e)}f=i===void 0?null:V(i),sS(r.blobs,o.originalRegistryDigest),dS(r.blobs,o,l),u(`authority`,{bytesDigest:oS(r.blobs,Buffer.from(z(p))),relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId});for(let t of n.holdEvidence){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.commentId})).data;if(oS(r.blobs,Buffer.from(z(n)))!==t.digest)throw new D(`Retained hold changed during preservation.`)}})},recordClaim:e=>{p=oS(r.blobs,e),u(`claim`,{bytesDigest:p,previousBytesDigest:f})},afterClaim:e=>{if(V(e)!==p)throw new D(`Actual writer claim bytes disagree with their recorded intent.`);u(`claimed`,{bytesDigest:p})},recordRelease:e=>{if(V(e)!==p)throw new D(`Writer changed before its exact recorded release.`);u(`release`,{bytesDigest:oS(r.blobs,e)})},afterRelease:async()=>{u(`released`,{absent:!0}),m&&o&&await cx(n,async({current:e})=>{if(z(e??null)!==z(g))throw new D(`Transition row changed before completion sealing.`);for(let e of n.inventory)sS(r.blobs,e.digest);let t=lS(a,o);dS(r.blobs,o,t);let c={schemaVersion:`ai-delivery.worktree-transition-completion@1`,planId:n.planId,intentId:o.intentId,completed:!0,writerReleased:!0,result:s,rowAfter:g,inventoryId:n.inventoryId,attempts:t.map(e=>e.stepId),completedAt:new Date().toISOString()};aS(i,{...c,completionId:B(c)})})}},async()=>{await cx(n,async({current:r,writeOwner:i,commitRow:a,removeRow:o})=>{let s=d.some(e=>e.event===`removal-intent`);if(await fS(e,n,!1,s,t.runtimeEntryPath),await vS(e,n,t),r!==void 0&&(i(),u(`owner`,{exactWitness:!0}),g=a(),u(`row`,{rowDigest:B(g)})),n.disposition===`remove`){if(u(`removal-intent`,{head:n.head,path:n.row.path}),Wx(n,ES(e).remote),Qx(n.row.path))throw new D(`Terminal source removal readback is not absent.`);u(`removed`,{absent:!0}),o(),g=null}m=!0})}),{planId:n.planId,result:s,replayed:d.length>0,receiptPath:i}}async function mS(e){if(e.clients.authSource!==`personal`||e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new D(`Worktree relinquishment requires the configured authenticated personal operator.`);let t=await e.clients.authenticatedAuthor();if(!/^user:[1-9]\d*$/u.test(t.credentialIdentity))throw new D(`Operator user identity is unavailable.`);let n=await vh({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(n.authSource!==`app`||!n.appActorLogin)throw new D(`Configured reviewer App identity is unavailable.`);let r=await n.appActorLogin();if(r.toLowerCase()===t.actorLogin.toLowerCase())throw new D(`Transition acceptance requires a distinct configured reviewer App.`);return{operator:t,reviewerActor:r,reviewer:n}}function hS(e){return z({schemaVersion:`ai-delivery.worktree-relinquishment@1`,plan:_S(e),acceptedScope:`the-complete-content-addressed-plan-and-every-original-in-its-inventory`,authority:`relinquish-only-the-inventoried-public-posix-writers`,operationalClosure:`the-inventory-is-the-complete-remaining-launcher-writer-and-managed-process-set-all-are-quiescent-no-unknown-resources`,maintainedExclusion:`all-old-launchers-and-writers-remain-excluded-through-apply-including-interruption-and-exact-plan-replay`,historicalAuthority:`preservation-only-no-current-verification-review-or-retirement-authority`,sourceDisposition:e.disposition===`remove`?`no-outstanding-holds-remove-only-clean-merged-source`:`retain-source-and-all-outstanding-holds`,exclusions:[`private-adoption`,`hold-release`,`launcher-changes`,`shared-runtime-admission`,`legacy-protocol-retirement`]})}function gS(e,t){return z({schemaVersion:`ai-delivery.worktree-transition-acceptance@1`,plan:_S(e),acceptedScope:`independent-acceptance-of-the-complete-content-addressed-plan-and-inventory-including-complete-launcher-set-and-maintained-exclusion`,relinquishmentCommentId:t,relinquishmentDigest:V(Buffer.from(hS(e))),result:`approved`})}function _S(e){let t=Jx.parse(e);return{planId:t.planId,inventoryId:t.inventoryId,repository:t.repository,repoRoot:t.repoRoot,row:t.row,head:t.head,purpose:t.purpose,disposition:t.disposition,terminalPrNumber:t.terminalPrNumber,lineage:t.lineage,remoteRefs:t.remoteRefs,holdEvidence:t.holdEvidence,closure:t.closure,currentRuntimeId:t.currentRuntime.admissionId,currentConfigDigest:t.currentRuntime.configDigest,policyDigest:t.policyDigest,operator:t.operator,reviewerActor:t.reviewerActor,historicalProducer:t.historicalProducer}}async function vS(e,t,n){let r=await mS(e);if(z(r.operator)!==z(t.operator)||r.reviewerActor!==t.reviewerActor)throw new D(`Configured transition authority identities drifted.`);if(t.lineage.some(e=>e.authorLogin.toLowerCase()===r.reviewerActor.toLowerCase()))throw new D(`Configured transition reviewer App is also the native PR author.`);let i=t.terminalPrNumber??t.row.issueNumber;return yS(e,{repository:t.repository,subject:i,operator:t.operator,reviewerActor:t.reviewerActor,authorityCommentId:n.relinquishmentCommentId,acceptanceCommentId:n.acceptanceCommentId,operatorBody:hS(t),reviewerBody:gS(t,n.relinquishmentCommentId),revokedBody:z({schemaVersion:`ai-delivery.worktree-relinquishment-revocation@1`,planId:t.planId,relinquishmentCommentId:n.relinquishmentCommentId})})}async function yS(e,t){let n=await mS(e);if(z(n.operator)!==z(t.operator)||n.reviewerActor!==t.reviewerActor)throw new D(`Configured transition authority identities drifted.`);let r=t.subject,i=`https://api.github.com/repos/${t.repository}/issues/${String(r)}`,a=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.authorityCommentId})).data,o=(await n.reviewer.rest.issues.getComment({...e.repo,comment_id:t.acceptanceCommentId})).data;if(a?.id!==t.authorityCommentId||a.issue_url?.toLowerCase()!==i.toLowerCase()||a.user?.type!==`User`||a.user?.login.toLowerCase()!==n.operator.actorLogin.toLowerCase()||`user:${String(a.user?.id)}`!==n.operator.credentialIdentity||a.body!==t.operatorBody)throw new D(`Native operator relinquishment is missing, changed or belongs to another subject.`);if(o?.id!==t.acceptanceCommentId||o.issue_url?.toLowerCase()!==i.toLowerCase()||o.user?.type!==`Bot`||o.user.login.toLowerCase()!==n.reviewerActor.toLowerCase()||o.body!==t.reviewerBody)throw new D(`Native configured reviewer-App exact-plan acceptance is missing or changed.`);for(let i=1;;i+=1){let a=(await e.clients.rest.issues.listComments({...e.repo,issue_number:r,per_page:100,page:i})).data;if(a.some(e=>e.body===t.revokedBody&&e.user?.login.toLowerCase()===n.operator.actorLogin.toLowerCase()&&`user:${String(e.user.id)}`===n.operator.credentialIdentity))throw new D(`Native operator relinquishment has been revoked.`);if(a.length<100)break}return{relinquishment:a,acceptance:o}}async function bS(e,t,n){let r=(await e.clients.rest.pulls.get({...e.repo,pull_number:n})).data,i=(await e.clients.graphql(`query WorktreeTransitionLineage($owner: String!, $repo: String!, $number: Int!) {
292
292
  repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
293
293
  closingIssuesReferences(first: 100) { nodes { number repository { nameWithOwner } } pageInfo { hasNextPage } }
294
294
  } }
295
- }`,{...e.repo,number:n})).repository.pullRequest?.closingIssuesReferences;if(r.number!==n||r.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||r.base.repo.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!i||i.pageInfo.hasNextPage||!i.nodes.some(n=>n.number===t&&n.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()))throw new D(`Native PR lineage does not establish the exact repository and closing issue.`);return Kx.parse({prNumber:n,headSha:r.head.sha,headBranch:r.head.ref,baseSha:r.base.sha,baseBranch:r.base.ref,mergeSha:r.merge_commit_sha,merged:r.merged,authorLogin:r.user?.login})}async function bS(e,t,n){let r=[...new Set([t.prNumber,n].filter(e=>e!=null))];return Promise.all(r.map(n=>yS(e,t.issueNumber,n)))}function xS(e,t,n,r,i,a,o,s){if(n===`active-resume`){if(![`active`,`pr-published`].includes(t.status)||o!==`open`||a.some(e=>e.merged||e.headSha!==i.sha||e.headBranch!==t.branch))throw new D(`Active resume requires the exact open issue and unmerged source lineage.`);if(s.some(e=>/^git\/ai-delivery\/(?:publications|reviews|merges|merge-intents|merge-attempts|merge-results)\//u.test(e.path)))throw new D(`Existing current publication/review/merge slots require separate authority reconciliation; active resume cannot overwrite them.`)}else{let n=a.find(e=>e.prNumber===r);if(!n||o!==`closed`||!n.merged||n.headSha!==i.sha||n.headBranch!==t.branch||a.some(r=>!r.merged||!r.mergeSha||r.headBranch!==t.branch||r.baseBranch!==n.baseBranch||dd(e,`merge-base`,`--is-ancestor`,r.mergeSha,r.prNumber===n.prNumber?n.mergeSha:i.sha)!==0))throw new D(`Terminal native PR lineage or merged-result ancestry does not bind the retained exact source.`)}}async function SS(e,t,n){let r=async t=>{try{let n=(await e.clients.rest.repos.getBranch({...e.repo,branch:t})).data;if(n.name!==t)throw new D(`Native branch readback belongs to another ref.`);return vd.parse(n.commit.sha)}catch(e){if(e.status===404)return null;throw e}},i=await r(t),a=await r(n);if(a===null)throw new D(`Native retaining base branch is missing.`);return{headSha:i,baseSha:a}}async function CS(e,t){let n=[],r=md(e.root),i=lx(r).filter(e=>e.type===`issue`&&e.issueNumber===t.issueNumber);if(i.length!==1)return{ready:!1,blockers:[`Expected one canonical legacy issue row.`],plan:null,inventory:[]};let a=[];try{let o=Gx.parse(i[0]);if(a.push(...$x(r,o)),!e.configuration||e.config.repository!==`${e.repo.owner}/${e.repo.repo}`)throw new D(`Transition requires exact current repository configuration.`);if(o.path!==w(r,`.worktrees`,`issue-${String(o.issueNumber)}`)||o.branch!==`issue/${String(o.issueNumber)}`||fd(o.path)!==h(o.path)||pd(o.path)!==pd(r)||ud(o.path,`branch`,`--show-current`)!==o.branch)throw new D(`Legacy row path, branch or Git ownership disagrees.`);gd(o.path);for(let e of[`v1`,`v2`])Zx(w(pd(r),`issue-cli`,`verification-stages`,e))&&n.push(`Unsupported operative issue-cli verification-stages/${e}; no authenticated supported operational closure is available.`);if((!t.retainedAdmissionPath||!t.retainedArchivePath)&&n.push(`Missing retained supported public producer admission/archive and operational closure. Historical UNKNOWN is preservation-only.`),n.length>0)return{ready:!1,blockers:n,plan:null,inventory:a};let s=await uy({repoRoot:r,configuration:e.configuration,...t.runtimeEntryPath===void 0?{}:{runtimeEntryPath:t.runtimeEntryPath}}),{inventory:c,...l}=Yx(e,h(t.retainedAdmissionPath),h(t.retainedArchivePath));a.push(...c);let u={sha:ud(o.path,`rev-parse`,`HEAD`),tree:ud(o.path,`rev-parse`,`HEAD^{tree}`)},d=Xx(r,o,a,l.producerDigest,u);if(a.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(t=>yb(Qx(t.source)).classification.repository!==e.config.repository))throw new D(`Operational run inventory belongs to another repository.`);if(t.disposition===`remove`&&c.some(e=>{let t=se(o.path,e.source);return t===``||!t.startsWith(`..`)&&!t.startsWith(`/`)}))throw new D(`Retained operational producer must remain outside the source selected for removal.`);let f=a.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));ub(o.path,f===void 0?void 0:Qx(f.source));let p=t.purpose===`merged-cleanup`?t.terminalPrNumber??o.prNumber??null:null,m=await bS(e,o,p),g=(await e.clients.rest.issues.get({...e.repo,issue_number:o.issueNumber})).data;xS(r,o,t.purpose,p,u,m,g.state,a);let _=await pS(e);if(m.some(e=>e.authorLogin.toLowerCase()===_.reviewerActor.toLowerCase()))throw new D(`Configured transition reviewer App is also the native PR author.`);let v=t.disposition===`remove`?await SS(e,o.branch,m.find(e=>e.prNumber===p).baseBranch):null;if(v&&(v.headSha!==null&&v.headSha!==u.sha||ud(r,`rev-parse`,_d(r,TS(e).remote))!==v.baseSha))throw new D(`Native remote branch readback disagrees with exact source or local retaining ref.`);let y=[...t.retainedHoldCommentIds??[]].sort((e,t)=>e-t);if(new Set(y).size!==y.length)throw new D(`Retained hold inventory has duplicates.`);let b=[];for(let t of y){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t})).data;if(!n.body||n.issue_url?.toLowerCase()!==`https://api.github.com/repos/${e.config.repository}/issues/${String(p??o.issueNumber)}`.toLowerCase())throw new D(`Retained hold comment belongs to another subject or is unavailable.`);let r=Buffer.from(z(n));b.push({commentId:t,digest:V(r)})}a.sort((e,t)=>e.path.localeCompare(t.path));let x={schemaVersion:`ai-delivery.worktree-transition-plan@1`,repository:e.config.repository,repoRoot:r,row:o,purpose:t.purpose,disposition:t.disposition??`retain`,head:u,terminalPrNumber:p,lineage:m,remoteRefs:v,retainedHoldCommentIds:y,holdEvidence:b,inventory:a,inventoryId:B(a),historicalProducer:`UNKNOWN`,closure:{family:`public-ai-delivery-0.3.5-posix@1`,...l,runManifestIds:d},currentRuntime:s,policyDigest:V(Qx(TS(e).policyModulePath)),operator:_.operator,reviewerActor:_.reviewerActor},ee=qx.parse({...x,planId:B(x)});return{ready:!0,blockers:n,plan:ee,inventory:a,relinquishmentBody:mS(ee)}}catch(e){return n.push(e instanceof Error?e.message:String(e)),{ready:!1,blockers:n,plan:null,inventory:a}}}function wS(e,t){for(let n of t){let t=Qx(n.source);if(t.length!==n.size||V(t)!==n.digest)throw new D(`Historical evidence drifted: ${n.path}`);wd(w(e,`${n.digest.slice(7)}.bin`),t,n.digest)}}function TS(e){if(!e.configuration||!(`policyModulePath`in e.configuration))throw new D(`Historical repository configuration binding is unsupported by this runtime; preserve its original controller and records. No policy module was loaded.`);return e.configuration}var ES=A().regex(/^[a-f0-9]{40}$/u),DS=A().regex(/^sha256:[a-f0-9]{64}$/u),OS=P({artifactId:DS,authorIdentity:A().min(1),checks:N(A().min(1)).min(1),diffScopeHash:DS,deliveryMetrics:P({blockerTimeMs:j().int().nonnegative().nullable(),reviewRound:j().int().positive()}).strict().optional(),elapsedMs:j().int().nonnegative(),findings:N(A()),head:P({sha:ES,tree:ES}).strict(),issueNumber:j().int().positive(),prNumber:j().int().positive().nullable(),readOnly:L(!0),requestedEffort:A().min(1),requestedModel:A().min(1),effectiveEffort:A().min(1),effectiveModel:A().min(1),reviewerIdentity:A().min(1),schemaVersion:L(`ai-delivery.review-artifact@1`),summary:A().min(1),verdict:I([`approve`,`request-changes`])}).strict().superRefine((e,t)=>{let{artifactId:n,...r}=e;(n!==B(r)||e.authorIdentity===e.reviewerIdentity)&&t.addIssue({code:`custom`,message:`Review artifact identity or role separation is invalid.`})});P({artifact:OS,completedAt:Du(),githubReviewId:j().int().positive(),githubReviewUrl:ml(),headSha:ES,login:A().min(1),prNumber:j().int().positive(),publicationEvidenceId:DS,receiptId:DS,schemaVersion:L(`ai-delivery.review-receipt@1`),state:L(`APPROVED`)}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||e.headSha!==e.artifact.head.sha||e.artifact.prNumber!==null&&e.artifact.prNumber!==e.prNumber)&&t.addIssue({code:`custom`,message:`Submitted review receipt is not bound to its artifact.`})});async function kS(e,t,n,r){let i;try{i=await e.clients.graphql(`query DeliveryReviewDecision($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid reviewDecision } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t})}catch{return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is unavailable.`}}let a=i.repository?.pullRequest;if(!a)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; PR decision readback is unavailable.`};if(a.headRefOid!==n)throw new D(`GitHub review decision does not match the exact PR head.`);if(a.reviewDecision!==null&&a.reviewDecision!==`APPROVED`&&a.reviewDecision!==`REVIEW_REQUIRED`&&a.reviewDecision!==`CHANGES_REQUESTED`)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is malformed.`};let o=null;if(r)try{let i=await e.clients.graphql(`query DeliveryReviewAccess($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviews(last: 100) { nodes { fullDatabaseId author { login } authorCanPushToRepository commit { oid } state } } } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t}),a=r.login.toLowerCase().replace(/\[bot\]$/u,``),s=i.repository?.pullRequest?.reviews.nodes.find(e=>e!==null&&String(e.fullDatabaseId)===String(r.id)&&e.author?.login.toLowerCase().replace(/\[bot\]$/u,``)===a&&e.commit?.oid===n&&e.state===`APPROVED`);typeof s?.authorCanPushToRepository==`boolean`&&(o=s.authorCanPushToRepository)}catch{}return a.reviewDecision===`APPROVED`?{reviewDecision:`APPROVED`,submittedReviewAuthorCanPushToRepository:o,status:`satisfied`,nextAction:`Continue only after required checks pass.`}:a.reviewDecision===`REVIEW_REQUIRED`?{reviewDecision:`REVIEW_REQUIRED`,submittedReviewAuthorCanPushToRepository:o,status:`still-required`,nextAction:o===!1?`GitHub still requires a qualifying approval; the submitted reviewer App review has no repository write access. Inspect the active rule and the App installation Contents grant, then obtain approval from an eligible independent reviewer.`:`GitHub still requires a qualifying approval. Inspect the active rule and obtain approval from an eligible independent reviewer; do not change actors or protections automatically.`}:a.reviewDecision===`CHANGES_REQUESTED`?{reviewDecision:`CHANGES_REQUESTED`,submittedReviewAuthorCanPushToRepository:o,status:`changes-requested`,nextAction:`Resolve the blocking review and obtain a fresh exact-head independent approval.`}:{reviewDecision:null,submittedReviewAuthorCanPushToRepository:o,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; no required-review decision was exposed.`}}function AS(e){let t=typeof e==`string`?JSON.parse(e):e;return OS.parse(t)}function jS(e){try{if(typeof e!=`string`||Buffer.byteLength(e,`utf8`)>65536)throw Error(`Invalid size.`);let t=e.match(/<!-- ai-delivery-review-artifact:[\s\S]*?-->/gu)??[],n=e.match(/<!-- ai-delivery-review-artifact-data:[\s\S]*?-->/gu)??[];if(t.length!==1||n.length!==1)throw Error(`Ambiguous binding.`);let r=t[0].match(/^<!-- ai-delivery-review-artifact: (sha256:[a-f0-9]{64}) -->$/u)?.[1],i=n[0].match(/^<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->$/u)?.[1];if(!r||!i)throw Error(`Invalid binding.`);let a=Buffer.from(i,`base64url`),o=a.toString(`utf8`);if(a.toString(`base64url`)!==i||!Buffer.from(o,`utf8`).equals(a))throw Error(`Invalid encoding.`);let s=AS(o);if(s.artifactId!==r)throw Error(`Artifact identity differs.`);return s}catch{throw new D(`GitHub review artifact binding is missing, invalid or ambiguous; obtain a fresh review.`)}}function MS(e){OS.parse(e);let t=`${e.summary}\n\n<!-- ai-delivery-review-artifact: ${e.artifactId} -->\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(e)).toString(`base64url`)} -->`;return jS(t),t}async function NS(e,t,n){let r=[];for(let n=1;n<=30;n++){let i=(await e.clients.rest.pulls.listFiles({...e.repo,pull_number:t,page:n,per_page:100})).data;if(r.push(...i.map(e=>e.filename)),i.length<100)break}if(!Number.isSafeInteger(n)||r.length!==n||new Set(r).size!==r.length)throw new D(`Independent review scope is incomplete or differs from the remote PR diff.`);return B(r.sort())}async function PS(e,t){let n=[];for(let r=1;r<=20;r+=1){let i=await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,per_page:100,page:r});if(n.push(...i.data),i.data.length<100)return n}throw new D(`Review history exceeds the bounded readback window.`)}async function FS(e){let{artifact:t,context:n,issueNumber:r,prNumber:i}=e;if(OS.parse(t),t.verdict!==`approve`||t.issueNumber!==r||t.authorIdentity!==n.config.roles.author.identity||t.reviewerIdentity!==n.config.roles.reviewer.identity||t.prNumber!==null&&t.prNumber!==i)throw new D(`Independent review artifact is foreign or rejected.`);if(n.clients.authSource!==`app`||n.clients.role!==`reviewer`||!n.clients.appActorLogin)throw new D(`Formal review requires the independent reviewer GitHub App role.`);let a=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(a.number!==i||a.head.sha!==t.head.sha||a.state!==`open`||a.base.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase()||a.head.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase())throw new D(`PR identity or head changed before formal review.`);let o=await n.clients.appActorLogin();if(!o||!a.user?.login||o.toLowerCase()===a.user.login.toLowerCase())throw new D(`Reviewer GitHub actor must differ from PR author.`);let s=(await n.clients.rest.git.getCommit({...n.repo,commit_sha:t.head.sha})).data;if(s.sha!==t.head.sha||s.tree.sha!==t.head.tree)throw new D(`Independent review tree differs from the remote commit.`);if(t.diffScopeHash!==await NS(n,i,a.changed_files))throw new D(`Independent review scope is incomplete or differs from the remote PR diff.`);let c=MS(t),l=`<!-- ai-delivery-review-artifact: ${t.artifactId} -->`,u=await PS(n,i);if(u.some(e=>e.user?.login.toLowerCase()===o.toLowerCase()&&e.commit_id===t.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``)&&!e.body?.includes(l)))throw new D(`Another independent artifact conflicts with the existing exact-head App approval.`);let d=u.filter(e=>e.body?.includes(l));if(d.length>1)throw new D(`Conflicting GitHub reviews claim the same artifact identity.`);let f=d[0];if(f&&(f.state!==`APPROVED`||f.commit_id!==t.head.sha||f.user?.login.toLowerCase()!==o.toLowerCase()||!f.html_url||jS(f.body).artifactId!==t.artifactId))throw new D(`Prior GitHub review marker conflicts with exact-head approval.`);let p=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(p.head.sha!==t.head.sha||p.base.sha!==a.base.sha||p.state!==`open`)throw new D(`PR moved during independent review validation.`);if(e.dryRun)return{dryRun:!0,artifactId:t.artifactId,headSha:t.head.sha};let m=f??(await n.clients.rest.pulls.createReview({...n.repo,pull_number:i,commit_id:t.head.sha,body:c,event:`APPROVE`})).data;if(!m.id||m.state!==`APPROVED`||m.commit_id!==t.head.sha||m.user?.login.toLowerCase()!==o.toLowerCase()||!m.html_url)throw new D(`GitHub did not return complete exact-head independent approval.`);let h={artifact:t,repository:n.config.repository,baseSha:a.base.sha,headSha:t.head.sha,githubReviewId:m.id,githubReviewUrl:m.html_url,login:m.user.login,prNumber:i,schemaVersion:`ai-delivery.github-review@1`,state:`APPROVED`},g={...h,receiptId:B(h)},_=(await n.clients.rest.pulls.getReview({...n.repo,pull_number:i,review_id:m.id})).data;if(_.id!==g.githubReviewId||_.html_url!==g.githubReviewUrl||_.state!==`APPROVED`||_.commit_id!==g.headSha||_.user?.login!==g.login||jS(_.body).artifactId!==t.artifactId)throw new D(`GitHub exact-head App review readback disagrees.`);let v=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(v.head.sha!==t.head.sha||v.base.sha!==a.base.sha||v.state!==`open`)throw new D(`PR moved during independent review submission; approval is not current.`);return g}var IS=/^[a-f0-9]{40}$/u,LS=/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;function RS(e){if(typeof e!=`string`)throw new D(`Incomplete non-closing message readback.`);let t=e.replace(/[*_~`\\<>[\]]/gu,``);if(/\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\b(?:\s*:\s*|\s+)[^\n]*?(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(t))throw new D(`Non-closing delivery refuses closing directives in body, title or commit messages.`)}function zS(e,t){return`References ${e.config.repository}#${t}`}function BS(e,t,n){RS(n);let r=zS(e,t),i=n.startsWith(`${r}\n`)||n===r?n:`${r}\n\n${n}`;return VS(e,t,i),i}function VS(e,t,n){RS(n);let r=n.split(/\r?\n/u);if(r[0]!==zS(e,t)||r.filter(e=>/^References\s/iu.test(e)).length!==1)throw new D(`Non-closing PR body must retain one leading canonical References line.`)}function HS(e,t){let n=e.pageInfo;if(!n||typeof n.hasNextPage!=`boolean`||n.endCursor!==null&&typeof n.endCursor!=`string`)throw new D(`Incomplete non-closing native pagination.`);if(!n.hasNextPage)return null;if(!n.endCursor||t.has(n.endCursor))throw new D(`Non-closing native pagination did not advance.`);return t.add(n.endCursor),n.endCursor}async function US(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(n.number!==t||`pull_request`in n||n.state!==`open`||typeof n.node_id!=`string`||!n.node_id||typeof n.title!=`string`||typeof n.body!=`string`||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/issues/${t}`.toLowerCase())throw new D(`Non-closing delivery requires the exact canonical OPEN issue and complete title/body.`);return n}function WS(e,t,n=!1){if(n?e.state!==`open`||e.draft||e.merged||t.state!==`closed`||t.draft||!t.merged:e.state!==t.state||e.draft!==t.draft||e.merged!==t.merged)throw new D(`Non-closing PR state/draft/merged readback drifted; reconcile read-only.`);if(e.node_id!==t.node_id||e.head.sha!==t.head.sha||e.head.ref!==t.head.ref||e.base.sha!==t.base.sha||e.base.ref!==t.base.ref||e.body!==t.body||e.title!==t.title||e.user.login.toLowerCase()!==t.user.login.toLowerCase())throw new D(`Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.`)}function GS(e,t){if(e.node_id!==t.node_id||e.title!==t.title||e.body!==t.body)throw new D(`Non-closing issue identity/title/criteria drifted; reconcile read-only.`)}function KS(e){if(e!==void 0&&typeof e!=`boolean`)throw new D(`nonClosing must be a boolean.`);return e===!0}async function qS(e,t){let n=await uC(e.clients.role===`author`?e:{...e,clients:await vh({config:e.config,identity:e.config.roles.author.identity,role:`author`}),reviewerClients:e.clients},t);if(n.rules.visibility!==`complete`||n.approvalEligibility===`insufficient-permission`)throw new D(`Non-closing delivery requires complete native rule visibility and an independent reviewer route.`);return n}async function JS(e,t){let n=null,r=new Set,i=new Map,a;for(let o=0;o<20;o++){let o=await e.clients.graphql(`query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t.number,cursor:n}),s=o.repository?.pullRequest,c=s?.commits;if(o.repository?.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||s?.id!==t.node_id||s.number!==t.number||s.headRefOid!==t.head.sha||s.baseRefOid!==t.base.sha||s.baseRefName!==t.base.ref||!c||!Array.isArray(c.nodes)||c.nodes.length>100||!Number.isSafeInteger(c.totalCount)||c.totalCount<1||c.totalCount>2e3||a!==void 0&&a!==c.totalCount)throw new D(`Incomplete or moved introduced commit graph at the non-closing head/base.`);a=c.totalCount;for(let e of c.nodes){let t=e?.commit;if(!t||!QS(t.oid)||i.has(t.oid)||!t.parents||!Array.isArray(t.parents.nodes)||t.parents.nodes.length>100||!Number.isSafeInteger(t.parents.totalCount)||t.parents.totalCount<1||t.parents.totalCount!==t.parents.nodes.length||t.parents.pageInfo?.hasNextPage!==!1||t.parents.nodes.some(e=>!QS(e?.oid)))throw new D(`Incomplete, duplicate or truncated introduced commit identity/parents.`);RS(t.message),i.set(t.oid,t.message)}if(n=HS(c,r),n===null){if(i.size!==a||!i.has(t.head.sha))throw new D(`Introduced commit count/head is incomplete.`);return}}throw new D(`Non-closing commit graph exceeds the bounded readback window.`)}async function YS(e,t,n){let r=new Set,i;for(let a=1;a<=20;a++){let o=(await e.clients.rest.repos.compareCommitsWithBasehead({...e.repo,basehead:`${t}...${n}`,per_page:100,page:a})).data;if(o.base_commit?.sha!==t||!QS(o.merge_base_commit?.sha)||![`ahead`,`diverged`].includes(o.status)||!Number.isSafeInteger(o.total_commits)||o.total_commits<1||o.total_commits>2e3||i!==void 0&&i!==o.total_commits||!Array.isArray(o.commits)||o.commits.length>100)throw new D(`Incomplete introduced commit range before non-closing publication.`);i=o.total_commits;for(let e of o.commits){if(!QS(e.sha)||r.has(e.sha)||!Array.isArray(e.parents)||e.parents.length<1||e.parents.length>100||e.parents.some(e=>!QS(e.sha)))throw new D(`Incomplete or duplicate introduced commit identity.`);RS(e.commit?.message),r.add(e.sha)}if(r.size===i&&r.has(n))return;if(o.commits.length<100)throw new D(`Truncated introduced commit range before publication.`)}throw new D(`Introduced commit range exceeds the bounded readback window.`)}async function XS(e,t,n){if(typeof n.node_id!=`string`||!n.node_id||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/pull/${n.number}`.toLowerCase())throw new D(`Incomplete non-closing PR node identity.`);VS(e,t,n.body),RS(n.title);let r=await US(e,t),i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||n.base.ref!==i.default_branch||typeof i.node_id!=`string`||!i.node_id)throw new D(`Non-closing PR must target the canonical default repository/base.`);let a=await qS(e,n.base.ref);if(n.user.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new D(`Non-closing PR author differs from the configured author.`);let o=null,s=new Set,c=new Map,l=!1;for(let u=0;u<20;u++){let d=await e.clients.graphql(`query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:o}),f=d.repository?.issue,p=f?.timelineItems;if(d.repository?.id!==i.node_id||d.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||f?.id!==r.node_id||f.number!==t||f.state!==`OPEN`||!p||!Array.isArray(p.nodes)||p.nodes.length>100)throw new D(`Incomplete or conflicting native non-closing issue identity.`);for(let o of p.nodes){let s=o?.source,u=o?.target;if(!o||!ZS(o.id)||!s||!u||![`Issue`,`PullRequest`].includes(s.__typename)||!ZS(s.id)||!Number.isSafeInteger(s.number)||s.number<=0||!ZS(s.repository?.id)||typeof s.repository.nameWithOwner!=`string`||u.__typename!==`Issue`||u.id!==r.node_id||u.number!==t||u.repository?.id!==i.node_id||u.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||typeof o.isCrossRepository!=`boolean`||typeof o.willCloseTarget!=`boolean`||!ZS(o.actor?.login))throw new D(`Incomplete native cross-reference event identity/actor.`);let d=JSON.stringify([s.__typename,s.id,s.number,s.repository.id,s.repository.nameWithOwner.toLowerCase(),u.id,u.number,u.repository.id,u.repository.nameWithOwner.toLowerCase(),o.actor.login.toLowerCase(),o.isCrossRepository,o.willCloseTarget]);if(c.has(o.id)&&c.get(o.id)!==d)throw new D(`Conflicting duplicate native reference event.`);if(c.set(o.id,d),s.id===n.node_id||s.__typename===`PullRequest`&&s.number===n.number&&s.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()){if(s.__typename!==`PullRequest`||s.id!==n.node_id||s.number!==n.number||s.repository.id!==i.node_id||s.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||o.isCrossRepository||o.willCloseTarget!==!1||o.actor.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new D(`Conflicting, closing or unauthorized native PR reference.`);l=!0}}if(o=HS(p,s),o===null)break;if(u===19)throw new D(`Native non-closing references exceed the bounded readback window.`)}if(!l)throw new D(`Missing authorized native non-closing PR-to-issue reference.`);if(await tC(e,n.number,t,!0,n.node_id),await JS(e,n),!n.merged){let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${n.base.ref}`})).data;if(t.ref!==`refs/heads/${n.base.ref}`||t.object.type!==`commit`||t.object.sha!==n.base.sha)throw new D(`Non-closing default base has moved or is incomplete.`)}return GS(r,await US(e,t)),WS(n,await eC(e,n.number)),r}function ZS(e){return typeof e==`string`&&e.trim().length>0}function QS(e){return typeof e==`string`&&IS.test(e)}function $S(e){if(typeof e!=`string`||!LS.test(e)||e.startsWith(`/`)||e.endsWith(`/`)||e.endsWith(`.lock`))throw new D(`Invalid GitHub branch name.`)}async function eC(e,t){if(e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Configured and selected GitHub repository identities disagree.`);let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data;if(n.number!==t||typeof n.base.repo?.full_name!=`string`||typeof n.head.repo?.full_name!=`string`||n.base.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||n.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!QS(n.head.sha)||!QS(n.base.sha)||n.state!==`open`&&n.state!==`closed`||typeof n.merged!=`boolean`||typeof n.draft!=`boolean`||n.merged&&n.state!==`closed`)throw new D(`GitHub PR identity or exact head readback is invalid.`);return $S(n.head.ref),$S(n.base.ref),n}async function tC(e,t,n,r=!1,i,a=!1,o,s){let c=null,l=new Set,u=0;for(let d=0;d<20;d++){let d=await e.clients.graphql(`query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:c}),f=d.repository?.pullRequest?.closingIssuesReferences;if(typeof d.repository?.nameWithOwner!=`string`||d.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||d.repository?.pullRequest?.number!==t||i!==void 0&&d.repository?.pullRequest?.id!==i||!f||!Array.isArray(f.nodes)||f.nodes.length>100||typeof f.pageInfo?.hasNextPage!=`boolean`||f.pageInfo.endCursor!==null&&typeof f.pageInfo.endCursor!=`string`)throw new D(`Incomplete or conflicting native GitHub PR issue association readback.`);for(let t of f.nodes){if(a&&(!t||t.__typename!==`Issue`||!ZS(o)||t.id!==o||!ZS(s)||t.repository?.id!==s))throw new D(`Incomplete or conflicting typed closing issue/repository identity before body transition.`);if(r)throw new D(`Non-closing PR has an unintended native closing association.`);if(!t||!Number.isSafeInteger(t.number)||t.number<=0||typeof t.repository?.nameWithOwner!=`string`||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(t.repository.nameWithOwner))throw new D(`Incomplete native PR closing-issue identity.`);if(t.number===n&&t.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase())u++;else if(a)throw new D(`Existing PR has conflicting closing associations; body transition refused.`)}if(!f.pageInfo.hasNextPage){if(!r&&u!==1)throw new D(`Native GitHub PR closing-issue association does not identify the intended issue.`);return}let p=f.pageInfo.endCursor;if(!p||l.has(p))throw new D(`Native PR issue pagination did not advance.`);l.add(p),c=p}throw new D(`Native PR issue association exceeds the bounded readback window.`)}async function nC(e,t,n){let r=[];for(let i=1;i<=20;i++){let a=(await e.clients.rest.pulls.list({...e.repo,head:`${e.repo.owner}:${t}`,...n===void 0?{}:{base:n},state:`all`,page:i,per_page:100})).data;if(!Array.isArray(a)||a.some(e=>!e||!Number.isSafeInteger(e.number)||e.number<=0))throw new D(`Incomplete GitHub PR match readback.`);if(r.push(...a),a.length<100)return r}throw new D(`GitHub PR match history exceeds the bounded readback window.`)}async function rC(e,t,n,r=!1){let i=await eC(e,n);if(r?await XS(e,t,i):await tC(e,n,t),!i.merged){let n=await Jv(e,t);if(n.length>0){let e=n.filter(e=>e.name===i.head.ref);if(e.length!==1||e[0].sha!==i.head.sha)throw new D(`Native linked issue branches conflict with the exact PR head/ref.`)}let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.head.ref}`})).data;if(r.ref!==`refs/heads/${i.head.ref}`||r.object.type!==`commit`||r.object.sha!==i.head.sha)throw new D(`Current remote PR head/ref readback is incomplete or has moved.`)}return i}async function iC(e,t){let n=KS(t.nonClosing);if(n&&(t.issueNumber===void 0||t.prNumber===void 0))throw new D(`Non-closing inspection requires explicit canonical issue and PR numbers.`);let r=t.prNumber;if(r===void 0){if(t.issueNumber===void 0)throw new D(`prNumber or issueNumber is required.`);let n=await Jv(e,t.issueNumber);if(n.length!==1)throw new D(`Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.`);let i=n[0].name,a=await nC(e,i);if(a.length!==1)throw new D(`Select an explicit PR number when the remote issue branch has zero or multiple PRs.`);r=a[0].number}let i=t.issueNumber===void 0?await eC(e,r):await rC(e,t.issueNumber,r,n);return{prNumber:i.number,url:i.html_url,state:i.state,draft:i.draft,headSha:i.head.sha,headBranch:i.head.ref,baseBranch:i.base.ref,merged:i.merged}}async function aC(e,t=`open`){return{schemaVersion:`ai-delivery.pr-list@1`,pullRequests:(await e.clients.rest.paginate(e.clients.rest.pulls.list,{...e.repo,state:t,per_page:100})).map(e=>({number:e.number,state:e.state,draft:e.draft??!1,headSha:e.head.sha,baseSha:e.base.sha,url:e.html_url}))}}async function oC(e,t){let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data,[r,i,a]=await Promise.all([e.clients.rest.checks.listForRef({...e.repo,ref:n.head.sha,per_page:100}),e.clients.rest.repos.getCombinedStatusForRef({...e.repo,ref:n.head.sha}),kS(e,t,n.head.sha)]);return{schemaVersion:`ai-delivery.pr-checks@1`,prNumber:n.number,headSha:n.head.sha,combinedStatus:i.data.state,reviewState:a,checkRuns:r.data.check_runs.map(e=>({name:e.name,status:e.status,conclusion:e.conclusion}))}}function sC(e){if(typeof e!=`object`||!e)return null;let t=e.required_approving_review_count;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:null}function cC(e){return e.status===200&&Array.isArray(e.data)&&e.headers!==void 0&&e.headers!==null&&(e.headers.link===void 0||e.headers.link===``)}function lC(e){return cC(e)&&Array.isArray(e.data)&&e.data.length===0}async function uC(e,t,n,r=`publication`,i){if(t===void 0)try{t=(await e.clients.rest.repos.get({...e.repo})).data.default_branch}catch{throw new D(`Author cannot read the selected GitHub repository; verify configured access.`)}let a=async()=>{await i?.checkResources(),i?.signal.throwIfAborted()};await a();let o=e.config.roles.author.authSource??`app`,s=r===`development`&&o===`app`&&e.clients.authSource===`personal`;if(e.clients.authSource!==o&&!s)throw new D(r===`publication`?`PR publication requires the configured author credential; configure the personal author role for personal publication.`:`Development access preflight requires the configured author credential or the explicit personal author override.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new D(`Delivery access preflight requires authenticated author identity readback.`);let c=await e.clients.authenticatedAuthor(i?.signal);if(await a(),!c.actorLogin||!c.credentialIdentity)throw new D(`Author GitHub identity readback is incomplete.`);let l=n??e.reviewerClients??await vh({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients,...i===void 0?{}:{signal:i.signal}});if(await a(),l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new D(`Configured reviewer GitHub App identity is unavailable.`);let u=await l.appActorLogin(i?.signal);if(await a(),!u)throw new D(`Reviewer GitHub App actor lookup is incomplete.`);if(c.actorLogin.toLowerCase()===u.toLowerCase())throw new D(`Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.`);try{let t=(await l.rest.repos.get({...e.repo,...i===void 0?{}:{request:{signal:i.signal}}})).data;if(await a(),t.full_name.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Reviewer GitHub App repository readback disagrees with the selected checkout.`)}catch(e){throw e instanceof D?e:new D(`Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`)}let[d,f]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}/rules/branches/{branch}`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}}),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}/protection`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}})]);await a();let p=!1,m=!1;if(d.status===`fulfilled`&&cC(d.value)&&f.status===`rejected`&&wh(f.reason,e.clients,e.repo,t)){let n={...e.repo,...i===void 0?{}:{request:{signal:i.signal}}},[r,o,s]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}`,n),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}`,{...n,branch:t}),e.clients.rest.request(`GET /repos/{owner}/{repo}/rulesets`,{...n,includes_parents:!0,per_page:100,page:1})]);if(await a(),r.status===`fulfilled`&&o.status===`fulfilled`&&s.status===`fulfilled`){let n=r.value.data,i=o.value.data,a=r.value.status===200&&o.value.status===200&&typeof n?.full_name==`string`&&n.full_name.toLowerCase()===`${e.repo.owner}/${e.repo.repo}`.toLowerCase()&&(n.permissions?.push===!0||n.permissions?.admin===!0)&&i?.name===t;p=a&&lC(d.value)&&i?.protected===!1&&i.protection?.enabled===!1&&lC(s.value),m=a&&i?.protected===!0&&typeof i.protection?.enabled==`boolean`&&cC(s.value)&&d.value.data.length>0&&d.value.data.every(t=>{if(typeof t!=`object`||!t||typeof t.type!=`string`||!t.type||typeof t.ruleset_id!=`number`||!Number.isSafeInteger(t.ruleset_id)||t.ruleset_id<=0||typeof t.ruleset_source!=`string`||(t.ruleset_source_type===`Repository`?t.ruleset_source.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase():t.ruleset_source_type!==`Organization`||t.ruleset_source.toLowerCase()!==e.repo.owner.toLowerCase())||t.type===`pull_request`&&sC(t.parameters)===null)return!1;let n=s.value.data.filter(e=>e?.id===t.ruleset_id);return n.length===1&&n[0]?.source_type===t.ruleset_source_type&&n[0]?.source===t.ruleset_source&&n[0]?.enforcement===`active`})}}let h=[],g=d.status===`fulfilled`&&cC(d.value);if(d.status===`fulfilled`&&Array.isArray(d.value.data)){for(let e of d.value.data)if((typeof e!=`object`||!e||typeof e.type!=`string`||!e.type)&&(g=!1),e?.type===`pull_request`){let t=sC(e.parameters);t===null?g=!1:h.push(t)}}if(f.status===`fulfilled`){let e=f.value.data,t=typeof e==`object`&&e&&!Array.isArray(e)?sC(e.required_pull_request_reviews):null;(f.value.status!==200||t===null)&&(g=!1),t!==null&&h.push(t)}else!p&&!m&&(g=!1);let _=d.status===`fulfilled`&&Array.isArray(d.value.data)&&(d.value.headers?.link===void 0||d.value.headers.link===``),v=Number(_)+Number(f.status===`fulfilled`||p||m),y=v===2?`complete`:v===1?`partial`:`unknown`,b=h.length>0&&(g||h.some(e=>e>0))?Math.max(...h):g&&p?0:null,x=b!==null&&b>0&&l.effectiveContentsPermission===`read`;return{author:{actorLogin:c.actorLogin,authSource:e.clients.authSource,credentialSource:e.clients.credentialSource??`unreported`,identity:s?`personal`:e.config.roles.author.identity},reviewer:{actorLogin:u,credentialSource:l.credentialSource??`unreported`,effectiveContentsPermission:l.effectiveContentsPermission??`unknown`,identity:e.config.roles.reviewer.identity,repositoryAccess:`readable`},rules:{observedRequiredApprovals:b,visibility:y},approvalEligibility:x?`insufficient-permission`:`unknown`,nextAction:x?`The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.`:y===`complete`&&b===null?`No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.`:y===`complete`?`Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.`:`Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.`}}async function dC(e,t){let n=KS(t.nonClosing);if(t.prNumber!==void 0&&(!Number.isSafeInteger(t.prNumber)||t.prNumber<=0))throw new D(`Existing PR selector must be a positive safe integer.`);let r=n?await US(e,t.issueNumber):(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber||r.state!==`open`)throw new D(`PR creation requires the requested open GitHub issue.`);let i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Configured and selected GitHub repository identities disagree.`);if(n&&!ZS(i.node_id))throw new D(`Incomplete canonical non-closing repository node identity.`);let a=t.baseBranch??i.default_branch;if(a!==i.default_branch)throw new D(`PR delivery requires the repository default branch for durable issue association.`);$S(a),t.headBranch!==void 0&&$S(t.headBranch);let o=t.prNumber===void 0?void 0:await eC(e,t.prNumber),s=t.draft===!1&&t.headBranch!==void 0,c=o?await nC(e,o.head.ref,a):s?await nC(e,t.headBranch,a):void 0,l=o?o.head.ref:s&&c.length>0?t.headBranch:await Yv(e,t.issueNumber,t.headBranch);if(t.headBranch!==void 0&&l!==t.headBranch)throw new D(`Explicit PR and head selectors disagree.`);$S(l);let u=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data;if(u.ref!==`refs/heads/${l}`||u.object.type!==`commit`||!QS(u.object.sha))throw new D(`Remote issue branch head/ref readback is invalid.`);let d=c??await nC(e,l,a);if(d.length>1||o&&(d.length!==1||d[0].number!==o.number))throw new D(`Remote issue branch has conflicting PR matches.`);let f=o??(d[0]===void 0?void 0:await eC(e,d[0].number)),p=t.body??(n?f?.body??zS(e,t.issueNumber):`Closes #${t.issueNumber}`);if(!p.trim())throw new D(`PR body must contain text.`);let m=n?BS(e,t.issueNumber,p):RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${t.issueNumber}(?![0-9])`,`iu`).test(p)?p:`${p}\n\nCloses #${t.issueNumber}`,h=n&&f!==void 0&&f.body!==m;if(h&&(t.prNumber===void 0||t.body===void 0))throw new D(`Non-closing body transition requires an explicit existing PR number and body.`);if(f&&(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a||f.state!==`open`||f.merged||!h&&t.body!==void 0&&f.body!==m||t.title!==void 0&&f.title!==t.title))throw new D(`Existing remote PR conflicts with the requested branch, intent or state.`);let g=n?await qS(e,a):await uC(e,a);if(f&&f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new D(`Existing PR author differs from the configured authenticated author.`);if(f&&(typeof f.node_id!=`string`||!f.node_id))throw new D(`Existing PR publication identity is incomplete.`);n&&RS(t.title??f?.title??r.title);let _=t.title??r.title,v,y=f,b=h,x=f?.body,ee=f?.draft,S=!1,te=async()=>{n&&GS(r,await US(e,t.issueNumber))},ne=async()=>{let o=await rC(e,t.issueNumber,y.number,n&&!b);if(o.state!==`open`||o.merged||o.node_id!==y.node_id||o.head.sha!==u.object.sha||o.head.ref!==l||o.base.ref!==a||o.base.sha!==y.base.sha||o.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase()||h&&!S&&o.draft!==ee||o.body!==x||o.title!==y.title)throw new D(`Existing PR publication head, identity, intent or author readback drifted.`);if(b){await tC(e,o.number,t.issueNumber,!1,o.node_id,!0,r.node_id,i.node_id),RS(o.title),await JS(e,o);let n=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(n.ref!==`refs/heads/${a}`||n.object.type!==`commit`||n.object.sha!==o.base.sha)throw new D(`Non-closing transition default base drifted.`);WS(o,await eC(e,o.number))}return await te(),o},re=async()=>{let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(t.ref!==`refs/heads/${a}`||t.object.type!==`commit`||!QS(t.object.sha))throw new D(`Incomplete publication default base.`);if(v!==void 0&&v!==t.object.sha)throw new D(`Publication default base drifted before creation.`);v=t.object.sha,n&&await YS(e,t.object.sha,u.object.sha);let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data,i=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(r.ref!==u.ref||r.object.type!==`commit`||r.object.sha!==u.object.sha||i.ref!==t.ref||i.object.type!==`commit`||i.object.sha!==t.object.sha)throw new D(`Non-closing publication head/base drifted.`);await te()};if(f?f=await ne():await re(),t.dryRun)return{dryRun:!0,...f===void 0?{}:{prNumber:f.number,draft:f.draft},...n?{nonClosing:!0,nonClosingVerified:f!==void 0&&!b,body:m,bodyTransition:b}:{},headSha:u.object.sha,headBranch:l,baseBranch:a,reviewRoute:g};let ie=!1;if(f){if(b&&(f=await ne(),await e.clients.rest.pulls.update({...e.repo,pull_number:f.number,body:m}),b=!1,x=m,f=await ne()),t.draft===!1&&f.draft){if(f=await ne(),f.draft){let t=await e.clients.graphql(`mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}`,{id:f.node_id});if(t?.markPullRequestReadyForReview?.pullRequest?.id!==f.node_id||t.markPullRequestReadyForReview.pullRequest.isDraft!==!1)throw new D(`PR promotion mutation readback is incomplete or conflicting; reconcile this PR.`);S=!0}if(f=await ne(),f.draft)throw new D(`PR promotion readback is still draft.`)}}else{await re();let n;try{n=await e.clients.rest.pulls.create({...e.repo,head:l,base:a,title:_,body:m,draft:t.draft!==!1})}catch(e){throw new D(`PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${e instanceof Error?e.message:`Unknown failure`}`)}if(!Number.isSafeInteger(n.data.number)||n.data.number<=0)throw new D(`PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.`);ie=!0;try{f=await eC(e,n.data.number)}catch(e){throw new D(`GitHub returned created PR #${n.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`)}}try{if(ie&&(f.body!==m||f.title!==_||f.draft!==(t.draft!==!1)||f.state!==`open`||f.merged||f.base.sha!==v))throw new D(`Created PR body, title, draft/open state or default base differs from publication intent.`);if(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a)throw new D(`GitHub PR creation readback drifted.`);if(f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new D(`Published PR author differs from the configured authenticated author.`);if(n){let n=await rC(e,t.issueNumber,f.number,!0);WS(f,n),f=n,await te()}else await tC(e,f.number,t.issueNumber);if(ie){let t=await eC(e,f.number);WS(f,t),f=t}}catch(e){throw ie?new D(`GitHub created PR #${f.number} (${f.html_url}) at ${f.head.sha}; post-publication association/identity verification is unresolved. Reconcile this PR read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`):e}return{prNumber:f.number,url:f.html_url,headSha:f.head.sha,draft:f.draft,reviewRoute:g,...n?{nonClosing:!0}:{}}}async function fC(e,t){let n=KS(t.nonClosing),r=await rC(e,t.issueNumber,t.prNumber,n),i=n?await US(e,t.issueNumber):void 0,a=await FS({context:e,artifact:AS(t.artifact),issueNumber:t.issueNumber,prNumber:t.prNumber,...t.dryRun===void 0?{}:{dryRun:t.dryRun}});return n&&(WS(r,await rC(e,t.issueNumber,t.prNumber,!0)),GS(i,await US(e,t.issueNumber))),a}async function pC(e,t){let n=[];for(let r=1;r<=20;r++){let i=(await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,page:r,per_page:100})).data;if(n.push(...i),i.length<100)return n}throw new D(`GitHub review history exceeds the bounded readback window.`)}async function mC(e,t){let n=KS(t.nonClosing);if(n&&t.strategy!==void 0&&t.strategy!==`squash`)throw new D(`Non-closing merge requires squash with explicit safe messages.`);if(e.clients.role!==`author`||e.clients.authSource!==(e.config.roles.author.authSource??`app`)||!e.clients.authenticatedAuthor)throw new D(`Merge and finish require the configured authenticated author role.`);let r=await e.clients.authenticatedAuthor();if(!r.actorLogin||!r.credentialIdentity)throw new D(`Author identity readback is incomplete.`);let i=await rC(e,t.issueNumber,t.prNumber,n),a=i,o=n?await US(e,t.issueNumber):void 0,s=n?{commit_title:i.title,commit_message:`${zS(e,t.issueNumber)}\n\nDelivered by PR #${i.number}.`}:void 0;if(s&&(RS(s.commit_title),RS(s.commit_message)),t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==i.head.sha)throw new D(`Requested reviewed head differs from the GitHub PR.`);if(i.merged&&i.state===`closed`&&QS(i.merge_commit_sha))return{mergeSha:i.merge_commit_sha,headSha:i.head.sha,reused:!0};let c=await uC(e,i.base.ref);if(c.approvalEligibility===`insufficient-permission`)throw new D(`Configured reviewer App is ineligible for the required approval.`);if(i.state!==`open`||i.draft)throw new D(`GitHub PR must be open and ready for merge.`);let l=e.reviewerClients??await vh({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new D(`Independent reviewer App route is unavailable.`);let u=await l.appActorLogin();if(!i.user?.login||u.toLowerCase()===i.user.login.toLowerCase())throw new D(`Reviewer App must differ from the PR author.`);let d=(await pC(e,t.prNumber)).filter(e=>e.user?.login.toLowerCase()===u.toLowerCase()&&e.commit_id===i.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``));if(d.length!==1)throw new D(`GitHub requires one unambiguous exact-head independent App review.`);let f=d[0],p=(await e.clients.rest.pulls.getReview({...e.repo,pull_number:t.prNumber,review_id:f.id})).data;if(p.id!==f.id||p.state!==`APPROVED`||p.commit_id!==i.head.sha||p.user?.login.toLowerCase()!==u.toLowerCase()||p.body!==f.body)throw new D(`Independent GitHub review readback changed or was dismissed.`);let m=jS(p.body);if(m.verdict!==`approve`||m.issueNumber!==t.issueNumber||m.prNumber!==null&&m.prNumber!==t.prNumber||m.authorIdentity!==e.config.roles.author.identity||m.reviewerIdentity!==e.config.roles.reviewer.identity||m.head.sha!==i.head.sha)throw new D(`Independent review artifact binding is stale, foreign or rejected.`);let h=(await e.clients.rest.git.getCommit({...e.repo,commit_sha:i.head.sha})).data;if(h.sha!==m.head.sha||h.tree.sha!==m.head.tree)throw new D(`Independent review tree differs from the remote commit.`);if(m.diffScopeHash!==await NS(e,t.prNumber,i.changed_files))throw new D(`Independent review scope differs from the remote PR diff.`);let g=m.head.sha;if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==g)throw new D(`Requested reviewed head differs from the independent GitHub review.`);let _=await kS(e,t.prNumber,g,{id:f.id,login:u});if(_.submittedReviewAuthorCanPushToRepository!==!0)throw new D(`Specific reviewer App approval is not verifiably qualifying for required review.`);let v=_.status===`unknown`&&_.reviewDecision===null&&c.rules.visibility===`complete`&&c.rules.observedRequiredApprovals===0;if(_.status!==`satisfied`&&!v)throw new D(`GitHub review eligibility is ${_.status}: ${_.nextAction}`);if((await D_({graphql:e.clients.graphql,issueNumber:t.issueNumber,repo:e.repo})).blockers.some(e=>e.state===`OPEN`))throw new D(`GitHub issue has unresolved native blockers.`);if(i=await rC(e,t.issueNumber,t.prNumber,n),n&&(WS(a,i),GS(o,await US(e,t.issueNumber)),RS(s.commit_title),RS(s.commit_message)),v&&(i.base.ref!==a.base.ref||i.base.sha!==a.base.sha))throw new D(`GitHub base changed; refresh the zero-review requirement observation before merge.`);if(i.head.sha!==g||i.state!==`open`||i.draft||i.mergeable!==!0||i.mergeable_state!==`clean`)throw new D(`GitHub merge eligibility is ${i.mergeable_state??`unknown`}; CLEAN at the reviewed head is required.`);let y=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.base.ref}`})).data.object.sha;if(!QS(y)||y!==i.base.sha)throw new D(`GitHub base moved; refresh clean eligibility and independent review before merge.`);if(t.dryRun)return{dryRun:!0,headSha:g,prNumber:i.number,...s===void 0?{}:{nonClosing:!0,...s}};let b=(await e.clients.rest.pulls.merge({...e.repo,pull_number:t.prNumber,sha:g,merge_method:t.strategy??`squash`,...s})).data;if(!b.merged||!QS(b.sha))throw new D(`GitHub refused the reviewed-head merge.`);let x=await rC(e,t.issueNumber,t.prNumber,n);if(n&&(WS(a,x,!0),GS(o,await US(e,t.issueNumber))),!x.merged||x.state!==`closed`||x.head.sha!==g||x.merge_commit_sha!==b.sha)throw new D(`GitHub merged PR readback disagrees with the reviewed-head mutation.`);return{mergeSha:b.sha,headSha:g,reused:!1}}async function hC(e,t){if(KS(t.nonClosing))throw new D(`Non-closing delivery cannot finish or close its retained issue.`);let n=await mC(e,t);if(t.dryRun)return n;let r=await rC(e,t.issueNumber,t.prNumber);if(!r.merged||r.state!==`closed`||r.merge_commit_sha!==n.mergeSha)throw new D(`Intended GitHub PR is not verifiably merged; issue remains open.`);let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(i.number!==t.issueNumber||`pull_request`in i)throw new D(`Finish target is not the intended GitHub issue.`);i.state!==`closed`&&await e.clients.rest.issues.update({...e.repo,issue_number:t.issueNumber,state:`closed`,state_reason:`completed`});let a=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(a.number!==t.issueNumber||a.state!==`closed`)throw new D(`GitHub issue closure readback disagrees.`);return{...n,issueClosed:!0}}function gC(e){let t=md(e.root),n=cd(t,`origin`);if(`${n.owner}/${n.repo}`.toLowerCase()!==e.config.repository.toLowerCase()||`${e.repo.owner}/${e.repo.repo}`.toLowerCase()!==e.config.repository.toLowerCase())throw new D(`Investigation repository identity disagrees.`);return t}async function _C(e,t,n){let r=pd(e);for(let e of[w(r,`ai-delivery`),w(r,`ai-delivery`,`writers@1`)]){try{let t=c(e);if(!t.isDirectory()||t.isSymbolicLink())throw new D(`Investigation writer namespace is unsafe.`)}catch(e){if(e.code!==`ENOENT`)throw e}Qv(e)}return fb(e,t,n)}async function vC(e,t,n,r){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(i.number!==t||`pull_request`in i||i.state!==r||new URL(i.html_url).pathname.toLowerCase()!==`/${e.config.repository}/issues/${String(t)}`.toLowerCase())throw new D(`Investigation requires the exact native issue and expected state.`);let a=await Jv(e,t);if(a.length!==1||a[0].name!==`issue/${String(t)}`||a[0].sha!==n)throw new D(`Investigation requires one exact unchanged native linked branch.`);if((await e.clients.rest.pulls.list({...e.repo,state:`all`,head:`${e.repo.owner}:${a[0].name}`,per_page:100})).data.length!==0)throw new D(`Investigation completion cannot substitute for PR delivery.`)}function yC(e){return z({schemaVersion:`ai-delivery.investigation-preparation-acknowledgement@1`,preparation:e,authority:`prospective-registration-before-investigation-no-legacy-adoption`})}function bC(e,t){return z({schemaVersion:`ai-delivery.investigation-removal-authority@1`,preparationId:e.preparationId,repository:e.repository,issueNumber:e.row.issueNumber,head:e.head,worktree:e.row.path,branch:e.row.branch,resultDigest:t,disposition:`remove-only-this-unchanged-investigation-worktree-retain-branch-and-evidence`,operationalClosure:`all-investigation-producers-quiescent-and-excluded-through-completion-and-resume-no-outstanding-holds`})}function xC(e,t,n){return z({schemaVersion:`ai-delivery.investigation-result-acceptance@1`,authority:JSON.parse(bC(e,t)),authorityCommentId:n,verdict:`approved`,independentlyReviewed:`complete-durable-result-exact-source-and-removal-scope`})}async function SC(e,t){if(!Number.isSafeInteger(t.issueNumber)||t.issueNumber<=0||!IS.test(t.expectedHeadSha))throw new D(`Investigation preparation requires a positive issue and expected commit.`);let n=gC(e),r=w(n,`.worktrees`,`issue-${String(t.issueNumber)}`);if(t.investigationWorktree!==r||h(r)!==r)throw new D(`Investigation worktree must be the exact canonical .worktrees/issue-N path.`);if(i(w(n,`.issue-cli`,`issues`,String(t.issueNumber))))throw new D(`Historical issue custody remains preservation-only; investigation cannot adopt it.`);let a=await pS(e),o=zx(n,t.issueNumber),s=Dx(n,t.issueNumber);if(await vC(e,t.issueNumber,o.head.sha,`open`),o.head.sha!==t.expectedHeadSha)throw new D(`Investigation preparation source drifted from the expected head.`);if(s===void 0){let t=(await e.clients.rest.repos.get({...e.repo})).data;if(t.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!t.default_branch)throw new D(`Investigation native repository identity is incomplete.`);if((await e.clients.rest.git.getRef({...e.repo,ref:`heads/${t.default_branch}`})).data.object.sha!==o.head.sha)throw new D(`Prospective investigation must begin at the current native default commit.`)}let c=new Date().toISOString(),l={schemaVersion:`ai-delivery.investigation-preparation@1`,repository:e.config.repository,repoRoot:n,row:s?.row??{branch:`issue/${String(t.issueNumber)}`,createdAt:c,identity:e.config.roles.author.identity,issueNumber:t.issueNumber,path:r,status:`active`,type:`issue`,updatedAt:c},...o,operator:{actorLogin:a.operator.actorLogin,credentialIdentity:a.operator.credentialIdentity},reviewerActor:a.reviewerActor},u=xx.parse({...l,preparationId:B(l)});return await _C(n,r,()=>Mx(u,async()=>{if(z(zx(n,t.issueNumber))!==z(o))throw new D(`Investigation source changed before preparation acknowledgement.`);await vC(e,t.issueNumber,o.head.sha,`open`);let{commentId:r,url:i,body:a}=await Ov(e,{issueNumber:t.issueNumber,body:yC(u)});if(z(zx(n,t.issueNumber))!==z(o))throw new D(`Investigation source changed during preparation acknowledgement.`);return{commentId:r,url:i,body:a}})),{preparation:u,acknowledgement:Ox(n,t.issueNumber),registered:!0}}async function CC(e,t){if([`prNumber`,`strategy`,`reviewedHeadSha`,`nonClosing`].some(e=>e in t))throw new D(`Investigation completion refuses PR or merge options.`);let n=gC(e),r=Dx(n,t.issueNumber);if(!r)throw new D(`No prospective investigation preparation; historical custody cannot be reconstructed.`);let i=T(t.resultPath),a=se(r.row.path,i),o=a===`..`||a.startsWith(`..${ce}`)||oe(a);if(h(i)!==i||!o)throw new D(`Durable investigation result must be canonical and outside the removable worktree.`);let s=H(i,{maxBytes:524288});if(s.length===0)throw new D(`Investigation result must contain durable evidence.`);let c=V(s),l=bC(r,c),u=t.authorityCommentId===void 0?void 0:xC(r,c,t.authorityCommentId),d=async()=>{await vC(e,t.issueNumber,r.head.sha,`closed`);let i=await Hv(e,t.issueNumber);if(i.state!==`closed`||i.closeReason!==`completed`||i.duplicateOf!==null)throw new D(`Investigation requires native completed closed-issue authority.`);let a=Ox(n,t.issueNumber),o=(await e.clients.rest.issues.getComment({...e.repo,comment_id:a.commentId})).data;if(o.id!==a.commentId||o.body!==yC(r)||o.body!==a.body||o.issue_url.toLowerCase()!==`https://api.github.com/repos/${r.repository}/issues/${String(t.issueNumber)}`.toLowerCase()||o.user?.type!==`User`||o.user.login.toLowerCase()!==r.operator.actorLogin.toLowerCase()||`user:${String(o.user.id)}`!==r.operator.credentialIdentity)throw new D(`Native prospective preparation acknowledgement changed.`);if(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0||u===void 0)throw new D(`Existing authentic operator and independent App acceptance comments are required.`);let s=await vS(e,{repository:r.repository,subject:t.issueNumber,operator:r.operator,reviewerActor:r.reviewerActor,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,operatorBody:l,reviewerBody:u,revokedBody:z({schemaVersion:`ai-delivery.investigation-removal-revocation@1`,preparationId:r.preparationId,resultDigest:c,authorityCommentId:t.authorityCommentId})}),d=Date.parse(o.created_at);for(let e of[s.relinquishment,s.acceptance]){let t=Date.parse(e.created_at);if(!Number.isFinite(d)||!Number.isFinite(t)||t<d)throw new D(`Investigation acceptance must follow its prospective preparation.`)}return{acknowledgement:o,closure:i,...s}};if(t.dryRun&&(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0))return Bx(r,e.root),await vC(e,t.issueNumber,r.head.sha,`closed`),{completed:!1,ready:!1,preparationId:r.preparationId,resultDigest:c,authorityBody:l,...u===void 0?{}:{acceptanceBody:u},missingEvidence:`Existing authentic operator and configured-App exact-result acceptance are prerequisites; no submission route is supplied.`};if(!Number.isSafeInteger(t.authorityCommentId)||!Number.isSafeInteger(t.acceptanceCommentId)||t.authorityCommentId<=0||t.acceptanceCommentId<=0)throw new D(`Investigation evidence requires positive native comment IDs.`);return _C(n,r.row.path,()=>Nx({preparation:r,result:s,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,dryRun:t.dryRun===!0,authorize:d,assertSource:t=>Bx(r,e.root,t),removeSource:()=>Vx(r,e.root)}))}var wC=A().regex(/^sha256:[a-f0-9]{64}$/u),TC=F({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2)}),EC=F({archivePath:A().min(1),archiveSha256:wC,configDigest:wC,packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),repoRoot:A().min(1),repository:A().min(1),reviewRouteDigest:wC,runtimeDirectory:A().min(1),nativePluginRoot:A().min(1).optional(),sourceCommit:A().regex(/^[a-f0-9]{40}$/u),resourceBounds:TC.optional()}),DC=F({schemaVersion:L(`ai-delivery.runtime-stage@1`),stageId:wC,intent:EC,directory:F({device:j().int(),inode:j().int()}),admission:oy.optional(),status:I([`incomplete`,`complete`]),recordId:wC}).superRefine((e,t)=>{let{recordId:n,...r}=e;(n!==B(r)||e.stageId!==B(e.intent)||e.status===`complete`!=(e.admission!==void 0)||e.admission!==void 0&&(e.admission.sourceCommit!==e.intent.sourceCommit||e.admission.sourceArchiveSha256!==e.intent.archiveSha256||e.admission.packageVersion!==e.intent.packageVersion||e.admission.configDigest!==e.intent.configDigest||e.admission.repository!==e.intent.repository||e.admission.cliPath!==kC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).cliPath||e.admission.mcpLauncherPath!==kC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).mcpLauncherPath||e.admission.pluginManifestPath!==kC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).pluginManifestPath))&&t.addIssue({code:`custom`,message:`Runtime stage identity or completion is corrupt.`})});function OC(e){if(!oe(e)||T(e)!==e)throw new D(`Runtime setup paths must be absolute and canonical.`);let t=e.split(ce).filter(Boolean),n=ce;for(let e of t){n=w(n,e);try{if(c(n).isSymbolicLink())throw new D(`Runtime setup path contains a symbolic link.`)}catch(e){if(e.code!==`ENOENT`)throw e}}return e}function kC(e,t){let n=w(e,`node_modules`,`@aviaratech`,`ai-delivery`),r=t??w(n,`plugins`,`ai-delivery`);return{cliPath:t?w(r,`runtime`,`dist`,`cli.js`):w(n,`dist`,`cli.js`),mcpLauncherPath:w(r,`dist`,`mcp-launcher.js`),pluginManifestPath:w(r,`.claude-plugin`,`plugin.json`)}}function AC(e,t){if(t!==void 0&&(OC(t),t===e||t.startsWith(`${e}${ce}`)||e.startsWith(`${t}${ce}`)))throw new D(`Native plugin cache and owned runtime stage paths must not overlap.`)}function jC(e){if(e.nativePluginRoot===void 0)return;AC(e.runtimeDirectory,e.nativePluginRoot);let t=OC(w(e.runtimeDirectory,`node_modules/@aviaratech/ai-delivery/plugins/ai-delivery`)),n=0,r=(e,t,i)=>{if(i>16||++n>4096)throw new D(`Native plugin inventory exceeds the reviewed layout bound.`);let a=c(e),o=c(t);if(a.isDirectory()&&o.isDirectory()){let n=p(e).sort();if(JSON.stringify(n)!==JSON.stringify(p(t).sort()))throw new D(`Selected native plugin inventory disagrees with reviewed archive bytes.`);for(let a of n)r(w(e,a),w(t,a),i+1)}else if(!a.isFile()||!o.isFile()||a.nlink!==1||o.nlink!==1||a.size!==o.size||!d(e).equals(d(t)))throw new D(`Selected native plugin files disagree with reviewed archive bytes.`)};try{r(t,e.nativePluginRoot,0)}catch(e){throw e instanceof D?e:new D(`Selected native plugin cannot be matched to reviewed archive bytes.`)}}function MC(e,t){OC(e),wC.parse(t);let n=c(e);if(!n.isFile()||n.nlink!==1)throw new D(`Reviewed runtime archive bytes do not match the expected digest.`);let r=d(e);if(V(r)!==t)throw new D(`Reviewed runtime archive bytes do not match the expected digest.`);return r}function NC(e){let t=OC(w(e.runtimeDirectory,`reviewed-archive.tgz`));if(V(H(t))!==e.archiveSha256)throw new D(`Runtime stage archive snapshot bytes changed.`);return t}async function PC(e,t,n,r){if(await n?.(),typeof e.identity!=`string`||!e.identity.trim())throw new D(`Runtime setup requires an explicit configured author identity.`);let i=fd(e.repoRoot);if(i!==md(i))throw new D(`Runtime setup requires the primary consumer controller checkout.`);if(gd(i),hd(i).sha!==e.expectedSourceCommit)throw new D(`Primary controller source commit changed.`);OC(e.runtimeDirectory);let a=await Av({identity:e.identity,repoRoot:i,role:`author`,...r===void 0?{}:{signal:r},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});await n?.();let o=Zh({commandName:t,deliveryConfig:a.config,identity:e.identity,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(o.error)throw new D(o.error);if(!a.configuration||a.configuration.configDigest!==e.expectedConfigDigest)throw new D(`Primary controller resolver config digest changed.`);let s=await uC(a,void 0,void 0,`publication`,n===void 0||r===void 0?void 0:{signal:r,checkResources:n});if(await n?.(),gd(i),hd(i).sha!==e.expectedSourceCommit)throw new D(`Primary controller source commit changed during preflight.`);return{root:i,configuration:a.configuration,reviewRoute:s}}function FC(e){OC(e);let t=c(e);if(!t.isDirectory()||(t.mode&511)!=448)throw new D(`Runtime stage directory must be private and owned.`);let n;try{n=DC.parse(JSON.parse(H(w(e,`runtime-stage.json`)).toString(`utf8`)))}catch{throw new D(`Runtime stage is unowned, incompatible or corrupt.`)}if(n.intent.runtimeDirectory!==e||t.dev!==n.directory.device||t.ino!==n.directory.inode)throw new D(`Runtime stage directory ownership changed.`);return n.status===`complete`&&(NC(n.intent),jC(n.intent)),n}function IC(e,t){let n=DC.parse({...t,recordId:B(t)});ey(w(e,`runtime-stage.json`),n);let r=FC(e);if(r.recordId!==n.recordId)throw new D(`Runtime stage completion readback changed.`);return r}function LC(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function RC(e){let t=H(e),r=u(e,`r`);try{o(r)}finally{n(r)}if(LC(C(e)),!H(e).equals(t))throw new D(`Runtime admission third-party replacement conflict.`)}function zC(e,t,n){if(!e.admission)throw new D(`Runtime stage completion is missing.`);return{stageId:e.stageId,admission:e.admission,reused:n,reviewRoute:t,launch:{cli:{command:process.execPath,args:[e.admission.cliPath]},mcp:{command:process.execPath,args:[e.admission.mcpLauncherPath]}}}}function BC(e,t,n){if(e.intent.repoRoot!==t.root||e.intent.repository!==t.configuration.config.repository||e.intent.sourceCommit!==n.expectedSourceCommit||e.intent.configDigest!==n.expectedConfigDigest)throw new D(`Runtime stage primary controller source or configuration changed.`);if(e.intent.reviewRouteDigest!==B(t.reviewRoute))throw new D(`Runtime stage configured actors or review route changed.`)}async function VC(e){if(e.authority!==`runtime:stage`)throw new D(`Explicit runtime:stage authority is required.`);let t=TC.parse({maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2,maxCapturedOutputBytes:1024**2,...e.resourceBounds});return OC(e.runtimeDirectory),AC(e.runtimeDirectory,e.nativePluginRoot),Rb(e.repoRoot,async n=>{let r=await PC(e,`runtime:stage`,n.checkResources,n.signal);MC(e.archivePath,e.expectedArchiveSha256);let a=EC.parse({archivePath:e.archivePath,archiveSha256:e.expectedArchiveSha256,configDigest:e.expectedConfigDigest,sourceCommit:e.expectedSourceCommit,packageVersion:e.packageVersion,repoRoot:r.root,repository:r.configuration.config.repository,reviewRouteDigest:B(r.reviewRoute),runtimeDirectory:e.runtimeDirectory,resourceBounds:t,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot}}),o=B(a);if(n.bindCapturedOutput(o),i(e.runtimeDirectory)){let t=FC(e.runtimeDirectory);if(t.stageId!==o)throw new D(`Runtime stage belongs to an incompatible setup intent.`);if(t.status===`complete`){let r=await PC(e,`runtime:stage`,n.checkResources,n.signal);return BC(t,r,e),MC(a.archivePath,a.archiveSha256),RC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),NC(a),dy(t.admission,r.configuration,t.admission.cliPath),RC(w(e.runtimeDirectory,`runtime-stage.json`)),LC(C(e.runtimeDirectory)),await n.checkResources(),zC(t,r.reviewRoute,!0)}n.assertQuiescent(),_(e.runtimeDirectory,{recursive:!0})}Qv(C(e.runtimeDirectory)),l(e.runtimeDirectory,{mode:448});let s=c(e.runtimeDirectory),u={schemaVersion:`ai-delivery.runtime-stage@1`,stageId:o,intent:a,directory:{device:s.dev,inode:s.ino},status:`incomplete`},d=!1;try{if(LC(C(e.runtimeDirectory)),IC(e.runtimeDirectory,u),d=!0,e.signal?.aborted)throw new D(`Runtime stage cancelled.`);let r=MC(e.archivePath,e.expectedArchiveSha256);if(!Number.isSafeInteger(t.maxNewOutputBytes)||r.length>=t.maxNewOutputBytes)throw new D(`Reviewed archive snapshot exceeds the stage output limit.`);wd(w(e.runtimeDirectory,`reviewed-archive.tgz`),r);let i=NC(a),o=w(e.runtimeDirectory,`.npm`),s=w(o,`cache`),c=w(o,`logs`),l=w(o,`tmp`);for(let e of[s,c,l])Qv(e);let f=w(o,`user.npmrc`),p=w(o,`global.npmrc`);wd(f,Buffer.alloc(0)),wd(p,Buffer.alloc(0)),await n.checkResources(),await n.run([`npm`,`install`,`--prefix`,e.runtimeDirectory,`--omit=dev`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--package-lock=false`,`--cache`,s,`--logs-dir`,c,`--logs-max`,`0`,`--userconfig`,f,`--globalconfig`,p,i],{...t,maxNewOutputBytes:t.maxNewOutputBytes-r.length,outputRoots:[e.runtimeDirectory]},e.signal,{...process.env,TMPDIR:l,TMP:l,TEMP:l},e.runtimeDirectory);let m=await PC(e,`runtime:stage`,n.checkResources,n.signal);BC({...u,recordId:B(u)},m,e),MC(e.archivePath,e.expectedArchiveSha256),NC(a),jC(a);let h=fy({...kC(e.runtimeDirectory,e.nativePluginRoot),packageVersion:e.packageVersion,sourceArchiveSha256:e.expectedArchiveSha256,sourceCommit:e.expectedSourceCommit,configuration:m.configuration});if(jC(a),e.signal?.aborted)throw new D(`Runtime stage cancelled.`);n.assertQuiescent(),dy(h,m.configuration,h.cliPath),await n.checkResources();let g=IC(e.runtimeDirectory,{...u,status:`complete`,admission:h});return dy(g.admission,m.configuration,g.admission.cliPath),zC(g,m.reviewRoute,!1)}catch(t){if(d){n.assertQuiescent();let t=FC(e.runtimeDirectory);if(t.stageId!==o)throw new D(`Runtime stage cleanup ownership changed.`);if(t.status===`incomplete`)_(e.runtimeDirectory,{recursive:!0});else{let r=await PC(e,`runtime:stage`,n.checkResources,n.signal);return BC(t,r,e),MC(a.archivePath,a.archiveSha256),RC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),NC(a),dy(t.admission,r.configuration,t.admission.cliPath),RC(w(e.runtimeDirectory,`runtime-stage.json`)),LC(C(e.runtimeDirectory)),zC(t,r.reviewRoute,!0)}}else{n.assertQuiescent();let t=c(e.runtimeDirectory);if(t.dev!==s.dev||t.ino!==s.ino||t.isSymbolicLink())throw new D(`Runtime stage cleanup ownership changed.`);_(e.runtimeDirectory,{recursive:!0})}throw t}},{bounds:{...t,outputRoots:[e.runtimeDirectory]},maxCapturedOutputBytes:t.maxCapturedOutputBytes,...e.signal===void 0?{}:{signal:e.signal}})}var HC=class extends D{admissionId;stageId;status=`commit-status-unknown`;constructor(e,t){super(`Runtime admission commit-status-unknown for ${e}; retry runtime:admit with the same stage ${t} to reconcile durability.`),this.admissionId=e,this.stageId=t}};async function UC(e){if(e.authority!==`runtime:admit`)throw new D(`Explicit runtime:admit authority is required.`);wC.parse(e.stageId),e.expectedPriorAdmissionSha256!==null&&wC.parse(e.expectedPriorAdmissionSha256);let t=await PC(e,`runtime:admit`),n=w(pd(t.root),`ai-delivery`,`runtime-admission.json`);return OC(n),Qv(C(n)),Oy(n,{projectRoot:t.root,timeout:200,operation:async()=>{let t=FC(e.runtimeDirectory);if(t.stageId!==e.stageId||t.status!==`complete`||!t.admission)throw new D(`Exact completed runtime stage identity is required.`);let r=await PC(e,`runtime:admit`);BC(t,r,e),MC(t.intent.archivePath,t.intent.archiveSha256),NC(t.intent),dy(t.admission,r.configuration,t.admission.cliPath);let a=Buffer.from(`${JSON.stringify(t.admission,null,2)}\n`);OC(n);let o=i(n)?H(n):void 0,s=()=>{if(OC(n),NC(t.intent),dy(t.admission,r.configuration,t.admission.cliPath),!i(n)||!H(n).equals(a))throw new D(`Runtime admission third-party replacement conflict; current bytes preserved.`);try{RC(n)}catch{throw!i(n)||!H(n).equals(a)?new D(`Runtime admission third-party replacement conflict; current bytes preserved.`):new HC(t.admission.admissionId,t.stageId)}return{admission:t.admission,reused:!0}};if(o?.equals(a))return s();if((o===void 0?null:V(o))!==e.expectedPriorAdmissionSha256)throw new D(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);let c=await PC(e,`runtime:admit`);BC(t,c,e),MC(t.intent.archivePath,t.intent.archiveSha256),NC(t.intent),dy(t.admission,c.configuration,t.admission.cliPath),OC(n);let l=i(n)?H(n):void 0;if((l===void 0?null:V(l))!==e.expectedPriorAdmissionSha256)throw new D(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);try{ey(n,t.admission)}catch(t){let r=i(n)?H(n):void 0;if(r?.equals(a))return s();throw(r===void 0?null:V(r))===e.expectedPriorAdmissionSha256?t:new D(`Runtime admission third-party replacement conflict; current bytes preserved.`)}return s(),{admission:t.admission,reused:!1}}})}var U=j().int().positive(),WC=N(A().trim().min(1)),GC=`GitHub owner/name. Pass the repository named by the user. An explicit repo avoids launch-directory Git for ordinary remote issue/PR work; retained local modes keep their own checkout requirements.`,KC=A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional().describe(GC),qC={blockedBy:N(U).optional(),blocks:N(U).optional(),overrideReason:z_.optional(),body:A().optional(),issueType:A().min(1).optional(),labels:WC.optional(),milestone:U.optional(),parentIssueNumber:U.optional(),points:U.optional(),priority:A().min(1).optional(),repo:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional().describe(GC),title:A().trim().min(1).max(256)},JC=F({repo:KC,issueNumber:U,investigationWorktree:A().min(1),expectedHeadSha:A().regex(/^[a-f0-9]{40}$/u)}),YC=F({...qC,title:qC.title.optional(),issueNumber:U.optional(),request:A().min(1).optional(),requestId:A().trim().min(1).max(256).optional(),resumeCreated:M().optional(),branch:A().min(1).optional()}),XC=F({repo:KC,issueNumber:U,prNumber:U,nonClosing:M().optional(),reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:I([`merge`,`squash`,`rebase`]).optional(),dryRun:M().optional()}),ZC=F({repo:KC,issueNumber:U,investigation:L(!0),resultPath:A().min(1),authorityCommentId:U.optional(),acceptanceCommentId:U.optional(),dryRun:M().optional()});function QC(e,t,n){let r=e.safeParse(t);r.success||n.addIssue({code:`custom`,message:r.error.message})}var $C={repo:KC,state:I([`open`,`closed`,`all`]).optional(),labels:N(A().min(1).regex(/^[^"\\\r\n]+$/u)).optional(),parentIssueNumber:U.nullable().optional(),issueType:A().min(1).optional(),projectStatus:I([`Todo`,`In Progress`,`Blocked`,`Done`]).nullable().optional(),updatedSince:Du({offset:!0}).optional(),page:U.optional(),perPage:U.max(100).optional()},ew=A().trim().min(1).max(256).regex(/^[^"\\\r\n]+$/u),tw={repo:KC,identity:A().min(1).optional(),expectedSourceCommit:A().regex(/^[a-f0-9]{40}$/u),expectedConfigDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),runtimeDirectory:A().min(1)},nw=[{name:`delivery_health`,commandName:`health`,description:`Read bounded native delivery health for an explicit repository and UTC window`,inputSchema:$u},{name:`issue_comment`,commandName:`comment`,description:`Post a typed issue journal with authoritative comment readback`,inputSchema:F({...wv.shape,repo:KC}).superRefine(({repo:e,...t},n)=>{let r=wv.safeParse(t);if(!r.success)for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message})})},{name:`runtime_stage`,commandName:`runtime:stage`,description:`Explicitly stage a reviewed local public archive without host activation or admission`,inputSchema:F({...tw,authority:L(`runtime:stage`),archivePath:A().min(1),expectedArchiveSha256:A().regex(/^sha256:[a-f0-9]{64}$/u),packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),nativePluginRoot:A().min(1).optional(),resourceBounds:F({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2).optional()}).optional()})},{name:`runtime_admit`,commandName:`runtime:admit`,description:`Explicitly admit an exact completed stage with prior-byte compare-and-swap and reconciliation`,inputSchema:F({...tw,authority:L(`runtime:admit`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),expectedPriorAdmissionSha256:A().regex(/^sha256:[a-f0-9]{64}$/u).nullable()})},{name:`issue_create`,commandName:`create`,description:`Create a native GitHub tracking issue with configured metadata and relationships`,issueContract:iv,inputSchema:sv(F({...qC,...av,title:X_.shape.title}))},{name:`issue_start`,commandName:`start`,description:`Start a linked issue, or prospectively register an unchanged host-created investigation worktree`,inputSchema:YC.extend({investigationWorktree:A().optional(),expectedHeadSha:A().optional()}).superRefine((e,t)=>QC(e.investigationWorktree!==void 0||e.expectedHeadSha!==void 0?JC:YC,e,t))},{name:`issue_list`,commandName:`list`,description:`List repository issues with native filters, named organization fields and pagination`,inputSchema:F({...$C,query:ew.optional()})},{name:`issue_search`,commandName:`search`,description:`Search literal issue text in the selected repository with native filters and pagination`,inputSchema:F({...$C,query:ew})},{name:`issue_update`,commandName:`update`,description:`Update native issue fields and exact relationship sets with readback`,inputSchema:sv(F({...av,repo:KC,blockedBy:N(U).optional(),blocks:N(U).optional(),overrideReason:z_.optional(),body:A().optional(),issueNumber:U,issueType:av.issueType,labels:WC.optional(),milestone:U.nullable().optional(),parentIssueNumber:U.nullable().optional(),park:L(!0).optional(),points:av.points,priority:A().min(1).optional(),state:I([`open`,`closed`]).optional(),preserveHistory:M().optional(),closeReason:I([`completed`,`not_planned`,`duplicate`]).optional(),supersededBy:U.optional(),title:av.title}).superRefine((e,t)=>{(e.closeReason!==void 0||e.supersededBy!==void 0)&&e.state!==`closed`&&t.addIssue({code:`custom`,path:[`state`],message:`Closure details require state closed`,params:{issueCode:`closure.state`}})}))},{name:`issue_info`,commandName:`info`,description:`Read live GitHub issue metadata, relationships and Project status. Pass the requested owner/name as repo; an explicit repo works outside Git without a checkout. This read does not start or update the issue.`,inputSchema:F({issueNumber:U,repo:KC})},{name:`issue_ready_check`,commandName:`ready:check`,description:`Evaluate deterministic readiness from live native issue state`,inputSchema:F({issueNumber:U,repo:qC.repo})},{name:`issue_pr_create`,commandName:`pr:create`,description:`Create or reuse a PR from its GitHub-linked issue branch`,inputSchema:F({repo:KC,issueNumber:U,prNumber:U.optional(),nonClosing:M().optional(),body:A().min(1).optional(),draft:M().optional(),dryRun:M().optional(),title:A().min(1).optional(),headBranch:A().min(1).optional()})},{name:`issue_pr_info`,commandName:`pr:info`,description:`Inspect a PR by number or its GitHub-linked issue branch`,inputSchema:F({repo:KC,issueNumber:U.optional(),prNumber:U.optional(),nonClosing:M().optional()})},{name:`issue_pr_review`,commandName:`pr:review`,description:`Submit one existing exact-head independent review with the reviewer App role`,inputSchema:F({repo:KC,issueNumber:U,prNumber:U,nonClosing:M().optional(),artifact:A().min(1),identity:A().min(1).optional(),dryRun:M().optional()})},{name:`issue_pr_merge`,commandName:`pr:merge`,description:`Guarded exact-head merge with live blocker, check and review readback`,inputSchema:F({repo:KC,issueNumber:U,prNumber:U,nonClosing:M().optional(),reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:I([`merge`,`squash`,`rebase`]).optional(),dryRun:M().optional()})},{name:`issue_finish`,commandName:`finish`,description:`Finish merged delivery, or remove a prospectively registered unchanged investigation with native acceptance`,inputSchema:XC.extend({prNumber:U.optional(),investigation:L(!0).optional(),resultPath:A().optional(),authorityCommentId:U.optional(),acceptanceCommentId:U.optional()}).superRefine((e,t)=>QC(e.investigation===!0?ZC:XC,e,t))},{name:`issue_worktree_transition_inspect`,commandName:`worktree:transition:inspect`,description:`Read a legacy issue row, original evidence and exact closure gaps without changing ownership`,inputSchema:F({repo:KC,issueNumber:U,purpose:I([`active-resume`,`merged-cleanup`]),disposition:I([`retain`,`remove`]).optional(),terminalPrNumber:U.optional(),retainedHoldCommentIds:N(U).optional(),retainedAdmissionPath:A().min(1).optional(),retainedArchivePath:A().min(1).optional()})},{name:`issue_worktree_transition_apply`,commandName:`worktree:transition:apply`,description:`Apply or resume one exact independently accepted transition with immutable preservation and closure proof`,inputSchema:F({repo:KC,authority:L(`worktree:transition`),planPath:A().min(1),expectedPlanId:A().regex(/^sha256:[a-f0-9]{64}$/u),relinquishmentCommentId:U,acceptanceCommentId:U})}];function rw(e){return nw.find(t=>t.name===e)??null}function iw(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw new D(`${t} must be positive.`);return n}function aw(e,t){return typeof e[t]==`string`?e[t]:void 0}function ow(e,t){let n=aw(e,t);if(!n?.trim())throw new D(`${t} is required.`);return n}function sw(e){let{issueNumber:t,request:n,requestId:r,repo:i,resumeCreated:a,branch:o,...s}=e;return{...s,issueNumber:iw({issueNumber:t},`issueNumber`)}}async function cw(e,t,n=`author`){let r=await Kh(),i=e.identity??r.roles[n].identity,a=Zh({commandName:t,deliveryConfig:r,identity:i,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(a.error)throw new D(a.error);return Av({identity:i,repoRoot:e.repoRoot,role:n,...e.repo===void 0?{}:{repository:e.repo},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}})}async function lw(e,t){let n=t.issueNumber===void 0?void 0:iw(t,`issueNumber`),r,i,a,o=!1,s=`branch-or-journal`,c=(o,s)=>({status:`created-not-started`,repository:e.config.repository,createdIssue:r,failure:{phase:o,message:s instanceof Error?s.message:String(s)},safeResume:{tool:`issue_start`,arguments:{...o===`tracking`?{...t,...i===void 0?{}:{body:i},resumeCreated:!0}:{},repo:e.config.repository,issueNumber:n,...(a?.branch??aw(t,`branch`))===void 0?{}:{branch:a?.branch??aw(t,`branch`)}}}});if(n===void 0){let a=aw(t,`title`)??ow(t,`request`),o={...t,title:a,body:aw(t,`body`)??aw(t,`request`)??a};o.body=Nv(o);let s=B(Object.fromEntries(Object.entries({title:a,body:o.body,issueType:o.issueType,points:o.points,priority:o.priority,labels:o.labels,blockedBy:o.blockedBy,blocks:o.blocks,overrideReason:o.overrideReason,parentIssueNumber:o.parentIssueNumber,milestone:o.milestone,branch:t.branch}).filter(([,e])=>e!==void 0))),l=aw(t,`requestId`)??s,u=`<!-- ai-delivery-start: ${B({repository:e.config.repository.toLowerCase(),requestKey:l})} -->`;o.body=`${o.body}\n\n<!-- ai-delivery-start-intent: ${s} -->\n${u}`,i=o.body;let d=!1,f=[];for(let t=1;t<=20;t++){let n=(await e.clients.rest.issues.listForRepo({...e.repo,state:`all`,page:t,per_page:100})).data;if(f.push(...n.filter(e=>!(`pull_request`in e)&&e.body?.includes(u))),n.length<100){d=!0;break}}if(!d)throw new D(`Issue-start retry search exceeds the bounded readback window; select a known issue number.`);if(f.length>1)throw new D(`Conflicting issues claim the same start request.`);let p=f[0];if(p&&(p.title!==a||p.body!==o.body||p.state!==`open`))throw new D(`Prior issue-start request conflicts with the requested intent or state.`);try{p?(r={number:p.number,title:p.title,url:p.html_url},n=p.number,await Wv(e,{...o,issueNumber:n})):(r=(await Fv(e,o)).created,n=r.number)}catch(e){if(e instanceof Pv)r=e.created,n=r.number;else if(!r)throw e;return c(`tracking`,e)}}else if(t.resumeCreated===!0){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:n})).data;if(i.number!==n||`pull_request`in i)throw new D(`Known-created issue readback disagrees.`);r={number:n,title:i.title,url:i.html_url};try{await Wv(e,sw(t))}catch(e){return c(`tracking`,e)}}try{let r=await qv(e,n);if(!r.ready)throw new uv(r.failures);return o=!0,a=await Xv(e,n,aw(t,`branch`)),s=`project-status`,await Zv(e,n),s=`journal`,await kv(e,n),{issueNumber:n,repository:e.config.repository,branch:a.branch,headSha:a.headSha,reused:a.reused}}catch(i){if(r)return c(s,i);if(!o)throw i;return{status:`start-incomplete`,issueNumber:n,repository:e.config.repository,failure:{phase:s,message:i instanceof Error?i.message:String(i)},safeResume:{tool:`issue_start`,arguments:{repo:e.config.repository,issueNumber:n,...(a?.branch??aw(t,`branch`))===void 0?{}:{branch:a?.branch??aw(t,`branch`)}}}}}}async function uw(e,t,n){let r=rw(e);if(!r)throw new D(`Unknown ai-delivery tool ${e}.`);let{repo:i,...a}=r.inputSchema.parse(t);if(e===`issue_finish`&&a.nonClosing===!0)throw new D(`Non-closing delivery cannot finish or close its retained issue.`);if(i!==void 0&&n.repo!==void 0&&i!==n.repo)throw new D(`Tool and execution repository selectors disagree.`);e===`issue_create`&&Nv(a);let o=typeof i==`string`?i:n.repo,s={...n,...o===void 0?{}:{repo:o}},c=e===`runtime_stage`||e===`runtime_admit`||e.startsWith(`issue_worktree_transition_`)||e===`issue_start`&&a.investigationWorktree!==void 0||e===`issue_finish`&&a.investigation===!0,l=n.repoRoot;if(c){let t=await Kh();if(l=ld({repository:o??(()=>{let e=cd(l,`origin`);return`${e.owner}/${e.repo}`})(),launchDirectory:l,checkoutRoots:t.checkoutRoots}),e===`runtime_stage`||e===`runtime_admit`){let r={...a,repoRoot:l,identity:aw(a,`identity`)??n.identity??t.roles.author.identity,...n.personalAuth===void 0?{}:{personalAuth:n.personalAuth},...n.signal===void 0?{}:{signal:n.signal}};return e===`runtime_stage`?VC(r):UC(r)}}let u=e===`issue_pr_review`?aw(a,`identity`):void 0,d=await cw({...s,...u===void 0?{}:{identity:u}},r.commandName,e===`issue_pr_review`?`reviewer`:`author`);switch(c&&(d.root=l),e){case`delivery_health`:return td(d,{...a,repo:o});case`issue_comment`:return Ov(d,a);case`issue_create`:return Fv(d,a);case`issue_start`:return a.investigationWorktree===void 0?lw(d,a):SC(d,{issueNumber:iw(a,`issueNumber`),investigationWorktree:ow(a,`investigationWorktree`),expectedHeadSha:ow(a,`expectedHeadSha`)});case`issue_update`:return Uv(d,a);case`issue_list`:case`issue_search`:return Bv(d,a);case`issue_info`:return Gv(d,iw(a,`issueNumber`));case`issue_ready_check`:return qv(d,iw(a,`issueNumber`));case`issue_pr_create`:return dC(d,{...a.prNumber===void 0?{}:{prNumber:iw(a,`prNumber`)},issueNumber:iw(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},...a.body===void 0?{}:{body:ow(a,`body`)},...a.title===void 0?{}:{title:ow(a,`title`)},...a.headBranch===void 0?{}:{headBranch:ow(a,`headBranch`)},draft:a.draft!==!1,dryRun:a.dryRun===!0});case`issue_pr_info`:return iC(d,a);case`issue_pr_review`:return fC(d,{artifact:ow(a,`artifact`),issueNumber:iw(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:iw(a,`prNumber`),dryRun:a.dryRun===!0});case`issue_pr_merge`:case`issue_finish`:{if(e===`issue_finish`&&a.investigation===!0)return CC(d,{issueNumber:iw(a,`issueNumber`),resultPath:ow(a,`resultPath`),...a.authorityCommentId===void 0?{}:{authorityCommentId:iw(a,`authorityCommentId`)},...a.acceptanceCommentId===void 0?{}:{acceptanceCommentId:iw(a,`acceptanceCommentId`)},dryRun:a.dryRun===!0});let t={issueNumber:iw(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:iw(a,`prNumber`),...a.strategy===void 0?{}:{strategy:a.strategy},...a.reviewedHeadSha===void 0?{}:{reviewedHeadSha:ow(a,`reviewedHeadSha`)},dryRun:a.dryRun===!0};return e===`issue_finish`?hC(d,t):mC(d,t)}case`issue_worktree_transition_inspect`:return CS(d,{...a,...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}});case`issue_worktree_transition_apply`:return fS(d,{authority:`worktree:transition`,planPath:ow(a,`planPath`),expectedPlanId:ow(a,`expectedPlanId`),relinquishmentCommentId:iw(a,`relinquishmentCommentId`),acceptanceCommentId:iw(a,`acceptanceCommentId`),...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}})}}var dw;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(dw||={});var fw;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(fw||={});var W=dw.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),pw=e=>{switch(typeof e){case`undefined`:return W.undefined;case`string`:return W.string;case`number`:return Number.isNaN(e)?W.nan:W.number;case`boolean`:return W.boolean;case`function`:return W.function;case`bigint`:return W.bigint;case`symbol`:return W.symbol;case`object`:return Array.isArray(e)?W.array:e===null?W.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?W.promise:typeof Map<`u`&&e instanceof Map?W.map:typeof Set<`u`&&e instanceof Set?W.set:typeof Date<`u`&&e instanceof Date?W.date:W.object;default:return W.unknown}},G=dw.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),mw=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,dw.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};mw.create=e=>new mw(e);var hw=(e,t)=>{let n;switch(e.code){case G.invalid_type:n=e.received===W.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case G.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,dw.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:n=`Unrecognized key(s) in object: ${dw.joinValues(e.keys,`, `)}`;break;case G.invalid_union:n=`Invalid input`;break;case G.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${dw.joinValues(e.options)}`;break;case G.invalid_enum_value:n=`Invalid enum value. Expected ${dw.joinValues(e.options)}, received '${e.received}'`;break;case G.invalid_arguments:n=`Invalid function arguments`;break;case G.invalid_return_type:n=`Invalid function return type`;break;case G.invalid_date:n=`Invalid date`;break;case G.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:dw.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case G.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case G.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case G.custom:n=`Invalid input`;break;case G.invalid_intersection_types:n=`Intersection results could not be merged`;break;case G.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case G.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,dw.assertNever(e)}return{message:n}},gw=hw;function _w(){return gw}var vw=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function K(e,t){let n=_w(),r=vw({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===hw?void 0:hw].filter(e=>!!e)});e.common.issues.push(r)}var yw=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return q;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return q;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:`aborted`}),bw=e=>({status:`dirty`,value:e}),xw=e=>({status:`valid`,value:e}),Sw=e=>e.status===`aborted`,Cw=e=>e.status===`dirty`,ww=e=>e.status===`valid`,Tw=e=>typeof Promise<`u`&&e instanceof Promise,J;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(J||={});var Ew=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Dw=(e,t)=>{if(ww(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new mw(e.common.issues);return this._error=t,this._error}}};function Y(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var Ow=class{get description(){return this._def.description}_getType(e){return pw(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:pw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new yw,ctx:{common:e.parent.common,data:e.data,parsedType:pw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Tw(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pw(e)};return Dw(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pw(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ww(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ww(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pw(e)},r=this._parse({data:e,path:n.path,parent:n});return Dw(n,await(Tw(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:G.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new jT({schema:this,typeName:X.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return MT.create(this,this._def)}nullable(){return NT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fT.create(this)}promise(){return AT.create(this,this._def)}or(e){return hT.create([this,e],this._def)}and(e){return yT.create(this,e,this._def)}transform(e){return new jT({...Y(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new PT({...Y(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new LT({typeName:X.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new FT({...Y(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return RT.create(this,e)}readonly(){return zT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kw=/^c[^\s-]{8,}$/i,Aw=/^[0-9a-z]+$/,jw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Mw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Nw=/^[a-z0-9_-]{21}$/i,Pw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Iw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Lw=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,Rw,zw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Bw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Vw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Hw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Uw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ww=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gw=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Kw=RegExp(`^${Gw}$`);function qw(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Jw(e){return RegExp(`^${qw(e)}$`)}function Yw(e){let t=`${Gw}T${qw(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Xw(e,t){return!((t!==`v4`&&t||!zw.test(e))&&(t!==`v6`&&t||!Vw.test(e)))}function Zw(e,t){if(!Pw.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Qw(e,t){return!((t!==`v4`&&t||!Bw.test(e))&&(t!==`v6`&&t||!Hw.test(e)))}var $w=class e extends Ow{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.string,received:t.parsedType}),q}let t=new yw,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Iw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`email`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Rw||=new RegExp(Lw,`u`),Rw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`emoji`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Mw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`uuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Nw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`nanoid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)kw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Aw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid2`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)jw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ulid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),K(n,{validation:`url`,code:G.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`regex`,code:G.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Yw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Kw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Jw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Fw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`duration`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Xw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ip`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Zw(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`jwt`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Qw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cidr`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Uw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ww.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64url`,code:G.invalid_string,message:r.message}),t.dirty()):dw.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:G.invalid_string,...J.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...J.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...J.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...J.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...J.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...J.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...J.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...J.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...J.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...J.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...J.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...J.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};$w.create=e=>new $w({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...Y(e)});function eT(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var tT=class e extends Ow{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==W.number){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.number,received:t.parsedType}),q}let t,n=new yw;for(let r of this._def.checks)r.kind===`int`?dw.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?eT(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_finite,message:r.message}),n.dirty()):dw.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:J.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:J.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:J.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&dw.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};tT.create=e=>new tT({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...Y(e)});var nT=class e extends Ow{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let t,n=new yw;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):dw.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};nT.create=e=>new nT({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...Y(e)});var rT=class extends Ow{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.boolean,received:t.parsedType}),q}return xw(e.data)}};rT.create=e=>new rT({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...Y(e)});var iT=class e extends Ow{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.date,received:t.parsedType}),q}if(Number.isNaN(e.data.getTime()))return K(this._getOrReturnCtx(e),{code:G.invalid_date}),q;let t=new yw,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):dw.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};iT.create=e=>new iT({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...Y(e)});var aT=class extends Ow{_parse(e){if(this._getType(e)!==W.symbol){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.symbol,received:t.parsedType}),q}return xw(e.data)}};aT.create=e=>new aT({typeName:X.ZodSymbol,...Y(e)});var oT=class extends Ow{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.undefined,received:t.parsedType}),q}return xw(e.data)}};oT.create=e=>new oT({typeName:X.ZodUndefined,...Y(e)});var sT=class extends Ow{_parse(e){if(this._getType(e)!==W.null){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.null,received:t.parsedType}),q}return xw(e.data)}};sT.create=e=>new sT({typeName:X.ZodNull,...Y(e)});var cT=class extends Ow{constructor(){super(...arguments),this._any=!0}_parse(e){return xw(e.data)}};cT.create=e=>new cT({typeName:X.ZodAny,...Y(e)});var lT=class extends Ow{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xw(e.data)}};lT.create=e=>new lT({typeName:X.ZodUnknown,...Y(e)});var uT=class extends Ow{_parse(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.never,received:t.parsedType}),q}};uT.create=e=>new uT({typeName:X.ZodNever,...Y(e)});var dT=class extends Ow{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.void,received:t.parsedType}),q}return xw(e.data)}};dT.create=e=>new dT({typeName:X.ZodVoid,...Y(e)});var fT=class e extends Ow{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==W.array)return K(t,{code:G.invalid_type,expected:W.array,received:t.parsedType}),q;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(K(t,{code:e?G.too_big:G.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(K(t,{code:G.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(K(t,{code:G.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Ew(t,e,t.path,n)))).then(e=>yw.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Ew(t,e,t.path,n)));return yw.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(e){return this.min(1,e)}};fT.create=(e,t)=>new fT({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...Y(t)});function pT(e){if(e instanceof mT){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=MT.create(pT(r))}return new mT({...e._def,shape:()=>t})}return e instanceof fT?new fT({...e._def,type:pT(e.element)}):e instanceof MT?MT.create(pT(e.unwrap())):e instanceof NT?NT.create(pT(e.unwrap())):e instanceof bT?bT.create(e.items.map(e=>pT(e))):e}var mT=class e extends Ow{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=dw.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==W.object){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof uT&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Ew(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof uT){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(K(n,{code:G.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Ew(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>yw.mergeObjectSync(t,e)):yw.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return J.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:J.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of dw.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of dw.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return pT(this)}partial(t){let n={};for(let e of dw.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of dw.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof MT;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return DT(dw.objectKeys(this.shape))}};mT.create=(e,t)=>new mT({shape:()=>e,unknownKeys:`strip`,catchall:uT.create(),typeName:X.ZodObject,...Y(t)}),mT.strictCreate=(e,t)=>new mT({shape:()=>e,unknownKeys:`strict`,catchall:uT.create(),typeName:X.ZodObject,...Y(t)}),mT.lazycreate=(e,t)=>new mT({shape:e,unknownKeys:`strip`,catchall:uT.create(),typeName:X.ZodObject,...Y(t)});var hT=class extends Ow{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new mw(e.ctx.common.issues));return K(t,{code:G.invalid_union,unionErrors:n}),q}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new mw(e));return K(t,{code:G.invalid_union,unionErrors:i}),q}}get options(){return this._def.options}};hT.create=(e,t)=>new hT({options:e,typeName:X.ZodUnion,...Y(t)});var gT=e=>e instanceof TT?gT(e.schema):e instanceof jT?gT(e.innerType()):e instanceof ET?[e.value]:e instanceof OT?e.options:e instanceof kT?dw.objectValues(e.enum):e instanceof PT?gT(e._def.innerType):e instanceof oT?[void 0]:e instanceof sT?[null]:e instanceof MT?[void 0,...gT(e.unwrap())]:e instanceof NT?[null,...gT(e.unwrap())]:e instanceof LT||e instanceof zT?gT(e.unwrap()):e instanceof FT?gT(e._def.innerType):[],_T=class e extends Ow{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.object)return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:G.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=gT(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Y(r)})}};function vT(e,t){let n=pw(e),r=pw(t);if(e===t)return{valid:!0,data:e};if(n===W.object&&r===W.object){let n=dw.objectKeys(t),r=dw.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=vT(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===W.array&&r===W.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=vT(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===W.date&&r===W.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var yT=class extends Ow{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Sw(e)||Sw(r))return q;let i=vT(e.value,r.value);return i.valid?((Cw(e)||Cw(r))&&t.dirty(),{status:t.value,value:i.data}):(K(n,{code:G.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};yT.create=(e,t,n)=>new yT({left:e,right:t,typeName:X.ZodIntersection,...Y(n)});var bT=class e extends Ow{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.array)return K(n,{code:G.invalid_type,expected:W.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return K(n,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),q;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Ew(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>yw.mergeArray(t,e)):yw.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};bT.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new bT({items:e,typeName:X.ZodTuple,rest:null,...Y(t)})};var xT=class e extends Ow{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.object)return K(n,{code:G.invalid_type,expected:W.object,received:n.parsedType}),q;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Ew(n,e,n.path,e)),value:a._parse(new Ew(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?yw.mergeObjectAsync(t,r):yw.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Ow?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...Y(r)}):new e({keyType:$w.create(),valueType:t,typeName:X.ZodRecord,...Y(n)})}},ST=class extends Ow{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.map)return K(n,{code:G.invalid_type,expected:W.map,received:n.parsedType}),q;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Ew(n,e,n.path,[a,`key`])),value:i._parse(new Ew(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ST.create=(e,t,n)=>new ST({valueType:t,keyType:e,typeName:X.ZodMap,...Y(n)});var CT=class e extends Ow{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.set)return K(n,{code:G.invalid_type,expected:W.set,received:n.parsedType}),q;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(K(n,{code:G.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(K(n,{code:G.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return q;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Ew(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};CT.create=(e,t)=>new CT({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...Y(t)});var wT=class e extends Ow{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.function)return K(t,{code:G.invalid_type,expected:W.function,received:t.parsedType}),q;function n(e,n){return vw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,_w(),hw].filter(e=>!!e),issueData:{code:G.invalid_arguments,argumentsError:n}})}function r(e,n){return vw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,_w(),hw].filter(e=>!!e),issueData:{code:G.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof AT){let e=this;return xw(async function(...t){let o=new mw([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return xw(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new mw([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new mw([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:bT.create(t).rest(lT.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||bT.create([]).rest(lT.create()),returns:n||lT.create(),typeName:X.ZodFunction,...Y(r)})}},TT=class extends Ow{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};TT.create=(e,t)=>new TT({getter:e,typeName:X.ZodLazy,...Y(t)});var ET=class extends Ow{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:G.invalid_literal,expected:this._def.value}),q}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ET.create=(e,t)=>new ET({value:e,typeName:X.ZodLiteral,...Y(t)});function DT(e,t){return new OT({values:e,typeName:X.ZodEnum,...Y(t)})}var OT=class e extends Ow{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:dw.joinValues(n),received:t.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:G.invalid_enum_value,options:n}),q}return xw(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};OT.create=DT;var kT=class extends Ow{_parse(e){let t=dw.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==W.string&&n.parsedType!==W.number){let e=dw.objectValues(t);return K(n,{expected:dw.joinValues(e),received:n.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(dw.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=dw.objectValues(t);return K(n,{received:n.data,code:G.invalid_enum_value,options:e}),q}return xw(e.data)}get enum(){return this._def.values}};kT.create=(e,t)=>new kT({values:e,typeName:X.ZodNativeEnum,...Y(t)});var AT=class extends Ow{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==W.promise&&t.common.async===!1?(K(t,{code:G.invalid_type,expected:W.promise,received:t.parsedType}),q):xw((t.parsedType===W.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};AT.create=(e,t)=>new AT({type:e,typeName:X.ZodPromise,...Y(t)});var jT=class extends Ow{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{K(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return q;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?bw(r.value):r});{if(t.value===`aborted`)return q;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?bw(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?q:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?q:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ww(e))return q;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ww(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):q)}dw.assertNever(r)}};jT.create=(e,t,n)=>new jT({schema:e,typeName:X.ZodEffects,effect:t,...Y(n)}),jT.createWithPreprocess=(e,t,n)=>new jT({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...Y(n)});var MT=class extends Ow{_parse(e){return this._getType(e)===W.undefined?xw(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};MT.create=(e,t)=>new MT({innerType:e,typeName:X.ZodOptional,...Y(t)});var NT=class extends Ow{_parse(e){return this._getType(e)===W.null?xw(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};NT.create=(e,t)=>new NT({innerType:e,typeName:X.ZodNullable,...Y(t)});var PT=class extends Ow{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===W.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};PT.create=(e,t)=>new PT({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...Y(t)});var FT=class extends Ow{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Tw(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new mw(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new mw(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};FT.create=(e,t)=>new FT({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...Y(t)});var IT=class extends Ow{_parse(e){if(this._getType(e)!==W.nan){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.nan,received:t.parsedType}),q}return{status:`valid`,value:e.data}}};IT.create=e=>new IT({typeName:X.ZodNaN,...Y(e)});var LT=class extends Ow{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},RT=class e extends Ow{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),bw(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},zT=class extends Ow{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ww(e)&&(e.value=Object.freeze(e.value)),e);return Tw(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};zT.create=(e,t)=>new zT({innerType:e,typeName:X.ZodReadonly,...Y(t)}),mT.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),$w.create,tT.create,IT.create,nT.create,rT.create,iT.create,aT.create,oT.create,sT.create,cT.create,lT.create,uT.create,dT.create,fT.create;var BT=mT.create;mT.strictCreate,hT.create,_T.create,yT.create,bT.create,xT.create,ST.create,CT.create,wT.create,TT.create,ET.create,OT.create,kT.create,AT.create,jT.create,MT.create,NT.create,jT.createWithPreprocess,RT.create;var VT=k(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ri.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){nn(this,`with`,e)},parse(e,t){return In(this,e,t,{callee:this.parse})},parseAsync(e,t){return Rn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Bn(this,e,t)},safeParseAsync(e,t){return Un(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return At(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),HT=k(`ZodMiniObject`,(e,t)=>{aa.init(e,t),VT.init(e,t),fn(e,`shape`,e=>e._zod.def.shape,!1)});function UT(e,t){return new HT({type:`object`,shape:e??{},...O(t)})}function WT(e){return!!e._zod}function GT(e){let t=Object.values(e);if(t.length===0)return UT({});let n=t.every(WT),r=t.every(e=>!WT(e));if(n)return UT(e);if(r)return BT(e);throw Error(`Mixed Zod versions detected in object shape.`)}function KT(e,t){return WT(e)?Bn(e,t):e.safeParse(t)}async function qT(e,t){return WT(e)?await Un(e,t):await e.safeParseAsync(t)}function JT(e){if(!e)return;let t;if(t=WT(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function YT(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return GT(e)}}if(WT(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function XT(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function ZT(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${XT(e.path)}`:e.message).join(`
296
- `);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function QT(e){return e.description}function $T(e){if(WT(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function eE(e){if(WT(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}var tE=`2025-11-25`,nE=[tE,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],rE=`io.modelcontextprotocol/related-task`,iE=Cu(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),aE=Wl([A(),j().int()]),oE=A();Hl({ttl:j().optional(),pollInterval:j().optional()});var sE=P({ttl:j().optional()}),cE=P({taskId:A()}),lE=Hl({progressToken:aE.optional(),[rE]:cE.optional()}),uE=P({_meta:lE.optional()}),dE=uE.extend({task:sE.optional()}),fE=e=>dE.safeParse(e).success,pE=P({method:A(),params:uE.loose().optional()}),mE=P({_meta:lE.optional()}),hE=P({method:A(),params:mE.loose().optional()}),gE=Hl({_meta:lE.optional()}),_E=Wl([A(),j().int()]),vE=P({jsonrpc:L(`2.0`),id:_E,...pE.shape}).strict(),yE=e=>vE.safeParse(e).success,bE=P({jsonrpc:L(`2.0`),...hE.shape}).strict(),xE=e=>bE.safeParse(e).success,SE=P({jsonrpc:L(`2.0`),id:_E,result:gE}).strict(),CE=e=>SE.safeParse(e).success,Z;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Z||={});var wE=P({jsonrpc:L(`2.0`),id:_E.optional(),error:P({code:j().int(),message:A(),data:Ll().optional()})}).strict(),TE=e=>wE.safeParse(e).success,EE=Wl([vE,bE,SE,wE]);Wl([SE,wE]);var DE=gE.strict(),OE=mE.extend({requestId:_E.optional(),reason:A().optional()}),kE=hE.extend({method:L(`notifications/cancelled`),params:OE}),AE=P({icons:N(P({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:I([`light`,`dark`]).optional()})).optional()}),jE=P({name:A(),title:A().optional()}),ME=jE.extend({...jE.shape,...AE.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),NE=Eu(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Jl(P({form:Jl(P({applyDefaults:M().optional()}),Ql(A(),Ll())).optional(),url:iE.optional()}),Ql(A(),Ll()).optional())),PE=Hl({list:iE.optional(),cancel:iE.optional(),requests:Hl({sampling:Hl({createMessage:iE.optional()}).optional(),elicitation:Hl({create:iE.optional()}).optional()}).optional()}),FE=Hl({list:iE.optional(),cancel:iE.optional(),requests:Hl({tools:Hl({call:iE.optional()}).optional()}).optional()}),IE=P({experimental:Ql(A(),iE).optional(),sampling:P({context:iE.optional(),tools:iE.optional()}).optional(),elicitation:NE.optional(),roots:P({listChanged:M().optional()}).optional(),tasks:PE.optional(),extensions:Ql(A(),iE).optional()}),LE=uE.extend({protocolVersion:A(),capabilities:IE,clientInfo:ME}),RE=pE.extend({method:L(`initialize`),params:LE}),zE=P({experimental:Ql(A(),iE).optional(),logging:iE.optional(),completions:iE.optional(),prompts:P({listChanged:M().optional()}).optional(),resources:P({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:P({listChanged:M().optional()}).optional(),tasks:FE.optional(),extensions:Ql(A(),iE).optional()}),BE=gE.extend({protocolVersion:A(),capabilities:zE,serverInfo:ME,instructions:A().optional()}),VE=hE.extend({method:L(`notifications/initialized`),params:mE.optional()}),HE=pE.extend({method:L(`ping`),params:uE.optional()}),UE=P({progress:j(),total:iu(j()),message:iu(A())}),WE=P({...mE.shape,...UE.shape,progressToken:aE}),GE=hE.extend({method:L(`notifications/progress`),params:WE}),KE=uE.extend({cursor:oE.optional()}),qE=pE.extend({params:KE.optional()}),JE=gE.extend({nextCursor:oE.optional()}),YE=I([`working`,`input_required`,`completed`,`failed`,`cancelled`]),XE=P({taskId:A(),status:YE,ttl:Wl([j(),Fl()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:iu(j()),statusMessage:iu(A())}),ZE=gE.extend({task:XE}),QE=mE.merge(XE),$E=hE.extend({method:L(`notifications/tasks/status`),params:QE}),eD=pE.extend({method:L(`tasks/get`),params:uE.extend({taskId:A()})}),tD=gE.merge(XE),nD=pE.extend({method:L(`tasks/result`),params:uE.extend({taskId:A()})});gE.loose();var rD=qE.extend({method:L(`tasks/list`)}),iD=JE.extend({tasks:N(XE)}),aD=pE.extend({method:L(`tasks/cancel`),params:uE.extend({taskId:A()})}),oD=gE.merge(XE),sD=P({uri:A(),mimeType:iu(A()),_meta:Ql(A(),Ll()).optional()}),cD=sD.extend({text:A()}),lD=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),uD=sD.extend({blob:lD}),dD=I([`user`,`assistant`]),fD=P({audience:N(dD).optional(),priority:j().min(0).max(1).optional(),lastModified:Du({offset:!0}).optional()}),pD=P({...jE.shape,...AE.shape,uri:A(),description:iu(A()),mimeType:iu(A()),size:iu(j()),annotations:fD.optional(),_meta:iu(Hl({}))}),mD=P({...jE.shape,...AE.shape,uriTemplate:A(),description:iu(A()),mimeType:iu(A()),annotations:fD.optional(),_meta:iu(Hl({}))}),hD=qE.extend({method:L(`resources/list`)}),gD=JE.extend({resources:N(pD)}),_D=qE.extend({method:L(`resources/templates/list`)}),vD=JE.extend({resourceTemplates:N(mD)}),yD=uE.extend({uri:A()}),bD=yD,xD=pE.extend({method:L(`resources/read`),params:bD}),SD=gE.extend({contents:N(Wl([cD,uD]))}),CD=hE.extend({method:L(`notifications/resources/list_changed`),params:mE.optional()}),wD=yD,TD=pE.extend({method:L(`resources/subscribe`),params:wD}),ED=yD,DD=pE.extend({method:L(`resources/unsubscribe`),params:ED}),OD=mE.extend({uri:A()}),kD=hE.extend({method:L(`notifications/resources/updated`),params:OD}),AD=P({name:A(),description:iu(A()),required:iu(M())}),jD=P({...jE.shape,...AE.shape,description:iu(A()),arguments:iu(N(AD)),_meta:iu(Hl({}))}),MD=qE.extend({method:L(`prompts/list`)}),ND=JE.extend({prompts:N(jD)}),PD=uE.extend({name:A(),arguments:Ql(A(),A()).optional()}),FD=pE.extend({method:L(`prompts/get`),params:PD}),ID=P({type:L(`text`),text:A(),annotations:fD.optional(),_meta:Ql(A(),Ll()).optional()}),LD=P({type:L(`image`),data:lD,mimeType:A(),annotations:fD.optional(),_meta:Ql(A(),Ll()).optional()}),RD=P({type:L(`audio`),data:lD,mimeType:A(),annotations:fD.optional(),_meta:Ql(A(),Ll()).optional()}),zD=P({type:L(`tool_use`),name:A(),id:A(),input:Ql(A(),Ll()),_meta:Ql(A(),Ll()).optional()}),BD=P({type:L(`resource`),resource:Wl([cD,uD]),annotations:fD.optional(),_meta:Ql(A(),Ll()).optional()}),VD=Wl([ID,LD,RD,pD.extend({type:L(`resource_link`)}),BD]),HD=P({role:dD,content:VD}),UD=gE.extend({description:A().optional(),messages:N(HD)}),WD=hE.extend({method:L(`notifications/prompts/list_changed`),params:mE.optional()}),GD=P({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),KD=P({taskSupport:I([`required`,`optional`,`forbidden`]).optional()}),qD=P({...jE.shape,...AE.shape,description:A().optional(),inputSchema:P({type:L(`object`),properties:Ql(A(),iE).optional(),required:N(A()).optional()}).catchall(Ll()),outputSchema:P({type:L(`object`),properties:Ql(A(),iE).optional(),required:N(A()).optional()}).catchall(Ll()).optional(),annotations:GD.optional(),execution:KD.optional(),_meta:Ql(A(),Ll()).optional()}),JD=qE.extend({method:L(`tools/list`)}),YD=JE.extend({tools:N(qD)}),XD=gE.extend({content:N(VD).default([]),structuredContent:Ql(A(),Ll()).optional(),isError:M().optional()});XD.or(gE.extend({toolResult:Ll()}));var ZD=dE.extend({name:A(),arguments:Ql(A(),Ll()).optional()}),QD=pE.extend({method:L(`tools/call`),params:ZD}),$D=hE.extend({method:L(`notifications/tools/list_changed`),params:mE.optional()}),eO=P({autoRefresh:M().default(!0),debounceMs:j().int().nonnegative().default(300)}),tO=I([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),nO=uE.extend({level:tO}),rO=pE.extend({method:L(`logging/setLevel`),params:nO}),iO=mE.extend({level:tO,logger:A().optional(),data:Ll()}),aO=hE.extend({method:L(`notifications/message`),params:iO}),oO=P({hints:N(P({name:A().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),sO=P({mode:I([`auto`,`required`,`none`]).optional()}),cO=P({type:L(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(VD).default([]),structuredContent:P({}).loose().optional(),isError:M().optional(),_meta:Ql(A(),Ll()).optional()}),lO=Kl(`type`,[ID,LD,RD]),uO=Kl(`type`,[ID,LD,RD,zD,cO]),dO=P({role:dD,content:Wl([uO,N(uO)]),_meta:Ql(A(),Ll()).optional()}),fO=dE.extend({messages:N(dO),modelPreferences:oO.optional(),systemPrompt:A().optional(),includeContext:I([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:N(A()).optional(),metadata:iE.optional(),tools:N(qD).optional(),toolChoice:sO.optional()}),pO=pE.extend({method:L(`sampling/createMessage`),params:fO}),mO=gE.extend({model:A(),stopReason:iu(I([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:dD,content:lO}),hO=gE.extend({model:A(),stopReason:iu(I([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:dD,content:Wl([uO,N(uO)])}),gO=P({type:L(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),_O=P({type:L(`string`),title:A().optional(),description:A().optional(),minLength:j().optional(),maxLength:j().optional(),format:I([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),vO=P({type:I([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),yO=P({type:L(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),bO=P({type:L(`string`),title:A().optional(),description:A().optional(),oneOf:N(P({const:A(),title:A()})),default:A().optional()}),xO=Wl([Wl([P({type:L(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),Wl([yO,bO]),Wl([P({type:L(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:P({type:L(`string`),enum:N(A())}),default:N(A()).optional()}),P({type:L(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:P({anyOf:N(P({const:A(),title:A()}))}),default:N(A()).optional()})])]),gO,_O,vO]),SO=Wl([dE.extend({mode:L(`form`).optional(),message:A(),requestedSchema:P({type:L(`object`),properties:Ql(A(),xO),required:N(A()).optional()})}),dE.extend({mode:L(`url`),message:A(),elicitationId:A(),url:A().url()})]),CO=pE.extend({method:L(`elicitation/create`),params:SO}),wO=mE.extend({elicitationId:A()}),TO=hE.extend({method:L(`notifications/elicitation/complete`),params:wO}),EO=gE.extend({action:I([`accept`,`decline`,`cancel`]),content:Eu(e=>e===null?void 0:e,Ql(A(),Wl([A(),j(),M(),N(A())])).optional())}),DO=P({type:L(`ref/resource`),uri:A()}),OO=P({type:L(`ref/prompt`),name:A()}),kO=uE.extend({ref:Wl([OO,DO]),argument:P({name:A(),value:A()}),context:P({arguments:Ql(A(),A()).optional()}).optional()}),AO=pE.extend({method:L(`completion/complete`),params:kO});function jO(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function MO(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var NO=gE.extend({completion:Hl({values:N(A()).max(100),total:iu(j().int()),hasMore:iu(M())})}),PO=P({uri:A().startsWith(`file://`),name:A().optional(),_meta:Ql(A(),Ll()).optional()}),FO=pE.extend({method:L(`roots/list`),params:uE.optional()}),IO=gE.extend({roots:N(PO)}),LO=hE.extend({method:L(`notifications/roots/list_changed`),params:mE.optional()});Wl([HE,RE,AO,rO,FD,MD,hD,_D,xD,TD,DD,QD,JD,eD,nD,rD,aD]),Wl([kE,GE,VE,LO,$E]),Wl([DE,mO,hO,EO,IO,tD,iD,ZE]),Wl([HE,pO,CO,FO,eD,nD,rD,aD]),Wl([kE,GE,aO,kD,CD,$D,WD,$E,TO]),Wl([DE,BE,NO,UD,ND,gD,vD,SD,XD,YD,tD,iD,ZE]);var Q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new RO(e.elicitations,n)}return new e(t,n,r)}},RO=class extends Q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function zO(e){return e===`completed`||e===`failed`||e===`cancelled`}var BO=Symbol(`Let zodToJsonSchema decide on which parser to use`),VO={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},HO=e=>typeof e==`string`?{...VO,name:e}:{...VO,...e},UO=e=>{let t=HO(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function WO(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function GO(e,t,n,r,i){e[t]=n,WO(e,t,r,i)}var KO=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function qO(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?KO(t,e.currentPath):t.join(`/`)}}function JO(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=Rk(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&GO(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&GO(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(GO(n,`minItems`,e.exactLength.value,e.exactLength.message,t),GO(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function YO(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?GO(n,`minimum`,r.value,r.message,t):GO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),GO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?GO(n,`maximum`,r.value,r.message,t):GO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),GO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:GO(n,`multipleOf`,r.value,r.message,t)}return n}function XO(){return{type:`boolean`}}function ZO(e,t){return Rk(e.type._def,t)}var QO=(e,t)=>Rk(e.innerType._def,t);function $O(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>$O(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return ek(e,t)}}var ek=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:GO(n,`minimum`,r.value,r.message,t);break;case`max`:GO(n,`maximum`,r.value,r.message,t)}return n};function tk(e,t){return{...Rk(e.innerType._def,t),default:e.defaultValue()}}function nk(e,t){return t.effectStrategy===`input`?Rk(e.schema._def,t):qO(t)}function rk(e){return{type:`string`,enum:Array.from(e.values)}}var ik=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function ak(e,t){let n=[Rk(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Rk(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(ik(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function ok(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var sk=void 0,ck={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(sk===void 0&&(sk=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),sk),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function lk(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:GO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:GO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:pk(n,`email`,r.message,t);break;case`format:idn-email`:pk(n,`idn-email`,r.message,t);break;case`pattern:zod`:mk(n,ck.email,r.message,t)}break;case`url`:pk(n,`uri`,r.message,t);break;case`uuid`:pk(n,`uuid`,r.message,t);break;case`regex`:mk(n,r.regex,r.message,t);break;case`cuid`:mk(n,ck.cuid,r.message,t);break;case`cuid2`:mk(n,ck.cuid2,r.message,t);break;case`startsWith`:mk(n,RegExp(`^${uk(r.value,t)}`),r.message,t);break;case`endsWith`:mk(n,RegExp(`${uk(r.value,t)}$`),r.message,t);break;case`datetime`:pk(n,`date-time`,r.message,t);break;case`date`:pk(n,`date`,r.message,t);break;case`time`:pk(n,`time`,r.message,t);break;case`duration`:pk(n,`duration`,r.message,t);break;case`length`:GO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),GO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:mk(n,RegExp(uk(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&pk(n,`ipv4`,r.message,t),r.version!==`v4`&&pk(n,`ipv6`,r.message,t);break;case`base64url`:mk(n,ck.base64url,r.message,t);break;case`jwt`:mk(n,ck.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&mk(n,ck.ipv4Cidr,r.message,t),r.version!==`v4`&&mk(n,ck.ipv6Cidr,r.message,t);break;case`emoji`:mk(n,ck.emoji(),r.message,t);break;case`ulid`:mk(n,ck.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:pk(n,`binary`,r.message,t);break;case`contentEncoding:base64`:GO(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:mk(n,ck.base64,r.message,t)}break;case`nanoid`:mk(n,ck.nanoid,r.message,t)}return n}function uk(e,t){return t.patternStrategy===`escape`?fk(e):e}var dk=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function fk(e){let t=``;for(let n=0;n<e.length;n++)dk.has(e[n])||(t+=`\\`),t+=e[n];return t}function pk(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):GO(e,`format`,t,n,r)}function mk(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:hk(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):GO(e,`pattern`,hk(t,r),n,r)}function hk(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
295
+ }`,{...e.repo,number:n})).repository.pullRequest?.closingIssuesReferences;if(r.number!==n||r.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||r.base.repo.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!i||i.pageInfo.hasNextPage||!i.nodes.some(n=>n.number===t&&n.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()))throw new D(`Native PR lineage does not establish the exact repository and closing issue.`);return qx.parse({prNumber:n,headSha:r.head.sha,headBranch:r.head.ref,baseSha:r.base.sha,baseBranch:r.base.ref,mergeSha:r.merge_commit_sha,merged:r.merged,authorLogin:r.user?.login})}async function xS(e,t,n){let r=[...new Set([t.prNumber,n].filter(e=>e!=null))];return Promise.all(r.map(n=>bS(e,t.issueNumber,n)))}function SS(e,t,n,r,i,a,o,s){if(n===`active-resume`){if(![`active`,`pr-published`].includes(t.status)||o!==`open`||a.some(e=>e.merged||e.headSha!==i.sha||e.headBranch!==t.branch))throw new D(`Active resume requires the exact open issue and unmerged source lineage.`);if(s.some(e=>/^git\/ai-delivery\/(?:publications|reviews|merges|merge-intents|merge-attempts|merge-results)\//u.test(e.path)))throw new D(`Existing current publication/review/merge slots require separate authority reconciliation; active resume cannot overwrite them.`)}else{let n=a.find(e=>e.prNumber===r);if(!n||o!==`closed`||!n.merged||n.headSha!==i.sha||n.headBranch!==t.branch||a.some(r=>!r.merged||!r.mergeSha||r.headBranch!==t.branch||r.baseBranch!==n.baseBranch||dd(e,`merge-base`,`--is-ancestor`,r.mergeSha,r.prNumber===n.prNumber?n.mergeSha:i.sha)!==0))throw new D(`Terminal native PR lineage or merged-result ancestry does not bind the retained exact source.`)}}async function CS(e,t,n){let r=async t=>{try{let n=(await e.clients.rest.repos.getBranch({...e.repo,branch:t})).data;if(n.name!==t)throw new D(`Native branch readback belongs to another ref.`);return vd.parse(n.commit.sha)}catch(e){if(e.status===404)return null;throw e}},i=await r(t),a=await r(n);if(a===null)throw new D(`Native retaining base branch is missing.`);return{headSha:i,baseSha:a}}async function wS(e,t){let n=[],r=md(e.root),i=ux(r).filter(e=>e.type===`issue`&&e.issueNumber===t.issueNumber);if(i.length!==1)return{ready:!1,blockers:[`Expected one canonical legacy issue row.`],plan:null,inventory:[]};let a=[];try{let o=Kx.parse(i[0]);if(a.push(...eS(r,o)),!e.configuration||e.config.repository!==`${e.repo.owner}/${e.repo.repo}`)throw new D(`Transition requires exact current repository configuration.`);if(o.path!==w(r,`.worktrees`,`issue-${String(o.issueNumber)}`)||o.branch!==`issue/${String(o.issueNumber)}`||fd(o.path)!==h(o.path)||pd(o.path)!==pd(r)||ud(o.path,`branch`,`--show-current`)!==o.branch)throw new D(`Legacy row path, branch or Git ownership disagrees.`);gd(o.path);for(let e of[`v1`,`v2`])Qx(w(pd(r),`issue-cli`,`verification-stages`,e))&&n.push(`Unsupported operative issue-cli verification-stages/${e}; no authenticated supported operational closure is available.`);if((!t.retainedAdmissionPath||!t.retainedArchivePath)&&n.push(`Missing retained supported public producer admission/archive and operational closure. Historical UNKNOWN is preservation-only.`),n.length>0)return{ready:!1,blockers:n,plan:null,inventory:a};let s=await uy({repoRoot:r,configuration:e.configuration,...t.runtimeEntryPath===void 0?{}:{runtimeEntryPath:t.runtimeEntryPath}}),{inventory:c,...l}=Xx(e,h(t.retainedAdmissionPath),h(t.retainedArchivePath));a.push(...c);let u={sha:ud(o.path,`rev-parse`,`HEAD`),tree:ud(o.path,`rev-parse`,`HEAD^{tree}`)},d=Zx(r,o,a,l.producerDigest,u);if(a.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(t=>bb($x(t.source)).classification.repository!==e.config.repository))throw new D(`Operational run inventory belongs to another repository.`);if(t.disposition===`remove`&&c.some(e=>{let t=se(o.path,e.source);return t===``||!t.startsWith(`..`)&&!t.startsWith(`/`)}))throw new D(`Retained operational producer must remain outside the source selected for removal.`);let f=a.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));db(o.path,f===void 0?void 0:$x(f.source));let p=t.purpose===`merged-cleanup`?t.terminalPrNumber??o.prNumber??null:null,m=await xS(e,o,p),g=(await e.clients.rest.issues.get({...e.repo,issue_number:o.issueNumber})).data;SS(r,o,t.purpose,p,u,m,g.state,a);let _=await mS(e);if(m.some(e=>e.authorLogin.toLowerCase()===_.reviewerActor.toLowerCase()))throw new D(`Configured transition reviewer App is also the native PR author.`);let v=t.disposition===`remove`?await CS(e,o.branch,m.find(e=>e.prNumber===p).baseBranch):null;if(v&&(v.headSha!==null&&v.headSha!==u.sha||ud(r,`rev-parse`,_d(r,ES(e).remote))!==v.baseSha))throw new D(`Native remote branch readback disagrees with exact source or local retaining ref.`);let y=[...t.retainedHoldCommentIds??[]].sort((e,t)=>e-t);if(new Set(y).size!==y.length)throw new D(`Retained hold inventory has duplicates.`);let b=[];for(let t of y){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t})).data;if(!n.body||n.issue_url?.toLowerCase()!==`https://api.github.com/repos/${e.config.repository}/issues/${String(p??o.issueNumber)}`.toLowerCase())throw new D(`Retained hold comment belongs to another subject or is unavailable.`);let r=Buffer.from(z(n));b.push({commentId:t,digest:V(r)})}a.sort((e,t)=>e.path.localeCompare(t.path));let x={schemaVersion:`ai-delivery.worktree-transition-plan@1`,repository:e.config.repository,repoRoot:r,row:o,purpose:t.purpose,disposition:t.disposition??`retain`,head:u,terminalPrNumber:p,lineage:m,remoteRefs:v,retainedHoldCommentIds:y,holdEvidence:b,inventory:a,inventoryId:B(a),historicalProducer:`UNKNOWN`,closure:{family:`public-ai-delivery-0.3.5-posix@1`,...l,runManifestIds:d},currentRuntime:s,policyDigest:V($x(ES(e).policyModulePath)),operator:_.operator,reviewerActor:_.reviewerActor},ee=Jx.parse({...x,planId:B(x)});return{ready:!0,blockers:n,plan:ee,inventory:a,relinquishmentBody:hS(ee)}}catch(e){return n.push(e instanceof Error?e.message:String(e)),{ready:!1,blockers:n,plan:null,inventory:a}}}function TS(e,t){for(let n of t){let t=$x(n.source);if(t.length!==n.size||V(t)!==n.digest)throw new D(`Historical evidence drifted: ${n.path}`);wd(w(e,`${n.digest.slice(7)}.bin`),t,n.digest)}}function ES(e){if(!e.configuration||!(`policyModulePath`in e.configuration))throw new D(`Historical repository configuration binding is unsupported by this runtime; preserve its original controller and records. No policy module was loaded.`);return e.configuration}var DS=A().regex(/^[a-f0-9]{40}$/u),OS=A().regex(/^sha256:[a-f0-9]{64}$/u),kS=P({artifactId:OS,authorIdentity:A().min(1),checks:N(A().min(1)).min(1),diffScopeHash:OS,deliveryMetrics:P({blockerTimeMs:j().int().nonnegative().nullable(),reviewRound:j().int().positive()}).strict().optional(),elapsedMs:j().int().nonnegative(),findings:N(A()),head:P({sha:DS,tree:DS}).strict(),issueNumber:j().int().positive(),prNumber:j().int().positive().nullable(),readOnly:L(!0),requestedEffort:A().min(1),requestedModel:A().min(1),effectiveEffort:A().min(1),effectiveModel:A().min(1),reviewerIdentity:A().min(1),schemaVersion:L(`ai-delivery.review-artifact@1`),summary:A().min(1),verdict:I([`approve`,`request-changes`])}).strict().superRefine((e,t)=>{let{artifactId:n,...r}=e;(n!==B(r)||e.authorIdentity===e.reviewerIdentity)&&t.addIssue({code:`custom`,message:`Review artifact identity or role separation is invalid.`})});P({artifact:kS,completedAt:Du(),githubReviewId:j().int().positive(),githubReviewUrl:ml(),headSha:DS,login:A().min(1),prNumber:j().int().positive(),publicationEvidenceId:OS,receiptId:OS,schemaVersion:L(`ai-delivery.review-receipt@1`),state:L(`APPROVED`)}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||e.headSha!==e.artifact.head.sha||e.artifact.prNumber!==null&&e.artifact.prNumber!==e.prNumber)&&t.addIssue({code:`custom`,message:`Submitted review receipt is not bound to its artifact.`})});async function AS(e,t,n,r){let i;try{i=await e.clients.graphql(`query DeliveryReviewDecision($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid reviewDecision } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t})}catch{return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is unavailable.`}}let a=i.repository?.pullRequest;if(!a)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; PR decision readback is unavailable.`};if(a.headRefOid!==n)throw new D(`GitHub review decision does not match the exact PR head.`);if(a.reviewDecision!==null&&a.reviewDecision!==`APPROVED`&&a.reviewDecision!==`REVIEW_REQUIRED`&&a.reviewDecision!==`CHANGES_REQUESTED`)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is malformed.`};let o=null;if(r)try{let i=await e.clients.graphql(`query DeliveryReviewAccess($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviews(last: 100) { nodes { fullDatabaseId author { login } authorCanPushToRepository commit { oid } state } } } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t}),a=r.login.toLowerCase().replace(/\[bot\]$/u,``),s=i.repository?.pullRequest?.reviews.nodes.find(e=>e!==null&&String(e.fullDatabaseId)===String(r.id)&&e.author?.login.toLowerCase().replace(/\[bot\]$/u,``)===a&&e.commit?.oid===n&&e.state===`APPROVED`);typeof s?.authorCanPushToRepository==`boolean`&&(o=s.authorCanPushToRepository)}catch{}return a.reviewDecision===`APPROVED`?{reviewDecision:`APPROVED`,submittedReviewAuthorCanPushToRepository:o,status:`satisfied`,nextAction:`Continue only after required checks pass.`}:a.reviewDecision===`REVIEW_REQUIRED`?{reviewDecision:`REVIEW_REQUIRED`,submittedReviewAuthorCanPushToRepository:o,status:`still-required`,nextAction:o===!1?`GitHub still requires a qualifying approval; the submitted reviewer App review has no repository write access. Inspect the active rule and the App installation Contents grant, then obtain approval from an eligible independent reviewer.`:`GitHub still requires a qualifying approval. Inspect the active rule and obtain approval from an eligible independent reviewer; do not change actors or protections automatically.`}:a.reviewDecision===`CHANGES_REQUESTED`?{reviewDecision:`CHANGES_REQUESTED`,submittedReviewAuthorCanPushToRepository:o,status:`changes-requested`,nextAction:`Resolve the blocking review and obtain a fresh exact-head independent approval.`}:{reviewDecision:null,submittedReviewAuthorCanPushToRepository:o,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; no required-review decision was exposed.`}}function jS(e){let t=typeof e==`string`?JSON.parse(e):e;return kS.parse(t)}function MS(e){try{if(typeof e!=`string`||Buffer.byteLength(e,`utf8`)>65536)throw Error(`Invalid size.`);let t=e.match(/<!-- ai-delivery-review-artifact:[\s\S]*?-->/gu)??[],n=e.match(/<!-- ai-delivery-review-artifact-data:[\s\S]*?-->/gu)??[];if(t.length!==1||n.length!==1)throw Error(`Ambiguous binding.`);let r=t[0].match(/^<!-- ai-delivery-review-artifact: (sha256:[a-f0-9]{64}) -->$/u)?.[1],i=n[0].match(/^<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->$/u)?.[1];if(!r||!i)throw Error(`Invalid binding.`);let a=Buffer.from(i,`base64url`),o=a.toString(`utf8`);if(a.toString(`base64url`)!==i||!Buffer.from(o,`utf8`).equals(a))throw Error(`Invalid encoding.`);let s=jS(o);if(s.artifactId!==r)throw Error(`Artifact identity differs.`);return s}catch{throw new D(`GitHub review artifact binding is missing, invalid or ambiguous; obtain a fresh review.`)}}function NS(e){kS.parse(e);let t=`${e.summary}\n\n<!-- ai-delivery-review-artifact: ${e.artifactId} -->\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(e)).toString(`base64url`)} -->`;return MS(t),t}async function PS(e,t,n){let r=[];for(let n=1;n<=30;n++){let i=(await e.clients.rest.pulls.listFiles({...e.repo,pull_number:t,page:n,per_page:100})).data;if(r.push(...i.map(e=>e.filename)),i.length<100)break}if(!Number.isSafeInteger(n)||r.length!==n||new Set(r).size!==r.length)throw new D(`Independent review scope is incomplete or differs from the remote PR diff.`);return B(r.sort())}async function FS(e,t){let n=[];for(let r=1;r<=20;r+=1){let i=await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,per_page:100,page:r});if(n.push(...i.data),i.data.length<100)return n}throw new D(`Review history exceeds the bounded readback window.`)}async function IS(e){let{artifact:t,context:n,issueNumber:r,prNumber:i}=e;if(kS.parse(t),t.verdict!==`approve`||t.issueNumber!==r||t.authorIdentity!==n.config.roles.author.identity||t.reviewerIdentity!==n.config.roles.reviewer.identity||t.prNumber!==null&&t.prNumber!==i)throw new D(`Independent review artifact is foreign or rejected.`);if(n.clients.authSource!==`app`||n.clients.role!==`reviewer`||!n.clients.appActorLogin)throw new D(`Formal review requires the independent reviewer GitHub App role.`);let a=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(a.number!==i||a.head.sha!==t.head.sha||a.state!==`open`||a.base.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase()||a.head.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase())throw new D(`PR identity or head changed before formal review.`);let o=await n.clients.appActorLogin();if(!o||!a.user?.login||o.toLowerCase()===a.user.login.toLowerCase())throw new D(`Reviewer GitHub actor must differ from PR author.`);let s=(await n.clients.rest.git.getCommit({...n.repo,commit_sha:t.head.sha})).data;if(s.sha!==t.head.sha||s.tree.sha!==t.head.tree)throw new D(`Independent review tree differs from the remote commit.`);if(t.diffScopeHash!==await PS(n,i,a.changed_files))throw new D(`Independent review scope is incomplete or differs from the remote PR diff.`);let c=NS(t),l=`<!-- ai-delivery-review-artifact: ${t.artifactId} -->`,u=await FS(n,i);if(u.some(e=>e.user?.login.toLowerCase()===o.toLowerCase()&&e.commit_id===t.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``)&&!e.body?.includes(l)))throw new D(`Another independent artifact conflicts with the existing exact-head App approval.`);let d=u.filter(e=>e.body?.includes(l));if(d.length>1)throw new D(`Conflicting GitHub reviews claim the same artifact identity.`);let f=d[0];if(f&&(f.state!==`APPROVED`||f.commit_id!==t.head.sha||f.user?.login.toLowerCase()!==o.toLowerCase()||!f.html_url||MS(f.body).artifactId!==t.artifactId))throw new D(`Prior GitHub review marker conflicts with exact-head approval.`);let p=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(p.head.sha!==t.head.sha||p.base.sha!==a.base.sha||p.state!==`open`)throw new D(`PR moved during independent review validation.`);if(e.dryRun)return{dryRun:!0,artifactId:t.artifactId,headSha:t.head.sha};let m=f??(await n.clients.rest.pulls.createReview({...n.repo,pull_number:i,commit_id:t.head.sha,body:c,event:`APPROVE`})).data;if(!m.id||m.state!==`APPROVED`||m.commit_id!==t.head.sha||m.user?.login.toLowerCase()!==o.toLowerCase()||!m.html_url)throw new D(`GitHub did not return complete exact-head independent approval.`);let h={artifact:t,repository:n.config.repository,baseSha:a.base.sha,headSha:t.head.sha,githubReviewId:m.id,githubReviewUrl:m.html_url,login:m.user.login,prNumber:i,schemaVersion:`ai-delivery.github-review@1`,state:`APPROVED`},g={...h,receiptId:B(h)},_=(await n.clients.rest.pulls.getReview({...n.repo,pull_number:i,review_id:m.id})).data;if(_.id!==g.githubReviewId||_.html_url!==g.githubReviewUrl||_.state!==`APPROVED`||_.commit_id!==g.headSha||_.user?.login!==g.login||MS(_.body).artifactId!==t.artifactId)throw new D(`GitHub exact-head App review readback disagrees.`);let v=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(v.head.sha!==t.head.sha||v.base.sha!==a.base.sha||v.state!==`open`)throw new D(`PR moved during independent review submission; approval is not current.`);return g}var LS=/^[a-f0-9]{40}$/u,RS=/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;function zS(e){if(typeof e!=`string`)throw new D(`Incomplete non-closing message readback.`);let t=e.replace(/[*_~`\\<>[\]]/gu,``);if(/\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\b(?:\s*:\s*|\s+)[^\n]*?(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(t))throw new D(`Non-closing delivery refuses closing directives in body, title or commit messages.`)}function BS(e,t){return`References ${e.config.repository}#${t}`}function VS(e,t,n){zS(n);let r=BS(e,t),i=n.startsWith(`${r}\n`)||n===r?n:`${r}\n\n${n}`;return HS(e,t,i),i}function HS(e,t,n){zS(n);let r=n.split(/\r?\n/u);if(r[0]!==BS(e,t)||r.filter(e=>/^References\s/iu.test(e)).length!==1)throw new D(`Non-closing PR body must retain one leading canonical References line.`)}function US(e,t){let n=e.pageInfo;if(!n||typeof n.hasNextPage!=`boolean`||n.endCursor!==null&&typeof n.endCursor!=`string`)throw new D(`Incomplete non-closing native pagination.`);if(!n.hasNextPage)return null;if(!n.endCursor||t.has(n.endCursor))throw new D(`Non-closing native pagination did not advance.`);return t.add(n.endCursor),n.endCursor}async function WS(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(n.number!==t||`pull_request`in n||n.state!==`open`||typeof n.node_id!=`string`||!n.node_id||typeof n.title!=`string`||typeof n.body!=`string`||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/issues/${t}`.toLowerCase())throw new D(`Non-closing delivery requires the exact canonical OPEN issue and complete title/body.`);return n}function GS(e,t,n=!1){if(n?e.state!==`open`||e.draft||e.merged||t.state!==`closed`||t.draft||!t.merged:e.state!==t.state||e.draft!==t.draft||e.merged!==t.merged)throw new D(`Non-closing PR state/draft/merged readback drifted; reconcile read-only.`);if(e.node_id!==t.node_id||e.head.sha!==t.head.sha||e.head.ref!==t.head.ref||e.base.sha!==t.base.sha||e.base.ref!==t.base.ref||e.body!==t.body||e.title!==t.title||e.user.login.toLowerCase()!==t.user.login.toLowerCase())throw new D(`Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.`)}function KS(e,t){if(e.node_id!==t.node_id||e.title!==t.title||e.body!==t.body)throw new D(`Non-closing issue identity/title/criteria drifted; reconcile read-only.`)}function qS(e){if(e!==void 0&&typeof e!=`boolean`)throw new D(`nonClosing must be a boolean.`);return e===!0}async function JS(e,t){let n=await dC(e.clients.role===`author`?e:{...e,clients:await vh({config:e.config,identity:e.config.roles.author.identity,role:`author`}),reviewerClients:e.clients},t);if(n.rules.visibility!==`complete`||n.approvalEligibility===`insufficient-permission`)throw new D(`Non-closing delivery requires complete native rule visibility and an independent reviewer route.`);return n}async function YS(e,t){let n=null,r=new Set,i=new Map,a;for(let o=0;o<20;o++){let o=await e.clients.graphql(`query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t.number,cursor:n}),s=o.repository?.pullRequest,c=s?.commits;if(o.repository?.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||s?.id!==t.node_id||s.number!==t.number||s.headRefOid!==t.head.sha||s.baseRefOid!==t.base.sha||s.baseRefName!==t.base.ref||!c||!Array.isArray(c.nodes)||c.nodes.length>100||!Number.isSafeInteger(c.totalCount)||c.totalCount<1||c.totalCount>2e3||a!==void 0&&a!==c.totalCount)throw new D(`Incomplete or moved introduced commit graph at the non-closing head/base.`);a=c.totalCount;for(let e of c.nodes){let t=e?.commit;if(!t||!$S(t.oid)||i.has(t.oid)||!t.parents||!Array.isArray(t.parents.nodes)||t.parents.nodes.length>100||!Number.isSafeInteger(t.parents.totalCount)||t.parents.totalCount<1||t.parents.totalCount!==t.parents.nodes.length||t.parents.pageInfo?.hasNextPage!==!1||t.parents.nodes.some(e=>!$S(e?.oid)))throw new D(`Incomplete, duplicate or truncated introduced commit identity/parents.`);zS(t.message),i.set(t.oid,t.message)}if(n=US(c,r),n===null){if(i.size!==a||!i.has(t.head.sha))throw new D(`Introduced commit count/head is incomplete.`);return}}throw new D(`Non-closing commit graph exceeds the bounded readback window.`)}async function XS(e,t,n){let r=new Set,i;for(let a=1;a<=20;a++){let o=(await e.clients.rest.repos.compareCommitsWithBasehead({...e.repo,basehead:`${t}...${n}`,per_page:100,page:a})).data;if(o.base_commit?.sha!==t||!$S(o.merge_base_commit?.sha)||![`ahead`,`diverged`].includes(o.status)||!Number.isSafeInteger(o.total_commits)||o.total_commits<1||o.total_commits>2e3||i!==void 0&&i!==o.total_commits||!Array.isArray(o.commits)||o.commits.length>100)throw new D(`Incomplete introduced commit range before non-closing publication.`);i=o.total_commits;for(let e of o.commits){if(!$S(e.sha)||r.has(e.sha)||!Array.isArray(e.parents)||e.parents.length<1||e.parents.length>100||e.parents.some(e=>!$S(e.sha)))throw new D(`Incomplete or duplicate introduced commit identity.`);zS(e.commit?.message),r.add(e.sha)}if(r.size===i&&r.has(n))return;if(o.commits.length<100)throw new D(`Truncated introduced commit range before publication.`)}throw new D(`Introduced commit range exceeds the bounded readback window.`)}async function ZS(e,t,n){if(typeof n.node_id!=`string`||!n.node_id||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/pull/${n.number}`.toLowerCase())throw new D(`Incomplete non-closing PR node identity.`);HS(e,t,n.body),zS(n.title);let r=await WS(e,t),i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||n.base.ref!==i.default_branch||typeof i.node_id!=`string`||!i.node_id)throw new D(`Non-closing PR must target the canonical default repository/base.`);let a=await JS(e,n.base.ref);if(n.user.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new D(`Non-closing PR author differs from the configured author.`);let o=null,s=new Set,c=new Map,l=!1;for(let u=0;u<20;u++){let d=await e.clients.graphql(`query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:o}),f=d.repository?.issue,p=f?.timelineItems;if(d.repository?.id!==i.node_id||d.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||f?.id!==r.node_id||f.number!==t||f.state!==`OPEN`||!p||!Array.isArray(p.nodes)||p.nodes.length>100)throw new D(`Incomplete or conflicting native non-closing issue identity.`);for(let o of p.nodes){let s=o?.source,u=o?.target;if(!o||!QS(o.id)||!s||!u||![`Issue`,`PullRequest`].includes(s.__typename)||!QS(s.id)||!Number.isSafeInteger(s.number)||s.number<=0||!QS(s.repository?.id)||typeof s.repository.nameWithOwner!=`string`||u.__typename!==`Issue`||u.id!==r.node_id||u.number!==t||u.repository?.id!==i.node_id||u.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||typeof o.isCrossRepository!=`boolean`||typeof o.willCloseTarget!=`boolean`||!QS(o.actor?.login))throw new D(`Incomplete native cross-reference event identity/actor.`);let d=JSON.stringify([s.__typename,s.id,s.number,s.repository.id,s.repository.nameWithOwner.toLowerCase(),u.id,u.number,u.repository.id,u.repository.nameWithOwner.toLowerCase(),o.actor.login.toLowerCase(),o.isCrossRepository,o.willCloseTarget]);if(c.has(o.id)&&c.get(o.id)!==d)throw new D(`Conflicting duplicate native reference event.`);if(c.set(o.id,d),s.id===n.node_id||s.__typename===`PullRequest`&&s.number===n.number&&s.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()){if(s.__typename!==`PullRequest`||s.id!==n.node_id||s.number!==n.number||s.repository.id!==i.node_id||s.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||o.isCrossRepository||o.willCloseTarget!==!1||o.actor.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new D(`Conflicting, closing or unauthorized native PR reference.`);l=!0}}if(o=US(p,s),o===null)break;if(u===19)throw new D(`Native non-closing references exceed the bounded readback window.`)}if(!l)throw new D(`Missing authorized native non-closing PR-to-issue reference.`);if(await nC(e,n.number,t,!0,n.node_id),await YS(e,n),!n.merged){let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${n.base.ref}`})).data;if(t.ref!==`refs/heads/${n.base.ref}`||t.object.type!==`commit`||t.object.sha!==n.base.sha)throw new D(`Non-closing default base has moved or is incomplete.`)}return KS(r,await WS(e,t)),GS(n,await tC(e,n.number)),r}function QS(e){return typeof e==`string`&&e.trim().length>0}function $S(e){return typeof e==`string`&&LS.test(e)}function eC(e){if(typeof e!=`string`||!RS.test(e)||e.startsWith(`/`)||e.endsWith(`/`)||e.endsWith(`.lock`))throw new D(`Invalid GitHub branch name.`)}async function tC(e,t){if(e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Configured and selected GitHub repository identities disagree.`);let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data;if(n.number!==t||typeof n.base.repo?.full_name!=`string`||typeof n.head.repo?.full_name!=`string`||n.base.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||n.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!$S(n.head.sha)||!$S(n.base.sha)||n.state!==`open`&&n.state!==`closed`||typeof n.merged!=`boolean`||typeof n.draft!=`boolean`||n.merged&&n.state!==`closed`)throw new D(`GitHub PR identity or exact head readback is invalid.`);return eC(n.head.ref),eC(n.base.ref),n}async function nC(e,t,n,r=!1,i,a=!1,o,s){let c=null,l=new Set,u=0;for(let d=0;d<20;d++){let d=await e.clients.graphql(`query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:c}),f=d.repository?.pullRequest?.closingIssuesReferences;if(typeof d.repository?.nameWithOwner!=`string`||d.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||d.repository?.pullRequest?.number!==t||i!==void 0&&d.repository?.pullRequest?.id!==i||!f||!Array.isArray(f.nodes)||f.nodes.length>100||typeof f.pageInfo?.hasNextPage!=`boolean`||f.pageInfo.endCursor!==null&&typeof f.pageInfo.endCursor!=`string`)throw new D(`Incomplete or conflicting native GitHub PR issue association readback.`);for(let t of f.nodes){if(a&&(!t||t.__typename!==`Issue`||!QS(o)||t.id!==o||!QS(s)||t.repository?.id!==s))throw new D(`Incomplete or conflicting typed closing issue/repository identity before body transition.`);if(r)throw new D(`Non-closing PR has an unintended native closing association.`);if(!t||!Number.isSafeInteger(t.number)||t.number<=0||typeof t.repository?.nameWithOwner!=`string`||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(t.repository.nameWithOwner))throw new D(`Incomplete native PR closing-issue identity.`);if(t.number===n&&t.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase())u++;else if(a)throw new D(`Existing PR has conflicting closing associations; body transition refused.`)}if(!f.pageInfo.hasNextPage){if(!r&&u!==1)throw new D(`Native GitHub PR closing-issue association does not identify the intended issue.`);return}let p=f.pageInfo.endCursor;if(!p||l.has(p))throw new D(`Native PR issue pagination did not advance.`);l.add(p),c=p}throw new D(`Native PR issue association exceeds the bounded readback window.`)}async function rC(e,t,n){let r=[];for(let i=1;i<=20;i++){let a=(await e.clients.rest.pulls.list({...e.repo,head:`${e.repo.owner}:${t}`,...n===void 0?{}:{base:n},state:`all`,page:i,per_page:100})).data;if(!Array.isArray(a)||a.some(e=>!e||!Number.isSafeInteger(e.number)||e.number<=0))throw new D(`Incomplete GitHub PR match readback.`);if(r.push(...a),a.length<100)return r}throw new D(`GitHub PR match history exceeds the bounded readback window.`)}async function iC(e,t,n,r=!1){let i=await tC(e,n);if(r?await ZS(e,t,i):await nC(e,n,t),!i.merged){let n=await Jv(e,t);if(n.length>0){let e=n.filter(e=>e.name===i.head.ref);if(e.length!==1||e[0].sha!==i.head.sha)throw new D(`Native linked issue branches conflict with the exact PR head/ref.`)}let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.head.ref}`})).data;if(r.ref!==`refs/heads/${i.head.ref}`||r.object.type!==`commit`||r.object.sha!==i.head.sha)throw new D(`Current remote PR head/ref readback is incomplete or has moved.`)}return i}async function aC(e,t){let n=qS(t.nonClosing);if(n&&(t.issueNumber===void 0||t.prNumber===void 0))throw new D(`Non-closing inspection requires explicit canonical issue and PR numbers.`);let r=t.prNumber;if(r===void 0){if(t.issueNumber===void 0)throw new D(`prNumber or issueNumber is required.`);let n=await Jv(e,t.issueNumber);if(n.length!==1)throw new D(`Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.`);let i=n[0].name,a=await rC(e,i);if(a.length!==1)throw new D(`Select an explicit PR number when the remote issue branch has zero or multiple PRs.`);r=a[0].number}let i=t.issueNumber===void 0?await tC(e,r):await iC(e,t.issueNumber,r,n);return{prNumber:i.number,url:i.html_url,state:i.state,draft:i.draft,headSha:i.head.sha,headBranch:i.head.ref,baseBranch:i.base.ref,merged:i.merged}}async function oC(e,t=`open`){return{schemaVersion:`ai-delivery.pr-list@1`,pullRequests:(await e.clients.rest.paginate(e.clients.rest.pulls.list,{...e.repo,state:t,per_page:100})).map(e=>({number:e.number,state:e.state,draft:e.draft??!1,headSha:e.head.sha,baseSha:e.base.sha,url:e.html_url}))}}async function sC(e,t){let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data,[r,i,a]=await Promise.all([e.clients.rest.checks.listForRef({...e.repo,ref:n.head.sha,per_page:100}),e.clients.rest.repos.getCombinedStatusForRef({...e.repo,ref:n.head.sha}),AS(e,t,n.head.sha)]);return{schemaVersion:`ai-delivery.pr-checks@1`,prNumber:n.number,headSha:n.head.sha,combinedStatus:i.data.state,reviewState:a,checkRuns:r.data.check_runs.map(e=>({name:e.name,status:e.status,conclusion:e.conclusion}))}}function cC(e){if(typeof e!=`object`||!e)return null;let t=e.required_approving_review_count;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:null}function lC(e){return e.status===200&&Array.isArray(e.data)&&e.headers!==void 0&&e.headers!==null&&(e.headers.link===void 0||e.headers.link===``)}function uC(e){return lC(e)&&Array.isArray(e.data)&&e.data.length===0}async function dC(e,t,n,r=`publication`,i){if(t===void 0)try{t=(await e.clients.rest.repos.get({...e.repo})).data.default_branch}catch{throw new D(`Author cannot read the selected GitHub repository; verify configured access.`)}let a=async()=>{await i?.checkResources(),i?.signal.throwIfAborted()};await a();let o=e.config.roles.author.authSource??`app`,s=r===`development`&&o===`app`&&e.clients.authSource===`personal`;if(e.clients.authSource!==o&&!s)throw new D(r===`publication`?`PR publication requires the configured author credential; configure the personal author role for personal publication.`:`Development access preflight requires the configured author credential or the explicit personal author override.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new D(`Delivery access preflight requires authenticated author identity readback.`);let c=await e.clients.authenticatedAuthor(i?.signal);if(await a(),!c.actorLogin||!c.credentialIdentity)throw new D(`Author GitHub identity readback is incomplete.`);let l=n??e.reviewerClients??await vh({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients,...i===void 0?{}:{signal:i.signal}});if(await a(),l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new D(`Configured reviewer GitHub App identity is unavailable.`);let u=await l.appActorLogin(i?.signal);if(await a(),!u)throw new D(`Reviewer GitHub App actor lookup is incomplete.`);if(c.actorLogin.toLowerCase()===u.toLowerCase())throw new D(`Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.`);try{let t=(await l.rest.repos.get({...e.repo,...i===void 0?{}:{request:{signal:i.signal}}})).data;if(await a(),t.full_name.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Reviewer GitHub App repository readback disagrees with the selected checkout.`)}catch(e){throw e instanceof D?e:new D(`Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`)}let[d,f]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}/rules/branches/{branch}`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}}),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}/protection`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}})]);await a();let p=!1,m=!1;if(d.status===`fulfilled`&&lC(d.value)&&f.status===`rejected`&&wh(f.reason,e.clients,e.repo,t)){let n={...e.repo,...i===void 0?{}:{request:{signal:i.signal}}},[r,o,s]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}`,n),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}`,{...n,branch:t}),e.clients.rest.request(`GET /repos/{owner}/{repo}/rulesets`,{...n,includes_parents:!0,per_page:100,page:1})]);if(await a(),r.status===`fulfilled`&&o.status===`fulfilled`&&s.status===`fulfilled`){let n=r.value.data,i=o.value.data,a=r.value.status===200&&o.value.status===200&&typeof n?.full_name==`string`&&n.full_name.toLowerCase()===`${e.repo.owner}/${e.repo.repo}`.toLowerCase()&&(n.permissions?.push===!0||n.permissions?.admin===!0)&&i?.name===t;p=a&&uC(d.value)&&i?.protected===!1&&i.protection?.enabled===!1&&uC(s.value),m=a&&i?.protected===!0&&typeof i.protection?.enabled==`boolean`&&lC(s.value)&&d.value.data.length>0&&d.value.data.every(t=>{if(typeof t!=`object`||!t||typeof t.type!=`string`||!t.type||typeof t.ruleset_id!=`number`||!Number.isSafeInteger(t.ruleset_id)||t.ruleset_id<=0||typeof t.ruleset_source!=`string`||(t.ruleset_source_type===`Repository`?t.ruleset_source.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase():t.ruleset_source_type!==`Organization`||t.ruleset_source.toLowerCase()!==e.repo.owner.toLowerCase())||t.type===`pull_request`&&cC(t.parameters)===null)return!1;let n=s.value.data.filter(e=>e?.id===t.ruleset_id);return n.length===1&&n[0]?.source_type===t.ruleset_source_type&&n[0]?.source===t.ruleset_source&&n[0]?.enforcement===`active`})}}let h=[],g=d.status===`fulfilled`&&lC(d.value);if(d.status===`fulfilled`&&Array.isArray(d.value.data)){for(let e of d.value.data)if((typeof e!=`object`||!e||typeof e.type!=`string`||!e.type)&&(g=!1),e?.type===`pull_request`){let t=cC(e.parameters);t===null?g=!1:h.push(t)}}if(f.status===`fulfilled`){let e=f.value.data,t=typeof e==`object`&&e&&!Array.isArray(e)?cC(e.required_pull_request_reviews):null;(f.value.status!==200||t===null)&&(g=!1),t!==null&&h.push(t)}else!p&&!m&&(g=!1);let _=d.status===`fulfilled`&&Array.isArray(d.value.data)&&(d.value.headers?.link===void 0||d.value.headers.link===``),v=Number(_)+Number(f.status===`fulfilled`||p||m),y=v===2?`complete`:v===1?`partial`:`unknown`,b=h.length>0&&(g||h.some(e=>e>0))?Math.max(...h):g&&p?0:null,x=b!==null&&b>0&&l.effectiveContentsPermission===`read`;return{author:{actorLogin:c.actorLogin,authSource:e.clients.authSource,credentialSource:e.clients.credentialSource??`unreported`,identity:s?`personal`:e.config.roles.author.identity},reviewer:{actorLogin:u,credentialSource:l.credentialSource??`unreported`,effectiveContentsPermission:l.effectiveContentsPermission??`unknown`,identity:e.config.roles.reviewer.identity,repositoryAccess:`readable`},rules:{observedRequiredApprovals:b,visibility:y},approvalEligibility:x?`insufficient-permission`:`unknown`,nextAction:x?`The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.`:y===`complete`&&b===null?`No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.`:y===`complete`?`Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.`:`Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.`}}async function fC(e,t){let n=qS(t.nonClosing);if(t.prNumber!==void 0&&(!Number.isSafeInteger(t.prNumber)||t.prNumber<=0))throw new D(`Existing PR selector must be a positive safe integer.`);let r=n?await WS(e,t.issueNumber):(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber||r.state!==`open`)throw new D(`PR creation requires the requested open GitHub issue.`);let i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new D(`Configured and selected GitHub repository identities disagree.`);if(n&&!QS(i.node_id))throw new D(`Incomplete canonical non-closing repository node identity.`);let a=t.baseBranch??i.default_branch;if(a!==i.default_branch)throw new D(`PR delivery requires the repository default branch for durable issue association.`);eC(a),t.headBranch!==void 0&&eC(t.headBranch);let o=t.prNumber===void 0?void 0:await tC(e,t.prNumber),s=t.draft===!1&&t.headBranch!==void 0,c=o?await rC(e,o.head.ref,a):s?await rC(e,t.headBranch,a):void 0,l=o?o.head.ref:s&&c.length>0?t.headBranch:await Yv(e,t.issueNumber,t.headBranch);if(t.headBranch!==void 0&&l!==t.headBranch)throw new D(`Explicit PR and head selectors disagree.`);eC(l);let u=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data;if(u.ref!==`refs/heads/${l}`||u.object.type!==`commit`||!$S(u.object.sha))throw new D(`Remote issue branch head/ref readback is invalid.`);let d=c??await rC(e,l,a);if(d.length>1||o&&(d.length!==1||d[0].number!==o.number))throw new D(`Remote issue branch has conflicting PR matches.`);let f=o??(d[0]===void 0?void 0:await tC(e,d[0].number)),p=t.body??(n?f?.body??BS(e,t.issueNumber):`Closes #${t.issueNumber}`);if(!p.trim())throw new D(`PR body must contain text.`);let m=n?VS(e,t.issueNumber,p):RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${t.issueNumber}(?![0-9])`,`iu`).test(p)?p:`${p}\n\nCloses #${t.issueNumber}`,h=n&&f!==void 0&&f.body!==m;if(h&&(t.prNumber===void 0||t.body===void 0))throw new D(`Non-closing body transition requires an explicit existing PR number and body.`);if(f&&(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a||f.state!==`open`||f.merged||!h&&t.body!==void 0&&f.body!==m||t.title!==void 0&&f.title!==t.title))throw new D(`Existing remote PR conflicts with the requested branch, intent or state.`);let g=n?await JS(e,a):await dC(e,a);if(f&&f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new D(`Existing PR author differs from the configured authenticated author.`);if(f&&(typeof f.node_id!=`string`||!f.node_id))throw new D(`Existing PR publication identity is incomplete.`);n&&zS(t.title??f?.title??r.title);let _=t.title??r.title,v,y=f,b=h,x=f?.body,ee=f?.draft,S=!1,te=async()=>{n&&KS(r,await WS(e,t.issueNumber))},ne=async()=>{let o=await iC(e,t.issueNumber,y.number,n&&!b);if(o.state!==`open`||o.merged||o.node_id!==y.node_id||o.head.sha!==u.object.sha||o.head.ref!==l||o.base.ref!==a||o.base.sha!==y.base.sha||o.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase()||h&&!S&&o.draft!==ee||o.body!==x||o.title!==y.title)throw new D(`Existing PR publication head, identity, intent or author readback drifted.`);if(b){await nC(e,o.number,t.issueNumber,!1,o.node_id,!0,r.node_id,i.node_id),zS(o.title),await YS(e,o);let n=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(n.ref!==`refs/heads/${a}`||n.object.type!==`commit`||n.object.sha!==o.base.sha)throw new D(`Non-closing transition default base drifted.`);GS(o,await tC(e,o.number))}return await te(),o},re=async()=>{let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(t.ref!==`refs/heads/${a}`||t.object.type!==`commit`||!$S(t.object.sha))throw new D(`Incomplete publication default base.`);if(v!==void 0&&v!==t.object.sha)throw new D(`Publication default base drifted before creation.`);v=t.object.sha,n&&await XS(e,t.object.sha,u.object.sha);let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data,i=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(r.ref!==u.ref||r.object.type!==`commit`||r.object.sha!==u.object.sha||i.ref!==t.ref||i.object.type!==`commit`||i.object.sha!==t.object.sha)throw new D(`Non-closing publication head/base drifted.`);await te()};if(f?f=await ne():await re(),t.dryRun)return{dryRun:!0,...f===void 0?{}:{prNumber:f.number,draft:f.draft},...n?{nonClosing:!0,nonClosingVerified:f!==void 0&&!b,body:m,bodyTransition:b}:{},headSha:u.object.sha,headBranch:l,baseBranch:a,reviewRoute:g};let ie=!1;if(f){if(b&&(f=await ne(),await e.clients.rest.pulls.update({...e.repo,pull_number:f.number,body:m}),b=!1,x=m,f=await ne()),t.draft===!1&&f.draft){if(f=await ne(),f.draft){let t=await e.clients.graphql(`mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}`,{id:f.node_id});if(t?.markPullRequestReadyForReview?.pullRequest?.id!==f.node_id||t.markPullRequestReadyForReview.pullRequest.isDraft!==!1)throw new D(`PR promotion mutation readback is incomplete or conflicting; reconcile this PR.`);S=!0}if(f=await ne(),f.draft)throw new D(`PR promotion readback is still draft.`)}}else{await re();let n;try{n=await e.clients.rest.pulls.create({...e.repo,head:l,base:a,title:_,body:m,draft:t.draft!==!1})}catch(e){throw new D(`PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${e instanceof Error?e.message:`Unknown failure`}`)}if(!Number.isSafeInteger(n.data.number)||n.data.number<=0)throw new D(`PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.`);ie=!0;try{f=await tC(e,n.data.number)}catch(e){throw new D(`GitHub returned created PR #${n.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`)}}try{if(ie&&(f.body!==m||f.title!==_||f.draft!==(t.draft!==!1)||f.state!==`open`||f.merged||f.base.sha!==v))throw new D(`Created PR body, title, draft/open state or default base differs from publication intent.`);if(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a)throw new D(`GitHub PR creation readback drifted.`);if(f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new D(`Published PR author differs from the configured authenticated author.`);if(n){let n=await iC(e,t.issueNumber,f.number,!0);GS(f,n),f=n,await te()}else await nC(e,f.number,t.issueNumber);if(ie){let t=await tC(e,f.number);GS(f,t),f=t}}catch(e){throw ie?new D(`GitHub created PR #${f.number} (${f.html_url}) at ${f.head.sha}; post-publication association/identity verification is unresolved. Reconcile this PR read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`):e}return{prNumber:f.number,url:f.html_url,headSha:f.head.sha,draft:f.draft,reviewRoute:g,...n?{nonClosing:!0}:{}}}async function pC(e,t){let n=qS(t.nonClosing),r=await iC(e,t.issueNumber,t.prNumber,n),i=n?await WS(e,t.issueNumber):void 0,a=await IS({context:e,artifact:jS(t.artifact),issueNumber:t.issueNumber,prNumber:t.prNumber,...t.dryRun===void 0?{}:{dryRun:t.dryRun}});return n&&(GS(r,await iC(e,t.issueNumber,t.prNumber,!0)),KS(i,await WS(e,t.issueNumber))),a}async function mC(e,t){let n=[];for(let r=1;r<=20;r++){let i=(await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,page:r,per_page:100})).data;if(n.push(...i),i.length<100)return n}throw new D(`GitHub review history exceeds the bounded readback window.`)}async function hC(e,t){let n=qS(t.nonClosing);if(n&&t.strategy!==void 0&&t.strategy!==`squash`)throw new D(`Non-closing merge requires squash with explicit safe messages.`);if(e.clients.role!==`author`||e.clients.authSource!==(e.config.roles.author.authSource??`app`)||!e.clients.authenticatedAuthor)throw new D(`Merge and finish require the configured authenticated author role.`);let r=await e.clients.authenticatedAuthor();if(!r.actorLogin||!r.credentialIdentity)throw new D(`Author identity readback is incomplete.`);let i=await iC(e,t.issueNumber,t.prNumber,n),a=i,o=n?await WS(e,t.issueNumber):void 0,s=n?{commit_title:i.title,commit_message:`${BS(e,t.issueNumber)}\n\nDelivered by PR #${i.number}.`}:void 0;if(s&&(zS(s.commit_title),zS(s.commit_message)),t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==i.head.sha)throw new D(`Requested reviewed head differs from the GitHub PR.`);if(i.merged&&i.state===`closed`&&$S(i.merge_commit_sha))return{mergeSha:i.merge_commit_sha,headSha:i.head.sha,reused:!0};let c=await dC(e,i.base.ref);if(c.approvalEligibility===`insufficient-permission`)throw new D(`Configured reviewer App is ineligible for the required approval.`);if(i.state!==`open`||i.draft)throw new D(`GitHub PR must be open and ready for merge.`);let l=e.reviewerClients??await vh({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new D(`Independent reviewer App route is unavailable.`);let u=await l.appActorLogin();if(!i.user?.login||u.toLowerCase()===i.user.login.toLowerCase())throw new D(`Reviewer App must differ from the PR author.`);let d=(await mC(e,t.prNumber)).filter(e=>e.user?.login.toLowerCase()===u.toLowerCase()&&e.commit_id===i.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``));if(d.length!==1)throw new D(`GitHub requires one unambiguous exact-head independent App review.`);let f=d[0],p=(await e.clients.rest.pulls.getReview({...e.repo,pull_number:t.prNumber,review_id:f.id})).data;if(p.id!==f.id||p.state!==`APPROVED`||p.commit_id!==i.head.sha||p.user?.login.toLowerCase()!==u.toLowerCase()||p.body!==f.body)throw new D(`Independent GitHub review readback changed or was dismissed.`);let m=MS(p.body);if(m.verdict!==`approve`||m.issueNumber!==t.issueNumber||m.prNumber!==null&&m.prNumber!==t.prNumber||m.authorIdentity!==e.config.roles.author.identity||m.reviewerIdentity!==e.config.roles.reviewer.identity||m.head.sha!==i.head.sha)throw new D(`Independent review artifact binding is stale, foreign or rejected.`);let h=(await e.clients.rest.git.getCommit({...e.repo,commit_sha:i.head.sha})).data;if(h.sha!==m.head.sha||h.tree.sha!==m.head.tree)throw new D(`Independent review tree differs from the remote commit.`);if(m.diffScopeHash!==await PS(e,t.prNumber,i.changed_files))throw new D(`Independent review scope differs from the remote PR diff.`);let g=m.head.sha;if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==g)throw new D(`Requested reviewed head differs from the independent GitHub review.`);let _=await AS(e,t.prNumber,g,{id:f.id,login:u});if(_.submittedReviewAuthorCanPushToRepository!==!0)throw new D(`Specific reviewer App approval is not verifiably qualifying for required review.`);let v=_.status===`unknown`&&_.reviewDecision===null&&c.rules.visibility===`complete`&&c.rules.observedRequiredApprovals===0;if(_.status!==`satisfied`&&!v)throw new D(`GitHub review eligibility is ${_.status}: ${_.nextAction}`);if((await D_({graphql:e.clients.graphql,issueNumber:t.issueNumber,repo:e.repo})).blockers.some(e=>e.state===`OPEN`))throw new D(`GitHub issue has unresolved native blockers.`);if(i=await iC(e,t.issueNumber,t.prNumber,n),n&&(GS(a,i),KS(o,await WS(e,t.issueNumber)),zS(s.commit_title),zS(s.commit_message)),v&&(i.base.ref!==a.base.ref||i.base.sha!==a.base.sha))throw new D(`GitHub base changed; refresh the zero-review requirement observation before merge.`);if(i.head.sha!==g||i.state!==`open`||i.draft||i.mergeable!==!0||i.mergeable_state!==`clean`)throw new D(`GitHub merge eligibility is ${i.mergeable_state??`unknown`}; CLEAN at the reviewed head is required.`);let y=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.base.ref}`})).data.object.sha;if(!$S(y)||y!==i.base.sha)throw new D(`GitHub base moved; refresh clean eligibility and independent review before merge.`);if(t.dryRun)return{dryRun:!0,headSha:g,prNumber:i.number,...s===void 0?{}:{nonClosing:!0,...s}};let b=(await e.clients.rest.pulls.merge({...e.repo,pull_number:t.prNumber,sha:g,merge_method:t.strategy??`squash`,...s})).data;if(!b.merged||!$S(b.sha))throw new D(`GitHub refused the reviewed-head merge.`);let x=await iC(e,t.issueNumber,t.prNumber,n);if(n&&(GS(a,x,!0),KS(o,await WS(e,t.issueNumber))),!x.merged||x.state!==`closed`||x.head.sha!==g||x.merge_commit_sha!==b.sha)throw new D(`GitHub merged PR readback disagrees with the reviewed-head mutation.`);return{mergeSha:b.sha,headSha:g,reused:!1}}async function gC(e,t){if(qS(t.nonClosing))throw new D(`Non-closing delivery cannot finish or close its retained issue.`);let n=await hC(e,t);if(t.dryRun)return n;let r=await iC(e,t.issueNumber,t.prNumber);if(!r.merged||r.state!==`closed`||r.merge_commit_sha!==n.mergeSha)throw new D(`Intended GitHub PR is not verifiably merged; issue remains open.`);let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(i.number!==t.issueNumber||`pull_request`in i)throw new D(`Finish target is not the intended GitHub issue.`);i.state!==`closed`&&await e.clients.rest.issues.update({...e.repo,issue_number:t.issueNumber,state:`closed`,state_reason:`completed`});let a=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(a.number!==t.issueNumber||a.state!==`closed`)throw new D(`GitHub issue closure readback disagrees.`);return{...n,issueClosed:!0}}function _C(e){let t=md(e.root),n=cd(t,`origin`);if(`${n.owner}/${n.repo}`.toLowerCase()!==e.config.repository.toLowerCase()||`${e.repo.owner}/${e.repo.repo}`.toLowerCase()!==e.config.repository.toLowerCase())throw new D(`Investigation repository identity disagrees.`);return t}async function vC(e,t,n){let r=pd(e);for(let e of[w(r,`ai-delivery`),w(r,`ai-delivery`,`writers@1`)]){try{let t=c(e);if(!t.isDirectory()||t.isSymbolicLink())throw new D(`Investigation writer namespace is unsafe.`)}catch(e){if(e.code!==`ENOENT`)throw e}Qv(e)}return pb(e,t,n)}async function yC(e,t,n,r){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(i.number!==t||`pull_request`in i||i.state!==r||new URL(i.html_url).pathname.toLowerCase()!==`/${e.config.repository}/issues/${String(t)}`.toLowerCase())throw new D(`Investigation requires the exact native issue and expected state.`);let a=await Jv(e,t);if(a.length!==1||a[0].name!==`issue/${String(t)}`||a[0].sha!==n)throw new D(`Investigation requires one exact unchanged native linked branch.`);if((await e.clients.rest.pulls.list({...e.repo,state:`all`,head:`${e.repo.owner}:${a[0].name}`,per_page:100})).data.length!==0)throw new D(`Investigation completion cannot substitute for PR delivery.`)}function bC(e){return z({schemaVersion:`ai-delivery.investigation-preparation-acknowledgement@1`,preparation:e,authority:`prospective-registration-before-investigation-no-legacy-adoption`})}function xC(e,t){return z({schemaVersion:`ai-delivery.investigation-removal-authority@1`,preparationId:e.preparationId,repository:e.repository,issueNumber:e.row.issueNumber,head:e.head,worktree:e.row.path,branch:e.row.branch,resultDigest:t,disposition:`remove-only-this-unchanged-investigation-worktree-retain-branch-and-evidence`,operationalClosure:`all-investigation-producers-quiescent-and-excluded-through-completion-and-resume-no-outstanding-holds`})}function SC(e,t,n){return z({schemaVersion:`ai-delivery.investigation-result-acceptance@1`,authority:JSON.parse(xC(e,t)),authorityCommentId:n,verdict:`approved`,independentlyReviewed:`complete-durable-result-exact-source-and-removal-scope`})}async function CC(e,t){if(!Number.isSafeInteger(t.issueNumber)||t.issueNumber<=0||!LS.test(t.expectedHeadSha))throw new D(`Investigation preparation requires a positive issue and expected commit.`);let n=_C(e),r=w(n,`.worktrees`,`issue-${String(t.issueNumber)}`);if(t.investigationWorktree!==r||h(r)!==r)throw new D(`Investigation worktree must be the exact canonical .worktrees/issue-N path.`);if(i(w(n,`.issue-cli`,`issues`,String(t.issueNumber))))throw new D(`Historical issue custody remains preservation-only; investigation cannot adopt it.`);let a=await mS(e),o=Bx(n,t.issueNumber),s=Ox(n,t.issueNumber);if(await yC(e,t.issueNumber,o.head.sha,`open`),o.head.sha!==t.expectedHeadSha)throw new D(`Investigation preparation source drifted from the expected head.`);if(s===void 0){let t=(await e.clients.rest.repos.get({...e.repo})).data;if(t.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!t.default_branch)throw new D(`Investigation native repository identity is incomplete.`);if((await e.clients.rest.git.getRef({...e.repo,ref:`heads/${t.default_branch}`})).data.object.sha!==o.head.sha)throw new D(`Prospective investigation must begin at the current native default commit.`)}let c=new Date().toISOString(),l={schemaVersion:`ai-delivery.investigation-preparation@1`,repository:e.config.repository,repoRoot:n,row:s?.row??{branch:`issue/${String(t.issueNumber)}`,createdAt:c,identity:e.config.roles.author.identity,issueNumber:t.issueNumber,path:r,status:`active`,type:`issue`,updatedAt:c},...o,operator:{actorLogin:a.operator.actorLogin,credentialIdentity:a.operator.credentialIdentity},reviewerActor:a.reviewerActor},u=Sx.parse({...l,preparationId:B(l)});return await vC(n,r,()=>Nx(u,async()=>{if(z(Bx(n,t.issueNumber))!==z(o))throw new D(`Investigation source changed before preparation acknowledgement.`);await yC(e,t.issueNumber,o.head.sha,`open`);let{commentId:r,url:i,body:a}=await Ov(e,{issueNumber:t.issueNumber,body:bC(u)});if(z(Bx(n,t.issueNumber))!==z(o))throw new D(`Investigation source changed during preparation acknowledgement.`);return{commentId:r,url:i,body:a}})),{preparation:u,acknowledgement:kx(n,t.issueNumber),registered:!0}}async function wC(e,t){if([`prNumber`,`strategy`,`reviewedHeadSha`,`nonClosing`].some(e=>e in t))throw new D(`Investigation completion refuses PR or merge options.`);let n=_C(e),r=Ox(n,t.issueNumber);if(!r)throw new D(`No prospective investigation preparation; historical custody cannot be reconstructed.`);let i=T(t.resultPath),a=se(r.row.path,i),o=a===`..`||a.startsWith(`..${ce}`)||oe(a);if(h(i)!==i||!o)throw new D(`Durable investigation result must be canonical and outside the removable worktree.`);let s=H(i,{maxBytes:524288});if(s.length===0)throw new D(`Investigation result must contain durable evidence.`);let c=V(s),l=xC(r,c),u=t.authorityCommentId===void 0?void 0:SC(r,c,t.authorityCommentId),d=async()=>{await yC(e,t.issueNumber,r.head.sha,`closed`);let i=await Hv(e,t.issueNumber);if(i.state!==`closed`||i.closeReason!==`completed`||i.duplicateOf!==null)throw new D(`Investigation requires native completed closed-issue authority.`);let a=kx(n,t.issueNumber),o=(await e.clients.rest.issues.getComment({...e.repo,comment_id:a.commentId})).data;if(o.id!==a.commentId||o.body!==bC(r)||o.body!==a.body||o.issue_url.toLowerCase()!==`https://api.github.com/repos/${r.repository}/issues/${String(t.issueNumber)}`.toLowerCase()||o.user?.type!==`User`||o.user.login.toLowerCase()!==r.operator.actorLogin.toLowerCase()||`user:${String(o.user.id)}`!==r.operator.credentialIdentity)throw new D(`Native prospective preparation acknowledgement changed.`);if(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0||u===void 0)throw new D(`Existing authentic operator and independent App acceptance comments are required.`);let s=await yS(e,{repository:r.repository,subject:t.issueNumber,operator:r.operator,reviewerActor:r.reviewerActor,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,operatorBody:l,reviewerBody:u,revokedBody:z({schemaVersion:`ai-delivery.investigation-removal-revocation@1`,preparationId:r.preparationId,resultDigest:c,authorityCommentId:t.authorityCommentId})}),d=Date.parse(o.created_at);for(let e of[s.relinquishment,s.acceptance]){let t=Date.parse(e.created_at);if(!Number.isFinite(d)||!Number.isFinite(t)||t<d)throw new D(`Investigation acceptance must follow its prospective preparation.`)}return{acknowledgement:o,closure:i,...s}};if(t.dryRun&&(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0))return Vx(r,e.root),await yC(e,t.issueNumber,r.head.sha,`closed`),{completed:!1,ready:!1,preparationId:r.preparationId,resultDigest:c,authorityBody:l,...u===void 0?{}:{acceptanceBody:u},missingEvidence:`Existing authentic operator and configured-App exact-result acceptance are prerequisites; no submission route is supplied.`};if(!Number.isSafeInteger(t.authorityCommentId)||!Number.isSafeInteger(t.acceptanceCommentId)||t.authorityCommentId<=0||t.acceptanceCommentId<=0)throw new D(`Investigation evidence requires positive native comment IDs.`);return vC(n,r.row.path,()=>Px({preparation:r,result:s,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,dryRun:t.dryRun===!0,authorize:d,assertSource:t=>Vx(r,e.root,t),removeSource:()=>Hx(r,e.root)}))}var TC=A().regex(/^sha256:[a-f0-9]{64}$/u),EC=F({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2)}),DC=F({archivePath:A().min(1),archiveSha256:TC,configDigest:TC,packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),repoRoot:A().min(1),repository:A().min(1),reviewRouteDigest:TC,runtimeDirectory:A().min(1),nativePluginRoot:A().min(1).optional(),sourceCommit:A().regex(/^[a-f0-9]{40}$/u),resourceBounds:EC.optional()}),OC=F({schemaVersion:L(`ai-delivery.runtime-stage@1`),stageId:TC,intent:DC,directory:F({device:j().int(),inode:j().int()}),admission:oy.optional(),status:I([`incomplete`,`complete`]),recordId:TC}).superRefine((e,t)=>{let{recordId:n,...r}=e;(n!==B(r)||e.stageId!==B(e.intent)||e.status===`complete`!=(e.admission!==void 0)||e.admission!==void 0&&(e.admission.sourceCommit!==e.intent.sourceCommit||e.admission.sourceArchiveSha256!==e.intent.archiveSha256||e.admission.packageVersion!==e.intent.packageVersion||e.admission.configDigest!==e.intent.configDigest||e.admission.repository!==e.intent.repository||e.admission.cliPath!==AC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).cliPath||e.admission.mcpLauncherPath!==AC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).mcpLauncherPath||e.admission.pluginManifestPath!==AC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).pluginManifestPath))&&t.addIssue({code:`custom`,message:`Runtime stage identity or completion is corrupt.`})});function kC(e){if(!oe(e)||T(e)!==e)throw new D(`Runtime setup paths must be absolute and canonical.`);let t=e.split(ce).filter(Boolean),n=ce;for(let e of t){n=w(n,e);try{if(c(n).isSymbolicLink())throw new D(`Runtime setup path contains a symbolic link.`)}catch(e){if(e.code!==`ENOENT`)throw e}}return e}function AC(e,t){let n=w(e,`node_modules`,`@aviaratech`,`ai-delivery`),r=t??w(n,`plugins`,`ai-delivery`);return{cliPath:t?w(r,`runtime`,`dist`,`cli.js`):w(n,`dist`,`cli.js`),mcpLauncherPath:w(r,`dist`,`mcp-launcher.js`),pluginManifestPath:w(r,`.claude-plugin`,`plugin.json`)}}function jC(e,t){if(t!==void 0&&(kC(t),t===e||t.startsWith(`${e}${ce}`)||e.startsWith(`${t}${ce}`)))throw new D(`Native plugin cache and owned runtime stage paths must not overlap.`)}function MC(e){if(e.nativePluginRoot===void 0)return;jC(e.runtimeDirectory,e.nativePluginRoot);let t=kC(w(e.runtimeDirectory,`node_modules/@aviaratech/ai-delivery/plugins/ai-delivery`)),n=0,r=(e,t,i)=>{if(i>16||++n>4096)throw new D(`Native plugin inventory exceeds the reviewed layout bound.`);let a=c(e),o=c(t);if(a.isDirectory()&&o.isDirectory()){let n=p(e).sort();if(JSON.stringify(n)!==JSON.stringify(p(t).sort()))throw new D(`Selected native plugin inventory disagrees with reviewed archive bytes.`);for(let a of n)r(w(e,a),w(t,a),i+1)}else if(!a.isFile()||!o.isFile()||a.nlink!==1||o.nlink!==1||a.size!==o.size||!d(e).equals(d(t)))throw new D(`Selected native plugin files disagree with reviewed archive bytes.`)};try{r(t,e.nativePluginRoot,0)}catch(e){throw e instanceof D?e:new D(`Selected native plugin cannot be matched to reviewed archive bytes.`)}}function NC(e,t){kC(e),TC.parse(t);let n=c(e);if(!n.isFile()||n.nlink!==1)throw new D(`Reviewed runtime archive bytes do not match the expected digest.`);let r=d(e);if(V(r)!==t)throw new D(`Reviewed runtime archive bytes do not match the expected digest.`);return r}function PC(e){let t=kC(w(e.runtimeDirectory,`reviewed-archive.tgz`));if(V(H(t))!==e.archiveSha256)throw new D(`Runtime stage archive snapshot bytes changed.`);return t}function FC(e){let t=t=>{let i=kC(w(e.runtimeDirectory,t)),s=u(i,r.O_RDONLY|r.O_NOFOLLOW|r.O_NONBLOCK);try{let e=a(s);if(!e.isFile()||e.nlink!==1||e.size>8*1024**2)throw Error(`Invalid dependency metadata file.`);let t=Buffer.alloc(e.size),n=0;for(;n<t.length;){let e=f(s,t,n,t.length-n,n);if(!e)throw Error(`Dependency metadata was truncated.`);n+=e}o(s);let r=a(s),l=c(i);for(let t of[`dev`,`ino`,`size`,`mode`,`nlink`,`uid`,`mtimeMs`,`ctimeMs`])if(e[t]!==r[t]||e[t]!==l[t])throw Error(`Dependency metadata identity changed.`);return JSON.parse(t.toString(`utf8`))}finally{n(s)}};try{let n=F({dependencies:F({"@aviaratech/ai-delivery":L(`file:reviewed-archive.tgz`)})});n.parse(t(`package.json`));let r=P({lockfileVersion:L(3),packages:Ql(A(),Ll())}).parse(t(`package-lock.json`));n.parse(r.packages[``]);let i=`sha512-${pe(`sha512`).update(H(PC(e))).digest(`base64`)}`;P({version:L(e.packageVersion),resolved:L(`file:reviewed-archive.tgz`),integrity:L(i)}).parse(r.packages[`node_modules/@aviaratech/ai-delivery`]),zC(e.runtimeDirectory)}catch{throw new D(`Runtime stage dependency metadata is missing, incompatible or corrupt.`)}}async function IC(e,t,n,r){if(await n?.(),typeof e.identity!=`string`||!e.identity.trim())throw new D(`Runtime setup requires an explicit configured author identity.`);let i=fd(e.repoRoot);if(i!==md(i))throw new D(`Runtime setup requires the primary consumer controller checkout.`);if(gd(i),hd(i).sha!==e.expectedSourceCommit)throw new D(`Primary controller source commit changed.`);kC(e.runtimeDirectory);let a=await Av({identity:e.identity,repoRoot:i,role:`author`,...r===void 0?{}:{signal:r},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});await n?.();let o=Zh({commandName:t,deliveryConfig:a.config,identity:e.identity,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(o.error)throw new D(o.error);if(!a.configuration||a.configuration.configDigest!==e.expectedConfigDigest)throw new D(`Primary controller resolver config digest changed.`);let s=await dC(a,void 0,void 0,`publication`,n===void 0||r===void 0?void 0:{signal:r,checkResources:n});if(await n?.(),gd(i),hd(i).sha!==e.expectedSourceCommit)throw new D(`Primary controller source commit changed during preflight.`);return{root:i,configuration:a.configuration,reviewRoute:s}}function LC(e){kC(e);let t=c(e);if(!t.isDirectory()||(t.mode&511)!=448)throw new D(`Runtime stage directory must be private and owned.`);let n;try{n=OC.parse(JSON.parse(H(w(e,`runtime-stage.json`)).toString(`utf8`)))}catch{throw new D(`Runtime stage is unowned, incompatible or corrupt.`)}if(n.intent.runtimeDirectory!==e||t.dev!==n.directory.device||t.ino!==n.directory.inode)throw new D(`Runtime stage directory ownership changed.`);return n.status===`complete`&&(PC(n.intent),MC(n.intent),FC(n.intent)),n}function RC(e,t){let n=OC.parse({...t,recordId:B(t)});ey(w(e,`runtime-stage.json`),n);let r=LC(e);if(r.recordId!==n.recordId)throw new D(`Runtime stage completion readback changed.`);return r}function zC(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function BC(e){let t=H(e),r=u(e,`r`);try{o(r)}finally{n(r)}if(zC(C(e)),!H(e).equals(t))throw new D(`Runtime admission third-party replacement conflict.`)}function VC(e,t,n){if(!e.admission)throw new D(`Runtime stage completion is missing.`);return{stageId:e.stageId,admission:e.admission,reused:n,reviewRoute:t,launch:{cli:{command:process.execPath,args:[e.admission.cliPath]},mcp:{command:process.execPath,args:[e.admission.mcpLauncherPath]}}}}function HC(e,t,n){if(e.intent.repoRoot!==t.root||e.intent.repository!==t.configuration.config.repository||e.intent.sourceCommit!==n.expectedSourceCommit||e.intent.configDigest!==n.expectedConfigDigest)throw new D(`Runtime stage primary controller source or configuration changed.`);if(e.intent.reviewRouteDigest!==B(t.reviewRoute))throw new D(`Runtime stage configured actors or review route changed.`)}async function UC(e){if(e.authority!==`runtime:stage`)throw new D(`Explicit runtime:stage authority is required.`);let t=EC.parse({maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2,maxCapturedOutputBytes:1024**2,...e.resourceBounds});return kC(e.runtimeDirectory),jC(e.runtimeDirectory,e.nativePluginRoot),zb(e.repoRoot,async n=>{let r=await IC(e,`runtime:stage`,n.checkResources,n.signal);NC(e.archivePath,e.expectedArchiveSha256);let a=DC.parse({archivePath:e.archivePath,archiveSha256:e.expectedArchiveSha256,configDigest:e.expectedConfigDigest,sourceCommit:e.expectedSourceCommit,packageVersion:e.packageVersion,repoRoot:r.root,repository:r.configuration.config.repository,reviewRouteDigest:B(r.reviewRoute),runtimeDirectory:e.runtimeDirectory,resourceBounds:t,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot}}),o=B(a);if(n.bindCapturedOutput(o),i(e.runtimeDirectory)){let t=LC(e.runtimeDirectory);if(t.stageId!==o)throw new D(`Runtime stage belongs to an incompatible setup intent.`);if(t.status===`complete`){let r=await IC(e,`runtime:stage`,n.checkResources,n.signal);return HC(t,r,e),NC(a.archivePath,a.archiveSha256),BC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),PC(a),dy(t.admission,r.configuration,t.admission.cliPath),BC(w(e.runtimeDirectory,`runtime-stage.json`)),zC(C(e.runtimeDirectory)),await n.checkResources(),FC(a),VC(t,r.reviewRoute,!0)}n.assertQuiescent(),_(e.runtimeDirectory,{recursive:!0})}Qv(C(e.runtimeDirectory)),l(e.runtimeDirectory,{mode:448});let s=c(e.runtimeDirectory),u={schemaVersion:`ai-delivery.runtime-stage@1`,stageId:o,intent:a,directory:{device:s.dev,inode:s.ino},status:`incomplete`},d=!1;try{if(zC(C(e.runtimeDirectory)),RC(e.runtimeDirectory,u),d=!0,e.signal?.aborted)throw new D(`Runtime stage cancelled.`);let r=NC(e.archivePath,e.expectedArchiveSha256);if(!Number.isSafeInteger(t.maxNewOutputBytes)||r.length>=t.maxNewOutputBytes)throw new D(`Reviewed archive snapshot exceeds the stage output limit.`);wd(w(e.runtimeDirectory,`reviewed-archive.tgz`),r);let i=PC(a),o=w(e.runtimeDirectory,`.npm`),s=w(o,`cache`),c=w(o,`logs`),l=w(o,`tmp`);for(let e of[s,c,l])Qv(e);let f=w(o,`user.npmrc`),p=w(o,`global.npmrc`);wd(f,Buffer.alloc(0)),wd(p,Buffer.alloc(0)),await n.checkResources(),await n.run([`npm`,`install`,`--prefix`,e.runtimeDirectory,`--omit=dev`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--package-lock=true`,`--cache`,s,`--logs-dir`,c,`--logs-max`,`0`,`--userconfig`,f,`--globalconfig`,p,i],{...t,maxNewOutputBytes:t.maxNewOutputBytes-r.length,outputRoots:[e.runtimeDirectory]},e.signal,{...process.env,TMPDIR:l,TMP:l,TEMP:l},e.runtimeDirectory);let m=await IC(e,`runtime:stage`,n.checkResources,n.signal);HC({...u,recordId:B(u)},m,e),NC(e.archivePath,e.expectedArchiveSha256),PC(a),MC(a),FC(a);let h=fy({...AC(e.runtimeDirectory,e.nativePluginRoot),packageVersion:e.packageVersion,sourceArchiveSha256:e.expectedArchiveSha256,sourceCommit:e.expectedSourceCommit,configuration:m.configuration});if(MC(a),e.signal?.aborted)throw new D(`Runtime stage cancelled.`);n.assertQuiescent(),dy(h,m.configuration,h.cliPath),await n.checkResources();let g=RC(e.runtimeDirectory,{...u,status:`complete`,admission:h});return dy(g.admission,m.configuration,g.admission.cliPath),VC(g,m.reviewRoute,!1)}catch(t){if(d){n.assertQuiescent();let t=LC(e.runtimeDirectory);if(t.stageId!==o)throw new D(`Runtime stage cleanup ownership changed.`);if(t.status===`incomplete`)_(e.runtimeDirectory,{recursive:!0});else{let r=await IC(e,`runtime:stage`,n.checkResources,n.signal);return HC(t,r,e),NC(a.archivePath,a.archiveSha256),BC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),PC(a),dy(t.admission,r.configuration,t.admission.cliPath),BC(w(e.runtimeDirectory,`runtime-stage.json`)),zC(C(e.runtimeDirectory)),FC(a),VC(t,r.reviewRoute,!0)}}else{n.assertQuiescent();let t=c(e.runtimeDirectory);if(t.dev!==s.dev||t.ino!==s.ino||t.isSymbolicLink())throw new D(`Runtime stage cleanup ownership changed.`);_(e.runtimeDirectory,{recursive:!0})}throw t}},{bounds:{...t,outputRoots:[e.runtimeDirectory]},maxCapturedOutputBytes:t.maxCapturedOutputBytes,...e.signal===void 0?{}:{signal:e.signal}})}var WC=class extends D{admissionId;stageId;status=`commit-status-unknown`;constructor(e,t){super(`Runtime admission commit-status-unknown for ${e}; retry runtime:admit with the same stage ${t} to reconcile durability.`),this.admissionId=e,this.stageId=t}};async function GC(e){if(e.authority!==`runtime:admit`)throw new D(`Explicit runtime:admit authority is required.`);TC.parse(e.stageId),e.expectedPriorAdmissionSha256!==null&&TC.parse(e.expectedPriorAdmissionSha256);let t=await IC(e,`runtime:admit`),n=w(pd(t.root),`ai-delivery`,`runtime-admission.json`);return kC(n),Qv(C(n)),Oy(n,{projectRoot:t.root,timeout:200,operation:async()=>{let t=LC(e.runtimeDirectory);if(t.stageId!==e.stageId||t.status!==`complete`||!t.admission)throw new D(`Exact completed runtime stage identity is required.`);let r=await IC(e,`runtime:admit`);HC(t,r,e),NC(t.intent.archivePath,t.intent.archiveSha256),PC(t.intent),FC(t.intent),dy(t.admission,r.configuration,t.admission.cliPath);let a=Buffer.from(`${JSON.stringify(t.admission,null,2)}\n`);kC(n);let o=i(n)?H(n):void 0,s=()=>{if(kC(n),PC(t.intent),FC(t.intent),dy(t.admission,r.configuration,t.admission.cliPath),!i(n)||!H(n).equals(a))throw new D(`Runtime admission third-party replacement conflict; current bytes preserved.`);try{BC(n)}catch{throw!i(n)||!H(n).equals(a)?new D(`Runtime admission third-party replacement conflict; current bytes preserved.`):new WC(t.admission.admissionId,t.stageId)}return{admission:t.admission,reused:!0}};if(o?.equals(a))return s();if((o===void 0?null:V(o))!==e.expectedPriorAdmissionSha256)throw new D(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);let c=await IC(e,`runtime:admit`);HC(t,c,e),NC(t.intent.archivePath,t.intent.archiveSha256),PC(t.intent),FC(t.intent),dy(t.admission,c.configuration,t.admission.cliPath),kC(n);let l=i(n)?H(n):void 0;if((l===void 0?null:V(l))!==e.expectedPriorAdmissionSha256)throw new D(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);try{ey(n,t.admission)}catch(t){let r=i(n)?H(n):void 0;if(r?.equals(a))return s();throw(r===void 0?null:V(r))===e.expectedPriorAdmissionSha256?t:new D(`Runtime admission third-party replacement conflict; current bytes preserved.`)}return s(),{admission:t.admission,reused:!1}}})}var U=j().int().positive(),KC=N(A().trim().min(1)),qC=`GitHub owner/name. Pass the repository named by the user. An explicit repo avoids launch-directory Git for ordinary remote issue/PR work; retained local modes keep their own checkout requirements.`,JC=A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional().describe(qC),YC={blockedBy:N(U).optional(),blocks:N(U).optional(),overrideReason:z_.optional(),body:A().optional(),issueType:A().min(1).optional(),labels:KC.optional(),milestone:U.optional(),parentIssueNumber:U.optional(),points:U.optional(),priority:A().min(1).optional(),repo:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional().describe(qC),title:A().trim().min(1).max(256)},XC=F({repo:JC,issueNumber:U,investigationWorktree:A().min(1),expectedHeadSha:A().regex(/^[a-f0-9]{40}$/u)}),ZC=F({...YC,title:YC.title.optional(),issueNumber:U.optional(),request:A().min(1).optional(),requestId:A().trim().min(1).max(256).optional(),resumeCreated:M().optional(),branch:A().min(1).optional()}),QC=F({repo:JC,issueNumber:U,prNumber:U,nonClosing:M().optional(),reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:I([`merge`,`squash`,`rebase`]).optional(),dryRun:M().optional()}),$C=F({repo:JC,issueNumber:U,investigation:L(!0),resultPath:A().min(1),authorityCommentId:U.optional(),acceptanceCommentId:U.optional(),dryRun:M().optional()});function ew(e,t,n){let r=e.safeParse(t);r.success||n.addIssue({code:`custom`,message:r.error.message})}var tw={repo:JC,state:I([`open`,`closed`,`all`]).optional(),labels:N(A().min(1).regex(/^[^"\\\r\n]+$/u)).optional(),parentIssueNumber:U.nullable().optional(),issueType:A().min(1).optional(),projectStatus:I([`Todo`,`In Progress`,`Blocked`,`Done`]).nullable().optional(),updatedSince:Du({offset:!0}).optional(),page:U.optional(),perPage:U.max(100).optional()},nw=A().trim().min(1).max(256).regex(/^[^"\\\r\n]+$/u),rw={repo:JC,identity:A().min(1).optional(),expectedSourceCommit:A().regex(/^[a-f0-9]{40}$/u),expectedConfigDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),runtimeDirectory:A().min(1)},iw=[{name:`delivery_health`,commandName:`health`,description:`Read bounded native delivery health for an explicit repository and UTC window`,inputSchema:$u},{name:`issue_comment`,commandName:`comment`,description:`Post a typed issue journal with authoritative comment readback`,inputSchema:F({...wv.shape,repo:JC}).superRefine(({repo:e,...t},n)=>{let r=wv.safeParse(t);if(!r.success)for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message})})},{name:`runtime_stage`,commandName:`runtime:stage`,description:`Explicitly stage a reviewed local public archive without host activation or admission`,inputSchema:F({...rw,authority:L(`runtime:stage`),archivePath:A().min(1),expectedArchiveSha256:A().regex(/^sha256:[a-f0-9]{64}$/u),packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),nativePluginRoot:A().min(1).optional(),resourceBounds:F({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2).optional()}).optional()})},{name:`runtime_admit`,commandName:`runtime:admit`,description:`Explicitly admit an exact completed stage with prior-byte compare-and-swap and reconciliation`,inputSchema:F({...rw,authority:L(`runtime:admit`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),expectedPriorAdmissionSha256:A().regex(/^sha256:[a-f0-9]{64}$/u).nullable()})},{name:`issue_create`,commandName:`create`,description:`Create a native GitHub tracking issue with configured metadata and relationships`,issueContract:iv,inputSchema:sv(F({...YC,...av,title:X_.shape.title}))},{name:`issue_start`,commandName:`start`,description:`Start a linked issue, or prospectively register an unchanged host-created investigation worktree`,inputSchema:ZC.extend({investigationWorktree:A().optional(),expectedHeadSha:A().optional()}).superRefine((e,t)=>ew(e.investigationWorktree!==void 0||e.expectedHeadSha!==void 0?XC:ZC,e,t))},{name:`issue_list`,commandName:`list`,description:`List repository issues with native filters, named organization fields and pagination`,inputSchema:F({...tw,query:nw.optional()})},{name:`issue_search`,commandName:`search`,description:`Search literal issue text in the selected repository with native filters and pagination`,inputSchema:F({...tw,query:nw})},{name:`issue_update`,commandName:`update`,description:`Update native issue fields and exact relationship sets with readback`,inputSchema:sv(F({...av,repo:JC,blockedBy:N(U).optional(),blocks:N(U).optional(),overrideReason:z_.optional(),body:A().optional(),issueNumber:U,issueType:av.issueType,labels:KC.optional(),milestone:U.nullable().optional(),parentIssueNumber:U.nullable().optional(),park:L(!0).optional(),points:av.points,priority:A().min(1).optional(),state:I([`open`,`closed`]).optional(),preserveHistory:M().optional(),closeReason:I([`completed`,`not_planned`,`duplicate`]).optional(),supersededBy:U.optional(),title:av.title}).superRefine((e,t)=>{(e.closeReason!==void 0||e.supersededBy!==void 0)&&e.state!==`closed`&&t.addIssue({code:`custom`,path:[`state`],message:`Closure details require state closed`,params:{issueCode:`closure.state`}})}))},{name:`issue_info`,commandName:`info`,description:`Read live GitHub issue metadata, relationships and Project status. Pass the requested owner/name as repo; an explicit repo works outside Git without a checkout. This read does not start or update the issue.`,inputSchema:F({issueNumber:U,repo:JC})},{name:`issue_ready_check`,commandName:`ready:check`,description:`Evaluate deterministic readiness from live native issue state`,inputSchema:F({issueNumber:U,repo:YC.repo})},{name:`issue_pr_create`,commandName:`pr:create`,description:`Create or reuse a PR from its GitHub-linked issue branch`,inputSchema:F({repo:JC,issueNumber:U,prNumber:U.optional(),nonClosing:M().optional(),body:A().min(1).optional(),draft:M().optional(),dryRun:M().optional(),title:A().min(1).optional(),headBranch:A().min(1).optional()})},{name:`issue_pr_info`,commandName:`pr:info`,description:`Inspect a PR by number or its GitHub-linked issue branch`,inputSchema:F({repo:JC,issueNumber:U.optional(),prNumber:U.optional(),nonClosing:M().optional()})},{name:`issue_pr_review`,commandName:`pr:review`,description:`Submit one existing exact-head independent review with the reviewer App role`,inputSchema:F({repo:JC,issueNumber:U,prNumber:U,nonClosing:M().optional(),artifact:A().min(1),identity:A().min(1).optional(),dryRun:M().optional()})},{name:`issue_pr_merge`,commandName:`pr:merge`,description:`Guarded exact-head merge with live blocker, check and review readback`,inputSchema:F({repo:JC,issueNumber:U,prNumber:U,nonClosing:M().optional(),reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:I([`merge`,`squash`,`rebase`]).optional(),dryRun:M().optional()})},{name:`issue_finish`,commandName:`finish`,description:`Finish merged delivery, or remove a prospectively registered unchanged investigation with native acceptance`,inputSchema:QC.extend({prNumber:U.optional(),investigation:L(!0).optional(),resultPath:A().optional(),authorityCommentId:U.optional(),acceptanceCommentId:U.optional()}).superRefine((e,t)=>ew(e.investigation===!0?$C:QC,e,t))},{name:`issue_worktree_transition_inspect`,commandName:`worktree:transition:inspect`,description:`Read a legacy issue row, original evidence and exact closure gaps without changing ownership`,inputSchema:F({repo:JC,issueNumber:U,purpose:I([`active-resume`,`merged-cleanup`]),disposition:I([`retain`,`remove`]).optional(),terminalPrNumber:U.optional(),retainedHoldCommentIds:N(U).optional(),retainedAdmissionPath:A().min(1).optional(),retainedArchivePath:A().min(1).optional()})},{name:`issue_worktree_transition_apply`,commandName:`worktree:transition:apply`,description:`Apply or resume one exact independently accepted transition with immutable preservation and closure proof`,inputSchema:F({repo:JC,authority:L(`worktree:transition`),planPath:A().min(1),expectedPlanId:A().regex(/^sha256:[a-f0-9]{64}$/u),relinquishmentCommentId:U,acceptanceCommentId:U})}];function aw(e){return iw.find(t=>t.name===e)??null}function ow(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw new D(`${t} must be positive.`);return n}function sw(e,t){return typeof e[t]==`string`?e[t]:void 0}function cw(e,t){let n=sw(e,t);if(!n?.trim())throw new D(`${t} is required.`);return n}function lw(e){let{issueNumber:t,request:n,requestId:r,repo:i,resumeCreated:a,branch:o,...s}=e;return{...s,issueNumber:ow({issueNumber:t},`issueNumber`)}}async function uw(e,t,n=`author`){let r=await Kh(),i=e.identity??r.roles[n].identity,a=Zh({commandName:t,deliveryConfig:r,identity:i,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(a.error)throw new D(a.error);return Av({identity:i,repoRoot:e.repoRoot,role:n,...e.repo===void 0?{}:{repository:e.repo},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}})}async function dw(e,t){let n=t.issueNumber===void 0?void 0:ow(t,`issueNumber`),r,i,a,o=!1,s=`branch-or-journal`,c=(o,s)=>({status:`created-not-started`,repository:e.config.repository,createdIssue:r,failure:{phase:o,message:s instanceof Error?s.message:String(s)},safeResume:{tool:`issue_start`,arguments:{...o===`tracking`?{...t,...i===void 0?{}:{body:i},resumeCreated:!0}:{},repo:e.config.repository,issueNumber:n,...(a?.branch??sw(t,`branch`))===void 0?{}:{branch:a?.branch??sw(t,`branch`)}}}});if(n===void 0){let a=sw(t,`title`)??cw(t,`request`),o={...t,title:a,body:sw(t,`body`)??sw(t,`request`)??a};o.body=Nv(o);let s=B(Object.fromEntries(Object.entries({title:a,body:o.body,issueType:o.issueType,points:o.points,priority:o.priority,labels:o.labels,blockedBy:o.blockedBy,blocks:o.blocks,overrideReason:o.overrideReason,parentIssueNumber:o.parentIssueNumber,milestone:o.milestone,branch:t.branch}).filter(([,e])=>e!==void 0))),l=sw(t,`requestId`)??s,u=`<!-- ai-delivery-start: ${B({repository:e.config.repository.toLowerCase(),requestKey:l})} -->`;o.body=`${o.body}\n\n<!-- ai-delivery-start-intent: ${s} -->\n${u}`,i=o.body;let d=!1,f=[];for(let t=1;t<=20;t++){let n=(await e.clients.rest.issues.listForRepo({...e.repo,state:`all`,page:t,per_page:100})).data;if(f.push(...n.filter(e=>!(`pull_request`in e)&&e.body?.includes(u))),n.length<100){d=!0;break}}if(!d)throw new D(`Issue-start retry search exceeds the bounded readback window; select a known issue number.`);if(f.length>1)throw new D(`Conflicting issues claim the same start request.`);let p=f[0];if(p&&(p.title!==a||p.body!==o.body||p.state!==`open`))throw new D(`Prior issue-start request conflicts with the requested intent or state.`);try{p?(r={number:p.number,title:p.title,url:p.html_url},n=p.number,await Wv(e,{...o,issueNumber:n})):(r=(await Fv(e,o)).created,n=r.number)}catch(e){if(e instanceof Pv)r=e.created,n=r.number;else if(!r)throw e;return c(`tracking`,e)}}else if(t.resumeCreated===!0){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:n})).data;if(i.number!==n||`pull_request`in i)throw new D(`Known-created issue readback disagrees.`);r={number:n,title:i.title,url:i.html_url};try{await Wv(e,lw(t))}catch(e){return c(`tracking`,e)}}try{let r=await qv(e,n);if(!r.ready)throw new uv(r.failures);return o=!0,a=await Xv(e,n,sw(t,`branch`)),s=`project-status`,await Zv(e,n),s=`journal`,await kv(e,n),{issueNumber:n,repository:e.config.repository,branch:a.branch,headSha:a.headSha,reused:a.reused}}catch(i){if(r)return c(s,i);if(!o)throw i;return{status:`start-incomplete`,issueNumber:n,repository:e.config.repository,failure:{phase:s,message:i instanceof Error?i.message:String(i)},safeResume:{tool:`issue_start`,arguments:{repo:e.config.repository,issueNumber:n,...(a?.branch??sw(t,`branch`))===void 0?{}:{branch:a?.branch??sw(t,`branch`)}}}}}}async function fw(e,t,n){let r=aw(e);if(!r)throw new D(`Unknown ai-delivery tool ${e}.`);let{repo:i,...a}=r.inputSchema.parse(t);if(e===`issue_finish`&&a.nonClosing===!0)throw new D(`Non-closing delivery cannot finish or close its retained issue.`);if(i!==void 0&&n.repo!==void 0&&i!==n.repo)throw new D(`Tool and execution repository selectors disagree.`);e===`issue_create`&&Nv(a);let o=typeof i==`string`?i:n.repo,s={...n,...o===void 0?{}:{repo:o}},c=e===`runtime_stage`||e===`runtime_admit`||e.startsWith(`issue_worktree_transition_`)||e===`issue_start`&&a.investigationWorktree!==void 0||e===`issue_finish`&&a.investigation===!0,l=n.repoRoot;if(c){let t=await Kh();if(l=ld({repository:o??(()=>{let e=cd(l,`origin`);return`${e.owner}/${e.repo}`})(),launchDirectory:l,checkoutRoots:t.checkoutRoots}),e===`runtime_stage`||e===`runtime_admit`){let r={...a,repoRoot:l,identity:sw(a,`identity`)??n.identity??t.roles.author.identity,...n.personalAuth===void 0?{}:{personalAuth:n.personalAuth},...n.signal===void 0?{}:{signal:n.signal}};return e===`runtime_stage`?UC(r):GC(r)}}let u=e===`issue_pr_review`?sw(a,`identity`):void 0,d=await uw({...s,...u===void 0?{}:{identity:u}},r.commandName,e===`issue_pr_review`?`reviewer`:`author`);switch(c&&(d.root=l),e){case`delivery_health`:return td(d,{...a,repo:o});case`issue_comment`:return Ov(d,a);case`issue_create`:return Fv(d,a);case`issue_start`:return a.investigationWorktree===void 0?dw(d,a):CC(d,{issueNumber:ow(a,`issueNumber`),investigationWorktree:cw(a,`investigationWorktree`),expectedHeadSha:cw(a,`expectedHeadSha`)});case`issue_update`:return Uv(d,a);case`issue_list`:case`issue_search`:return Bv(d,a);case`issue_info`:return Gv(d,ow(a,`issueNumber`));case`issue_ready_check`:return qv(d,ow(a,`issueNumber`));case`issue_pr_create`:return fC(d,{...a.prNumber===void 0?{}:{prNumber:ow(a,`prNumber`)},issueNumber:ow(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},...a.body===void 0?{}:{body:cw(a,`body`)},...a.title===void 0?{}:{title:cw(a,`title`)},...a.headBranch===void 0?{}:{headBranch:cw(a,`headBranch`)},draft:a.draft!==!1,dryRun:a.dryRun===!0});case`issue_pr_info`:return aC(d,a);case`issue_pr_review`:return pC(d,{artifact:cw(a,`artifact`),issueNumber:ow(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:ow(a,`prNumber`),dryRun:a.dryRun===!0});case`issue_pr_merge`:case`issue_finish`:{if(e===`issue_finish`&&a.investigation===!0)return wC(d,{issueNumber:ow(a,`issueNumber`),resultPath:cw(a,`resultPath`),...a.authorityCommentId===void 0?{}:{authorityCommentId:ow(a,`authorityCommentId`)},...a.acceptanceCommentId===void 0?{}:{acceptanceCommentId:ow(a,`acceptanceCommentId`)},dryRun:a.dryRun===!0});let t={issueNumber:ow(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:ow(a,`prNumber`),...a.strategy===void 0?{}:{strategy:a.strategy},...a.reviewedHeadSha===void 0?{}:{reviewedHeadSha:cw(a,`reviewedHeadSha`)},dryRun:a.dryRun===!0};return e===`issue_finish`?gC(d,t):hC(d,t)}case`issue_worktree_transition_inspect`:return wS(d,{...a,...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}});case`issue_worktree_transition_apply`:return pS(d,{authority:`worktree:transition`,planPath:cw(a,`planPath`),expectedPlanId:cw(a,`expectedPlanId`),relinquishmentCommentId:ow(a,`relinquishmentCommentId`),acceptanceCommentId:ow(a,`acceptanceCommentId`),...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}})}}var pw;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(pw||={});var mw;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(mw||={});var W=pw.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),hw=e=>{switch(typeof e){case`undefined`:return W.undefined;case`string`:return W.string;case`number`:return Number.isNaN(e)?W.nan:W.number;case`boolean`:return W.boolean;case`function`:return W.function;case`bigint`:return W.bigint;case`symbol`:return W.symbol;case`object`:return Array.isArray(e)?W.array:e===null?W.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?W.promise:typeof Map<`u`&&e instanceof Map?W.map:typeof Set<`u`&&e instanceof Set?W.set:typeof Date<`u`&&e instanceof Date?W.date:W.object;default:return W.unknown}},G=pw.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),gw=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pw.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};gw.create=e=>new gw(e);var _w=(e,t)=>{let n;switch(e.code){case G.invalid_type:n=e.received===W.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case G.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,pw.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:n=`Unrecognized key(s) in object: ${pw.joinValues(e.keys,`, `)}`;break;case G.invalid_union:n=`Invalid input`;break;case G.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${pw.joinValues(e.options)}`;break;case G.invalid_enum_value:n=`Invalid enum value. Expected ${pw.joinValues(e.options)}, received '${e.received}'`;break;case G.invalid_arguments:n=`Invalid function arguments`;break;case G.invalid_return_type:n=`Invalid function return type`;break;case G.invalid_date:n=`Invalid date`;break;case G.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:pw.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case G.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case G.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case G.custom:n=`Invalid input`;break;case G.invalid_intersection_types:n=`Intersection results could not be merged`;break;case G.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case G.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,pw.assertNever(e)}return{message:n}},vw=_w;function yw(){return vw}var bw=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function K(e,t){let n=yw(),r=bw({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===_w?void 0:_w].filter(e=>!!e)});e.common.issues.push(r)}var xw=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return q;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return q;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:`aborted`}),Sw=e=>({status:`dirty`,value:e}),Cw=e=>({status:`valid`,value:e}),ww=e=>e.status===`aborted`,Tw=e=>e.status===`dirty`,Ew=e=>e.status===`valid`,Dw=e=>typeof Promise<`u`&&e instanceof Promise,J;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(J||={});var Ow=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},kw=(e,t)=>{if(Ew(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new gw(e.common.issues);return this._error=t,this._error}}};function Y(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var Aw=class{get description(){return this._def.description}_getType(e){return hw(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:hw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xw,ctx:{common:e.parent.common,data:e.data,parsedType:hw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Dw(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hw(e)};return kw(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hw(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Ew(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Ew(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hw(e)},r=this._parse({data:e,path:n.path,parent:n});return kw(n,await(Dw(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:G.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new NT({schema:this,typeName:X.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return PT.create(this,this._def)}nullable(){return FT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mT.create(this)}promise(){return MT.create(this,this._def)}or(e){return _T.create([this,e],this._def)}and(e){return xT.create(this,e,this._def)}transform(e){return new NT({...Y(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new IT({...Y(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new zT({typeName:X.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new LT({...Y(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return BT.create(this,e)}readonly(){return VT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jw=/^c[^\s-]{8,}$/i,Mw=/^[0-9a-z]+$/,Nw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Pw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Fw=/^[a-z0-9_-]{21}$/i,Iw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Lw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Rw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zw=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,Bw,Vw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Uw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ww=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Gw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,qw=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Jw=RegExp(`^${qw}$`);function Yw(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Xw(e){return RegExp(`^${Yw(e)}$`)}function Zw(e){let t=`${qw}T${Yw(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Qw(e,t){return!((t!==`v4`&&t||!Vw.test(e))&&(t!==`v6`&&t||!Uw.test(e)))}function $w(e,t){if(!Iw.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function eT(e,t){return!((t!==`v4`&&t||!Hw.test(e))&&(t!==`v6`&&t||!Ww.test(e)))}var tT=class e extends Aw{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.string,received:t.parsedType}),q}let t=new xw,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Rw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`email`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Bw||=new RegExp(zw,`u`),Bw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`emoji`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Pw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`uuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Fw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`nanoid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)jw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Mw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid2`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Nw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ulid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),K(n,{validation:`url`,code:G.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`regex`,code:G.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Zw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Jw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Xw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Lw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`duration`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Qw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ip`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?$w(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`jwt`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?eT(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cidr`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Gw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Kw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64url`,code:G.invalid_string,message:r.message}),t.dirty()):pw.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:G.invalid_string,...J.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...J.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...J.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...J.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...J.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...J.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...J.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...J.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...J.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...J.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...J.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...J.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};tT.create=e=>new tT({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...Y(e)});function nT(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var rT=class e extends Aw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==W.number){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.number,received:t.parsedType}),q}let t,n=new xw;for(let r of this._def.checks)r.kind===`int`?pw.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?nT(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_finite,message:r.message}),n.dirty()):pw.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:J.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:J.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:J.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&pw.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};rT.create=e=>new rT({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...Y(e)});var iT=class e extends Aw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let t,n=new xw;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):pw.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};iT.create=e=>new iT({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...Y(e)});var aT=class extends Aw{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.boolean,received:t.parsedType}),q}return Cw(e.data)}};aT.create=e=>new aT({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...Y(e)});var oT=class e extends Aw{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.date,received:t.parsedType}),q}if(Number.isNaN(e.data.getTime()))return K(this._getOrReturnCtx(e),{code:G.invalid_date}),q;let t=new xw,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):pw.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};oT.create=e=>new oT({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...Y(e)});var sT=class extends Aw{_parse(e){if(this._getType(e)!==W.symbol){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.symbol,received:t.parsedType}),q}return Cw(e.data)}};sT.create=e=>new sT({typeName:X.ZodSymbol,...Y(e)});var cT=class extends Aw{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.undefined,received:t.parsedType}),q}return Cw(e.data)}};cT.create=e=>new cT({typeName:X.ZodUndefined,...Y(e)});var lT=class extends Aw{_parse(e){if(this._getType(e)!==W.null){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.null,received:t.parsedType}),q}return Cw(e.data)}};lT.create=e=>new lT({typeName:X.ZodNull,...Y(e)});var uT=class extends Aw{constructor(){super(...arguments),this._any=!0}_parse(e){return Cw(e.data)}};uT.create=e=>new uT({typeName:X.ZodAny,...Y(e)});var dT=class extends Aw{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Cw(e.data)}};dT.create=e=>new dT({typeName:X.ZodUnknown,...Y(e)});var fT=class extends Aw{_parse(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.never,received:t.parsedType}),q}};fT.create=e=>new fT({typeName:X.ZodNever,...Y(e)});var pT=class extends Aw{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.void,received:t.parsedType}),q}return Cw(e.data)}};pT.create=e=>new pT({typeName:X.ZodVoid,...Y(e)});var mT=class e extends Aw{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==W.array)return K(t,{code:G.invalid_type,expected:W.array,received:t.parsedType}),q;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(K(t,{code:e?G.too_big:G.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(K(t,{code:G.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(K(t,{code:G.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Ow(t,e,t.path,n)))).then(e=>xw.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Ow(t,e,t.path,n)));return xw.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(e){return this.min(1,e)}};mT.create=(e,t)=>new mT({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...Y(t)});function hT(e){if(e instanceof gT){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=PT.create(hT(r))}return new gT({...e._def,shape:()=>t})}return e instanceof mT?new mT({...e._def,type:hT(e.element)}):e instanceof PT?PT.create(hT(e.unwrap())):e instanceof FT?FT.create(hT(e.unwrap())):e instanceof ST?ST.create(e.items.map(e=>hT(e))):e}var gT=class e extends Aw{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=pw.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==W.object){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof fT&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Ow(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof fT){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(K(n,{code:G.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Ow(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>xw.mergeObjectSync(t,e)):xw.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return J.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:J.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of pw.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of pw.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return hT(this)}partial(t){let n={};for(let e of pw.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of pw.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof PT;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return kT(pw.objectKeys(this.shape))}};gT.create=(e,t)=>new gT({shape:()=>e,unknownKeys:`strip`,catchall:fT.create(),typeName:X.ZodObject,...Y(t)}),gT.strictCreate=(e,t)=>new gT({shape:()=>e,unknownKeys:`strict`,catchall:fT.create(),typeName:X.ZodObject,...Y(t)}),gT.lazycreate=(e,t)=>new gT({shape:e,unknownKeys:`strip`,catchall:fT.create(),typeName:X.ZodObject,...Y(t)});var _T=class extends Aw{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new gw(e.ctx.common.issues));return K(t,{code:G.invalid_union,unionErrors:n}),q}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new gw(e));return K(t,{code:G.invalid_union,unionErrors:i}),q}}get options(){return this._def.options}};_T.create=(e,t)=>new _T({options:e,typeName:X.ZodUnion,...Y(t)});var vT=e=>e instanceof DT?vT(e.schema):e instanceof NT?vT(e.innerType()):e instanceof OT?[e.value]:e instanceof AT?e.options:e instanceof jT?pw.objectValues(e.enum):e instanceof IT?vT(e._def.innerType):e instanceof cT?[void 0]:e instanceof lT?[null]:e instanceof PT?[void 0,...vT(e.unwrap())]:e instanceof FT?[null,...vT(e.unwrap())]:e instanceof zT||e instanceof VT?vT(e.unwrap()):e instanceof LT?vT(e._def.innerType):[],yT=class e extends Aw{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.object)return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:G.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=vT(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Y(r)})}};function bT(e,t){let n=hw(e),r=hw(t);if(e===t)return{valid:!0,data:e};if(n===W.object&&r===W.object){let n=pw.objectKeys(t),r=pw.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=bT(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===W.array&&r===W.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=bT(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===W.date&&r===W.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var xT=class extends Aw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ww(e)||ww(r))return q;let i=bT(e.value,r.value);return i.valid?((Tw(e)||Tw(r))&&t.dirty(),{status:t.value,value:i.data}):(K(n,{code:G.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};xT.create=(e,t,n)=>new xT({left:e,right:t,typeName:X.ZodIntersection,...Y(n)});var ST=class e extends Aw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.array)return K(n,{code:G.invalid_type,expected:W.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return K(n,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),q;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Ow(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>xw.mergeArray(t,e)):xw.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ST.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ST({items:e,typeName:X.ZodTuple,rest:null,...Y(t)})};var CT=class e extends Aw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.object)return K(n,{code:G.invalid_type,expected:W.object,received:n.parsedType}),q;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Ow(n,e,n.path,e)),value:a._parse(new Ow(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?xw.mergeObjectAsync(t,r):xw.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Aw?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...Y(r)}):new e({keyType:tT.create(),valueType:t,typeName:X.ZodRecord,...Y(n)})}},wT=class extends Aw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.map)return K(n,{code:G.invalid_type,expected:W.map,received:n.parsedType}),q;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Ow(n,e,n.path,[a,`key`])),value:i._parse(new Ow(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};wT.create=(e,t,n)=>new wT({valueType:t,keyType:e,typeName:X.ZodMap,...Y(n)});var TT=class e extends Aw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.set)return K(n,{code:G.invalid_type,expected:W.set,received:n.parsedType}),q;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(K(n,{code:G.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(K(n,{code:G.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return q;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Ow(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};TT.create=(e,t)=>new TT({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...Y(t)});var ET=class e extends Aw{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.function)return K(t,{code:G.invalid_type,expected:W.function,received:t.parsedType}),q;function n(e,n){return bw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,yw(),_w].filter(e=>!!e),issueData:{code:G.invalid_arguments,argumentsError:n}})}function r(e,n){return bw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,yw(),_w].filter(e=>!!e),issueData:{code:G.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof MT){let e=this;return Cw(async function(...t){let o=new gw([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return Cw(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new gw([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new gw([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ST.create(t).rest(dT.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||ST.create([]).rest(dT.create()),returns:n||dT.create(),typeName:X.ZodFunction,...Y(r)})}},DT=class extends Aw{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};DT.create=(e,t)=>new DT({getter:e,typeName:X.ZodLazy,...Y(t)});var OT=class extends Aw{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:G.invalid_literal,expected:this._def.value}),q}return{status:`valid`,value:e.data}}get value(){return this._def.value}};OT.create=(e,t)=>new OT({value:e,typeName:X.ZodLiteral,...Y(t)});function kT(e,t){return new AT({values:e,typeName:X.ZodEnum,...Y(t)})}var AT=class e extends Aw{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:pw.joinValues(n),received:t.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:G.invalid_enum_value,options:n}),q}return Cw(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};AT.create=kT;var jT=class extends Aw{_parse(e){let t=pw.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==W.string&&n.parsedType!==W.number){let e=pw.objectValues(t);return K(n,{expected:pw.joinValues(e),received:n.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(pw.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=pw.objectValues(t);return K(n,{received:n.data,code:G.invalid_enum_value,options:e}),q}return Cw(e.data)}get enum(){return this._def.values}};jT.create=(e,t)=>new jT({values:e,typeName:X.ZodNativeEnum,...Y(t)});var MT=class extends Aw{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==W.promise&&t.common.async===!1?(K(t,{code:G.invalid_type,expected:W.promise,received:t.parsedType}),q):Cw((t.parsedType===W.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};MT.create=(e,t)=>new MT({type:e,typeName:X.ZodPromise,...Y(t)});var NT=class extends Aw{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{K(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return q;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?Sw(r.value):r});{if(t.value===`aborted`)return q;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?Sw(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?q:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?q:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ew(e))return q;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Ew(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):q)}pw.assertNever(r)}};NT.create=(e,t,n)=>new NT({schema:e,typeName:X.ZodEffects,effect:t,...Y(n)}),NT.createWithPreprocess=(e,t,n)=>new NT({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...Y(n)});var PT=class extends Aw{_parse(e){return this._getType(e)===W.undefined?Cw(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};PT.create=(e,t)=>new PT({innerType:e,typeName:X.ZodOptional,...Y(t)});var FT=class extends Aw{_parse(e){return this._getType(e)===W.null?Cw(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};FT.create=(e,t)=>new FT({innerType:e,typeName:X.ZodNullable,...Y(t)});var IT=class extends Aw{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===W.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};IT.create=(e,t)=>new IT({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...Y(t)});var LT=class extends Aw{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Dw(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new gw(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new gw(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};LT.create=(e,t)=>new LT({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...Y(t)});var RT=class extends Aw{_parse(e){if(this._getType(e)!==W.nan){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.nan,received:t.parsedType}),q}return{status:`valid`,value:e.data}}};RT.create=e=>new RT({typeName:X.ZodNaN,...Y(e)});var zT=class extends Aw{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},BT=class e extends Aw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),Sw(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},VT=class extends Aw{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Ew(e)&&(e.value=Object.freeze(e.value)),e);return Dw(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};VT.create=(e,t)=>new VT({innerType:e,typeName:X.ZodReadonly,...Y(t)}),gT.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),tT.create,rT.create,RT.create,iT.create,aT.create,oT.create,sT.create,cT.create,lT.create,uT.create,dT.create,fT.create,pT.create,mT.create;var HT=gT.create;gT.strictCreate,_T.create,yT.create,xT.create,ST.create,CT.create,wT.create,TT.create,ET.create,DT.create,OT.create,AT.create,jT.create,MT.create,NT.create,PT.create,FT.create,NT.createWithPreprocess,BT.create;var UT=k(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ri.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){nn(this,`with`,e)},parse(e,t){return In(this,e,t,{callee:this.parse})},parseAsync(e,t){return Rn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Bn(this,e,t)},safeParseAsync(e,t){return Un(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return At(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),WT=k(`ZodMiniObject`,(e,t)=>{aa.init(e,t),UT.init(e,t),fn(e,`shape`,e=>e._zod.def.shape,!1)});function GT(e,t){return new WT({type:`object`,shape:e??{},...O(t)})}function KT(e){return!!e._zod}function qT(e){let t=Object.values(e);if(t.length===0)return GT({});let n=t.every(KT),r=t.every(e=>!KT(e));if(n)return GT(e);if(r)return HT(e);throw Error(`Mixed Zod versions detected in object shape.`)}function JT(e,t){return KT(e)?Bn(e,t):e.safeParse(t)}async function YT(e,t){return KT(e)?await Un(e,t):await e.safeParseAsync(t)}function XT(e){if(!e)return;let t;if(t=KT(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function ZT(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return qT(e)}}if(KT(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function QT(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function $T(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${QT(e.path)}`:e.message).join(`
296
+ `);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function eE(e){return e.description}function tE(e){if(KT(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function nE(e){if(KT(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}var rE=`2025-11-25`,iE=[rE,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],aE=`io.modelcontextprotocol/related-task`,oE=Cu(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),sE=Wl([A(),j().int()]),cE=A();Hl({ttl:j().optional(),pollInterval:j().optional()});var lE=P({ttl:j().optional()}),uE=P({taskId:A()}),dE=Hl({progressToken:sE.optional(),[aE]:uE.optional()}),fE=P({_meta:dE.optional()}),pE=fE.extend({task:lE.optional()}),mE=e=>pE.safeParse(e).success,hE=P({method:A(),params:fE.loose().optional()}),gE=P({_meta:dE.optional()}),_E=P({method:A(),params:gE.loose().optional()}),vE=Hl({_meta:dE.optional()}),yE=Wl([A(),j().int()]),bE=P({jsonrpc:L(`2.0`),id:yE,...hE.shape}).strict(),xE=e=>bE.safeParse(e).success,SE=P({jsonrpc:L(`2.0`),..._E.shape}).strict(),CE=e=>SE.safeParse(e).success,wE=P({jsonrpc:L(`2.0`),id:yE,result:vE}).strict(),TE=e=>wE.safeParse(e).success,Z;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Z||={});var EE=P({jsonrpc:L(`2.0`),id:yE.optional(),error:P({code:j().int(),message:A(),data:Ll().optional()})}).strict(),DE=e=>EE.safeParse(e).success,OE=Wl([bE,SE,wE,EE]);Wl([wE,EE]);var kE=vE.strict(),AE=gE.extend({requestId:yE.optional(),reason:A().optional()}),jE=_E.extend({method:L(`notifications/cancelled`),params:AE}),ME=P({icons:N(P({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:I([`light`,`dark`]).optional()})).optional()}),NE=P({name:A(),title:A().optional()}),PE=NE.extend({...NE.shape,...ME.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),FE=Eu(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Jl(P({form:Jl(P({applyDefaults:M().optional()}),Ql(A(),Ll())).optional(),url:oE.optional()}),Ql(A(),Ll()).optional())),IE=Hl({list:oE.optional(),cancel:oE.optional(),requests:Hl({sampling:Hl({createMessage:oE.optional()}).optional(),elicitation:Hl({create:oE.optional()}).optional()}).optional()}),LE=Hl({list:oE.optional(),cancel:oE.optional(),requests:Hl({tools:Hl({call:oE.optional()}).optional()}).optional()}),RE=P({experimental:Ql(A(),oE).optional(),sampling:P({context:oE.optional(),tools:oE.optional()}).optional(),elicitation:FE.optional(),roots:P({listChanged:M().optional()}).optional(),tasks:IE.optional(),extensions:Ql(A(),oE).optional()}),zE=fE.extend({protocolVersion:A(),capabilities:RE,clientInfo:PE}),BE=hE.extend({method:L(`initialize`),params:zE}),VE=P({experimental:Ql(A(),oE).optional(),logging:oE.optional(),completions:oE.optional(),prompts:P({listChanged:M().optional()}).optional(),resources:P({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:P({listChanged:M().optional()}).optional(),tasks:LE.optional(),extensions:Ql(A(),oE).optional()}),HE=vE.extend({protocolVersion:A(),capabilities:VE,serverInfo:PE,instructions:A().optional()}),UE=_E.extend({method:L(`notifications/initialized`),params:gE.optional()}),WE=hE.extend({method:L(`ping`),params:fE.optional()}),GE=P({progress:j(),total:iu(j()),message:iu(A())}),KE=P({...gE.shape,...GE.shape,progressToken:sE}),qE=_E.extend({method:L(`notifications/progress`),params:KE}),JE=fE.extend({cursor:cE.optional()}),YE=hE.extend({params:JE.optional()}),XE=vE.extend({nextCursor:cE.optional()}),ZE=I([`working`,`input_required`,`completed`,`failed`,`cancelled`]),QE=P({taskId:A(),status:ZE,ttl:Wl([j(),Fl()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:iu(j()),statusMessage:iu(A())}),$E=vE.extend({task:QE}),eD=gE.merge(QE),tD=_E.extend({method:L(`notifications/tasks/status`),params:eD}),nD=hE.extend({method:L(`tasks/get`),params:fE.extend({taskId:A()})}),rD=vE.merge(QE),iD=hE.extend({method:L(`tasks/result`),params:fE.extend({taskId:A()})});vE.loose();var aD=YE.extend({method:L(`tasks/list`)}),oD=XE.extend({tasks:N(QE)}),sD=hE.extend({method:L(`tasks/cancel`),params:fE.extend({taskId:A()})}),cD=vE.merge(QE),lD=P({uri:A(),mimeType:iu(A()),_meta:Ql(A(),Ll()).optional()}),uD=lD.extend({text:A()}),dD=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),fD=lD.extend({blob:dD}),pD=I([`user`,`assistant`]),mD=P({audience:N(pD).optional(),priority:j().min(0).max(1).optional(),lastModified:Du({offset:!0}).optional()}),hD=P({...NE.shape,...ME.shape,uri:A(),description:iu(A()),mimeType:iu(A()),size:iu(j()),annotations:mD.optional(),_meta:iu(Hl({}))}),gD=P({...NE.shape,...ME.shape,uriTemplate:A(),description:iu(A()),mimeType:iu(A()),annotations:mD.optional(),_meta:iu(Hl({}))}),_D=YE.extend({method:L(`resources/list`)}),vD=XE.extend({resources:N(hD)}),yD=YE.extend({method:L(`resources/templates/list`)}),bD=XE.extend({resourceTemplates:N(gD)}),xD=fE.extend({uri:A()}),SD=xD,CD=hE.extend({method:L(`resources/read`),params:SD}),wD=vE.extend({contents:N(Wl([uD,fD]))}),TD=_E.extend({method:L(`notifications/resources/list_changed`),params:gE.optional()}),ED=xD,DD=hE.extend({method:L(`resources/subscribe`),params:ED}),OD=xD,kD=hE.extend({method:L(`resources/unsubscribe`),params:OD}),AD=gE.extend({uri:A()}),jD=_E.extend({method:L(`notifications/resources/updated`),params:AD}),MD=P({name:A(),description:iu(A()),required:iu(M())}),ND=P({...NE.shape,...ME.shape,description:iu(A()),arguments:iu(N(MD)),_meta:iu(Hl({}))}),PD=YE.extend({method:L(`prompts/list`)}),FD=XE.extend({prompts:N(ND)}),ID=fE.extend({name:A(),arguments:Ql(A(),A()).optional()}),LD=hE.extend({method:L(`prompts/get`),params:ID}),RD=P({type:L(`text`),text:A(),annotations:mD.optional(),_meta:Ql(A(),Ll()).optional()}),zD=P({type:L(`image`),data:dD,mimeType:A(),annotations:mD.optional(),_meta:Ql(A(),Ll()).optional()}),BD=P({type:L(`audio`),data:dD,mimeType:A(),annotations:mD.optional(),_meta:Ql(A(),Ll()).optional()}),VD=P({type:L(`tool_use`),name:A(),id:A(),input:Ql(A(),Ll()),_meta:Ql(A(),Ll()).optional()}),HD=P({type:L(`resource`),resource:Wl([uD,fD]),annotations:mD.optional(),_meta:Ql(A(),Ll()).optional()}),UD=Wl([RD,zD,BD,hD.extend({type:L(`resource_link`)}),HD]),WD=P({role:pD,content:UD}),GD=vE.extend({description:A().optional(),messages:N(WD)}),KD=_E.extend({method:L(`notifications/prompts/list_changed`),params:gE.optional()}),qD=P({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),JD=P({taskSupport:I([`required`,`optional`,`forbidden`]).optional()}),YD=P({...NE.shape,...ME.shape,description:A().optional(),inputSchema:P({type:L(`object`),properties:Ql(A(),oE).optional(),required:N(A()).optional()}).catchall(Ll()),outputSchema:P({type:L(`object`),properties:Ql(A(),oE).optional(),required:N(A()).optional()}).catchall(Ll()).optional(),annotations:qD.optional(),execution:JD.optional(),_meta:Ql(A(),Ll()).optional()}),XD=YE.extend({method:L(`tools/list`)}),ZD=XE.extend({tools:N(YD)}),QD=vE.extend({content:N(UD).default([]),structuredContent:Ql(A(),Ll()).optional(),isError:M().optional()});QD.or(vE.extend({toolResult:Ll()}));var $D=pE.extend({name:A(),arguments:Ql(A(),Ll()).optional()}),eO=hE.extend({method:L(`tools/call`),params:$D}),tO=_E.extend({method:L(`notifications/tools/list_changed`),params:gE.optional()}),nO=P({autoRefresh:M().default(!0),debounceMs:j().int().nonnegative().default(300)}),rO=I([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),iO=fE.extend({level:rO}),aO=hE.extend({method:L(`logging/setLevel`),params:iO}),oO=gE.extend({level:rO,logger:A().optional(),data:Ll()}),sO=_E.extend({method:L(`notifications/message`),params:oO}),cO=P({hints:N(P({name:A().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),lO=P({mode:I([`auto`,`required`,`none`]).optional()}),uO=P({type:L(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(UD).default([]),structuredContent:P({}).loose().optional(),isError:M().optional(),_meta:Ql(A(),Ll()).optional()}),dO=Kl(`type`,[RD,zD,BD]),fO=Kl(`type`,[RD,zD,BD,VD,uO]),pO=P({role:pD,content:Wl([fO,N(fO)]),_meta:Ql(A(),Ll()).optional()}),mO=pE.extend({messages:N(pO),modelPreferences:cO.optional(),systemPrompt:A().optional(),includeContext:I([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:N(A()).optional(),metadata:oE.optional(),tools:N(YD).optional(),toolChoice:lO.optional()}),hO=hE.extend({method:L(`sampling/createMessage`),params:mO}),gO=vE.extend({model:A(),stopReason:iu(I([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:pD,content:dO}),_O=vE.extend({model:A(),stopReason:iu(I([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:pD,content:Wl([fO,N(fO)])}),vO=P({type:L(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),yO=P({type:L(`string`),title:A().optional(),description:A().optional(),minLength:j().optional(),maxLength:j().optional(),format:I([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),bO=P({type:I([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),xO=P({type:L(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),SO=P({type:L(`string`),title:A().optional(),description:A().optional(),oneOf:N(P({const:A(),title:A()})),default:A().optional()}),CO=Wl([Wl([P({type:L(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),Wl([xO,SO]),Wl([P({type:L(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:P({type:L(`string`),enum:N(A())}),default:N(A()).optional()}),P({type:L(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:P({anyOf:N(P({const:A(),title:A()}))}),default:N(A()).optional()})])]),vO,yO,bO]),wO=Wl([pE.extend({mode:L(`form`).optional(),message:A(),requestedSchema:P({type:L(`object`),properties:Ql(A(),CO),required:N(A()).optional()})}),pE.extend({mode:L(`url`),message:A(),elicitationId:A(),url:A().url()})]),TO=hE.extend({method:L(`elicitation/create`),params:wO}),EO=gE.extend({elicitationId:A()}),DO=_E.extend({method:L(`notifications/elicitation/complete`),params:EO}),OO=vE.extend({action:I([`accept`,`decline`,`cancel`]),content:Eu(e=>e===null?void 0:e,Ql(A(),Wl([A(),j(),M(),N(A())])).optional())}),kO=P({type:L(`ref/resource`),uri:A()}),AO=P({type:L(`ref/prompt`),name:A()}),jO=fE.extend({ref:Wl([AO,kO]),argument:P({name:A(),value:A()}),context:P({arguments:Ql(A(),A()).optional()}).optional()}),MO=hE.extend({method:L(`completion/complete`),params:jO});function NO(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function PO(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var FO=vE.extend({completion:Hl({values:N(A()).max(100),total:iu(j().int()),hasMore:iu(M())})}),IO=P({uri:A().startsWith(`file://`),name:A().optional(),_meta:Ql(A(),Ll()).optional()}),LO=hE.extend({method:L(`roots/list`),params:fE.optional()}),RO=vE.extend({roots:N(IO)}),zO=_E.extend({method:L(`notifications/roots/list_changed`),params:gE.optional()});Wl([WE,BE,MO,aO,LD,PD,_D,yD,CD,DD,kD,eO,XD,nD,iD,aD,sD]),Wl([jE,qE,UE,zO,tD]),Wl([kE,gO,_O,OO,RO,rD,oD,$E]),Wl([WE,hO,TO,LO,nD,iD,aD,sD]),Wl([jE,qE,sO,jD,TD,tO,KD,tD,DO]),Wl([kE,HE,FO,GD,FD,vD,bD,wD,QD,ZD,rD,oD,$E]);var Q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new BO(e.elicitations,n)}return new e(t,n,r)}},BO=class extends Q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function VO(e){return e===`completed`||e===`failed`||e===`cancelled`}var HO=Symbol(`Let zodToJsonSchema decide on which parser to use`),UO={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},WO=e=>typeof e==`string`?{...UO,name:e}:{...UO,...e},GO=e=>{let t=WO(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function KO(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function qO(e,t,n,r,i){e[t]=n,KO(e,t,r,i)}var JO=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function YO(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?JO(t,e.currentPath):t.join(`/`)}}function XO(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=Bk(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&qO(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&qO(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(qO(n,`minItems`,e.exactLength.value,e.exactLength.message,t),qO(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function ZO(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?qO(n,`minimum`,r.value,r.message,t):qO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),qO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?qO(n,`maximum`,r.value,r.message,t):qO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),qO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:qO(n,`multipleOf`,r.value,r.message,t)}return n}function QO(){return{type:`boolean`}}function $O(e,t){return Bk(e.type._def,t)}var ek=(e,t)=>Bk(e.innerType._def,t);function tk(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>tk(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return nk(e,t)}}var nk=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:qO(n,`minimum`,r.value,r.message,t);break;case`max`:qO(n,`maximum`,r.value,r.message,t)}return n};function rk(e,t){return{...Bk(e.innerType._def,t),default:e.defaultValue()}}function ik(e,t){return t.effectStrategy===`input`?Bk(e.schema._def,t):YO(t)}function ak(e){return{type:`string`,enum:Array.from(e.values)}}var ok=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function sk(e,t){let n=[Bk(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Bk(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(ok(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function ck(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var lk=void 0,uk={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(lk===void 0&&(lk=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),lk),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function dk(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:qO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:qO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:hk(n,`email`,r.message,t);break;case`format:idn-email`:hk(n,`idn-email`,r.message,t);break;case`pattern:zod`:gk(n,uk.email,r.message,t)}break;case`url`:hk(n,`uri`,r.message,t);break;case`uuid`:hk(n,`uuid`,r.message,t);break;case`regex`:gk(n,r.regex,r.message,t);break;case`cuid`:gk(n,uk.cuid,r.message,t);break;case`cuid2`:gk(n,uk.cuid2,r.message,t);break;case`startsWith`:gk(n,RegExp(`^${fk(r.value,t)}`),r.message,t);break;case`endsWith`:gk(n,RegExp(`${fk(r.value,t)}$`),r.message,t);break;case`datetime`:hk(n,`date-time`,r.message,t);break;case`date`:hk(n,`date`,r.message,t);break;case`time`:hk(n,`time`,r.message,t);break;case`duration`:hk(n,`duration`,r.message,t);break;case`length`:qO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),qO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:gk(n,RegExp(fk(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&hk(n,`ipv4`,r.message,t),r.version!==`v4`&&hk(n,`ipv6`,r.message,t);break;case`base64url`:gk(n,uk.base64url,r.message,t);break;case`jwt`:gk(n,uk.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&gk(n,uk.ipv4Cidr,r.message,t),r.version!==`v4`&&gk(n,uk.ipv6Cidr,r.message,t);break;case`emoji`:gk(n,uk.emoji(),r.message,t);break;case`ulid`:gk(n,uk.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:hk(n,`binary`,r.message,t);break;case`contentEncoding:base64`:qO(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:gk(n,uk.base64,r.message,t)}break;case`nanoid`:gk(n,uk.nanoid,r.message,t)}return n}function fk(e,t){return t.patternStrategy===`escape`?mk(e):e}var pk=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function mk(e){let t=``;for(let n=0;n<e.length;n++)pk.has(e[n])||(t+=`\\`),t+=e[n];return t}function hk(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):qO(e,`format`,t,n,r)}function gk(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:_k(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):qO(e,`pattern`,_k(t,r),n,r)}function _k(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
297
297
  ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
298
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function gk(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Rk(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??qO(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Rk(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=lk(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ZO(e.keyType._def,t);return{...n,propertyNames:i}}return n}function _k(e,t){return t.mapStrategy===`record`?gk(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Rk(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||qO(t),Rk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||qO(t)],minItems:2,maxItems:2}}}function vk(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function yk(e){return e.target===`openAi`?void 0:{not:qO({...e,currentPath:[...e.currentPath,`not`]})}}function bk(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var xk={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Sk(e,t){if(t.target===`openApi3`)return Ck(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in xk&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=xk[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Ck(e,t)}var Ck=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Rk(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function wk(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:xk[e.innerType._def.typeName],nullable:!0}:{type:[xk[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Rk(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Rk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Tk(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,WO(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?GO(n,`minimum`,r.value,r.message,t):GO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),GO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?GO(n,`maximum`,r.value,r.message,t):GO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),GO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:GO(n,`multipleOf`,r.value,r.message,t)}return n}function Ek(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Ok(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Rk(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Dk(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Dk(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Rk(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Ok(e){try{return e.isOptional()}catch{return!0}}var kk=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Rk(e.innerType._def,t);let n=Rk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:qO(t)},n]}:qO(t)},Ak=(e,t)=>{if(t.pipeStrategy===`input`)return Rk(e.in._def,t);if(t.pipeStrategy===`output`)return Rk(e.out._def,t);let n=Rk(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Rk(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function jk(e,t){return Rk(e.type._def,t)}function Mk(e,t){let n={type:`array`,uniqueItems:!0,items:Rk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&GO(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&GO(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Nk(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Rk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Rk(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Rk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Pk(e){return{not:qO(e)}}function Fk(e){return qO(e)}var Ik=(e,t)=>Rk(e.innerType._def,t),Lk=(e,t,n)=>{switch(t){case X.ZodString:return lk(e,n);case X.ZodNumber:return Tk(e,n);case X.ZodObject:return Ek(e,n);case X.ZodBigInt:return YO(e,n);case X.ZodBoolean:return XO();case X.ZodDate:return $O(e,n);case X.ZodUndefined:return Pk(n);case X.ZodNull:return bk(n);case X.ZodArray:return JO(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return Sk(e,n);case X.ZodIntersection:return ak(e,n);case X.ZodTuple:return Nk(e,n);case X.ZodRecord:return gk(e,n);case X.ZodLiteral:return ok(e,n);case X.ZodEnum:return rk(e);case X.ZodNativeEnum:return vk(e);case X.ZodNullable:return wk(e,n);case X.ZodOptional:return kk(e,n);case X.ZodMap:return _k(e,n);case X.ZodSet:return Mk(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return jk(e,n);case X.ZodNaN:case X.ZodNever:return yk(n);case X.ZodEffects:return nk(e,n);case X.ZodAny:return qO(n);case X.ZodUnknown:return Fk(n);case X.ZodDefault:return tk(e,n);case X.ZodBranded:return ZO(e,n);case X.ZodReadonly:return Ik(e,n);case X.ZodCatch:return QO(e,n);case X.ZodPipeline:return Ak(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function Rk(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==BO)return i}if(r&&!n){let e=zk(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Lk(e,e.typeName,t),o=typeof a==`function`?Rk(a(),t):a;if(o&&Bk(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var zk=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:KO(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),qO(t)):t.$refStrategy===`seen`?qO(t):void 0}},Bk=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Vk=(e,t)=>{let n=UO(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Rk(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??qO(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Rk(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??qO(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Hk(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Uk(e,t){return WT(e)?Lc(e,{target:Hk(t?.target),io:t?.pipeStrategy??`input`}):Vk(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Wk(e){let t=JT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=eE(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Gk(e,t){let n=KT(e,t);if(!n.success)throw n.error;return n.data}var Kk=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(kE,e=>{this._oncancel(e)}),this.setNotificationHandler(GE,e=>{this._onprogress(e)}),this.setRequestHandler(HE,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(eD,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(nD,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Q(Z.InvalidParams,`Task not found: ${r}`);if(!zO(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(zO(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[rE]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(rD,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Q(Z.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(aD,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Task not found: ${e.params.taskId}`);if(zO(n.status))throw new Q(Z.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Q(Z.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Q?e:new Q(Z.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(Z.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),CE(e)||TE(e)?this._onresponse(e):yE(e)?this._onrequest(e,t):xE(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Q.fromError(Z.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[rE]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Z.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=fE(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new Q(Z.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Z.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),CE(e)?n(e):n(new Q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(CE(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),CE(e)?r(e):r(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}return}let i;try{let r=await this.request(e,ZE,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Q(Z.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},zO(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[rE]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Q?e:new Q(Z.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=KT(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Q.fromError(Z.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},tD,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},iD,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},oD,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[rE]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[rE]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[rE]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Wk(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Gk(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Wk(e);this._notificationHandlers.set(n,n=>{let r=Gk(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&yE(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Q(Z.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new Q(Z.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new Q(Z.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=$E.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),zO(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Q(Z.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(zO(a.status))throw new Q(Z.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=$E.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),zO(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function qk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jk(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=qk(a)&&qk(i)?{...a,...i}:i}return n}var Yk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Xk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=Yk(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),$=E((e=>{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 t=Yk(),n=Xk(),r=Yk();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Xk();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=C(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=C(this.rhs,e,n),this}get names(){return ae(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=C(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(oe(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ie(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(w(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=C(this.condition,e,t),this}get names(){let e=super.names;return ae(e,this.condition),this.else&&ie(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=C(this.iteration,e,t),this}get names(){return ie(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ae(ae(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=C(this.iterable,e,t),this}get names(){return ie(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var S=class extends p{render(e){return`return `+super.render(e)}};S.kind=`return`;var te=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ie(e,this.catch.names),this.finally&&ie(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var re=class extends m{render(e){return`finally`+super.render(e)}};re.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
299
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new S;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(S)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new re,this.code(n)),this._endBlockNode(ne,re)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new ee(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ee)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ie(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ae(e,n){return n instanceof t._CodeOrName?ie(e,n.names):e}function C(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function oe(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function w(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${de(e)}`}e.not=w;var se=ue(e.operators.AND);function T(...e){return e.reduce(se)}e.and=T;var ce=ue(e.operators.OR);function le(...e){return e.reduce(ce)}e.or=le;function ue(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${de(n)} ${e} ${de(r)}`}function de(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Zk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=$(),n=Yk();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Qk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),$k=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=$(),n=Zk(),r=Qk();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),eA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=$k(),n=$(),r=Qk(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),tA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){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:{}}}e.getRules=r})),nA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),rA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=tA(),n=nA(),r=$k(),i=$(),a=Zk(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
298
+ ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function vk(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Bk(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??YO(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Bk(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=dk(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=$O(e.keyType._def,t);return{...n,propertyNames:i}}return n}function yk(e,t){return t.mapStrategy===`record`?vk(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Bk(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||YO(t),Bk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||YO(t)],minItems:2,maxItems:2}}}function bk(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function xk(e){return e.target===`openAi`?void 0:{not:YO({...e,currentPath:[...e.currentPath,`not`]})}}function Sk(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var Ck={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function wk(e,t){if(t.target===`openApi3`)return Tk(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Ck&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Ck[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Tk(e,t)}var Tk=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Bk(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Ek(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Ck[e.innerType._def.typeName],nullable:!0}:{type:[Ck[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Bk(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Bk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Dk(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,KO(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?qO(n,`minimum`,r.value,r.message,t):qO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),qO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?qO(n,`maximum`,r.value,r.message,t):qO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),qO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:qO(n,`multipleOf`,r.value,r.message,t)}return n}function Ok(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Ak(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Bk(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=kk(e,t);return o!==void 0&&(r.additionalProperties=o),r}function kk(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Bk(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Ak(e){try{return e.isOptional()}catch{return!0}}var jk=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Bk(e.innerType._def,t);let n=Bk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:YO(t)},n]}:YO(t)},Mk=(e,t)=>{if(t.pipeStrategy===`input`)return Bk(e.in._def,t);if(t.pipeStrategy===`output`)return Bk(e.out._def,t);let n=Bk(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Bk(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Nk(e,t){return Bk(e.type._def,t)}function Pk(e,t){let n={type:`array`,uniqueItems:!0,items:Bk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&qO(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&qO(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Fk(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Bk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Bk(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Bk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Ik(e){return{not:YO(e)}}function Lk(e){return YO(e)}var Rk=(e,t)=>Bk(e.innerType._def,t),zk=(e,t,n)=>{switch(t){case X.ZodString:return dk(e,n);case X.ZodNumber:return Dk(e,n);case X.ZodObject:return Ok(e,n);case X.ZodBigInt:return ZO(e,n);case X.ZodBoolean:return QO();case X.ZodDate:return tk(e,n);case X.ZodUndefined:return Ik(n);case X.ZodNull:return Sk(n);case X.ZodArray:return XO(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return wk(e,n);case X.ZodIntersection:return sk(e,n);case X.ZodTuple:return Fk(e,n);case X.ZodRecord:return vk(e,n);case X.ZodLiteral:return ck(e,n);case X.ZodEnum:return ak(e);case X.ZodNativeEnum:return bk(e);case X.ZodNullable:return Ek(e,n);case X.ZodOptional:return jk(e,n);case X.ZodMap:return yk(e,n);case X.ZodSet:return Pk(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return Nk(e,n);case X.ZodNaN:case X.ZodNever:return xk(n);case X.ZodEffects:return ik(e,n);case X.ZodAny:return YO(n);case X.ZodUnknown:return Lk(n);case X.ZodDefault:return rk(e,n);case X.ZodBranded:return $O(e,n);case X.ZodReadonly:return Rk(e,n);case X.ZodCatch:return ek(e,n);case X.ZodPipeline:return Mk(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function Bk(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==HO)return i}if(r&&!n){let e=Vk(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=zk(e,e.typeName,t),o=typeof a==`function`?Bk(a(),t):a;if(o&&Hk(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Vk=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:JO(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),YO(t)):t.$refStrategy===`seen`?YO(t):void 0}},Hk=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Uk=(e,t)=>{let n=GO(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Bk(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??YO(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Bk(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??YO(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Wk(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Gk(e,t){return KT(e)?Lc(e,{target:Wk(t?.target),io:t?.pipeStrategy??`input`}):Uk(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Kk(e){let t=XT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=nE(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function qk(e,t){let n=JT(e,t);if(!n.success)throw n.error;return n.data}var Jk=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(jE,e=>{this._oncancel(e)}),this.setNotificationHandler(qE,e=>{this._onprogress(e)}),this.setRequestHandler(WE,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(nD,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(iD,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Q(Z.InvalidParams,`Task not found: ${r}`);if(!VO(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(VO(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[aE]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(aD,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Q(Z.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(sD,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Task not found: ${e.params.taskId}`);if(VO(n.status))throw new Q(Z.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Q(Z.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Q?e:new Q(Z.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(Z.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),TE(e)||DE(e)?this._onresponse(e):xE(e)?this._onrequest(e,t):CE(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Q.fromError(Z.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[aE]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Z.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=mE(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new Q(Z.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Z.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),TE(e)?n(e):n(new Q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(TE(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),TE(e)?r(e):r(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}return}let i;try{let r=await this.request(e,$E,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Q(Z.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},VO(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[aE]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Q?e:new Q(Z.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=JT(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Q.fromError(Z.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},rD,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},oD,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},cD,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[aE]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[aE]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[aE]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Kk(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=qk(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Kk(e);this._notificationHandlers.set(n,n=>{let r=qk(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&xE(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Q(Z.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new Q(Z.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new Q(Z.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=tD.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),VO(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Q(Z.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(VO(a.status))throw new Q(Z.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=tD.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),VO(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Yk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xk(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Yk(a)&&Yk(i)?{...a,...i}:i}return n}var Zk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Qk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=Zk(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),$k=E((e=>{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 t=Zk(),n=Qk(),r=Zk();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Qk();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=C(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=C(this.rhs,e,n),this}get names(){return ae(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=C(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(oe(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ie(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(w(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=C(this.condition,e,t),this}get names(){let e=super.names;return ae(e,this.condition),this.else&&ie(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=C(this.iteration,e,t),this}get names(){return ie(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ae(ae(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=C(this.iterable,e,t),this}get names(){return ie(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var S=class extends p{render(e){return`return `+super.render(e)}};S.kind=`return`;var te=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ie(e,this.catch.names),this.finally&&ie(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var re=class extends m{render(e){return`finally`+super.render(e)}};re.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
299
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new S;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(S)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new re,this.code(n)),this._endBlockNode(ne,re)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new ee(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ee)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ie(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ae(e,n){return n instanceof t._CodeOrName?ie(e,n.names):e}function C(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function oe(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function w(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${de(e)}`}e.not=w;var se=ue(e.operators.AND);function T(...e){return e.reduce(se)}e.and=T;var ce=ue(e.operators.OR);function le(...e){return e.reduce(ce)}e.or=le;function ue(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${de(n)} ${e} ${de(r)}`}function de(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),eA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=$k(),n=Zk();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),tA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),nA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=$k(),n=eA(),r=tA();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),rA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=nA(),n=$k(),r=tA(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),iA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){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:{}}}e.getRules=r})),aA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),oA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=iA(),n=aA(),r=nA(),i=$k(),a=eA(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
300
300
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
301
301
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
302
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),iA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=$(),n=Zk();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),aA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=$(),n=Zk(),r=Qk(),i=Zk();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),oA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=$(),n=Qk(),r=aA(),i=$k();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),sA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=$(),n=Zk();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),cA=E(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),lA=E(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.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 r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),uA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=Zk(),n=cA(),r=lA(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),dA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=eA(),n=rA(),r=nA(),i=rA(),a=iA(),o=oA(),s=sA(),c=$(),l=Qk(),u=uA(),d=Zk(),f=$k();function p(e){if(ee(e)&&(te(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&oe(e),ie(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ne(e),w(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(ee(e)&&(te(e),x(e))){S(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function ee(e){return typeof e.schema!=`boolean`}function S(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&oe(e),ae(e),C(e);let a=r.const(`_errs`,l.default.errors);ne(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function te(e){(0,d.checkUnknownRules)(e),re(e)}function ne(e,t){if(e.opts.jtd)return T(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);T(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function re(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ie(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function ae(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function C(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function oe({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function w(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&se(e),t.return((0,c._)`${l.default.errors} === 0`))}function se({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function T(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ve(e,`$ref`,h.all.$ref.definition));return}p.jtd||le(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ce(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ce(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ce(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ve(e,n.keyword,n.definition,t.type)})}function le(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ue(e,t),e.opts.allowUnionTypes||de(e,t),fe(e,e.dataTypes))}function ue(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{me(e.dataTypes,t)||ge(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),he(e,t)}}function de(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ge(e,`use allowUnionTypes to allow union type keyword`)}function fe(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>pe(t,e))&&ge(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function me(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function he(e,t){let n=[];for(let r of e.dataTypes)me(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ge(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var _e=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,xe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=_e;function ve(e,t,n,r){let i=new _e(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var ye=/^\/(?:[^~]|~0|~1)*$/,be=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ye.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=be.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=xe})),fA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),pA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=uA();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),mA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=$(),n=fA(),r=Qk(),i=uA(),a=Zk(),o=dA(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),hA=ke({$id:()=>gA,additionalProperties:()=>!1,default:()=>xA,description:()=>_A,properties:()=>bA,required:()=>yA,type:()=>vA}),gA,_A,vA,yA,bA,xA,SA=Oe((()=>{gA=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,_A=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,vA=`object`,yA=[`$data`],bA={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},xA={$id:gA,description:_A,type:vA,required:yA,properties:bA,additionalProperties:!1}})),CA=E(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=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),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(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&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function ee(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}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]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.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}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var S={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},te=/[@/?#:]/g,ne=/[@/?#]/g;function re(e,t){let n=t?ne:te;return n.lastIndex=0,e.replace(n,e=>S[e])}function ie(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ae(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function C(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function oe(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function w(e){return oe(e,l)}function se(e){return oe(e,c)}function T(e){return oe(e,c)}function ce(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 le(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function ue(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function de(e){let t=[];if(e.userinfo!==void 0&&(t.push(w(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=ie(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:re(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:de,reescapeHostDelimiters:re,normalizePercentEncoding:ie,normalizePathEncoding:ae,serializePathEncoding:C,normalizeQueryFragmentEncoding:le,encodeUserinfo:w,encodeQuery:se,encodeFragment:T,escapePreservingEscapes:ue,removeDotSegments:ee,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),wA=E(((e,t)=>{var{isUUID:n}=CA(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(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 s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(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(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),TA=E(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=CA(),{SCHEMES:m,getSchemeHandler:h}=wA(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=ce(e,t):typeof e==`object`&&(e=T(S(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=se(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=se(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),ee=y.host,te=ee!==void 0&&ee!==``&&(f(ee)||n(ee).isIPV6);w(y,r||{},b,te);let ne=ee&&ee.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(ee);if(y.error&&!ne)throw Error(y.error);return i.skipEscape=!0,S(y,i)}function x(e,t,n,i){let a={};return i||(e=T(S(e,n),n),t=T(S(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function ee(e,t,n){let r=ue(e,n),i=ue(t,n);return r!==void 0&&i!==void 0&&r===i}function S(e,t){let n={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:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var te=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ne=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,re=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function ie(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 ae(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 C(e){return e[0]===`[`&&e[e.length-1]===`]`}function oe(e){let t=e[4];return ae(e[3])||t!==void 0&&!C(t)&&ae(t)||ae(e[6])||ae(e[7])||ae(e[8])}function w(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!C(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function se(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(ne);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let ee=e.match(re);if(ee!==null){let e=ee[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let S=e.match(te);if(S){if(i.scheme=S[1],i.userinfo=S[3],i.host=S[4],i.port=parseInt(S[5],10),i.path=S[6]||``,i.query=S[7],i.fragment=S[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=oe(S),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=S[5]);let t=ie(i,S);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=C(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=w(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function T(e,t){return se(e,t).parsed}function ce(e,t){return le(e,t).normalized}function le(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=se(e,t);return{normalized:r||i||a||o||s?e:S(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function ue(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:S(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=le(n,t);return i||a||o||s||c?void 0:r}var de={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:ee,serialize:S,parse:T};t.exports=de,t.exports.default=de,t.exports.fastUri=de})),EA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=TA();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),DA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=dA();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});var r=fA(),i=pA(),a=tA(),o=mA(),s=$(),c=uA(),l=rA(),u=Zk(),d=(SA(),Me(hA).default),f=EA(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;var m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={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.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},v=200;function y(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??v,loopEnum:e.loopEnum??v,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var b=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...y(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ae(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,g,e,`NOT SUPPORTED`),x.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=re.call(this),e.formats&&te.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ne.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw 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 r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=ee.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=ee.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(oe.call(this,n,t),!t)return(0,u.eachItem)(n,e=>w.call(this,e)),this;T.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>w.call(this,e,r):e=>r.type.forEach(t=>w.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=le(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};b.ValidationError=r.default,b.MissingRefError=i.default,e.default=b;function x(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function ee(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){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 te(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ne(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 n=e[t];n.keyword||=t,this.addKeyword(n)}}function re(){let e={...this.opts};for(let t of m)delete e[t];return e}var ie={log(){},warn(){},error(){}};function ae(e){if(e===!1)return ie;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var C=/^[a-z_$][a-z0-9_$:-]*$/i;function oe(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!C.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function w(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?se.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function se(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function T(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=le(t)),e.validateSchema=this.compile(t,!0))}var ce={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function le(e){return{anyOf:[e,ce]}}})),OA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),kA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=pA(),n=aA(),r=$(),i=Qk(),a=mA(),o=Zk(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),AA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=OA(),n=kA();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),jA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),MA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),NA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),PA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk(),r=NA();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),FA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=aA(),n=Zk(),r=$();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),IA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),LA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=aA(),n=$(),r=Zk();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),RA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),zA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cA();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),BA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=rA(),n=$(),r=Zk(),i=zA();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),VA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk(),r=zA();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),HA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk(),r=zA();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),UA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=jA(),n=MA(),r=PA(),i=FA(),a=IA(),o=LA(),s=RA(),c=BA(),l=VA(),u=HA();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),WA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=$(),n=Zk(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),GA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=$(),n=Zk(),r=aA(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),KA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=GA();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),qA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk(),r=aA(),i=WA();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),JA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),YA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=$(),n=Zk(),r=aA();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
302
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),sA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=$k(),n=eA();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),cA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=$k(),n=eA(),r=tA(),i=eA();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),lA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=$k(),n=tA(),r=cA(),i=nA();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),uA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=$k(),n=eA();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),dA=E(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),fA=E(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.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 r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),pA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=eA(),n=dA(),r=fA(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),mA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=rA(),n=oA(),r=aA(),i=oA(),a=sA(),o=lA(),s=uA(),c=$k(),l=tA(),u=pA(),d=eA(),f=nA();function p(e){if(ee(e)&&(te(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&oe(e),ie(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ne(e),w(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(ee(e)&&(te(e),x(e))){S(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function ee(e){return typeof e.schema!=`boolean`}function S(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&oe(e),ae(e),C(e);let a=r.const(`_errs`,l.default.errors);ne(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function te(e){(0,d.checkUnknownRules)(e),re(e)}function ne(e,t){if(e.opts.jtd)return T(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);T(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function re(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ie(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function ae(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function C(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function oe({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function w(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&se(e),t.return((0,c._)`${l.default.errors} === 0`))}function se({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function T(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ve(e,`$ref`,h.all.$ref.definition));return}p.jtd||le(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ce(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ce(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ce(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ve(e,n.keyword,n.definition,t.type)})}function le(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ue(e,t),e.opts.allowUnionTypes||de(e,t),fe(e,e.dataTypes))}function ue(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{me(e.dataTypes,t)||ge(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),he(e,t)}}function de(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ge(e,`use allowUnionTypes to allow union type keyword`)}function fe(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>pe(t,e))&&ge(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function me(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function he(e,t){let n=[];for(let r of e.dataTypes)me(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ge(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var _e=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,xe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=_e;function ve(e,t,n,r){let i=new _e(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var ye=/^\/(?:[^~]|~0|~1)*$/,be=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ye.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=be.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=xe})),hA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),gA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=pA();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),_A=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=$k(),n=hA(),r=tA(),i=pA(),a=eA(),o=mA(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),vA=ke({$id:()=>yA,additionalProperties:()=>!1,default:()=>wA,description:()=>bA,properties:()=>CA,required:()=>SA,type:()=>xA}),yA,bA,xA,SA,CA,wA,TA=Oe((()=>{yA=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,bA=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,xA=`object`,SA=[`$data`],CA={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},wA={$id:yA,description:bA,type:xA,required:SA,properties:CA,additionalProperties:!1}})),EA=E(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=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),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(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&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function ee(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}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]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.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}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var S={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},te=/[@/?#:]/g,ne=/[@/?#]/g;function re(e,t){let n=t?ne:te;return n.lastIndex=0,e.replace(n,e=>S[e])}function ie(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ae(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function C(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function oe(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function w(e){return oe(e,l)}function se(e){return oe(e,c)}function T(e){return oe(e,c)}function ce(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 le(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function ue(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function de(e){let t=[];if(e.userinfo!==void 0&&(t.push(w(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=ie(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:re(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:de,reescapeHostDelimiters:re,normalizePercentEncoding:ie,normalizePathEncoding:ae,serializePathEncoding:C,normalizeQueryFragmentEncoding:le,encodeUserinfo:w,encodeQuery:se,encodeFragment:T,escapePreservingEscapes:ue,removeDotSegments:ee,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),DA=E(((e,t)=>{var{isUUID:n}=EA(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(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 s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(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(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),OA=E(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=EA(),{SCHEMES:m,getSchemeHandler:h}=DA(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=ce(e,t):typeof e==`object`&&(e=T(S(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=se(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=se(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),ee=y.host,te=ee!==void 0&&ee!==``&&(f(ee)||n(ee).isIPV6);w(y,r||{},b,te);let ne=ee&&ee.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(ee);if(y.error&&!ne)throw Error(y.error);return i.skipEscape=!0,S(y,i)}function x(e,t,n,i){let a={};return i||(e=T(S(e,n),n),t=T(S(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function ee(e,t,n){let r=ue(e,n),i=ue(t,n);return r!==void 0&&i!==void 0&&r===i}function S(e,t){let n={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:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var te=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ne=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,re=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function ie(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 ae(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 C(e){return e[0]===`[`&&e[e.length-1]===`]`}function oe(e){let t=e[4];return ae(e[3])||t!==void 0&&!C(t)&&ae(t)||ae(e[6])||ae(e[7])||ae(e[8])}function w(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!C(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function se(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(ne);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let ee=e.match(re);if(ee!==null){let e=ee[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let S=e.match(te);if(S){if(i.scheme=S[1],i.userinfo=S[3],i.host=S[4],i.port=parseInt(S[5],10),i.path=S[6]||``,i.query=S[7],i.fragment=S[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=oe(S),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=S[5]);let t=ie(i,S);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=C(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=w(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function T(e,t){return se(e,t).parsed}function ce(e,t){return le(e,t).normalized}function le(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=se(e,t);return{normalized:r||i||a||o||s?e:S(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function ue(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:S(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=le(n,t);return i||a||o||s||c?void 0:r}var de={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:ee,serialize:S,parse:T};t.exports=de,t.exports.default=de,t.exports.fastUri=de})),kA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=OA();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),AA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=mA();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$k();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});var r=hA(),i=gA(),a=iA(),o=_A(),s=$k(),c=pA(),l=oA(),u=eA(),d=(TA(),Me(vA).default),f=kA(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;var m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={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.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},v=200;function y(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??v,loopEnum:e.loopEnum??v,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var b=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...y(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ae(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,g,e,`NOT SUPPORTED`),x.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=re.call(this),e.formats&&te.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ne.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw 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 r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=ee.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=ee.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(oe.call(this,n,t),!t)return(0,u.eachItem)(n,e=>w.call(this,e)),this;T.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>w.call(this,e,r):e=>r.type.forEach(t=>w.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=le(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};b.ValidationError=r.default,b.MissingRefError=i.default,e.default=b;function x(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function ee(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){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 te(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ne(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 n=e[t];n.keyword||=t,this.addKeyword(n)}}function re(){let e={...this.opts};for(let t of m)delete e[t];return e}var ie={log(){},warn(){},error(){}};function ae(e){if(e===!1)return ie;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var C=/^[a-z_$][a-z0-9_$:-]*$/i;function oe(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!C.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function w(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?se.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function se(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function T(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=le(t)),e.validateSchema=this.compile(t,!0))}var ce={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function le(e){return{anyOf:[e,ce]}}})),jA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),MA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=gA(),n=cA(),r=$k(),i=tA(),a=_A(),o=eA(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),NA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=jA(),n=MA();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),PA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),FA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),IA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),LA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA(),r=IA();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),RA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cA(),n=eA(),r=$k();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),zA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),BA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cA(),n=$k(),r=eA();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),VA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),HA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=dA();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),UA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=oA(),n=$k(),r=eA(),i=HA();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),WA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA(),r=HA();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),GA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA(),r=HA();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),KA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=PA(),n=FA(),r=LA(),i=RA(),a=zA(),o=BA(),s=VA(),c=UA(),l=WA(),u=GA();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),qA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=$k(),n=eA(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),JA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=$k(),n=eA(),r=cA(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),YA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=JA();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),XA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA(),r=cA(),i=qA();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),ZA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),QA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=$k(),n=eA(),r=cA();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
303
303
  missingProperty: ${i},
304
304
  depsCount: ${n},
305
- deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),XA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),ZA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=aA(),n=$(),r=Qk(),i=Zk();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),QA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=dA(),n=aA(),r=Zk(),i=ZA();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),$A=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=aA(),n=$(),r=Zk(),i=Zk();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),ej=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Zk();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),tj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:aA().validateUnion,error:{message:`must match a schema in anyOf`}}})),nj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),rj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Zk();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),ij=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Zk(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),aj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Zk();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),oj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=WA(),n=KA(),r=GA(),i=qA(),a=JA(),o=YA(),s=XA(),c=ZA(),l=QA(),u=$A(),d=ej(),f=tj(),p=nj(),m=rj(),h=ij(),g=aj();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),sj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),cj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[sj().default]})),lj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),uj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=AA(),n=UA(),r=oj(),i=cj(),a=lj();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),dj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),fj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=dj(),r=mA(),i=pA(),a=Zk();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),pj=ke({$id:()=>hj,$schema:()=>mj,default:()=>bj,definitions:()=>_j,properties:()=>yj,title:()=>gj,type:()=>vj}),mj,hj,gj,_j,vj,yj,bj,xj=Oe((()=>{mj=`http://json-schema.org/draft-07/schema#`,hj=`http://json-schema.org/draft-07/schema#`,gj=`Core schema meta-schema`,_j={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:[]}},vj=[`object`,`boolean`],yj={$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:`#`}},bj={$schema:mj,$id:hj,title:gj,definitions:_j,type:vj,properties:yj,default:!0}})),Sj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=DA(),r=uj(),i=fj(),a=(xj(),Me(pj).default),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`,c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=dA();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=fA();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=pA();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Cj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:re,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:ee},int64:{type:`number`,validate:S},float:{type:`number`,validate:te},double:{type:`number`,validate:te},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function ee(e){return Number.isInteger(e)&&e<=x&&e>=b}function S(e){return Number.isInteger(e)}function te(){return!0}var ne=/[^\\]\\Z/;function re(e){if(ne.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),wj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=Sj(),n=$(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Tj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=Cj(),r=wj(),i=$(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),Ej=je(Sj(),1),Dj=je(Tj(),1);function Oj(){let e=new Ej.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Dj.default)(e),e}var kj=class{constructor(e){this._ajv=e??Oj()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Aj=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},mO,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},EO,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function jj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function Mj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var Nj=class extends Kk{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(tO.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new kj,this.setRequestHandler(RE,e=>this._oninitialize(e)),this.setNotificationHandler(VE,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(rO,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=tO.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Aj(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Jk(this._capabilities,e)}setRequestHandler(e,t){let n=JT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=eE(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=KT(QD,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=KT(ZE,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=KT(XD,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Mj(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&jj(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nE.includes(t)?t:tE,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},DE)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},hO,t):this.request({method:`sampling/createMessage`,params:e},mO,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},EO,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},EO,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},IO,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},Pj=Symbol.for(`mcp.completable`);function Fj(e){return!!e&&typeof e==`object`&&Pj in e}function Ij(e){return e[Pj]?.complete}var Lj;(function(e){e.Completable=`McpCompletable`})(Lj||={});var Rj=/^[A-Za-z0-9._-]{1,128}$/;function zj(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Rj.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Bj(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Vj(e){let t=zj(e);return Bj(e,t.warnings),t.isValid}var Hj=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Uj=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Nj(e,t)}get experimental(){return this._experimental||={tasks:new Hj(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Xj(JD)),this.server.assertCanSetRequestHandler(Xj(QD)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(JD,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=YT(t.inputSchema);return e?Uk(e,{strictUnions:!0,pipeStrategy:`input`}):Wj})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=YT(t.outputSchema);e&&(n.outputSchema=Uk(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(QD,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Q(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Q(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await qT(YT(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=ZT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await qT(YT(e.outputSchema),t.structuredContent);if(!r.success){let e=ZT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Q(Z.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Xj(AO)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(AO,async e=>{switch(e.params.ref.type){case`ref/prompt`:return jO(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return MO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Qj;let r=JT(n.argsSchema)?.[e.params.argument.name];if(!Fj(r))return Qj;let i=Ij(r);return i?Zj(await i(e.params.argument.value,e.params.context)):Qj}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Qj;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Zj(await r(e.params.argument.value,e.params.context)):Qj}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Xj(hD)),this.server.assertCanSetRequestHandler(Xj(_D)),this.server.assertCanSetRequestHandler(Xj(xD)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(hD,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(_D,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(xD,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Q(Z.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Xj(MD)),this.server.assertCanSetRequestHandler(Xj(FD)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(MD,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Yj(t.argsSchema):void 0}))})),this.server.setRequestHandler(FD,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await qT(YT(n.argsSchema),e.params.arguments);if(!r.success){let t=ZT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:GT(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=GT(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Fj(e instanceof ru?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Vj(e);let l={title:t,description:n,inputSchema:Jj(r),outputSchema:Jj(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Vj(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=GT(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=GT(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(qj(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!qj(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Wj={type:`object`,properties:{}};function Gj(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Kj(e){return`_def`in e||`_zod`in e||Gj(e)}function qj(e){return typeof e!=`object`||!e||Kj(e)?!1:Object.keys(e).length===0||Object.values(e).some(Gj)}function Jj(e){if(e){if(qj(e))return GT(e);if(!Kj(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Yj(e){let t=JT(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:QT(t),required:!$T(t)})):[]}function Xj(e){let t=JT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=eE(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Zj(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Qj={completion:{values:[],hasMore:!1}},$j=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
306
- `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),eM(t)}clear(){this._buffer=void 0}};function eM(e){return EE.parse(JSON.parse(e))}function tM(e){return JSON.stringify(e)+`
307
- `}var nM=class{constructor(e=le.stdin,t=le.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new $j({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=tM(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}},rM=JSON.parse(d(new URL(`../package.json`,import.meta.url),`utf8`));if(typeof rM!=`object`||!rM||!(`version`in rM)||typeof rM.version!=`string`||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(rM.version))throw Error(`The adjacent ai-delivery package identity must contain a stable version.`);var iM=rM.version,aM=[`Use these ai-delivery GitHub issue and pull request tools for ordinary requests, including "Use the ai-delivery MCP issue_info tool to read owner/name issue N".`,`Carry the repository named by the user into the repo argument (owner/name). Ordinary remote issue/PR tools work outside Git with an explicit repo; do not move into a checkout to read an issue.`,`In Claude Code, when bare and plugin-qualified ai-delivery tools coexist, discover the installed plugin provider and inspect its schema before calling. The observed plugin example is mcp__plugin_ai-delivery_ai-delivery__issue_info with {"repo":"example/widget","issueNumber":17}; use the requested repository and issue instead. This Claude namespace is not a universal tool name for other hosts.`,`A different issue_info accepting issueNumber/cached but no repo cannot receive that repository argument. Do not add unsupported fields or select a provider by name similarity alone. Honor an explicitly requested provider; if it is unavailable or incompatible, report that limitation rather than silently substituting.`,`Preserve read-only and MCP-only intent: do not create/update/start, use another GitHub provider or fall back to a CLI for such a read. Do not alter registrations, permissions, actors, credentials or host settings to make it work.`,`Retained local runtime, transition and investigation modes keep their separate checkout and authority requirements.`].join(`
308
- `);function oM(e,t){let n=new Uj({name:`ai-delivery`,version:iM},{instructions:aM}),r=nw;for(let i of r)n.registerTool(i.name,{description:i.description,inputSchema:i.inputSchema},async(n,r)=>{let a=i.inputSchema.safeParse(n);if(!a.success)return{content:[{type:`text`,text:`Invalid arguments for ${i.name}.`}],isError:!0};try{let n=e.signal===void 0?r.signal:AbortSignal.any([e.signal,r.signal]),o=uw(i.name,a.data,{...e,signal:n});t?.add(o);let s;try{s=await o}finally{t?.delete(o)}return{content:[{type:`text`,text:JSON.stringify(s)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}});return n}async function sM(e){y_(!0);let t=new AbortController,n=new Set,r=oM({...e,signal:t.signal},n),i,a=()=>(i??=(async()=>{t.abort(),await Promise.allSettled(n),await r.close(),process.exit(0)})(),i);process.once(`SIGINT`,()=>{a()}),process.once(`SIGTERM`,()=>{a()}),await r.connect(new nM),process.stderr.write(`ai-delivery MCP server started
309
- `),await new Promise(()=>{})}var cM=e=>/^(?:area|risk):[^\s:]+$/u.test(e),lM=cM,uM=P({number:j().int().positive(),body:A(),labels:N(A()),trackingParent:M().optional(),resolvedLegacyBlockers:N(P({number:j().int().positive(),state:I([`OPEN`,`CLOSED`])}).strict()).optional(),existingNative:P({blockedBy:N(P({number:j().int().positive(),state:I([`OPEN`,`CLOSED`])}).strict()),issueType:A().optional(),points:j().int().positive().optional(),priority:A().optional(),projectStatus:I([`Todo`,`In Progress`,`Blocked`,`Done`]).optional()}).strict().optional()}).strict();function dM(e){let t=P({issues:N(uM),repositoryLabels:N(A()).optional()}).strict().parse(e),n=t.issues.map(e=>e.number);if(new Set(n).size!==n.length)throw new D(`Legacy issue input repeats an issue number.`);return{mode:`dry-run`,plans:t.issues.map(e=>{let t=e.existingNative,n=t===void 0?void 0:{blockedBy:t.blockedBy,...t.issueType===void 0?{}:{issueType:t.issueType},...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority},...t.projectStatus===void 0?{}:{projectStatus:t.projectStatus}};return{number:e.number,...hM({body:e.body,labels:e.labels,...n===void 0?{}:{existingNative:n},...e.resolvedLegacyBlockers===void 0?{}:{resolvedLegacyBlockers:e.resolvedLegacyBlockers},...e.trackingParent===void 0?{}:{trackingParent:e.trackingParent}})}}),retiredRepositoryLabels:gM(t.repositoryLabels??[]),schemaVersion:`ai-delivery.legacy-issue-migration@1`,validated:0}}var fM=new Map([[`effort:l`,5],[`effort:m`,3],[`effort:medium`,3],[`effort:s`,2],[`effort:xl`,8],[`effort:xs`,1]]),pM=new Map([[`priority:high`,`P1`],[`priority:p0`,`P0`],[`priority:p1`,`P1`],[`priority:p2`,`P2`],[`priority:p3`,`P3`],[`priority:p4`,`P4`]]),mM=new Map([[`type:bug`,`Bug`],[`type:design`,`Task`],[`type:epic`,`Task`],[`type:feature`,`Feature`],[`type:spike`,`Task`],[`type:task`,`Task`],[`type:tracking`,`Task`]]);function hM(e){let t=[...new Set(e.labels.map(e=>e.trim()).filter(Boolean))],n=_M(e.body),r=xM(e.body,`executionContract`),i=xM(e.body,`dependencyDeclaration`),a=xM(e.body,`related`),o=yM([...e.existingNative?.blockedBy??[],...e.resolvedLegacyBlockers??[]]),s=CM({dependencyDeclaration:i,executionContract:r,related:a}),c=[...new Set([...o.keys(),...s])].sort((e,t)=>e-t),l=new Set(c.filter(e=>o.get(e)!==`CLOSED`));if(t.some(e=>e.toLowerCase()===`type:tracking`)&&e.trackingParent!==!0)throw new D(`Legacy type:tracking requires a native sub-issue relationship before its label can be retired.`);let u=e.trackingParent===!0,d=u?void 0:e.existingNative?.points??EM({...n.points===void 0?{}:{bodyPoint:n.points},executionContract:r,labels:t}),f=e.existingNative?.priority??DM({label:`priority`,labels:t,mapping:pM}),p=e.existingNative?.issueType??DM({label:`issue type`,labels:t,mapping:mM});if(e.existingNative?.projectStatus===`Done`)throw new D(`An open issue cannot retain Project Done during legacy migration.`);let m=TM({existing:e.existingNative?.projectStatus,labels:t,unresolvedBlockers:l}),h=t.filter(cM);h.sort();let g=t.filter(e=>!h.includes(e)).sort();return{body:SM(n.body),clearPoints:u&&e.existingNative?.points!==void 0,native:{blockedBy:c,...p===void 0?{}:{issueType:p},...d===void 0?{}:{points:d},...f===void 0?{}:{priority:f},projectStatus:m},retainedLabels:h,retiredLabels:g}}function gM(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))].filter(e=>!lM(e)).sort((e,t)=>e.localeCompare(t))}function _M(e){let t=e.split(/\r?\n/u),n=t.flatMap((e,t)=>e.trim().toLowerCase()===`## fibonacci points`?[t]:[]);if(n.length===0)return{body:e};if(n.length>1)throw new D(`Found duplicate legacy Fibonacci points sections.`);let r=n[0];if(r===void 0)return{body:e};let i=t.length;for(let e=r+1;e<t.length;e+=1)if(t[e]?.trimStart().startsWith(`## `)===!0){i=e;break}let a=t.slice(r+1,i).map(e=>e.trim()).filter(Boolean);if(a.length!==1||!/^(?:1|2|3|5|8|13)$/u.test(a[0]??``))throw new D(`Legacy Fibonacci points section must contain exactly one supported numeric value.`);return{body:[...t.slice(0,r),...t.slice(i)].join(`
310
- `),points:Number(a[0])}}function vM(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function yM(e){let t=new Map;for(let n of e){if(!vM(n.number))throw new D(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new D(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function bM(e){if(vM(e))return e;if(typeof e!=`string`)return;let t=/^#?([1-9]\d*)$/u.exec(e.trim()),n=t?.[1]===void 0?NaN:Number(t[1]);return vM(n)?n:void 0}function xM(e,t){let n=RegExp(`<!--\\s*${t}:\\s*([\\s\\S]*?)\\s*-->`,`u`).exec(e)?.[1];if(n!==void 0)try{let e=JSON.parse(n);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`not an object`);return e}catch{throw new D(`Invalid legacy ${t} payload.`)}}function SM(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function CM({dependencyDeclaration:e,executionContract:t,related:n}){let r=[],i=t?.dependencies;if(Array.isArray(i))for(let e of i){if(typeof e!=`object`||!e)continue;let t=e,n=bM(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...wM(e?.blockedBy)),r.push(...wM(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function wM(e){return Array.isArray(e)?e.map(bM).filter(e=>e!==void 0):[]}function TM(e){if(e.unresolvedBlockers.size>0)return`Blocked`;let t=e.labels.some(e=>[`status:in-progress`,`status:review`].includes(e.toLowerCase()));return e.existing===`In Progress`||t?`In Progress`:`Todo`}function EM(e){let t=[];for(let n of e.labels){let e=fM.get(n.toLowerCase());e!==void 0&&t.push(e);let r=/^points:(1|2|3|5|8|13)$/u.exec(n.toLowerCase());r?.[1]!==void 0&&t.push(Number(r[1]))}let n=e.executionContract?.effort;if(typeof n==`string`){let e=n.startsWith(`effort:`)?n:`effort:${n}`,r=fM.get(e.toLowerCase());r!==void 0&&t.push(r)}e.bodyPoint!==void 0&&t.push(e.bodyPoint);let r=[...new Set(t)];if(r.length>1)throw new D(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new D(`Issue has no canonical Fibonacci sizing value; assign native Points before migration.`);return i}function DM({label:e,labels:t,mapping:n}){let r=t.flatMap(e=>{let t=n.get(e.toLowerCase());return t===void 0?[]:[t]}),i=[...new Set(r)];if(i.length>1)throw new D(`Found conflicting legacy ${e} values.`);return i[0]}var OM=class{constructor(e){this._client=e}async*callToolStream(e,t=XD,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof Q){yield{type:`error`,error:e};return}yield{type:`error`,error:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function kM(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&kM(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&kM(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&kM(n,t)}}function AM(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var jM=class extends Kk{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new kj,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,$D,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,WD,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,CD,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new OM(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Jk(this._capabilities,e)}setRequestHandler(e,t){let n=JT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=eE(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=KT(CO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=AM(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new Q(Z.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new Q(Z.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=KT(ZE,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=KT(EO,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new Q(Z.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{kM(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=KT(pO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=KT(ZE,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=KT(i.tools||i.toolChoice?hO:mO,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:tE,capabilities:this._capabilities,clientInfo:this._clientInfo}},BE,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!nE.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){jj(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&Mj(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},DE,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},NO,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},DE,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},UD,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},ND,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},gD,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},vD,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},SD,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},DE,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},DE,t)}async callTool(e,t=XD,n){if(this.isToolTaskRequired(e.name))throw new Q(Z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},YD,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=eO.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},MM=E(((e,t)=>{t.exports=a,a.sync=o;var n=Ne(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,!n&&i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),NM=E(((e,t)=>{t.exports=r,r.sync=i;var n=Ne(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),PM=E(((e,t)=>{Ne(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?MM():NM();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),FM=E(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=Ne(`path`),i=n?`;`:`:`,a=PM(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o){if(t.all)u.push(e+s);else return i(e+s)}return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o<n.length;o++){let s=n[o],u=/^".*"$/.test(s)?s.slice(1,-1):s,d=r.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<i.length;e++){let n=f+i[e];try{if(a.sync(n,{pathExt:c})){if(t.all)l.push(n);else return n}}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw o(e)}})),IM=E(((e,t)=>{var n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),LM=E(((e,t)=>{var n=Ne(`path`),r=FM(),i=IM();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),RM=E(((e,t)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),zM=E(((e,t)=>{t.exports=/^#!(.*)/})),BM=E(((e,t)=>{var n=zM();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),VM=E(((e,t)=>{var n=Ne(`fs`),r=BM();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),HM=E(((e,t)=>{var n=Ne(`path`),r=LM(),i=RM(),a=VM(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),UM=E(((e,t)=>{var n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),WM=je(E(((e,t)=>{var n=Ne(`child_process`),r=HM(),i=UM();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))(),1),GM=le.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function KM(){let e={};for(let t of GM){let n=le.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var qM=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new $j({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new xe)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=(0,WM.default)(this._serverParams.command,this._serverParams.args??[],{env:{...KM(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:le.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=tM(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}};async function JM(e,t,n,r=3e4,i){let a=new AbortController,o=()=>a.abort();i?.addEventListener(`abort`,o,{once:!0}),i?.aborted&&o();let s=setTimeout(o,r),c=``,l=!1;try{let r=await Sb(e,t,a.signal,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:1048576},void 0,void 0,{starting:()=>{},observed:()=>{},idle:()=>{l=!0},assertQuiescent:()=>{}},{environment:n,cwd:e,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>{let t=e.toString(`utf8`).trimEnd().split(/\r?\n/u).at(-1);return[`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`,`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`,`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(t??``)&&(c=t),` Authentication probe failed; raw output withheld.`}});return{failed:!l,stdout:l?r.toString(`utf8`):``,diagnostic:c,cleanupConfirmed:l}}catch{return{failed:!0,stdout:``,diagnostic:c,cleanupConfirmed:l}}finally{clearTimeout(s),i?.removeEventListener(`abort`,o)}}var YM=A().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),XM=F({action:I([`install`,`doctor`,`preview`,`update`,`rollback`,`remove`]),host:I([`codex`,`claude-code`]),scope:I([`user`,`project`,`local`]),version:YM.optional(),dryRun:M().default(!1),checkAuth:M().default(!1),repo:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),repoRoot:A().min(1)}),ZM=F({pid:j().int().positive(),birth:A().min(1)}),QM=F({action:XM.shape.action,targetVersion:YM.nullable(),owner:ZM,producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),staging:F({path:A(),device:j().int().nonnegative().optional(),inode:j().int().nonnegative().optional()}).optional(),command:Kl(`phase`,[F({phase:L(`idle`)}),F({phase:L(`starting`)}),F({phase:L(`running`),process:ZM,tracked:N(ZM.extend({pgid:j().int().positive()})).max(256)})])}),$M=F({owner:L(`@aviaratech/ai-delivery.plugin@1`),host:XM.shape.host,scope:XM.shape.scope,projectRoot:A().nullable(),nativeHome:A().min(1),marketplace:A(),currentVersion:YM.nullable(),previousVersion:YM.nullable(),installedPath:A().nullable(),nativeVersion:A().optional(),pending:QM.optional()}),eN=F({owner:L(`@aviaratech/ai-delivery.plugin-version@1`),version:YM,archiveSha256:A().regex(/^[a-f0-9]{64}$/u),files:Ql(A(),A().regex(/^[a-f0-9]{64}$/u))}),tN=e=>pe(`sha256`).update(e).digest(`hex`);function nN(e,t){let o={completeness:`incomplete`,registrations:[],nativeInventory:`not_checked`,plannedChanges:[],migration:`refused`,findings:[`native_session_scope_unverified`,`settings_preservation_unproved`,`native_writer_exclusion_unproved`]},s=e=>{let t;try{if(sN(e),!i(e))return;let n=c(e);if(!n.isFile()||n.nlink!==1||n.size>1048576)throw Error(`Unsafe configuration`);t=u(e,r.O_RDONLY|r.O_NOFOLLOW|r.O_NONBLOCK);let o=a(t);if(!o.isFile()||o.nlink!==1||o.size>1048576)throw Error(`Unsafe configuration`);let s=Buffer.alloc(1048577),l=0;for(;l<s.length;){let e=f(t,s,l,s.length-l,null);if(e===0)break;l+=e}if(l>1048576)throw Error(`Configuration exceeded read limit`);return s.subarray(0,l).toString(`utf8`)}catch{o.findings.push(`configuration_unavailable`);return}finally{t!==void 0&&n(t)}},l=e=>{let t=s(e);if(t!==void 0)try{let e=JSON.parse(t);return Ql(A(),Ll()).parse(e)}catch{o.findings.push(`configuration_unavailable`);return}},d=(e,t)=>{if(typeof t!=`object`||!t||Array.isArray(t)){t!==void 0&&o.findings.push(`configuration_unavailable`);return}Object.entries(t).some(([e,t])=>{if(e===`ai-delivery`)return!0;if(typeof t!=`object`||!t)return!1;let n=t;return n.command===`ai-delivery`||Array.isArray(n.args)&&n.args.some(e=>typeof e==`string`&&e.includes(`@aviaratech/ai-delivery`))})&&o.registrations.push({kind:`standalone`,scope:e,ownership:`unknown`,source:`unknown`,version:null,enabled:null})};if(e.host===`claude-code`){if(process.env.CLAUDE_CONFIG_DIR)o.findings.push(`custom_profile_configuration_unverified`);else{let e=l(w(h(fe()),`.claude.json`)),n=e?.projects;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n[t.projectRoot];typeof e==`object`&&e&&d(`local`,e.mcpServers)}d(`user`,e?.mcpServers)}let e=l(w(t.projectRoot,`.mcp.json`))?.mcpServers,n=o.registrations.findIndex(e=>e.scope===`user`);if(d(`project`,e),n!==-1&&o.registrations.at(-1)?.scope===`project`){let e=o.registrations.pop();o.registrations.splice(n,0,e)}}else for(let[e,n]of[[`project`,w(t.projectRoot,`.codex/config.toml`)],[`user`,w(t.nativeHome,`config.toml`)]]){if(e===`project`&&n===w(t.nativeHome,`config.toml`))continue;let r=s(n);r!==void 0&&(o.findings.push(`codex_configuration_not_fully_resolved`),/^\s*\[\s*mcp_servers\.(?:"ai-delivery"|'ai-delivery'|ai-delivery)\s*\]/mu.test(r)&&d(e,{"ai-delivery":{}}))}return o.findings=[...new Set(o.findings)],o}function rN(e,t,n,r,i){let a=e.diagnostics;a.nativeInventory=`observed`;let o=0;for(let s of r){let r=s.pluginId??s.id;if(!(s.name===`ai-delivery`||typeof r==`string`&&r.startsWith(`ai-delivery@`))||t.host===`codex`&&s.installed!==!0)continue;if(t.host===`claude-code`&&(s.scope===`project`||s.scope===`local`)){if(typeof s.projectPath==`string`&&s.projectPath!==n.projectRoot)continue;typeof s.projectPath!=`string`&&a.findings.push(`native_registration_project_unverified`)}if(++o>256){a.findings.push(`native_inventory_truncated`);break}let c=e.sourceIntegrity===!0&&s===i,l=YM.safeParse(s.version),u=t.host===`codex`?`user`:s.scope===`user`||s.scope===`project`||s.scope===`local`?s.scope:`unknown`;a.registrations.push({kind:`plugin`,scope:u,ownership:c?`managed`:`external`,source:c?`managed_archive`:`unknown`,version:l.success?l.data:null,enabled:typeof s.enabled==`boolean`?s.enabled:null})}}function iN(){let e={PATH:process.env.PATH??``,DISABLE_AUTOUPDATER:`1`};for(let t of[`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`])process.env[t]!==void 0&&(e[t]=process.env[t]);return e}var aN=P({routing:P({repository:XM.shape.repo.unwrap()}),reviewRoute:P({author:P({actorLogin:A().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),authSource:I([`app`,`personal`]),credentialSource:A().optional(),identity:A()}),reviewer:P({actorLogin:A().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),identity:A(),repositoryAccess:L(`readable`)}),rules:P({visibility:I([`complete`,`partial`,`unknown`]),observedRequiredApprovals:j().int().nonnegative().nullable()}),approvalEligibility:I([`unknown`,`insufficient-permission`])})});async function oN(e,t,n){let r;try{r=await Kh(),n.settings=`valid`}catch{n.settings=`unavailable_or_invalid`,n.outcome=`blocked`,n.reason=`settings_unavailable_or_invalid`;return}let i=Object.values(r.roles).flatMap(e=>Object.values(e.credentialEnv)),a=r.roles.author,o=a.authSource===`personal`&&nh(a.credentialEnv.token,process.env),s=o?i.filter(e=>e!==`GH_TOKEN`):i;n.processReferences.requiredNames=s;let c=s.filter(e=>!process.env[e]?.trim());if(n.processReferences.missingNames=c,c.length>0){n.processReferences.status=`missing`,n.outcome=`blocked`,n.reason=`missing_references`;return}if(i.some(e=>/^(?:NODE_|NPM_|GIT_)/u.test(e)||[...rh,`PATH`,`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`,`AI_DELIVERY_CONFIG`,`AI_DELIVERY_IDENTITY`,`DISABLE_AUTOUPDATER`].includes(e))){n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}let l={PATH:process.env.PATH??``,AI_DELIVERY_CONFIG:r.configPath,NODE_OPTIONS:`--max-old-space-size=512 --v8-pool-size=1`,DISABLE_AUTOUPDATER:`1`};for(let e of i)process.env[e]!==void 0&&(l[e]=process.env[e].trim());if(o)for(let e of rh)process.env[e]!==void 0&&(l[e]=process.env[e]);try{a.authSource===`personal`&&th(process.env);for(let e of[`author`,`reviewer`])r.roles[e].authSource!==`personal`&&Jh({config:r,role:e,env:l})}catch{n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}n.processReferences.status=`complete`;let u=await JM(e.repoRoot,[process.execPath,w(t,`runtime/dist/cli.js`),`--repo`,e.repo,`config:resolve`],l);if(!u.cleanupConfirmed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.reason=`probe_cleanup_unverified`;return}if(u.failed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`;let e=u.diagnostic;e===`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`||e===`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`?(n.authentication.status=`failed`,n.reason=`authentication_failed`):[`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(e??``)?(n.repositoryAccess.status=`denied`,n.reason=`repository_denied`):n.reason=`probe_failed`;return}try{let t=aN.parse(JSON.parse(u.stdout)),a=t.reviewRoute;if(t.routing.repository.toLowerCase()!==e.repo.toLowerCase()||a.author.authSource!==(r.roles.author.authSource??`app`)||a.author.identity!==r.roles.author.identity||a.reviewer.identity!==r.roles.reviewer.identity||a.author.actorLogin.toLowerCase()===a.reviewer.actorLogin.toLowerCase())throw Error(`Inconsistent readback`);let s={author:{actorLogin:a.author.actorLogin,authSource:a.author.authSource,...o&&a.author.credentialSource!==void 0?{credentialSource:a.author.credentialSource}:{}},reviewer:{actorLogin:a.reviewer.actorLogin,authSource:`app`}};if(o&&!a.author.credentialSource?.startsWith(`gh:github.com:`))throw Error(`Missing session route`);if(i.some(e=>l[e]!==void 0&&JSON.stringify(s).includes(l[e])))throw Error(`Unsafe readback`);n.authentication={status:`verified`,...s},n.repositoryAccess.status=`verified`,n.reviewRules={...a.rules,approvalEligibility:a.approvalEligibility},n.outcome=`readback_complete`}catch{n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.outcome=`failed`,n.reason=`invalid_readback`}}function sN(e){let t=T(e);for(;;){if(i(t)&&c(t).isSymbolicLink())throw Error(`Managed plugin paths must not use symlinks.`);let e=C(t);if(e===t)break;t=e}}function cN(e){let t=h(T(e.repoRoot)),n=T(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??w(fe(),e.host===`codex`?`.codex`:`.claude`)),r=[];for(;!i(n);)r.unshift(ie(n)),n=C(n);let a=w(h(n),...r),o=e.scope===`user`?`user`:`${e.scope}-${pe(`sha256`).update(t).digest(`hex`).slice(0,16)}`,s=w(fe(),`.cache`,`ai-delivery`,`plugins`,e.host,o);if(sN(s),i(s)&&(!c(s).isDirectory()||c(s).mode&63))throw Error(`Managed plugin directory is not private.`);return{directory:s,projectRoot:t,nativeHome:a,marketplace:`ai-delivery-${o}`,catalog:w(s,`marketplace`),statePath:w(s,`state.json`),tool:e.host===`codex`?`codex`:`claude`}}function lN(e,t){if(!i(t.statePath))return;let n=c(t.statePath);if(!n.isFile()||n.nlink!==1||n.mode&63||n.size>65536)throw Error(`Managed plugin state is unsafe.`);let r=$M.parse(JSON.parse(d(t.statePath,`utf8`)));if(r.nativeHome!==t.nativeHome)throw Error(`Managed plugin state belongs to a different native profile.`);if(r.host!==e.host||r.scope!==e.scope||r.marketplace!==t.marketplace||r.projectRoot!==(e.scope===`user`?null:t.projectRoot))throw Error(`Managed plugin state belongs to a different target.`);return r}function uN(e){let t=nb().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function dN(e){if(uN(e.owner.pid)===e.owner.birth)throw Error(`A live plugin installer still owns this target.`);if(e.command.phase===`starting`)throw Error(`Interrupted installer command ownership is unknown; preserve its state before recovery.`);if(e.command.phase!==`running`)return;let t={rootPid:e.command.process.pid,rootIdentity:e.command.process.birth,sampled:!0,tracked:new Map(e.command.tracked.map(({pid:e,birth:t,pgid:n})=>[e,{pid:e,identity:t,pgid:n,ppid:0,rssBytes:0,status:``}]))};sb(t),await ob(t)}async function fN(e,t,n,r,i,a=!1){return(await Sb(n,[e,...t],r,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2},void 0,void 0,{starting:()=>i?.({phase:`starting`}),observed:e=>i?.({phase:`running`,process:{pid:e.rootPid,birth:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,birth:t,pgid:n}))}),idle:()=>i?.({phase:`idle`}),assertQuiescent:()=>{}},{environment:a?iN():{...process.env,DISABLE_AUTOUPDATER:`1`},cwd:n,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>a?` Native inventory failed; raw output withheld.`:` Native command output: ${e.toString(`utf8`).slice(-2e3)}`})).toString(`utf8`)}function pN(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function mN(e,t){return w(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function hN(e,t){return w(e.catalog,`versions`,t)}function gN(e){let t={},n=0,r=(e,i,a)=>{if(a>16)throw Error(`Plugin tree exceeds the depth bound.`);for(let o of p(e).sort()){if(++n>4096)throw Error(`Plugin tree exceeds the entry bound.`);let s=w(e,o),l=`${i}${o}`,u=c(s);if(u.isSymbolicLink()||!u.isDirectory()&&(!u.isFile()||u.nlink!==1))throw Error(`Plugin tree contains links or special files.`);if(u.isDirectory())r(s,`${l}/`,a+1);else{if(u.size>32*1024**2)throw Error(`Plugin file exceeds the size bound.`);t[l]=tN(d(s))}}};return r(e,``,0),t}function _N(e,t){let n=hN(e,t);sN(n);let r=w(n,`version.json`);if(!i(r))throw Error(`No completed immutable plugin unit for ${t}.`);let a=c(r),o=w(n,`archive.tgz`),s=c(o);if(!a.isFile()||a.nlink!==1||a.size>1048576||!s.isFile()||s.nlink!==1||s.size>32*1024**2)throw Error(`Immutable plugin unit metadata is unsafe.`);let l=eN.parse(JSON.parse(d(r,`utf8`)));if(l.version!==t||JSON.stringify(gN(mN(e,t)))!==JSON.stringify(l.files)||tN(d(o))!==l.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return l}function vN(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=ye(e,{maxOutputLength:128*1024**2}),n=new Map;for(let e=0;e+512<=t.length;){let r=t.subarray(e,e+512);if(r.every(e=>e===0))break;let i=(e,t)=>r.subarray(e,e+t).toString().replace(/\0.*$/su,``).trim(),a=(e,t)=>{let n=i(e,t);if(!/^[0-7]+$/u.test(n))throw Error(`Unsupported tar numeric header.`);return Number.parseInt(n,8)};if([...r].reduce((e,t,n)=>e+(n>=148&&n<156?32:t),0)!==a(148,8))throw Error(`Plugin archive header checksum mismatch.`);let o=`${i(345,155)?`${i(345,155)}/`:``}${i(0,100)}`,s=a(124,12),c=i(156,1);if(!/^package\/[A-Za-z0-9_./-]+$/u.test(o)||o.split(`/`).some(e=>e===`..`||e===`.`)||o.split(`/`).length>16||![``,`0`,`5`].includes(c)||e+512+s>t.length||n.has(o)||n.size>=4096)throw Error(`Unsafe or unsupported plugin archive member.`);c!==`5`&&n.set(o,t.subarray(e+512,e+512+s)),e+=512+Math.ceil(s/512)*512}return n}async function yN(e,t,n,r,a){let o=hN(e,t);if(i(o)){_N(e,t);return}let s=C(o);Qv(s);let u=w(s,`.stage-${he()}`);a({path:u}),l(u,{mode:448});let f=c(u);pN(s),a({path:u,device:f.dev,inode:f.ino});let p=!0,m=!1,h,v=e=>{p=e.phase===`idle`,r(e)};try{let r=JSON.parse(await fN(`npm`,[`pack`,`@aviaratech/ai-delivery@${t}`,`--ignore-scripts`,`--json`,`--logs-max`,`0`,`--cache`,w(e.directory,`npm-cache`),`--pack-destination`,u],u,n,v))[0]?.filename;if(typeof r!=`string`||!/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(r))throw Error(`npm returned an unsafe archive path.`);let i=d(w(u,r)),c=vN(i),l=JSON.parse(c.get(`package/package.json`)?.toString()??`null`);if(l?.name!==`@aviaratech/ai-delivery`||l.version!==t)throw Error(`Archive package identity does not match the explicit version.`);let f=w(u,`plugins`,`ai-delivery`);for(let[e,t]of c)if(e.startsWith(`package/plugins/ai-delivery/`)){let n=w(f,e.slice(28));Qv(C(n)),ee(n,t,{mode:384,flag:`wx`}),pN(n)}let p=JSON.parse(d(w(f,`plugin.json`),`utf8`)),m=JSON.parse(d(w(f,`.claude-plugin/plugin.json`),`utf8`)),h=JSON.parse(d(w(f,`runtime/package.json`),`utf8`));if(p.name!==`ai-delivery`||p.version!==t||m.name!==p.name||m.version!==t||m.packageVersion!==t||m.deliveryCapabilityVersion!==2||h.name!==l.name||h.version!==t)throw Error(`Archive does not contain a coherent self-contained native plugin.`);if((await fN(process.execPath,[w(f,`runtime/dist/cli.js`),`--version`],u,n,v)).trim()!==t)throw Error(`Built native CLI version does not match its archive.`);g(w(u,r),w(u,`archive.tgz`)),pN(w(u,`archive.tgz`)),ey(w(u,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:tN(i),files:gN(f)}),g(u,o),pN(s),a(void 0),_N(e,t)}catch(e){m=!0,h=e}try{if(p&&i(u)){let e=c(u);if(e.dev!==f.dev||e.ino!==f.ino||!e.isDirectory()||e.isSymbolicLink())throw Error(`Owned staging directory identity changed.`);_(u,{recursive:!0}),pN(s)}p&&a(void 0)}catch(e){h=m?AggregateError([h,e],`Plugin preparation failed and staging cleanup also failed.`):e,m=!0}if(m)throw h}function bN(e,t){let n=`./versions/${t}/plugins/ai-delivery`;return[{path:w(e.catalog,`.agents/plugins/marketplace.json`),value:{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}},{path:w(e.catalog,`.claude-plugin/marketplace.json`),value:{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]}}]}function xN(e,t){return bN(e,t).map(({path:e})=>{sN(e);let t=c(e);if(!t.isFile()||t.nlink!==1||(t.mode&511)!=384||t.size>1024**2)throw Error(`Managed catalog is unsafe.`);return{path:e,bytes:d(e),device:t.dev,inode:t.ino}})}function SN(e,t,n){return bN(t,n).map(({value:t},n)=>JSON.stringify(JSON.parse(e[n].bytes.toString()))===JSON.stringify(t))}function CN(e){sN(e.path);let t=c(e.path);if(!t.isFile()||t.nlink!==1||(t.mode&511)!=384||t.size!==e.bytes.length||t.dev!==e.device||t.ino!==e.inode||!d(e.path).equals(e.bytes))throw Error(`Managed catalog changed during this operation.`)}function wN(e,t,n){_N(e,t);for(let[r,i]of bN(e,t).entries())n&&CN(n[r]),ey(i.path,i.value)}async function TN(e,t,n,r,i=!1){let a=JSON.parse(await fN(t.tool,[`plugin`,`list`,...e.host===`codex`&&!i?[`--marketplace`,t.marketplace,`--available`]:[],`--json`],t.projectRoot,n,r,e.action===`doctor`));if(e.host===`claude-code`)return N(Ql(A(),Ll())).parse(a);let o=P({installed:N(Ql(A(),Ll())),available:N(Ql(A(),Ll()))}).parse(a);return[...o.installed.map(e=>({...e,installed:!0})),...o.available.map(e=>({...e,installed:!1}))]}function EN(e,t,n){if(e.host===`claude-code`){let e=w(t.nativeHome,`plugins/known_marketplaces.json`);if(!i(e))return!1;if(!c(e).isFile()||c(e).size>1048576)throw Error(`Native marketplace registry is unsafe.`);let n=Ql(A(),Ll()).parse(JSON.parse(d(e,`utf8`)));if(n[t.marketplace]===void 0)return!1;let r=P({source:P({source:L(`directory`),path:A()}),installLocation:A()}).parse(n[t.marketplace]);if(T(r.source.path)!==t.catalog||T(r.installLocation)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`);return!0}let r=n.filter(e=>e.marketplaceName===t.marketplace);for(let e of r){let n=P({sourceType:L(`local`),source:A()}).parse(e.marketplaceSource);if(T(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return r.length>0}function DN(e,t,n){let r=n.filter(n=>(n.pluginId??n.id)===`ai-delivery@${t.marketplace}`&&(e.host===`codex`?n.installed===!0:n.scope===e.scope)&&(e.scope===`user`||n.projectPath===t.projectRoot));if(r.length>1)throw Error(`Native plugin readback is ambiguous.`);let i=r[0];if(!i)return;let a=e.host===`codex`?P({source:L(`local`),path:A()}).parse(i.source).path:void 0;return{registration:i,version:YM.parse(i.version),enabled:M().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Ql(A(),Ll()).parse(i.mcpServers)}:{}}}function ON(e){let t=w(e.catalog,`.claude-plugin/marketplace.json`);if(sN(t),!c(t).isFile()||c(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=P({name:L(e.marketplace),plugins:N(P({name:A(),version:YM,source:A()}))}).parse(JSON.parse(d(t,`utf8`))).plugins.filter(e=>e.name===`ai-delivery`);if(n.length!==1)throw Error(`Managed Claude catalog selection is ambiguous.`);let r=n[0];if(!r.source.startsWith(`./`)||T(e.catalog,r.source)!==mN(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function kN(e,t,n,r,i=n.version){let a=_N(t,n.version),o=mN(t,i);if(i!==n.version&&_N(t,i),e.host===`claude-code`&&ON(t).version!==i)throw Error(`Claude catalog version differs from its native selection.`);if(e.host===`codex`&&T(n.sourceRoot)!==o)throw Error(`Native plugin source differs from the managed version.`);let s=r;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`claude-code`&&(n.installedPath===void 0||T(n.installedPath)!==T(s)))throw Error(`Native cache path differs from the managed native selection.`);if(T(s)!==w(t.nativeHome,`plugins/cache`,t.marketplace,`ai-delivery`,n.version))throw Error(`Native cache path is outside the managed native selection.`);if(sN(s),JSON.stringify(gN(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!P({command:L(`node`),args:Xl([L("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function AN(e,t,n){let r=new qM({command:process.execPath,args:[w(e,`dist/mcp-launcher.js`)],cwd:n,env:{...Object.fromEntries(GM.map(e=>[e,``])),NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new jM({name:`ai-delivery-plugin-doctor`,version:`1.0.0`});try{if(await i.connect(r,{timeout:3e4}),i.getServerVersion()?.version!==t)throw Error(`MCP server version differs from the selected archive.`);return await i.listTools({},{timeout:3e4}),{configuration:`native_manifest_present`,startup:`ready`,version:t}}catch{return{configuration:`native_manifest_present`,startup:`failed`,error:`Bundled MCP startup failed; raw output withheld.`}}finally{await i.close(),await r.close()}}async function jN(e){let t=XM.parse(e);if(t.checkAuth&&t.action!==`doctor`)throw Error(`--check-auth is supported only for doctor.`);if(t.checkAuth&&t.repo===void 0)throw Error(`doctor --check-auth requires explicit --repo owner/name.`);if(t.host===`codex`&&t.scope!==`user`)throw Error(`Codex currently supports user plugin installation; select --scope user.`);if((t.action===`install`||t.action===`update`)&&t.version===void 0)throw Error(`An explicit --version is required for install and update.`);if(t.version!==void 0&&t.action!==`install`&&t.action!==`update`)throw Error(`--version is supported only for install and update; rollback selects the recorded previous version.`);if(![`darwin`,`linux`].includes(process.platform))throw Error(`Plugin management requires the supported POSIX runtime environment.`);let n=cN(t),r=lN(t,n),a={action:t.action,host:t.host,scope:t.scope,version:t.action===`remove`?null:t.version??(t.action===`rollback`?r?.previousVersion:r?.currentVersion)??null,changed:!1,dryRun:t.dryRun,installed:!1,marketplace:n.marketplace,managedDirectory:n.directory,repositoryAdmission:`explicit_stage_and_admit_required`};if(t.checkAuth&&(a.authProbe={invocationContext:`selected_runtime_cli`,nativeGuiPropagation:`unverified`,settings:`not_checked`,processReferences:{status:`not_checked`,requiredNames:[],missingNames:[]},authentication:{status:`not_checked`},repositoryAccess:{repository:t.repo,status:`not_checked`},outcome:t.dryRun?`not_checked`:`blocked`,reason:t.dryRun?`dry_run`:`native_plugin_not_ready`}),t.dryRun||(a.diagnostics=nN(t,n),a.activation={installedVersion:null,startupVersion:null,loadedVersion:null},t.action===`preview`))return a;if(t.action===`doctor`){if(r&&(a.recoveryRequired=r.pending!==void 0),r?.pending)return a;if(!r?.currentVersion){try{rN(a,t,n,await TN(t,n,new AbortController().signal,void 0,!0))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a}try{_N(n,r.currentVersion)}catch{return a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:`Managed archive integrity failed.`},a}let e=await TN(t,n,new AbortController().signal),i=EN(t,n,e),o=DN(t,n,e);if(a.installed=o?.version===r.currentVersion,a.enabled=o?.enabled??!1,r.installedPath&&(a.nativeCachePath=r.installedPath),r.nativeVersion&&(a.nativeVersion=r.nativeVersion),!i||!a.installed){a.mcp={configuration:`missing`,startup:`not_checked`};try{rN(a,t,n,await TN(t,n,new AbortController().signal,void 0,!0))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a}a.activation.installedVersion=r.currentVersion;try{a.nativePluginRoot=kN(t,n,o,r.installedPath),a.sourceIntegrity=!0,a.skills=p(w(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await AN(a.nativePluginRoot,r.currentVersion,n.projectRoot):{configuration:`disabled`,startup:`not_checked`}}catch(e){a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:t.checkAuth?`Selected native plugin integrity failed; raw output withheld.`:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}if(rN(a,t,n,e,o.registration),t.host===`codex`)try{let r=await TN(t,n,new AbortController().signal,void 0,!0),i=new Set(e.flatMap(e=>typeof e.pluginId==`string`?[e.pluginId]:[]));rN(a,t,n,r.filter(e=>typeof e.pluginId!=`string`||!i.has(e.pluginId)))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a.mcp?.startup===`ready`&&(a.activation.startupVersion=a.mcp.version??null),a.authProbe&&a.sourceIntegrity&&a.enabled&&a.mcp?.startup===`ready`&&(delete a.authProbe.reason,await oN(t,a.nativePluginRoot,a.authProbe)),a}if(!r&&t.action===`remove`)return a;if(!r&&i(n.directory)&&p(n.directory).length>0)throw Error(`Managed plugin directory contains unrecognized content.`);return Qv(n.directory),Oy(n.statePath,{projectRoot:n.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{if(r=lN(t,n),t.action===`rollback`){if(!r?.currentVersion)throw Error(`Preserving rollback requires a current managed selection; it cannot reinstall a removed plugin.`);if(r.previousVersion!==a.version)throw Error(`Managed rollback target changed before acquiring its ownership lock.`)}let e=i(n.statePath)?{bytes:d(n.statePath),metadata:c(n.statePath)}:void 0,o=()=>{if(sN(n.statePath),e){lN(t,n);let r=c(n.statePath);if(r.dev!==e.metadata.dev||r.ino!==e.metadata.ino||(r.mode&511)!=384||r.mode!==e.metadata.mode||!d(n.statePath).equals(e.bytes))throw Error(`Managed state changed during this operation.`)}else if(i(n.statePath))throw Error(`Managed state appeared during this operation.`);ey(n.statePath,r),e={bytes:d(n.statePath),metadata:c(n.statePath)}},s=r?.pending!==void 0;if(r?.pending){if(await dN(r.pending),r.pending.producerDigest!==_b(C(be(import.meta.url))))throw Error(`Interrupted plugin operation belongs to a different controller; resume with its original version.`);let e=r.pending.staging;if(e&&i(e.path)){let t=C(hN(n,r.pending.targetVersion));if(C(e.path)!==t||!/^\.stage-[a-f0-9-]{36}$/u.test(e.path.slice(t.length+1)))throw Error(`Recorded staging path is outside this version target.`);sN(e.path);let i=c(e.path);if(!i.isDirectory()||(e.device===void 0?p(e.path).length!==0:i.dev!==e.device||i.ino!==e.inode))throw Error(`Interrupted staging directory ownership is unresolved.`);_(e.path,{recursive:!0}),pN(t)}if(r.pending.action!==t.action||r.pending.targetVersion!==a.version)throw Error(`Resume the interrupted original plugin command before selecting a different operation.`)}if(t.action===`update`&&!r?.currentVersion)throw Error(`Install a managed plugin before updating or rolling it back.`);let l=t.action===`remove`?null:a.version;if(l===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let u=r?.currentVersion??null;r??={owner:`@aviaratech/ai-delivery.plugin@1`,host:t.host,scope:t.scope,projectRoot:t.scope===`user`?null:n.projectRoot,nativeHome:n.nativeHome,marketplace:n.marketplace,currentVersion:null,previousVersion:null,installedPath:null};let f=uN(process.pid);if(!f)throw Error(`Installer owner identity is unknown.`);r.pending={action:t.action,targetVersion:l,owner:{pid:process.pid,birth:f},producerDigest:_b(C(be(import.meta.url))),command:{phase:`idle`}},o();let m=new AbortController,h=()=>m.abort();process.once(`SIGINT`,h),process.once(`SIGTERM`,h);let g=e=>{r.pending.command=e,o()},v=e=>fN(n.tool,e,n.projectRoot,m.signal,g),y=`ai-delivery@${n.marketplace}`,b=t.host===`codex`?[`plugin`,`remove`,y,`--json`]:[`plugin`,`uninstall`,y,`--scope`,t.scope,`--keep-data`],x=t.host===`codex`?[`plugin`,`add`,y,`--json`]:[`plugin`,u?`update`:`install`,y,`--scope`,t.scope],ee=!1;try{if(r.nativeVersion=(await v([`--version`])).trim(),u&&l){if(t.host===`claude-code`){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;if(r.nativeVersion!==`2.1.296 (Claude Code)`||t.scope!==`user`||!e.test(u)||!e.test(l)||(l.split(`.`).map(BigInt).map((e,t)=>e-BigInt(u.split(`.`)[t])).find(e=>e!==0n)??0n)<0n)throw Error(`Claude preserving replacement is unqualified; no catalog or native selection was changed.`)}if(t.host===`codex`&&r.nativeVersion!==`codex-cli 0.162.1`)throw Error(`This native version has no qualified preserving replacement route.`)}if(t.host===`claude-code`&&!(await v([`plugin`,`uninstall`,`--help`])).includes(`--keep-data`))throw Error(`This Claude Code version cannot preserve plugin data; upgrade the native tool first.`);process.stderr.write(`ai-delivery.plugin ${JSON.stringify({action:t.action,host:t.host,scope:t.scope,stage:l?`prepare_version`:`native_remove`,version:l})}\n`);let e=await TN(t,n,m.signal,g),i=EN(t,n,e),c=DN(t,n,e);if(c&&!u&&!(s&&c.version===l))throw Error(`Existing native plugin is not owned by managed state.`);let d=c?.version;if(c&&s&&t.host===`claude-code`&&(d=ON(n).version,d!==u&&d!==l))throw Error(`Interrupted native selection has an incompatible catalog version.`);if(c&&l&&!c.enabled)throw Error(`Native plugin selection is disabled; preserving replacement cannot enable it.`);let f,p=!1;if(u&&l){if(!i||!c||c.version!==u&&!(s&&c.version===l))throw Error(`Managed native selection changed; replacement ownership is unresolved.`);f=xN(n,u);let e=SN(f,n,u),r=SN(f,n,l),a=e.every(Boolean),o=r.every(Boolean),m=s&&r[0]&&e[1];if(!a&&!o&&!m)throw Error(`Managed catalog differs from the owned prior or target publication.`);if(d=r[t.host===`codex`?0:1]?l:u,c.version===l){if(!o)throw Error(`Selected target has an incompatible managed catalog.`);p=!0}else if(o)throw Error(`Interrupted replacement is ambiguous; native selection will not be repeated.`)}else if(l&&c&&s){if(f=xN(n,l),!SN(f,n,l).every(Boolean))throw Error(`Selected target has an incompatible managed catalog.`);p=c.version===l}let h;c&&(h=kN(t,n,c,c.installedPath??(c.version===u?r.installedPath:w(n.nativeHome,`plugins/cache`,n.marketplace,`ai-delivery`,c.version)),d)),l&&(await yN(n,l,m.signal,g,e=>{e?r.pending.staging=e:delete r.pending.staging,o()}),p||(ee=!0,wN(n,l,f)),!i&&!p&&await v([`plugin`,`marketplace`,`add`,n.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),c&&t.action===`remove`&&(ee=!0,await v(b));let _=p?c?.installedPath??h??r.installedPath:r.installedPath;if(l&&!p){let e=await v(x);t.host===`codex`&&(_=P({installedPath:A()}).parse(JSON.parse(e)).installedPath)}let y=await TN(t,n,m.signal,g);if(!EN(t,n,y)&&l)throw Error(`Native marketplace registration is missing.`);let S=DN(t,n,y);if(l?S?.version!==l:S!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(l&&(kN(t,n,S,S?.installedPath??_),!S.enabled))throw Error(`Native plugin selection is disabled.`);return r.currentVersion=l,u!==l&&(r.previousVersion=u),r.installedPath=l?S?.installedPath??_:null,delete r.pending,o(),a.version=l,a.changed=u!==l,a.installed=l!==null,a.activation={installedVersion:l,startupVersion:null,loadedVersion:null},l&&(a.nativePluginRoot=r.installedPath??mN(n,l)),a}catch(e){if(!s&&!m.signal.aborted&&!ee&&r.pending?.command.phase===`idle`&&r.pending.staging===void 0){delete r.pending;try{o()}catch(t){throw AggregateError([e,t],`Plugin preparation failed and pending-state cleanup also failed.`)}}throw e}finally{process.removeListener(`SIGINT`,h),process.removeListener(`SIGTERM`,h)}}})}var MN=new qe;MN.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(iM).option(`--identity <name>`,`Configured author or reviewer identity`).option(`--personal-auth`,`Explicit legacy personal-token author override`).option(`--repo <owner/name>`,`GitHub repository owner/name; works from any directory`).option(`--repo-root <path>`,`Launch directory or explicit clone for local operations`,process.cwd());for(let e=2;e<process.argv.length;e++){let t=process.argv[e],n=MN.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&MN.enablePositionalOptions();break}function NN(){let e=MN.opts(),t=(e.identity??process.env.AI_DELIVERY_IDENTITY)?.trim()||void 0;return{repoRoot:e.repoRoot,...t===void 0?{}:{identity:t},personalAuth:e.personalAuth===!0,...e.repo===void 0?{}:{repo:e.repo}}}function PN(e){return e===void 0?void 0:Number(e)}function FN(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function IN(e){return FN(e)?.map(Number)}function LN(e,t){if(e!==void 0&&t!==void 0)throw Error(`Pass either --body or --body-file.`);return t===void 0?e:d(t,`utf8`)}function RN(e,t){let n=e===void 0?{}:JSON.parse(d(e,`utf8`));return{...ov.parse(n),...Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}}function zN(e,t){return uw(e,t,NN()).then(t=>rt(e,t))}function BN(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var VN=MN.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`preview`,`update`,`rollback`,`remove`]){let t=VN.command(e).requiredOption(`--host <host>`,`Native host: codex or claude-code`).option(`--scope <scope>`,`Native scope: user, project, or local; Codex supports user`,`user`).option(`--dry-run`,`Describe the selected target without changing files or contacting native tools`).option(`--json`,`Print the result as JSON`);(e===`install`||e===`update`)&&t.requiredOption(`--version <version>`,`Explicit published package version`),e===`doctor`&&t.option(`--check-auth`,`Read configured role identities and repository access; requires explicit --repo`),t.action(async t=>{let n=await jN({action:e,host:t.host,scope:t.scope,...t.version===void 0?{}:{version:t.version},dryRun:t.dryRun===!0,checkAuth:t.checkAuth===!0,...t.checkAuth&&NN().repo?{repo:NN().repo}:{},repoRoot:NN().repoRoot});if(t.json){BN(n);return}if(process.stdout.write(`${n.dryRun?`Dry run: `:``}${n.host} ${n.scope}: ${e}; version ${n.version??`none`}; installed ${n.installed}; changed ${n.changed}\n`),n.mcp&&process.stdout.write(`Bundled MCP startup: ${n.mcp.startup}${n.mcp.error?` (${n.mcp.error})`:``}\n`),n.diagnostics){process.stdout.write(`Registration observations: ${n.diagnostics.registrations.length}; completeness ${n.diagnostics.completeness}; migration ${n.diagnostics.migration}; planned changes ${n.diagnostics.plannedChanges.length}\n`);for(let e of n.diagnostics.registrations)process.stdout.write(`${e.kind} ${e.scope}: ownership ${e.ownership}; source ${e.source}; version ${e.version??`unknown`}\n`);process.stdout.write(`Unverified conditions: ${n.diagnostics.findings.join(`, `)}\n`)}n.activation&&process.stdout.write(`Native session loaded version: unverified. Installed observation: ${n.activation.installedVersion??`unknown`}; separate startup: ${n.activation.startupVersion??`not checked`}. Use the host's surface-specific activation guidance.\n`),n.recoveryRequired&&process.stdout.write(`Resume the interrupted original plugin command to recover this target.
311
- `),n.authProbe&&process.stdout.write(`Selected-runtime CLI auth probe: ${n.authProbe.outcome}; settings ${n.authProbe.settings}; process references ${n.authProbe.processReferences.status}; authentication ${n.authProbe.authentication.status}; repository access ${n.authProbe.repositoryAccess.status}${n.authProbe.reason?` (${n.authProbe.reason})`:``}\nNative GUI credential propagation and counted exact-head approval remain unverified.\n`)})}MN.command(`runtime:stage`).description(`Stage a reviewed archive in a private directory; does not activate or admit it`).requiredOption(`--archive <path>`).requiredOption(`--archive-sha256 <digest>`).requiredOption(`--package-version <version>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--native-plugin-root <path>`,`Bind the exact reviewed native plugin root`).option(`--max-aggregate-rss-bytes <bytes>`,`Sampled controller plus children RSS limit`).option(`--max-new-output-bytes <bytes>`,`Owned stage and metadata output limit`).option(`--min-free-disk-bytes <bytes>`,`Required free disk headroom`).option(`--max-captured-output-bytes <bytes>`,`Retained command log cap; defaults to 1 MiB`).option(`--authorize-stage`,`Explicit authority to stage this reviewed archive`).action(async e=>zN(`runtime_stage`,{authority:e.authorizeStage===!0?`runtime:stage`:``,archivePath:e.archive,expectedArchiveSha256:e.archiveSha256,packageVersion:e.packageVersion,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot},...[`maxAggregateRssBytes`,`maxNewOutputBytes`,`minFreeDiskBytes`,`maxCapturedOutputBytes`].some(t=>e[t]!==void 0)?{resourceBounds:{maxAggregateRssBytes:Number(e.maxAggregateRssBytes??1024**3),minFreeDiskBytes:Number(e.minFreeDiskBytes??256*1024**2),maxNewOutputBytes:Number(e.maxNewOutputBytes??512*1024**2),maxCapturedOutputBytes:Number(e.maxCapturedOutputBytes??1024**2)}}:{}})),MN.command(`runtime:admit`).description(`Explicitly publish the existing admission for an exact completed stage`).requiredOption(`--stage-id <digest>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--expected-prior <digest>`,`SHA-256 of the exact current private admission bytes`).option(`--expected-absent`,`Explicitly require no current admission`).option(`--authorize-admit`,`Explicit authority for the final admission write`).action(async e=>{if(e.expectedPrior===void 0==(e.expectedAbsent!==!0))throw Error(`Choose exactly one of --expected-prior or --expected-absent.`);return zN(`runtime_admit`,{authority:e.authorizeAdmit===!0?`runtime:admit`:``,stageId:e.stageId,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,expectedPriorAdmissionSha256:e.expectedAbsent===!0?null:e.expectedPrior})}),MN.command(`create`).requiredOption(`--title <title>`).option(`--fields-file <path>`,`UTF-8 JSON typed fields; explicit CLI fields take precedence`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).action(async e=>zN(`issue_create`,RN(e.fieldsFile,{title:e.title,body:LN(e.body,e.bodyFile),issueType:e.type,points:PN(e.points),priority:e.priority,labels:FN(e.labels),blockedBy:IN(e.blockedBy),blocks:IN(e.blocks),overrideReason:e.overrideReason,milestone:PN(e.milestone),parentIssueNumber:PN(e.parent),...e.draft===!0?{draft:!0}:{}}))),MN.command(`start`).option(`--issue <number>`).option(`--request <text>`).option(`--request-id <id>`,`Stable retry identity for a new issue start`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--branch <branch>`).option(`--resume-created`).option(`--investigation-worktree <path>`,`Prospectively register an already linked host-created investigation`).option(`--expected-head <sha>`,`Exact unchanged initial commit for investigation registration`).action(async e=>{if(e.investigationWorktree!==void 0||e.expectedHead!==void 0){if(Object.keys(e).some(e=>![`issue`,`investigationWorktree`,`expectedHead`].includes(e)))throw Error(`Investigation registration cannot create or change issue/branch metadata.`);return zN(`issue_start`,{issueNumber:PN(e.issue),investigationWorktree:e.investigationWorktree,expectedHeadSha:e.expectedHead})}return zN(`issue_start`,{issueNumber:PN(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:LN(e.body,e.bodyFile),issueType:e.type,points:PN(e.points),priority:e.priority,labels:FN(e.labels),blockedBy:IN(e.blockedBy),blocks:IN(e.blocks),overrideReason:e.overrideReason,milestone:PN(e.milestone),parentIssueNumber:PN(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0})});for(let e of[`list`,`search`])MN.command(e).option(`--query <text>`,`Literal text to search in the selected repository`).option(`--state <state>`).option(`--labels <labels>`).option(`--parent <number>`).option(`--type <type>`).option(`--project-status <status>`).option(`--updated-since <timestamp>`).option(`--page <number>`).option(`--per-page <number>`).action(async t=>zN(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:FN(t.labels),parentIssueNumber:PN(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:PN(t.page),perPage:PN(t.perPage)}));MN.command(`update`).requiredOption(`--issue <number>`).option(`--fields-file <path>`,`UTF-8 JSON typed issue field patch`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--state <state>`).option(`--preserve-history`,`Preserve the previous title and body before a rewrite`).option(`--close-reason <reason>`).option(`--superseded-by <number>`).option(`--park`,`Park execution while retaining the issue worktree`).action(async e=>zN(`issue_update`,RN(e.fieldsFile,{issueNumber:PN(e.issue),title:e.title,...e.draft===!0?{draft:!0}:{},body:LN(e.body,e.bodyFile),issueType:e.type,points:PN(e.points),priority:e.priority,labels:FN(e.labels),blockedBy:IN(e.blockedBy),blocks:IN(e.blocks),overrideReason:e.overrideReason,milestone:PN(e.milestone),parentIssueNumber:PN(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:PN(e.supersededBy),park:e.park===!0||void 0}))),MN.command(`health`).requiredOption(`--from <utc>`,`Inclusive UTC ISO timestamp`).requiredOption(`--to <utc>`,`Exclusive UTC ISO timestamp`).option(`--max-issues <number>`).option(`--max-timeline-pages <number>`).option(`--max-project-pages <number>`).option(`--oldest-limit <number>`).action(async e=>zN(`delivery_health`,{repo:NN().repo,from:e.from,to:e.to,maxIssues:PN(e.maxIssues),maxTimelinePages:PN(e.maxTimelinePages),maxProjectPages:PN(e.maxProjectPages),oldestLimit:PN(e.oldestLimit)})),MN.command(`info`).requiredOption(`--issue <number>`).action(async e=>zN(`issue_info`,{issueNumber:PN(e.issue)})),MN.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>zN(`issue_ready_check`,{issueNumber:PN(e.issue)}));for(let e of[`parent`,`blockers`])MN.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await uw(`issue_info`,{issueNumber:PN(t.issue)},NN());BN(e===`parent`?{issueNumber:PN(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:PN(t.issue),blockedBy:n.blockedBy})});MN.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await cw(NN(),`subissues`);BN({issueNumber:PN(e.issue),subissues:await Kv(t,Number(e.issue))})}),MN.command(`pr:create`).description(`Create a PR from a linked issue branch, or promote an existing associated PR with --head and --ready.`).requiredOption(`--issue <number>`).option(`--pr <number>`,`Exact existing PR selector; never creates a replacement`).option(`--non-closing`,`Retain the issue OPEN using native non-closing reference proof`).option(`--title <title>`).option(`--body-file <path>`).option(`--head <branch>`,`Explicit remote head; existing PR promotion verifies its native issue association`).option(`--ready`,`Publish ready, or promote the author-owned PR selected by --head`).option(`--dry-run`).action(async e=>zN(`issue_pr_create`,{issueNumber:PN(e.issue),prNumber:PN(e.pr),nonClosing:e.nonClosing,title:e.title,body:LN(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),MN.command(`pr:info`).description(`Inspect an exact PR; combine --issue and --pr to verify its native closing-issue association.`).option(`--non-closing`,`Verify an exact native non-closing PR-to-issue reference`).option(`--issue <number>`,`Issue to verify; issue-only lookup requires a GitHub-linked branch`).option(`--pr <number>`,`Exact PR number; include --issue after issue branch links are replaced on publication`).action(async e=>zN(`issue_pr_info`,{issueNumber:PN(e.issue),prNumber:PN(e.pr),nonClosing:e.nonClosing})),MN.command(`pr:list`).option(`--state <state>`,`open, closed or all`,`open`).action(async e=>{if(![`open`,`closed`,`all`].includes(e.state))throw Error(`Invalid PR state.`);BN(await aC(await cw(NN(),`pr:list`),e.state))}),MN.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{BN(await oC(await cw(NN(),`pr:checks`),Number(e.pr)))}),MN.command(`pr:review`).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).requiredOption(`--artifact <path>`,`Path to a UTF-8 JSON review artifact file (not inline JSON)`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`).action(async e=>zN(`issue_pr_review`,{issueNumber:PN(e.issue),prNumber:PN(e.pr),artifact:d(e.artifact,`utf8`),dryRun:e.dryRun===!0,nonClosing:e.nonClosing}));for(let[e,t]of[[`pr:merge`,`issue_pr_merge`],[`finish`,`issue_finish`]]){let n=MN.command(e).requiredOption(`--issue <number>`);e===`pr:merge`?n.requiredOption(`--pr <number>`):n.option(`--pr <number>`),n.option(`--strategy <method>`).option(`--reviewed-head <sha>`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`),e===`finish`&&n.option(`--investigation`,`Complete an unchanged prospectively registered investigation`).option(`--result <path>`,`Durable independently reviewed result outside the removable worktree`).option(`--authority-comment <number>`,`Exact native operator removal authority comment`).option(`--acceptance-comment <number>`,`Exact configured-App result acceptance comment`),n.action(async e=>{if(e.investigation===!0){if(e.pr!==void 0||e.strategy!==void 0||e.reviewedHead!==void 0||e.nonClosing!==void 0)throw Error(`Investigation completion cannot accept PR or merge options.`);return zN(t,{issueNumber:PN(e.issue),investigation:!0,resultPath:e.result,authorityCommentId:PN(e.authorityComment),acceptanceCommentId:PN(e.acceptanceComment),dryRun:e.dryRun===!0})}if(e.result!==void 0||e.authorityComment!==void 0||e.acceptanceComment!==void 0)throw Error(`Investigation evidence requires --investigation.`);return zN(t,{issueNumber:PN(e.issue),prNumber:PN(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0,nonClosing:e.nonClosing})})}MN.command(`worktree:transition:inspect`).requiredOption(`--issue <number>`).requiredOption(`--purpose <purpose>`,`active-resume or merged-cleanup`).option(`--disposition <disposition>`,`retain (default) or explicitly unheld remove`).option(`--terminal-pr <number>`).option(`--retained-holds <comment-ids>`,`Comma-separated native retained-hold comment IDs`).option(`--retained-admission <path>`).option(`--retained-archive <path>`).action(async e=>zN(`issue_worktree_transition_inspect`,{issueNumber:PN(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:PN(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:IN(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),MN.command(`worktree:transition:apply`).requiredOption(`--plan <path>`).requiredOption(`--plan-id <digest>`).requiredOption(`--relinquishment-comment <id>`).requiredOption(`--acceptance-comment <id>`).option(`--authorize-transition`,`Explicit authority for this exact independently accepted plan`).action(async e=>zN(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),MN.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=dM(JSON.parse(d(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),MN.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await cw(NN(),`config:resolve`);BN({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await uC(e,void 0,void 0,`development`)})}),MN.command(`mcp:serve`).action(async()=>sM(NN())),MN.parseAsync(process.argv).catch(it);export{};
305
+ deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),$A=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),ej=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cA(),n=$k(),r=tA(),i=eA();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),tj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mA(),n=cA(),r=eA(),i=ej();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),nj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cA(),n=$k(),r=eA(),i=eA();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),rj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eA();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),ij=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:cA().validateUnion,error:{message:`must match a schema in anyOf`}}})),aj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),oj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eA();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),sj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=eA(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),cj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eA();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),lj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=qA(),n=YA(),r=JA(),i=XA(),a=ZA(),o=QA(),s=$A(),c=ej(),l=tj(),u=nj(),d=rj(),f=ij(),p=aj(),m=oj(),h=sj(),g=cj();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),uj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),dj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[uj().default]})),fj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),pj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=NA(),n=KA(),r=lj(),i=dj(),a=fj();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),mj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),hj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$k(),n=mj(),r=_A(),i=gA(),a=eA();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),gj=ke({$id:()=>vj,$schema:()=>_j,default:()=>Cj,definitions:()=>bj,properties:()=>Sj,title:()=>yj,type:()=>xj}),_j,vj,yj,bj,xj,Sj,Cj,wj=Oe((()=>{_j=`http://json-schema.org/draft-07/schema#`,vj=`http://json-schema.org/draft-07/schema#`,yj=`Core schema meta-schema`,bj={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:[]}},xj=[`object`,`boolean`],Sj={$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:`#`}},Cj={$schema:_j,$id:vj,title:yj,definitions:bj,type:xj,properties:Sj,default:!0}})),Tj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=AA(),r=pj(),i=hj(),a=(wj(),Me(gj).default),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`,c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=mA();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=$k();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=hA();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=gA();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Ej=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:re,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:ee},int64:{type:`number`,validate:S},float:{type:`number`,validate:te},double:{type:`number`,validate:te},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function ee(e){return Number.isInteger(e)&&e<=x&&e>=b}function S(e){return Number.isInteger(e)}function te(){return!0}var ne=/[^\\]\\Z/;function re(e){if(ne.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Dj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=Tj(),n=$k(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Oj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=Ej(),r=Dj(),i=$k(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),kj=je(Tj(),1),Aj=je(Oj(),1);function jj(){let e=new kj.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Aj.default)(e),e}var Mj=class{constructor(e){this._ajv=e??jj()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Nj=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},gO,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},OO,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Pj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function Fj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var Ij=class extends Jk{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(rO.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Mj,this.setRequestHandler(BE,e=>this._oninitialize(e)),this.setNotificationHandler(UE,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(aO,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=rO.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Nj(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Xk(this._capabilities,e)}setRequestHandler(e,t){let n=XT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=nE(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=JT(eO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=JT($E,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=JT(QD,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Fj(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Pj(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:iE.includes(t)?t:rE,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},kE)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},_O,t):this.request({method:`sampling/createMessage`,params:e},gO,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},OO,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},OO,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},RO,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},Lj=Symbol.for(`mcp.completable`);function Rj(e){return!!e&&typeof e==`object`&&Lj in e}function zj(e){return e[Lj]?.complete}var Bj;(function(e){e.Completable=`McpCompletable`})(Bj||={});var Vj=/^[A-Za-z0-9._-]{1,128}$/;function Hj(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Vj.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Uj(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Wj(e){let t=Hj(e);return Uj(e,t.warnings),t.isValid}var Gj=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Kj=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ij(e,t)}get experimental(){return this._experimental||={tasks:new Gj(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler($j(XD)),this.server.assertCanSetRequestHandler($j(eO)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(XD,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=ZT(t.inputSchema);return e?Gk(e,{strictUnions:!0,pipeStrategy:`input`}):qj})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=ZT(t.outputSchema);e&&(n.outputSchema=Gk(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(eO,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Q(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Q(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await YT(ZT(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=$T(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await YT(ZT(e.outputSchema),t.structuredContent);if(!r.success){let e=$T(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Q(Z.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler($j(MO)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(MO,async e=>{switch(e.params.ref.type){case`ref/prompt`:return NO(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return PO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return tM;let r=XT(n.argsSchema)?.[e.params.argument.name];if(!Rj(r))return tM;let i=zj(r);return i?eM(await i(e.params.argument.value,e.params.context)):tM}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return tM;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?eM(await r(e.params.argument.value,e.params.context)):tM}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler($j(_D)),this.server.assertCanSetRequestHandler($j(yD)),this.server.assertCanSetRequestHandler($j(CD)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_D,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(yD,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(CD,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Q(Z.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler($j(PD)),this.server.assertCanSetRequestHandler($j(LD)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(PD,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Qj(t.argsSchema):void 0}))})),this.server.setRequestHandler(LD,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await YT(ZT(n.argsSchema),e.params.arguments);if(!r.success){let t=$T(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:qT(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=qT(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Rj(e instanceof ru?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Wj(e);let l={title:t,description:n,inputSchema:Zj(r),outputSchema:Zj(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Wj(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=qT(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=qT(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Xj(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Xj(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},qj={type:`object`,properties:{}};function Jj(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Yj(e){return`_def`in e||`_zod`in e||Jj(e)}function Xj(e){return typeof e!=`object`||!e||Yj(e)?!1:Object.keys(e).length===0||Object.values(e).some(Jj)}function Zj(e){if(e){if(Xj(e))return qT(e);if(!Yj(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Qj(e){let t=XT(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:eE(t),required:!tE(t)})):[]}function $j(e){let t=XT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=nE(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function eM(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var tM={completion:{values:[],hasMore:!1}},nM=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
306
+ `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),rM(t)}clear(){this._buffer=void 0}};function rM(e){return OE.parse(JSON.parse(e))}function iM(e){return JSON.stringify(e)+`
307
+ `}var aM=class{constructor(e=le.stdin,t=le.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new nM({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=iM(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}},oM=JSON.parse(d(new URL(`../package.json`,import.meta.url),`utf8`));if(typeof oM!=`object`||!oM||!(`version`in oM)||typeof oM.version!=`string`||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(oM.version))throw Error(`The adjacent ai-delivery package identity must contain a stable version.`);var sM=oM.version,cM=[`Use these ai-delivery GitHub issue and pull request tools for ordinary requests, including "Use the ai-delivery MCP issue_info tool to read owner/name issue N".`,`Carry the repository named by the user into the repo argument (owner/name). Ordinary remote issue/PR tools work outside Git with an explicit repo; do not move into a checkout to read an issue.`,`In Claude Code, when bare and plugin-qualified ai-delivery tools coexist, discover the installed plugin provider and inspect its schema before calling. The observed plugin example is mcp__plugin_ai-delivery_ai-delivery__issue_info with {"repo":"example/widget","issueNumber":17}; use the requested repository and issue instead. This Claude namespace is not a universal tool name for other hosts.`,`A different issue_info accepting issueNumber/cached but no repo cannot receive that repository argument. Do not add unsupported fields or select a provider by name similarity alone. Honor an explicitly requested provider; if it is unavailable or incompatible, report that limitation rather than silently substituting.`,`Preserve read-only and MCP-only intent: do not create/update/start, use another GitHub provider or fall back to a CLI for such a read. Do not alter registrations, permissions, actors, credentials or host settings to make it work.`,`Retained local runtime, transition and investigation modes keep their separate checkout and authority requirements.`].join(`
308
+ `);function lM(e,t){let n=new Kj({name:`ai-delivery`,version:sM},{instructions:cM}),r=iw;for(let i of r)n.registerTool(i.name,{description:i.description,inputSchema:i.inputSchema},async(n,r)=>{let a=i.inputSchema.safeParse(n);if(!a.success)return{content:[{type:`text`,text:`Invalid arguments for ${i.name}.`}],isError:!0};try{let n=e.signal===void 0?r.signal:AbortSignal.any([e.signal,r.signal]),o=fw(i.name,a.data,{...e,signal:n});t?.add(o);let s;try{s=await o}finally{t?.delete(o)}return{content:[{type:`text`,text:JSON.stringify(s)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}});return n}async function uM(e){y_(!0);let t=new AbortController,n=new Set,r=lM({...e,signal:t.signal},n),i,a=()=>(i??=(async()=>{t.abort(),await Promise.allSettled(n),await r.close(),process.exit(0)})(),i);process.once(`SIGINT`,()=>{a()}),process.once(`SIGTERM`,()=>{a()}),await r.connect(new aM),process.stderr.write(`ai-delivery MCP server started
309
+ `),await new Promise(()=>{})}var dM=e=>/^(?:area|risk):[^\s:]+$/u.test(e),fM=dM,pM=P({number:j().int().positive(),body:A(),labels:N(A()),trackingParent:M().optional(),resolvedLegacyBlockers:N(P({number:j().int().positive(),state:I([`OPEN`,`CLOSED`])}).strict()).optional(),existingNative:P({blockedBy:N(P({number:j().int().positive(),state:I([`OPEN`,`CLOSED`])}).strict()),issueType:A().optional(),points:j().int().positive().optional(),priority:A().optional(),projectStatus:I([`Todo`,`In Progress`,`Blocked`,`Done`]).optional()}).strict().optional()}).strict();function mM(e){let t=P({issues:N(pM),repositoryLabels:N(A()).optional()}).strict().parse(e),n=t.issues.map(e=>e.number);if(new Set(n).size!==n.length)throw new D(`Legacy issue input repeats an issue number.`);return{mode:`dry-run`,plans:t.issues.map(e=>{let t=e.existingNative,n=t===void 0?void 0:{blockedBy:t.blockedBy,...t.issueType===void 0?{}:{issueType:t.issueType},...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority},...t.projectStatus===void 0?{}:{projectStatus:t.projectStatus}};return{number:e.number,...vM({body:e.body,labels:e.labels,...n===void 0?{}:{existingNative:n},...e.resolvedLegacyBlockers===void 0?{}:{resolvedLegacyBlockers:e.resolvedLegacyBlockers},...e.trackingParent===void 0?{}:{trackingParent:e.trackingParent}})}}),retiredRepositoryLabels:yM(t.repositoryLabels??[]),schemaVersion:`ai-delivery.legacy-issue-migration@1`,validated:0}}var hM=new Map([[`effort:l`,5],[`effort:m`,3],[`effort:medium`,3],[`effort:s`,2],[`effort:xl`,8],[`effort:xs`,1]]),gM=new Map([[`priority:high`,`P1`],[`priority:p0`,`P0`],[`priority:p1`,`P1`],[`priority:p2`,`P2`],[`priority:p3`,`P3`],[`priority:p4`,`P4`]]),_M=new Map([[`type:bug`,`Bug`],[`type:design`,`Task`],[`type:epic`,`Task`],[`type:feature`,`Feature`],[`type:spike`,`Task`],[`type:task`,`Task`],[`type:tracking`,`Task`]]);function vM(e){let t=[...new Set(e.labels.map(e=>e.trim()).filter(Boolean))],n=bM(e.body),r=wM(e.body,`executionContract`),i=wM(e.body,`dependencyDeclaration`),a=wM(e.body,`related`),o=SM([...e.existingNative?.blockedBy??[],...e.resolvedLegacyBlockers??[]]),s=EM({dependencyDeclaration:i,executionContract:r,related:a}),c=[...new Set([...o.keys(),...s])].sort((e,t)=>e-t),l=new Set(c.filter(e=>o.get(e)!==`CLOSED`));if(t.some(e=>e.toLowerCase()===`type:tracking`)&&e.trackingParent!==!0)throw new D(`Legacy type:tracking requires a native sub-issue relationship before its label can be retired.`);let u=e.trackingParent===!0,d=u?void 0:e.existingNative?.points??kM({...n.points===void 0?{}:{bodyPoint:n.points},executionContract:r,labels:t}),f=e.existingNative?.priority??AM({label:`priority`,labels:t,mapping:gM}),p=e.existingNative?.issueType??AM({label:`issue type`,labels:t,mapping:_M});if(e.existingNative?.projectStatus===`Done`)throw new D(`An open issue cannot retain Project Done during legacy migration.`);let m=OM({existing:e.existingNative?.projectStatus,labels:t,unresolvedBlockers:l}),h=t.filter(dM);h.sort();let g=t.filter(e=>!h.includes(e)).sort();return{body:TM(n.body),clearPoints:u&&e.existingNative?.points!==void 0,native:{blockedBy:c,...p===void 0?{}:{issueType:p},...d===void 0?{}:{points:d},...f===void 0?{}:{priority:f},projectStatus:m},retainedLabels:h,retiredLabels:g}}function yM(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))].filter(e=>!fM(e)).sort((e,t)=>e.localeCompare(t))}function bM(e){let t=e.split(/\r?\n/u),n=t.flatMap((e,t)=>e.trim().toLowerCase()===`## fibonacci points`?[t]:[]);if(n.length===0)return{body:e};if(n.length>1)throw new D(`Found duplicate legacy Fibonacci points sections.`);let r=n[0];if(r===void 0)return{body:e};let i=t.length;for(let e=r+1;e<t.length;e+=1)if(t[e]?.trimStart().startsWith(`## `)===!0){i=e;break}let a=t.slice(r+1,i).map(e=>e.trim()).filter(Boolean);if(a.length!==1||!/^(?:1|2|3|5|8|13)$/u.test(a[0]??``))throw new D(`Legacy Fibonacci points section must contain exactly one supported numeric value.`);return{body:[...t.slice(0,r),...t.slice(i)].join(`
310
+ `),points:Number(a[0])}}function xM(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function SM(e){let t=new Map;for(let n of e){if(!xM(n.number))throw new D(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new D(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function CM(e){if(xM(e))return e;if(typeof e!=`string`)return;let t=/^#?([1-9]\d*)$/u.exec(e.trim()),n=t?.[1]===void 0?NaN:Number(t[1]);return xM(n)?n:void 0}function wM(e,t){let n=RegExp(`<!--\\s*${t}:\\s*([\\s\\S]*?)\\s*-->`,`u`).exec(e)?.[1];if(n!==void 0)try{let e=JSON.parse(n);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`not an object`);return e}catch{throw new D(`Invalid legacy ${t} payload.`)}}function TM(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function EM({dependencyDeclaration:e,executionContract:t,related:n}){let r=[],i=t?.dependencies;if(Array.isArray(i))for(let e of i){if(typeof e!=`object`||!e)continue;let t=e,n=CM(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...DM(e?.blockedBy)),r.push(...DM(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function DM(e){return Array.isArray(e)?e.map(CM).filter(e=>e!==void 0):[]}function OM(e){if(e.unresolvedBlockers.size>0)return`Blocked`;let t=e.labels.some(e=>[`status:in-progress`,`status:review`].includes(e.toLowerCase()));return e.existing===`In Progress`||t?`In Progress`:`Todo`}function kM(e){let t=[];for(let n of e.labels){let e=hM.get(n.toLowerCase());e!==void 0&&t.push(e);let r=/^points:(1|2|3|5|8|13)$/u.exec(n.toLowerCase());r?.[1]!==void 0&&t.push(Number(r[1]))}let n=e.executionContract?.effort;if(typeof n==`string`){let e=n.startsWith(`effort:`)?n:`effort:${n}`,r=hM.get(e.toLowerCase());r!==void 0&&t.push(r)}e.bodyPoint!==void 0&&t.push(e.bodyPoint);let r=[...new Set(t)];if(r.length>1)throw new D(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new D(`Issue has no canonical Fibonacci sizing value; assign native Points before migration.`);return i}function AM({label:e,labels:t,mapping:n}){let r=t.flatMap(e=>{let t=n.get(e.toLowerCase());return t===void 0?[]:[t]}),i=[...new Set(r)];if(i.length>1)throw new D(`Found conflicting legacy ${e} values.`);return i[0]}var jM=class{constructor(e){this._client=e}async*callToolStream(e,t=QD,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof Q){yield{type:`error`,error:e};return}yield{type:`error`,error:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function MM(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&MM(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&MM(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&MM(n,t)}}function NM(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var PM=class extends Jk{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Mj,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,tO,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,KD,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,TD,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new jM(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Xk(this._capabilities,e)}setRequestHandler(e,t){let n=XT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=nE(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=JT(TO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=NM(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new Q(Z.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new Q(Z.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=JT($E,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=JT(OO,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new Q(Z.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{MM(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=JT(hO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=JT($E,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=JT(i.tools||i.toolChoice?_O:gO,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:rE,capabilities:this._capabilities,clientInfo:this._clientInfo}},HE,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!iE.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Pj(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&Fj(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},kE,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},FO,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},kE,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},GD,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},FD,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},vD,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},bD,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},wD,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},kE,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},kE,t)}async callTool(e,t=QD,n){if(this.isToolTaskRequired(e.name))throw new Q(Z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},ZD,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=nO.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},FM=E(((e,t)=>{t.exports=a,a.sync=o;var n=Ne(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,!n&&i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),IM=E(((e,t)=>{t.exports=r,r.sync=i;var n=Ne(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),LM=E(((e,t)=>{Ne(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?FM():IM();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),RM=E(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=Ne(`path`),i=n?`;`:`:`,a=LM(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o){if(t.all)u.push(e+s);else return i(e+s)}return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o<n.length;o++){let s=n[o],u=/^".*"$/.test(s)?s.slice(1,-1):s,d=r.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<i.length;e++){let n=f+i[e];try{if(a.sync(n,{pathExt:c})){if(t.all)l.push(n);else return n}}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw o(e)}})),zM=E(((e,t)=>{var n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),BM=E(((e,t)=>{var n=Ne(`path`),r=RM(),i=zM();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),VM=E(((e,t)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),HM=E(((e,t)=>{t.exports=/^#!(.*)/})),UM=E(((e,t)=>{var n=HM();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),WM=E(((e,t)=>{var n=Ne(`fs`),r=UM();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),GM=E(((e,t)=>{var n=Ne(`path`),r=BM(),i=VM(),a=WM(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),KM=E(((e,t)=>{var n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),qM=je(E(((e,t)=>{var n=Ne(`child_process`),r=GM(),i=KM();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))(),1),JM=le.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function YM(){let e={};for(let t of JM){let n=le.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var XM=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new nM({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new xe)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=(0,qM.default)(this._serverParams.command,this._serverParams.args??[],{env:{...YM(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:le.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=iM(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}};async function ZM(e,t,n,r=3e4,i){let a=new AbortController,o=()=>a.abort();i?.addEventListener(`abort`,o,{once:!0}),i?.aborted&&o();let s=setTimeout(o,r),c=``,l=!1;try{let r=await Cb(e,t,a.signal,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:1048576},void 0,void 0,{starting:()=>{},observed:()=>{},idle:()=>{l=!0},assertQuiescent:()=>{}},{environment:n,cwd:e,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>{let t=e.toString(`utf8`).trimEnd().split(/\r?\n/u).at(-1);return[`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`,`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`,`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(t??``)&&(c=t),` Authentication probe failed; raw output withheld.`}});return{failed:!l,stdout:l?r.toString(`utf8`):``,diagnostic:c,cleanupConfirmed:l}}catch{return{failed:!0,stdout:``,diagnostic:c,cleanupConfirmed:l}}finally{clearTimeout(s),i?.removeEventListener(`abort`,o)}}var QM=A().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),$M=F({action:I([`install`,`doctor`,`preview`,`update`,`rollback`,`remove`]),host:I([`codex`,`claude-code`]),scope:I([`user`,`project`,`local`]),version:QM.optional(),dryRun:M().default(!1),checkAuth:M().default(!1),repo:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),repoRoot:A().min(1)}),eN=F({pid:j().int().positive(),birth:A().min(1)}),tN=F({action:$M.shape.action,targetVersion:QM.nullable(),owner:eN,producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),staging:F({path:A(),device:j().int().nonnegative().optional(),inode:j().int().nonnegative().optional()}).optional(),command:Kl(`phase`,[F({phase:L(`idle`)}),F({phase:L(`starting`)}),F({phase:L(`running`),process:eN,tracked:N(eN.extend({pgid:j().int().positive()})).max(256)})])}),nN=F({owner:L(`@aviaratech/ai-delivery.plugin@1`),host:$M.shape.host,scope:$M.shape.scope,projectRoot:A().nullable(),nativeHome:A().min(1),marketplace:A(),currentVersion:QM.nullable(),previousVersion:QM.nullable(),installedPath:A().nullable(),nativeVersion:A().optional(),pending:tN.optional()}),rN=F({owner:L(`@aviaratech/ai-delivery.plugin-version@1`),version:QM,archiveSha256:A().regex(/^[a-f0-9]{64}$/u),files:Ql(A(),A().regex(/^[a-f0-9]{64}$/u))}),iN=e=>pe(`sha256`).update(e).digest(`hex`);function aN(e,t){let o={completeness:`incomplete`,registrations:[],nativeInventory:`not_checked`,plannedChanges:[],migration:`refused`,findings:[`native_session_scope_unverified`,`settings_preservation_unproved`,`native_writer_exclusion_unproved`]},s=e=>{let t;try{if(uN(e),!i(e))return;let n=c(e);if(!n.isFile()||n.nlink!==1||n.size>1048576)throw Error(`Unsafe configuration`);t=u(e,r.O_RDONLY|r.O_NOFOLLOW|r.O_NONBLOCK);let o=a(t);if(!o.isFile()||o.nlink!==1||o.size>1048576)throw Error(`Unsafe configuration`);let s=Buffer.alloc(1048577),l=0;for(;l<s.length;){let e=f(t,s,l,s.length-l,null);if(e===0)break;l+=e}if(l>1048576)throw Error(`Configuration exceeded read limit`);return s.subarray(0,l).toString(`utf8`)}catch{o.findings.push(`configuration_unavailable`);return}finally{t!==void 0&&n(t)}},l=e=>{let t=s(e);if(t!==void 0)try{let e=JSON.parse(t);return Ql(A(),Ll()).parse(e)}catch{o.findings.push(`configuration_unavailable`);return}},d=(e,t)=>{if(typeof t!=`object`||!t||Array.isArray(t)){t!==void 0&&o.findings.push(`configuration_unavailable`);return}Object.entries(t).some(([e,t])=>{if(e===`ai-delivery`)return!0;if(typeof t!=`object`||!t)return!1;let n=t;return n.command===`ai-delivery`||Array.isArray(n.args)&&n.args.some(e=>typeof e==`string`&&e.includes(`@aviaratech/ai-delivery`))})&&o.registrations.push({kind:`standalone`,scope:e,ownership:`unknown`,source:`unknown`,version:null,enabled:null})};if(e.host===`claude-code`){if(process.env.CLAUDE_CONFIG_DIR)o.findings.push(`custom_profile_configuration_unverified`);else{let e=l(w(h(fe()),`.claude.json`)),n=e?.projects;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n[t.projectRoot];typeof e==`object`&&e&&d(`local`,e.mcpServers)}d(`user`,e?.mcpServers)}let e=l(w(t.projectRoot,`.mcp.json`))?.mcpServers,n=o.registrations.findIndex(e=>e.scope===`user`);if(d(`project`,e),n!==-1&&o.registrations.at(-1)?.scope===`project`){let e=o.registrations.pop();o.registrations.splice(n,0,e)}}else for(let[e,n]of[[`project`,w(t.projectRoot,`.codex/config.toml`)],[`user`,w(t.nativeHome,`config.toml`)]]){if(e===`project`&&n===w(t.nativeHome,`config.toml`))continue;let r=s(n);r!==void 0&&(o.findings.push(`codex_configuration_not_fully_resolved`),/^\s*\[\s*mcp_servers\.(?:"ai-delivery"|'ai-delivery'|ai-delivery)\s*\]/mu.test(r)&&d(e,{"ai-delivery":{}}))}return o.findings=[...new Set(o.findings)],o}function oN(e,t,n,r,i){let a=e.diagnostics;a.nativeInventory=`observed`;let o=0;for(let s of r){let r=s.pluginId??s.id;if(!(s.name===`ai-delivery`||typeof r==`string`&&r.startsWith(`ai-delivery@`))||t.host===`codex`&&s.installed!==!0)continue;if(t.host===`claude-code`&&(s.scope===`project`||s.scope===`local`)){if(typeof s.projectPath==`string`&&s.projectPath!==n.projectRoot)continue;typeof s.projectPath!=`string`&&a.findings.push(`native_registration_project_unverified`)}if(++o>256){a.findings.push(`native_inventory_truncated`);break}let c=e.sourceIntegrity===!0&&s===i,l=QM.safeParse(s.version),u=t.host===`codex`?`user`:s.scope===`user`||s.scope===`project`||s.scope===`local`?s.scope:`unknown`;a.registrations.push({kind:`plugin`,scope:u,ownership:c?`managed`:`external`,source:c?`managed_archive`:`unknown`,version:l.success?l.data:null,enabled:typeof s.enabled==`boolean`?s.enabled:null})}}function sN(){let e={PATH:process.env.PATH??``,DISABLE_AUTOUPDATER:`1`};for(let t of[`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`])process.env[t]!==void 0&&(e[t]=process.env[t]);return e}var cN=P({routing:P({repository:$M.shape.repo.unwrap()}),reviewRoute:P({author:P({actorLogin:A().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),authSource:I([`app`,`personal`]),credentialSource:A().optional(),identity:A()}),reviewer:P({actorLogin:A().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),identity:A(),repositoryAccess:L(`readable`)}),rules:P({visibility:I([`complete`,`partial`,`unknown`]),observedRequiredApprovals:j().int().nonnegative().nullable()}),approvalEligibility:I([`unknown`,`insufficient-permission`])})});async function lN(e,t,n){let r;try{r=await Kh(),n.settings=`valid`}catch{n.settings=`unavailable_or_invalid`,n.outcome=`blocked`,n.reason=`settings_unavailable_or_invalid`;return}let i=Object.values(r.roles).flatMap(e=>Object.values(e.credentialEnv)),a=r.roles.author,o=a.authSource===`personal`&&nh(a.credentialEnv.token,process.env),s=o?i.filter(e=>e!==`GH_TOKEN`):i;n.processReferences.requiredNames=s;let c=s.filter(e=>!process.env[e]?.trim());if(n.processReferences.missingNames=c,c.length>0){n.processReferences.status=`missing`,n.outcome=`blocked`,n.reason=`missing_references`;return}if(i.some(e=>/^(?:NODE_|NPM_|GIT_)/u.test(e)||[...rh,`PATH`,`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`,`AI_DELIVERY_CONFIG`,`AI_DELIVERY_IDENTITY`,`DISABLE_AUTOUPDATER`].includes(e))){n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}let l={PATH:process.env.PATH??``,AI_DELIVERY_CONFIG:r.configPath,NODE_OPTIONS:`--max-old-space-size=512 --v8-pool-size=1`,DISABLE_AUTOUPDATER:`1`};for(let e of i)process.env[e]!==void 0&&(l[e]=process.env[e].trim());if(o)for(let e of rh)process.env[e]!==void 0&&(l[e]=process.env[e]);try{a.authSource===`personal`&&th(process.env);for(let e of[`author`,`reviewer`])r.roles[e].authSource!==`personal`&&Jh({config:r,role:e,env:l})}catch{n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}n.processReferences.status=`complete`;let u=await ZM(e.repoRoot,[process.execPath,w(t,`runtime/dist/cli.js`),`--repo`,e.repo,`config:resolve`],l);if(!u.cleanupConfirmed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.reason=`probe_cleanup_unverified`;return}if(u.failed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`;let e=u.diagnostic;e===`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`||e===`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`?(n.authentication.status=`failed`,n.reason=`authentication_failed`):[`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(e??``)?(n.repositoryAccess.status=`denied`,n.reason=`repository_denied`):n.reason=`probe_failed`;return}try{let t=cN.parse(JSON.parse(u.stdout)),a=t.reviewRoute;if(t.routing.repository.toLowerCase()!==e.repo.toLowerCase()||a.author.authSource!==(r.roles.author.authSource??`app`)||a.author.identity!==r.roles.author.identity||a.reviewer.identity!==r.roles.reviewer.identity||a.author.actorLogin.toLowerCase()===a.reviewer.actorLogin.toLowerCase())throw Error(`Inconsistent readback`);let s={author:{actorLogin:a.author.actorLogin,authSource:a.author.authSource,...o&&a.author.credentialSource!==void 0?{credentialSource:a.author.credentialSource}:{}},reviewer:{actorLogin:a.reviewer.actorLogin,authSource:`app`}};if(o&&!a.author.credentialSource?.startsWith(`gh:github.com:`))throw Error(`Missing session route`);if(i.some(e=>l[e]!==void 0&&JSON.stringify(s).includes(l[e])))throw Error(`Unsafe readback`);n.authentication={status:`verified`,...s},n.repositoryAccess.status=`verified`,n.reviewRules={...a.rules,approvalEligibility:a.approvalEligibility},n.outcome=`readback_complete`}catch{n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.outcome=`failed`,n.reason=`invalid_readback`}}function uN(e){let t=T(e);for(;;){if(i(t)&&c(t).isSymbolicLink())throw Error(`Managed plugin paths must not use symlinks.`);let e=C(t);if(e===t)break;t=e}}function dN(e){let t=h(T(e.repoRoot)),n=T(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??w(fe(),e.host===`codex`?`.codex`:`.claude`)),r=[];for(;!i(n);)r.unshift(ie(n)),n=C(n);let a=w(h(n),...r),o=e.scope===`user`?`user`:`${e.scope}-${pe(`sha256`).update(t).digest(`hex`).slice(0,16)}`,s=w(fe(),`.cache`,`ai-delivery`,`plugins`,e.host,o);if(uN(s),i(s)&&(!c(s).isDirectory()||c(s).mode&63))throw Error(`Managed plugin directory is not private.`);return{directory:s,projectRoot:t,nativeHome:a,marketplace:`ai-delivery-${o}`,catalog:w(s,`marketplace`),statePath:w(s,`state.json`),tool:e.host===`codex`?`codex`:`claude`}}function fN(e,t){if(!i(t.statePath))return;let n=c(t.statePath);if(!n.isFile()||n.nlink!==1||n.mode&63||n.size>65536)throw Error(`Managed plugin state is unsafe.`);let r=nN.parse(JSON.parse(d(t.statePath,`utf8`)));if(r.nativeHome!==t.nativeHome)throw Error(`Managed plugin state belongs to a different native profile.`);if(r.host!==e.host||r.scope!==e.scope||r.marketplace!==t.marketplace||r.projectRoot!==(e.scope===`user`?null:t.projectRoot))throw Error(`Managed plugin state belongs to a different target.`);return r}function pN(e){let t=rb().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function mN(e){if(pN(e.owner.pid)===e.owner.birth)throw Error(`A live plugin installer still owns this target.`);if(e.command.phase===`starting`)throw Error(`Interrupted installer command ownership is unknown; preserve its state before recovery.`);if(e.command.phase!==`running`)return;let t={rootPid:e.command.process.pid,rootIdentity:e.command.process.birth,sampled:!0,tracked:new Map(e.command.tracked.map(({pid:e,birth:t,pgid:n})=>[e,{pid:e,identity:t,pgid:n,ppid:0,rssBytes:0,status:``}]))};cb(t),await sb(t)}async function hN(e,t,n,r,i,a=!1){return(await Cb(n,[e,...t],r,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2},void 0,void 0,{starting:()=>i?.({phase:`starting`}),observed:e=>i?.({phase:`running`,process:{pid:e.rootPid,birth:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,birth:t,pgid:n}))}),idle:()=>i?.({phase:`idle`}),assertQuiescent:()=>{}},{environment:a?sN():{...process.env,DISABLE_AUTOUPDATER:`1`},cwd:n,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>a?` Native inventory failed; raw output withheld.`:` Native command output: ${e.toString(`utf8`).slice(-2e3)}`})).toString(`utf8`)}function gN(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function _N(e,t){return w(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function vN(e,t){return w(e.catalog,`versions`,t)}function yN(e){let t={},n=0,r=(e,i,a)=>{if(a>16)throw Error(`Plugin tree exceeds the depth bound.`);for(let o of p(e).sort()){if(++n>4096)throw Error(`Plugin tree exceeds the entry bound.`);let s=w(e,o),l=`${i}${o}`,u=c(s);if(u.isSymbolicLink()||!u.isDirectory()&&(!u.isFile()||u.nlink!==1))throw Error(`Plugin tree contains links or special files.`);if(u.isDirectory())r(s,`${l}/`,a+1);else{if(u.size>32*1024**2)throw Error(`Plugin file exceeds the size bound.`);t[l]=iN(d(s))}}};return r(e,``,0),t}function bN(e,t){let n=vN(e,t);uN(n);let r=w(n,`version.json`);if(!i(r))throw Error(`No completed immutable plugin unit for ${t}.`);let a=c(r),o=w(n,`archive.tgz`),s=c(o);if(!a.isFile()||a.nlink!==1||a.size>1048576||!s.isFile()||s.nlink!==1||s.size>32*1024**2)throw Error(`Immutable plugin unit metadata is unsafe.`);let l=rN.parse(JSON.parse(d(r,`utf8`)));if(l.version!==t||JSON.stringify(yN(_N(e,t)))!==JSON.stringify(l.files)||iN(d(o))!==l.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return l}function xN(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=ye(e,{maxOutputLength:128*1024**2}),n=new Map;for(let e=0;e+512<=t.length;){let r=t.subarray(e,e+512);if(r.every(e=>e===0))break;let i=(e,t)=>r.subarray(e,e+t).toString().replace(/\0.*$/su,``).trim(),a=(e,t)=>{let n=i(e,t);if(!/^[0-7]+$/u.test(n))throw Error(`Unsupported tar numeric header.`);return Number.parseInt(n,8)};if([...r].reduce((e,t,n)=>e+(n>=148&&n<156?32:t),0)!==a(148,8))throw Error(`Plugin archive header checksum mismatch.`);let o=`${i(345,155)?`${i(345,155)}/`:``}${i(0,100)}`,s=a(124,12),c=i(156,1);if(!/^package\/[A-Za-z0-9_./-]+$/u.test(o)||o.split(`/`).some(e=>e===`..`||e===`.`)||o.split(`/`).length>16||![``,`0`,`5`].includes(c)||e+512+s>t.length||n.has(o)||n.size>=4096)throw Error(`Unsafe or unsupported plugin archive member.`);c!==`5`&&n.set(o,t.subarray(e+512,e+512+s)),e+=512+Math.ceil(s/512)*512}return n}async function SN(e,t,n,r,a){let o=vN(e,t);if(i(o)){bN(e,t);return}let s=C(o);Qv(s);let u=w(s,`.stage-${he()}`);a({path:u}),l(u,{mode:448});let f=c(u);gN(s),a({path:u,device:f.dev,inode:f.ino});let p=!0,m=!1,h,v=e=>{p=e.phase===`idle`,r(e)};try{let r=JSON.parse(await hN(`npm`,[`pack`,`@aviaratech/ai-delivery@${t}`,`--ignore-scripts`,`--json`,`--logs-max`,`0`,`--cache`,w(e.directory,`npm-cache`),`--pack-destination`,u],u,n,v))[0]?.filename;if(typeof r!=`string`||!/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(r))throw Error(`npm returned an unsafe archive path.`);let i=d(w(u,r)),c=xN(i),l=JSON.parse(c.get(`package/package.json`)?.toString()??`null`);if(l?.name!==`@aviaratech/ai-delivery`||l.version!==t)throw Error(`Archive package identity does not match the explicit version.`);let f=w(u,`plugins`,`ai-delivery`);for(let[e,t]of c)if(e.startsWith(`package/plugins/ai-delivery/`)){let n=w(f,e.slice(28));Qv(C(n)),ee(n,t,{mode:384,flag:`wx`}),gN(n)}let p=JSON.parse(d(w(f,`plugin.json`),`utf8`)),m=JSON.parse(d(w(f,`.claude-plugin/plugin.json`),`utf8`)),h=JSON.parse(d(w(f,`runtime/package.json`),`utf8`));if(p.name!==`ai-delivery`||p.version!==t||m.name!==p.name||m.version!==t||m.packageVersion!==t||m.deliveryCapabilityVersion!==2||h.name!==l.name||h.version!==t)throw Error(`Archive does not contain a coherent self-contained native plugin.`);if((await hN(process.execPath,[w(f,`runtime/dist/cli.js`),`--version`],u,n,v)).trim()!==t)throw Error(`Built native CLI version does not match its archive.`);g(w(u,r),w(u,`archive.tgz`)),gN(w(u,`archive.tgz`)),ey(w(u,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:iN(i),files:yN(f)}),g(u,o),gN(s),a(void 0),bN(e,t)}catch(e){m=!0,h=e}try{if(p&&i(u)){let e=c(u);if(e.dev!==f.dev||e.ino!==f.ino||!e.isDirectory()||e.isSymbolicLink())throw Error(`Owned staging directory identity changed.`);_(u,{recursive:!0}),gN(s)}p&&a(void 0)}catch(e){h=m?AggregateError([h,e],`Plugin preparation failed and staging cleanup also failed.`):e,m=!0}if(m)throw h}function CN(e,t){let n=`./versions/${t}/plugins/ai-delivery`;return[{path:w(e.catalog,`.agents/plugins/marketplace.json`),value:{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}},{path:w(e.catalog,`.claude-plugin/marketplace.json`),value:{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]}}]}function wN(e,t){return CN(e,t).map(({path:e})=>{uN(e);let t=c(e);if(!t.isFile()||t.nlink!==1||(t.mode&511)!=384||t.size>1024**2)throw Error(`Managed catalog is unsafe.`);return{path:e,bytes:d(e),device:t.dev,inode:t.ino}})}function TN(e,t,n){return CN(t,n).map(({value:t},n)=>JSON.stringify(JSON.parse(e[n].bytes.toString()))===JSON.stringify(t))}function EN(e){uN(e.path);let t=c(e.path);if(!t.isFile()||t.nlink!==1||(t.mode&511)!=384||t.size!==e.bytes.length||t.dev!==e.device||t.ino!==e.inode||!d(e.path).equals(e.bytes))throw Error(`Managed catalog changed during this operation.`)}function DN(e,t,n){bN(e,t);for(let[r,i]of CN(e,t).entries())n&&EN(n[r]),ey(i.path,i.value)}async function ON(e,t,n,r,i=!1){let a=JSON.parse(await hN(t.tool,[`plugin`,`list`,...e.host===`codex`&&!i?[`--marketplace`,t.marketplace,`--available`]:[],`--json`],t.projectRoot,n,r,e.action===`doctor`));if(e.host===`claude-code`)return N(Ql(A(),Ll())).parse(a);let o=P({installed:N(Ql(A(),Ll())),available:N(Ql(A(),Ll()))}).parse(a);return[...o.installed.map(e=>({...e,installed:!0})),...o.available.map(e=>({...e,installed:!1}))]}function kN(e,t,n){if(e.host===`claude-code`){let e=w(t.nativeHome,`plugins/known_marketplaces.json`);if(!i(e))return!1;if(!c(e).isFile()||c(e).size>1048576)throw Error(`Native marketplace registry is unsafe.`);let n=Ql(A(),Ll()).parse(JSON.parse(d(e,`utf8`)));if(n[t.marketplace]===void 0)return!1;let r=P({source:P({source:L(`directory`),path:A()}),installLocation:A()}).parse(n[t.marketplace]);if(T(r.source.path)!==t.catalog||T(r.installLocation)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`);return!0}let r=n.filter(e=>e.marketplaceName===t.marketplace);for(let e of r){let n=P({sourceType:L(`local`),source:A()}).parse(e.marketplaceSource);if(T(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return r.length>0}function AN(e,t,n){let r=n.filter(n=>(n.pluginId??n.id)===`ai-delivery@${t.marketplace}`&&(e.host===`codex`?n.installed===!0:n.scope===e.scope)&&(e.scope===`user`||n.projectPath===t.projectRoot));if(r.length>1)throw Error(`Native plugin readback is ambiguous.`);let i=r[0];if(!i)return;let a=e.host===`codex`?P({source:L(`local`),path:A()}).parse(i.source).path:void 0;return{registration:i,version:QM.parse(i.version),enabled:M().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Ql(A(),Ll()).parse(i.mcpServers)}:{}}}function jN(e){let t=w(e.catalog,`.claude-plugin/marketplace.json`);if(uN(t),!c(t).isFile()||c(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=P({name:L(e.marketplace),plugins:N(P({name:A(),version:QM,source:A()}))}).parse(JSON.parse(d(t,`utf8`))).plugins.filter(e=>e.name===`ai-delivery`);if(n.length!==1)throw Error(`Managed Claude catalog selection is ambiguous.`);let r=n[0];if(!r.source.startsWith(`./`)||T(e.catalog,r.source)!==_N(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function MN(e,t,n,r,i=n.version){let a=bN(t,n.version),o=_N(t,i);if(i!==n.version&&bN(t,i),e.host===`claude-code`&&jN(t).version!==i)throw Error(`Claude catalog version differs from its native selection.`);if(e.host===`codex`&&T(n.sourceRoot)!==o)throw Error(`Native plugin source differs from the managed version.`);let s=r;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`claude-code`&&(n.installedPath===void 0||T(n.installedPath)!==T(s)))throw Error(`Native cache path differs from the managed native selection.`);if(T(s)!==w(t.nativeHome,`plugins/cache`,t.marketplace,`ai-delivery`,n.version))throw Error(`Native cache path is outside the managed native selection.`);if(uN(s),JSON.stringify(yN(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!P({command:L(`node`),args:Xl([L("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function NN(e,t,n){let r=new XM({command:process.execPath,args:[w(e,`dist/mcp-launcher.js`)],cwd:n,env:{...Object.fromEntries(JM.map(e=>[e,``])),NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new PM({name:`ai-delivery-plugin-doctor`,version:`1.0.0`});try{if(await i.connect(r,{timeout:3e4}),i.getServerVersion()?.version!==t)throw Error(`MCP server version differs from the selected archive.`);return await i.listTools({},{timeout:3e4}),{configuration:`native_manifest_present`,startup:`ready`,version:t}}catch{return{configuration:`native_manifest_present`,startup:`failed`,error:`Bundled MCP startup failed; raw output withheld.`}}finally{await i.close(),await r.close()}}async function PN(e){let t=$M.parse(e);if(t.checkAuth&&t.action!==`doctor`)throw Error(`--check-auth is supported only for doctor.`);if(t.checkAuth&&t.repo===void 0)throw Error(`doctor --check-auth requires explicit --repo owner/name.`);if(t.host===`codex`&&t.scope!==`user`)throw Error(`Codex currently supports user plugin installation; select --scope user.`);if((t.action===`install`||t.action===`update`)&&t.version===void 0)throw Error(`An explicit --version is required for install and update.`);if(t.version!==void 0&&t.action!==`install`&&t.action!==`update`)throw Error(`--version is supported only for install and update; rollback selects the recorded previous version.`);if(![`darwin`,`linux`].includes(process.platform))throw Error(`Plugin management requires the supported POSIX runtime environment.`);let n=dN(t),r=fN(t,n),a={action:t.action,host:t.host,scope:t.scope,version:t.action===`remove`?null:t.version??(t.action===`rollback`?r?.previousVersion:r?.currentVersion)??null,changed:!1,dryRun:t.dryRun,installed:!1,marketplace:n.marketplace,managedDirectory:n.directory,repositoryAdmission:`explicit_stage_and_admit_required`};if(t.checkAuth&&(a.authProbe={invocationContext:`selected_runtime_cli`,nativeGuiPropagation:`unverified`,settings:`not_checked`,processReferences:{status:`not_checked`,requiredNames:[],missingNames:[]},authentication:{status:`not_checked`},repositoryAccess:{repository:t.repo,status:`not_checked`},outcome:t.dryRun?`not_checked`:`blocked`,reason:t.dryRun?`dry_run`:`native_plugin_not_ready`}),t.dryRun||(a.diagnostics=aN(t,n),a.activation={installedVersion:null,startupVersion:null,loadedVersion:null},t.action===`preview`))return a;if(t.action===`doctor`){if(r&&(a.recoveryRequired=r.pending!==void 0),r?.pending)return a;if(!r?.currentVersion){try{oN(a,t,n,await ON(t,n,new AbortController().signal,void 0,!0))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a}try{bN(n,r.currentVersion)}catch{return a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:`Managed archive integrity failed.`},a}let e=await ON(t,n,new AbortController().signal),i=kN(t,n,e),o=AN(t,n,e);if(a.installed=o?.version===r.currentVersion,a.enabled=o?.enabled??!1,r.installedPath&&(a.nativeCachePath=r.installedPath),r.nativeVersion&&(a.nativeVersion=r.nativeVersion),!i||!a.installed){a.mcp={configuration:`missing`,startup:`not_checked`};try{oN(a,t,n,await ON(t,n,new AbortController().signal,void 0,!0))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a}a.activation.installedVersion=r.currentVersion;try{a.nativePluginRoot=MN(t,n,o,r.installedPath),a.sourceIntegrity=!0,a.skills=p(w(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await NN(a.nativePluginRoot,r.currentVersion,n.projectRoot):{configuration:`disabled`,startup:`not_checked`}}catch(e){a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:t.checkAuth?`Selected native plugin integrity failed; raw output withheld.`:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}if(oN(a,t,n,e,o.registration),t.host===`codex`)try{let r=await ON(t,n,new AbortController().signal,void 0,!0),i=new Set(e.flatMap(e=>typeof e.pluginId==`string`?[e.pluginId]:[]));oN(a,t,n,r.filter(e=>typeof e.pluginId!=`string`||!i.has(e.pluginId)))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a.mcp?.startup===`ready`&&(a.activation.startupVersion=a.mcp.version??null),a.authProbe&&a.sourceIntegrity&&a.enabled&&a.mcp?.startup===`ready`&&(delete a.authProbe.reason,await lN(t,a.nativePluginRoot,a.authProbe)),a}if(!r&&t.action===`remove`)return a;if(!r&&i(n.directory)&&p(n.directory).length>0)throw Error(`Managed plugin directory contains unrecognized content.`);return Qv(n.directory),Oy(n.statePath,{projectRoot:n.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{if(r=fN(t,n),t.action===`rollback`){if(!r?.currentVersion)throw Error(`Preserving rollback requires a current managed selection; it cannot reinstall a removed plugin.`);if(r.previousVersion!==a.version)throw Error(`Managed rollback target changed before acquiring its ownership lock.`)}let e=i(n.statePath)?{bytes:d(n.statePath),metadata:c(n.statePath)}:void 0,o=()=>{if(uN(n.statePath),e){fN(t,n);let r=c(n.statePath);if(r.dev!==e.metadata.dev||r.ino!==e.metadata.ino||(r.mode&511)!=384||r.mode!==e.metadata.mode||!d(n.statePath).equals(e.bytes))throw Error(`Managed state changed during this operation.`)}else if(i(n.statePath))throw Error(`Managed state appeared during this operation.`);ey(n.statePath,r),e={bytes:d(n.statePath),metadata:c(n.statePath)}},s=r?.pending!==void 0;if(r?.pending){if(await mN(r.pending),r.pending.producerDigest!==vb(C(be(import.meta.url))))throw Error(`Interrupted plugin operation belongs to a different controller; resume with its original version.`);let e=r.pending.staging;if(e&&i(e.path)){let t=C(vN(n,r.pending.targetVersion));if(C(e.path)!==t||!/^\.stage-[a-f0-9-]{36}$/u.test(e.path.slice(t.length+1)))throw Error(`Recorded staging path is outside this version target.`);uN(e.path);let i=c(e.path);if(!i.isDirectory()||(e.device===void 0?p(e.path).length!==0:i.dev!==e.device||i.ino!==e.inode))throw Error(`Interrupted staging directory ownership is unresolved.`);_(e.path,{recursive:!0}),gN(t)}if(r.pending.action!==t.action||r.pending.targetVersion!==a.version)throw Error(`Resume the interrupted original plugin command before selecting a different operation.`)}if(t.action===`update`&&!r?.currentVersion)throw Error(`Install a managed plugin before updating or rolling it back.`);let l=t.action===`remove`?null:a.version;if(l===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let u=r?.currentVersion??null;r??={owner:`@aviaratech/ai-delivery.plugin@1`,host:t.host,scope:t.scope,projectRoot:t.scope===`user`?null:n.projectRoot,nativeHome:n.nativeHome,marketplace:n.marketplace,currentVersion:null,previousVersion:null,installedPath:null};let f=pN(process.pid);if(!f)throw Error(`Installer owner identity is unknown.`);r.pending={action:t.action,targetVersion:l,owner:{pid:process.pid,birth:f},producerDigest:vb(C(be(import.meta.url))),command:{phase:`idle`}},o();let m=new AbortController,h=()=>m.abort();process.once(`SIGINT`,h),process.once(`SIGTERM`,h);let g=e=>{r.pending.command=e,o()},v=e=>hN(n.tool,e,n.projectRoot,m.signal,g),y=`ai-delivery@${n.marketplace}`,b=t.host===`codex`?[`plugin`,`remove`,y,`--json`]:[`plugin`,`uninstall`,y,`--scope`,t.scope,`--keep-data`],x=t.host===`codex`?[`plugin`,`add`,y,`--json`]:[`plugin`,u?`update`:`install`,y,`--scope`,t.scope],ee=!1;try{if(r.nativeVersion=(await v([`--version`])).trim(),u&&l){if(t.host===`claude-code`){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;if(r.nativeVersion!==`2.1.296 (Claude Code)`||t.scope!==`user`||!e.test(u)||!e.test(l)||(l.split(`.`).map(BigInt).map((e,t)=>e-BigInt(u.split(`.`)[t])).find(e=>e!==0n)??0n)<0n)throw Error(`Claude preserving replacement is unqualified; no catalog or native selection was changed.`)}if(t.host===`codex`&&r.nativeVersion!==`codex-cli 0.162.1`)throw Error(`This native version has no qualified preserving replacement route.`)}if(t.host===`claude-code`&&!(await v([`plugin`,`uninstall`,`--help`])).includes(`--keep-data`))throw Error(`This Claude Code version cannot preserve plugin data; upgrade the native tool first.`);process.stderr.write(`ai-delivery.plugin ${JSON.stringify({action:t.action,host:t.host,scope:t.scope,stage:l?`prepare_version`:`native_remove`,version:l})}\n`);let e=await ON(t,n,m.signal,g),i=kN(t,n,e),c=AN(t,n,e);if(c&&!u&&!(s&&c.version===l))throw Error(`Existing native plugin is not owned by managed state.`);let d=c?.version;if(c&&s&&t.host===`claude-code`&&(d=jN(n).version,d!==u&&d!==l))throw Error(`Interrupted native selection has an incompatible catalog version.`);if(c&&l&&!c.enabled)throw Error(`Native plugin selection is disabled; preserving replacement cannot enable it.`);let f,p=!1;if(u&&l){if(!i||!c||c.version!==u&&!(s&&c.version===l))throw Error(`Managed native selection changed; replacement ownership is unresolved.`);f=wN(n,u);let e=TN(f,n,u),r=TN(f,n,l),a=e.every(Boolean),o=r.every(Boolean),m=s&&r[0]&&e[1];if(!a&&!o&&!m)throw Error(`Managed catalog differs from the owned prior or target publication.`);if(d=r[t.host===`codex`?0:1]?l:u,c.version===l){if(!o)throw Error(`Selected target has an incompatible managed catalog.`);p=!0}else if(o)throw Error(`Interrupted replacement is ambiguous; native selection will not be repeated.`)}else if(l&&c&&s){if(f=wN(n,l),!TN(f,n,l).every(Boolean))throw Error(`Selected target has an incompatible managed catalog.`);p=c.version===l}let h;c&&(h=MN(t,n,c,c.installedPath??(c.version===u?r.installedPath:w(n.nativeHome,`plugins/cache`,n.marketplace,`ai-delivery`,c.version)),d)),l&&(await SN(n,l,m.signal,g,e=>{e?r.pending.staging=e:delete r.pending.staging,o()}),p||(ee=!0,DN(n,l,f)),!i&&!p&&await v([`plugin`,`marketplace`,`add`,n.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),c&&t.action===`remove`&&(ee=!0,await v(b));let _=p?c?.installedPath??h??r.installedPath:r.installedPath;if(l&&!p){let e=await v(x);t.host===`codex`&&(_=P({installedPath:A()}).parse(JSON.parse(e)).installedPath)}let y=await ON(t,n,m.signal,g);if(!kN(t,n,y)&&l)throw Error(`Native marketplace registration is missing.`);let S=AN(t,n,y);if(l?S?.version!==l:S!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(l&&(MN(t,n,S,S?.installedPath??_),!S.enabled))throw Error(`Native plugin selection is disabled.`);return r.currentVersion=l,u!==l&&(r.previousVersion=u),r.installedPath=l?S?.installedPath??_:null,delete r.pending,o(),a.version=l,a.changed=u!==l,a.installed=l!==null,a.activation={installedVersion:l,startupVersion:null,loadedVersion:null},l&&(a.nativePluginRoot=r.installedPath??_N(n,l)),a}catch(e){if(!s&&!m.signal.aborted&&!ee&&r.pending?.command.phase===`idle`&&r.pending.staging===void 0){delete r.pending;try{o()}catch(t){throw AggregateError([e,t],`Plugin preparation failed and pending-state cleanup also failed.`)}}throw e}finally{process.removeListener(`SIGINT`,h),process.removeListener(`SIGTERM`,h)}}})}var FN=new qe;FN.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(sM).option(`--identity <name>`,`Configured author or reviewer identity`).option(`--personal-auth`,`Explicit legacy personal-token author override`).option(`--repo <owner/name>`,`GitHub repository owner/name; works from any directory`).option(`--repo-root <path>`,`Launch directory or explicit clone for local operations`,process.cwd());for(let e=2;e<process.argv.length;e++){let t=process.argv[e],n=FN.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&FN.enablePositionalOptions();break}function IN(){let e=FN.opts(),t=(e.identity??process.env.AI_DELIVERY_IDENTITY)?.trim()||void 0;return{repoRoot:e.repoRoot,...t===void 0?{}:{identity:t},personalAuth:e.personalAuth===!0,...e.repo===void 0?{}:{repo:e.repo}}}function $(e){return e===void 0?void 0:Number(e)}function LN(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function RN(e){return LN(e)?.map(Number)}function zN(e,t){if(e!==void 0&&t!==void 0)throw Error(`Pass either --body or --body-file.`);return t===void 0?e:d(t,`utf8`)}function BN(e,t){let n=e===void 0?{}:JSON.parse(d(e,`utf8`));return{...ov.parse(n),...Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}}function VN(e,t){return fw(e,t,IN()).then(t=>rt(e,t))}function HN(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var UN=FN.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`preview`,`update`,`rollback`,`remove`]){let t=UN.command(e).requiredOption(`--host <host>`,`Native host: codex or claude-code`).option(`--scope <scope>`,`Native scope: user, project, or local; Codex supports user`,`user`).option(`--dry-run`,`Describe the selected target without changing files or contacting native tools`).option(`--json`,`Print the result as JSON`);(e===`install`||e===`update`)&&t.requiredOption(`--version <version>`,`Explicit published package version`),e===`doctor`&&t.option(`--check-auth`,`Read configured role identities and repository access; requires explicit --repo`),t.action(async t=>{let n=await PN({action:e,host:t.host,scope:t.scope,...t.version===void 0?{}:{version:t.version},dryRun:t.dryRun===!0,checkAuth:t.checkAuth===!0,...t.checkAuth&&IN().repo?{repo:IN().repo}:{},repoRoot:IN().repoRoot});if(t.json){HN(n);return}if(process.stdout.write(`${n.dryRun?`Dry run: `:``}${n.host} ${n.scope}: ${e}; version ${n.version??`none`}; installed ${n.installed}; changed ${n.changed}\n`),n.mcp&&process.stdout.write(`Bundled MCP startup: ${n.mcp.startup}${n.mcp.error?` (${n.mcp.error})`:``}\n`),n.diagnostics){process.stdout.write(`Registration observations: ${n.diagnostics.registrations.length}; completeness ${n.diagnostics.completeness}; migration ${n.diagnostics.migration}; planned changes ${n.diagnostics.plannedChanges.length}\n`);for(let e of n.diagnostics.registrations)process.stdout.write(`${e.kind} ${e.scope}: ownership ${e.ownership}; source ${e.source}; version ${e.version??`unknown`}\n`);process.stdout.write(`Unverified conditions: ${n.diagnostics.findings.join(`, `)}\n`)}n.activation&&process.stdout.write(`Native session loaded version: unverified. Installed observation: ${n.activation.installedVersion??`unknown`}; separate startup: ${n.activation.startupVersion??`not checked`}. Use the host's surface-specific activation guidance.\n`),n.recoveryRequired&&process.stdout.write(`Resume the interrupted original plugin command to recover this target.
311
+ `),n.authProbe&&process.stdout.write(`Selected-runtime CLI auth probe: ${n.authProbe.outcome}; settings ${n.authProbe.settings}; process references ${n.authProbe.processReferences.status}; authentication ${n.authProbe.authentication.status}; repository access ${n.authProbe.repositoryAccess.status}${n.authProbe.reason?` (${n.authProbe.reason})`:``}\nNative GUI credential propagation and counted exact-head approval remain unverified.\n`)})}FN.command(`runtime:stage`).description(`Stage a reviewed archive in a private directory; does not activate or admit it`).requiredOption(`--archive <path>`).requiredOption(`--archive-sha256 <digest>`).requiredOption(`--package-version <version>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--native-plugin-root <path>`,`Bind the exact reviewed native plugin root`).option(`--max-aggregate-rss-bytes <bytes>`,`Sampled controller plus children RSS limit`).option(`--max-new-output-bytes <bytes>`,`Owned stage and metadata output limit`).option(`--min-free-disk-bytes <bytes>`,`Required free disk headroom`).option(`--max-captured-output-bytes <bytes>`,`Retained command log cap; defaults to 1 MiB`).option(`--authorize-stage`,`Explicit authority to stage this reviewed archive`).action(async e=>VN(`runtime_stage`,{authority:e.authorizeStage===!0?`runtime:stage`:``,archivePath:e.archive,expectedArchiveSha256:e.archiveSha256,packageVersion:e.packageVersion,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot},...[`maxAggregateRssBytes`,`maxNewOutputBytes`,`minFreeDiskBytes`,`maxCapturedOutputBytes`].some(t=>e[t]!==void 0)?{resourceBounds:{maxAggregateRssBytes:Number(e.maxAggregateRssBytes??1024**3),minFreeDiskBytes:Number(e.minFreeDiskBytes??256*1024**2),maxNewOutputBytes:Number(e.maxNewOutputBytes??512*1024**2),maxCapturedOutputBytes:Number(e.maxCapturedOutputBytes??1024**2)}}:{}})),FN.command(`runtime:admit`).description(`Explicitly publish the existing admission for an exact completed stage`).requiredOption(`--stage-id <digest>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--expected-prior <digest>`,`SHA-256 of the exact current private admission bytes`).option(`--expected-absent`,`Explicitly require no current admission`).option(`--authorize-admit`,`Explicit authority for the final admission write`).action(async e=>{if(e.expectedPrior===void 0==(e.expectedAbsent!==!0))throw Error(`Choose exactly one of --expected-prior or --expected-absent.`);return VN(`runtime_admit`,{authority:e.authorizeAdmit===!0?`runtime:admit`:``,stageId:e.stageId,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,expectedPriorAdmissionSha256:e.expectedAbsent===!0?null:e.expectedPrior})}),FN.command(`create`).requiredOption(`--title <title>`).option(`--fields-file <path>`,`UTF-8 JSON typed fields; explicit CLI fields take precedence`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).action(async e=>VN(`issue_create`,BN(e.fieldsFile,{title:e.title,body:zN(e.body,e.bodyFile),issueType:e.type,points:$(e.points),priority:e.priority,labels:LN(e.labels),blockedBy:RN(e.blockedBy),blocks:RN(e.blocks),overrideReason:e.overrideReason,milestone:$(e.milestone),parentIssueNumber:$(e.parent),...e.draft===!0?{draft:!0}:{}}))),FN.command(`start`).option(`--issue <number>`).option(`--request <text>`).option(`--request-id <id>`,`Stable retry identity for a new issue start`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--branch <branch>`).option(`--resume-created`).option(`--investigation-worktree <path>`,`Prospectively register an already linked host-created investigation`).option(`--expected-head <sha>`,`Exact unchanged initial commit for investigation registration`).action(async e=>{if(e.investigationWorktree!==void 0||e.expectedHead!==void 0){if(Object.keys(e).some(e=>![`issue`,`investigationWorktree`,`expectedHead`].includes(e)))throw Error(`Investigation registration cannot create or change issue/branch metadata.`);return VN(`issue_start`,{issueNumber:$(e.issue),investigationWorktree:e.investigationWorktree,expectedHeadSha:e.expectedHead})}return VN(`issue_start`,{issueNumber:$(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:zN(e.body,e.bodyFile),issueType:e.type,points:$(e.points),priority:e.priority,labels:LN(e.labels),blockedBy:RN(e.blockedBy),blocks:RN(e.blocks),overrideReason:e.overrideReason,milestone:$(e.milestone),parentIssueNumber:$(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0})});for(let e of[`list`,`search`])FN.command(e).option(`--query <text>`,`Literal text to search in the selected repository`).option(`--state <state>`).option(`--labels <labels>`).option(`--parent <number>`).option(`--type <type>`).option(`--project-status <status>`).option(`--updated-since <timestamp>`).option(`--page <number>`).option(`--per-page <number>`).action(async t=>VN(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:LN(t.labels),parentIssueNumber:$(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:$(t.page),perPage:$(t.perPage)}));FN.command(`update`).requiredOption(`--issue <number>`).option(`--fields-file <path>`,`UTF-8 JSON typed issue field patch`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--state <state>`).option(`--preserve-history`,`Preserve the previous title and body before a rewrite`).option(`--close-reason <reason>`).option(`--superseded-by <number>`).option(`--park`,`Park execution while retaining the issue worktree`).action(async e=>VN(`issue_update`,BN(e.fieldsFile,{issueNumber:$(e.issue),title:e.title,...e.draft===!0?{draft:!0}:{},body:zN(e.body,e.bodyFile),issueType:e.type,points:$(e.points),priority:e.priority,labels:LN(e.labels),blockedBy:RN(e.blockedBy),blocks:RN(e.blocks),overrideReason:e.overrideReason,milestone:$(e.milestone),parentIssueNumber:$(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:$(e.supersededBy),park:e.park===!0||void 0}))),FN.command(`health`).requiredOption(`--from <utc>`,`Inclusive UTC ISO timestamp`).requiredOption(`--to <utc>`,`Exclusive UTC ISO timestamp`).option(`--max-issues <number>`).option(`--max-timeline-pages <number>`).option(`--max-project-pages <number>`).option(`--oldest-limit <number>`).action(async e=>VN(`delivery_health`,{repo:IN().repo,from:e.from,to:e.to,maxIssues:$(e.maxIssues),maxTimelinePages:$(e.maxTimelinePages),maxProjectPages:$(e.maxProjectPages),oldestLimit:$(e.oldestLimit)})),FN.command(`info`).requiredOption(`--issue <number>`).action(async e=>VN(`issue_info`,{issueNumber:$(e.issue)})),FN.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>VN(`issue_ready_check`,{issueNumber:$(e.issue)}));for(let e of[`parent`,`blockers`])FN.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await fw(`issue_info`,{issueNumber:$(t.issue)},IN());HN(e===`parent`?{issueNumber:$(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:$(t.issue),blockedBy:n.blockedBy})});FN.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await uw(IN(),`subissues`);HN({issueNumber:$(e.issue),subissues:await Kv(t,Number(e.issue))})}),FN.command(`pr:create`).description(`Create a PR from a linked issue branch, or promote an existing associated PR with --head and --ready.`).requiredOption(`--issue <number>`).option(`--pr <number>`,`Exact existing PR selector; never creates a replacement`).option(`--non-closing`,`Retain the issue OPEN using native non-closing reference proof`).option(`--title <title>`).option(`--body-file <path>`).option(`--head <branch>`,`Explicit remote head; existing PR promotion verifies its native issue association`).option(`--ready`,`Publish ready, or promote the author-owned PR selected by --head`).option(`--dry-run`).action(async e=>VN(`issue_pr_create`,{issueNumber:$(e.issue),prNumber:$(e.pr),nonClosing:e.nonClosing,title:e.title,body:zN(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),FN.command(`pr:info`).description(`Inspect an exact PR; combine --issue and --pr to verify its native closing-issue association.`).option(`--non-closing`,`Verify an exact native non-closing PR-to-issue reference`).option(`--issue <number>`,`Issue to verify; issue-only lookup requires a GitHub-linked branch`).option(`--pr <number>`,`Exact PR number; include --issue after issue branch links are replaced on publication`).action(async e=>VN(`issue_pr_info`,{issueNumber:$(e.issue),prNumber:$(e.pr),nonClosing:e.nonClosing})),FN.command(`pr:list`).option(`--state <state>`,`open, closed or all`,`open`).action(async e=>{if(![`open`,`closed`,`all`].includes(e.state))throw Error(`Invalid PR state.`);HN(await oC(await uw(IN(),`pr:list`),e.state))}),FN.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{HN(await sC(await uw(IN(),`pr:checks`),Number(e.pr)))}),FN.command(`pr:review`).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).requiredOption(`--artifact <path>`,`Path to a UTF-8 JSON review artifact file (not inline JSON)`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`).action(async e=>VN(`issue_pr_review`,{issueNumber:$(e.issue),prNumber:$(e.pr),artifact:d(e.artifact,`utf8`),dryRun:e.dryRun===!0,nonClosing:e.nonClosing}));for(let[e,t]of[[`pr:merge`,`issue_pr_merge`],[`finish`,`issue_finish`]]){let n=FN.command(e).requiredOption(`--issue <number>`);e===`pr:merge`?n.requiredOption(`--pr <number>`):n.option(`--pr <number>`),n.option(`--strategy <method>`).option(`--reviewed-head <sha>`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`),e===`finish`&&n.option(`--investigation`,`Complete an unchanged prospectively registered investigation`).option(`--result <path>`,`Durable independently reviewed result outside the removable worktree`).option(`--authority-comment <number>`,`Exact native operator removal authority comment`).option(`--acceptance-comment <number>`,`Exact configured-App result acceptance comment`),n.action(async e=>{if(e.investigation===!0){if(e.pr!==void 0||e.strategy!==void 0||e.reviewedHead!==void 0||e.nonClosing!==void 0)throw Error(`Investigation completion cannot accept PR or merge options.`);return VN(t,{issueNumber:$(e.issue),investigation:!0,resultPath:e.result,authorityCommentId:$(e.authorityComment),acceptanceCommentId:$(e.acceptanceComment),dryRun:e.dryRun===!0})}if(e.result!==void 0||e.authorityComment!==void 0||e.acceptanceComment!==void 0)throw Error(`Investigation evidence requires --investigation.`);return VN(t,{issueNumber:$(e.issue),prNumber:$(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0,nonClosing:e.nonClosing})})}FN.command(`worktree:transition:inspect`).requiredOption(`--issue <number>`).requiredOption(`--purpose <purpose>`,`active-resume or merged-cleanup`).option(`--disposition <disposition>`,`retain (default) or explicitly unheld remove`).option(`--terminal-pr <number>`).option(`--retained-holds <comment-ids>`,`Comma-separated native retained-hold comment IDs`).option(`--retained-admission <path>`).option(`--retained-archive <path>`).action(async e=>VN(`issue_worktree_transition_inspect`,{issueNumber:$(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:$(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:RN(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),FN.command(`worktree:transition:apply`).requiredOption(`--plan <path>`).requiredOption(`--plan-id <digest>`).requiredOption(`--relinquishment-comment <id>`).requiredOption(`--acceptance-comment <id>`).option(`--authorize-transition`,`Explicit authority for this exact independently accepted plan`).action(async e=>VN(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),FN.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=mM(JSON.parse(d(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),FN.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await uw(IN(),`config:resolve`);HN({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await dC(e,void 0,void 0,`development`)})}),FN.command(`mcp:serve`).action(async()=>uM(IN())),FN.parseAsync(process.argv).catch(it);export{};