@aviaratech/ai-delivery 0.3.28 → 0.3.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -4
- package/dist/cli.js +9 -1
- package/dist/cli.js.map +1 -1
- package/dist/currentTrackingScenario.test.d.ts +1 -0
- package/dist/currentTrackingScenario.test.js +486 -0
- package/dist/currentTrackingScenario.test.js.map +1 -0
- package/dist/issue.d.ts +2 -0
- package/dist/issue.js +2 -0
- package/dist/issue.js.map +1 -1
- package/dist/issueInfoReadback.test.d.ts +1 -0
- package/dist/issueInfoReadback.test.js +203 -0
- package/dist/issueInfoReadback.test.js.map +1 -0
- package/dist/pluginDoctor.test.js +20 -2
- package/dist/pluginDoctor.test.js.map +1 -1
- package/dist/pluginInstaller.d.ts +22 -0
- package/dist/pluginInstaller.js +209 -8
- package/dist/pluginInstaller.js.map +1 -1
- package/dist/pluginInstaller.test.js +219 -6
- package/dist/pluginInstaller.test.js.map +1 -1
- package/package.json +1 -1
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/README.md +7 -1
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +3 -3
- package/plugins/ai-delivery/runtime/package.json +1 -1
|
@@ -280,7 +280,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
280
280
|
}
|
|
281
281
|
}
|
|
282
282
|
}
|
|
283
|
-
`,{owner:e.repo.owner,name:e.repo.repo,number:t}),i=N({repository:N({issue:N({number:A().int().positive().safe(),repository:n,state:F([`OPEN`,`CLOSED`]),stateReason:F([`COMPLETED`,`NOT_PLANNED`,`DUPLICATE`,`REOPENED`]).nullable(),duplicateOf:N({number:A().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 L(`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 L(`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 Ov(e,t){if(e.clients.role!==`author`)throw new L(`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 L(`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 L(`A superseding issue must be a different positive issue number.`);let{clients:n,config:r,repo:i}=e,a=await Av(e,t.issueNumber),o=_v(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 gv(e,t.labels);if(t.issueType!==void 0&&!r.native.issueTypes.includes(t.issueType))throw new L(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!r.native.points.values.includes(String(t.points)))throw new L(`Unsupported configured Points value.`);if(t.priority!==void 0&&!r.native.priority.values.includes(t.priority))throw new L(`Unsupported configured Priority value.`);if(t.parentIssueNumber!==void 0||t.blockedBy!==void 0){let e=await f_({graphql:n.graphql,issueNumber:t.issueNumber,repo:i});await v_({blockers:e.blockers.map(e=>e.number),...e.parentNumber===null?{}:{parentIssueNumber:e.parentNumber},repo:i,rest:n.rest}),await v_({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 E_(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 L(`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 L(`Native closure readback disagrees with the requested reason or superseding issue.`)};if(l!==void 0){let n=await Dv(e,t.issueNumber);if(n.state===`closed`)try{d(n)}catch{throw new L(`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 L(`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=Ev(a.title,a.body),r=J_({title:a.title,legacyBody:a.body,draft:!0},!1);if(r.failures.length)throw new Y_(r.failures);if(n.length>65536)throw new L(`Complete issue history exceeds the supported comment body limit; issue was not rewritten.`);p=a,f=await pv(e,{issueNumber:t.issueNumber,body:n})}}let m;if(l!==void 0&&(m=await pv(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 L(`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":rg}},...l!==`duplicate`||u===void 0?{}:{duplicate_issue_id:u},...t.title===void 0?{}:{title:t.title}});let h=l===void 0?void 0:await Dv(e,t.issueNumber);h!==void 0&&d(h),(t.points!==void 0||t.priority!==void 0)&&await dg({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:ig(r)}),t.parentIssueNumber!==void 0&&await __({graphql:n.graphql,issueNumber:t.issueNumber,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&t.parentIssueNumber!==null&&await og({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:ig(r)});try{t.blockedBy!==void 0&&await g_({...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 m_({...c===void 0?{}:{beforeAdd:c},blockers:[t.issueNumber],graphql:n.graphql,issueNumber:e,repo:i,rest:n.rest})}catch(e){throw new L(`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 Av(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 Du({graphql:n.graphql,issueNodeId:v.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tu(r),status:_});let y=await Av(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 L(`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 kv(e,t){return Ov(e,t)}async function Av(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 L(`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:ig(r)}),f_({graphql:n.graphql,issueNumber:t,repo:i}),Su({graphql:n.graphql,issueNodeId:a.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tu(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,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 jv(e,t){if(`pull_request`in(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data)throw new L(`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 Mv(e,t){let n=await Av(e,t),r=await p_({issueNumber:t,repo:e.repo,rest:e.clients.rest});return nv({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 Nv(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 L(`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 L(`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 L(`GitHub linked branch pagination did not advance.`);r.add(o),i=o}throw new L(`GitHub linked issue branches exceed the bounded readback window.`)}async function Pv(e,t,n){let r=(await Nv(e,t)).filter(e=>n===void 0||e.name===n);if(r.length!==1)throw new L(`Select exactly one GitHub-linked issue branch; no local worktree or receipt fallback is available.`);return r[0].name}async function Fv(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 L(`Start requires the requested open GitHub issue.`);let i=await Nv(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 L(`Invalid issue branch name.`);let o=i.filter(e=>e.name===a);if(i.length>0&&o.length!==1)throw new L(`Select exactly one existing GitHub-linked issue branch before start.`);if(o.length>1)throw new L(`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 L(`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 Nv(e,t)).filter(e=>e.name===a);if(l.length!==1||l[0].sha!==c)throw new L(`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 Iv(e,t){let n=await Mv(e,t);if(!n.ready)throw new Y_(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 L(`Start requires the requested open GitHub issue before Project synchronization.`);return Du({graphql:e.clients.graphql,issueNodeId:r.node_id,org:e.config.native.organization,...e.projectConfiguration===void 0?{}:{configuration:e.projectConfiguration},settings:Tu(e.config),status:`In Progress`})}function Lv(e){Bv(e,448)}function Rv(e,t){Hv({directoryMode:511,mode:438,path:e,value:t})}function zv(e,t){Hv({directoryMode:448,mode:384,path:e,value:t})}function Bv(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.`)}Vv(C(e))}}function Vv(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function Hv({directoryMode:e,mode:t,path:r,value:i}){let a=C(r);Bv(a,e);let s=w(a,`.${String(process.pid)}.${me()}.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 Uv=k().regex(/^sha256:[a-f0-9]{64}$/u),Wv=2,Gv=N({admissionId:Uv,capability:N({cli:A().int().positive(),mcp:A().int().positive()}).strict(),cliPath:k().min(1),cliSha256:Uv,configDigest:Uv,mcpLauncherPath:k().min(1),mcpLauncherSha256:Uv,packageDistSha256:Uv,packageManifestSha256:Uv,packageVersion:k().min(1),pluginManifestPath:k().min(1),pluginManifestSha256:Uv,repository:k().min(1),schemaVersion:I(`ai-delivery.runtime-admission@2`),sourceArchiveSha256:Uv,sourceCommit:k().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 Kv(e){return`sha256:${fe(`sha256`).update(d(e)).digest(`hex`)}`}function qv(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:Kv(a)});else throw new L(`Runtime distribution contains an unsupported link or file type.`)}};if(n(e,``),t.length===0)throw new L(`Runtime distribution is empty.`);return B(t)}function Jv(e){let t=JSON.parse(d(e,`utf8`));if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`Runtime package or plugin manifest is invalid.`);return t}async function Yv(e){let t=id(e.repoRoot),n=e.configuration??await Mh(t,e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}),r=w(ad(t),`ai-delivery`,`runtime-admission.json`),i;try{i=Gv.parse(JSON.parse(H(r).toString(`utf8`)))}catch{throw new L(`Missing or invalid private ai-delivery runtime admission; refresh the installed binding before lifecycle mutation.`)}return Xv(i,n,e.runtimeEntryPath)}function Xv(e,t,n){let r=n??process.argv[1];if(!r)throw new L(`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=Jv(s),l=Jv(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`||Kv(n)!==e.cliSha256&&`cliSha256`||Kv(i)!==e.mcpLauncherSha256&&`mcpLauncherSha256`||Kv(a)!==e.pluginManifestSha256&&`pluginManifestSha256`||Kv(s)!==e.packageManifestSha256&&`packageManifestSha256`||qv(o)!==e.packageDistSha256&&`packageDistSha256`||e.configDigest!==t.configDigest&&`configDigest`||e.repository!==t.config.repository&&`repository`||e.capability.cli!==Wv&&`cliCapability`||e.capability.mcp!==Wv&&`mcpCapability`||c.name!==`@aviaratech/ai-delivery`&&`packageName`||c.version!==e.packageVersion&&`packageVersion`||l.name!==`ai-delivery`&&`pluginName`||l.packageVersion!==e.packageVersion&&`pluginPackageVersion`||l.deliveryCapabilityVersion!==Wv&&`pluginCapability`;if(u)throw new L(`Installed CLI/MCP source, capability or repository admission disagrees with the running delivery contract. Failed predicate: ${u}.`)}catch(e){throw e instanceof L?e:new L(`Installed CLI/MCP source or capability readback is unavailable.`)}return e}function Zv(e){for(let t of[e.cliPath,e.mcpLauncherPath,e.pluginManifestPath])if(h(t)!==t)throw new L(`Installed runtime paths must be canonical regular files.`);let t=C(e.cliPath),n=w(C(t),`package.json`),r=Jv(n).bin;if(typeof r!=`object`||!r||!(`ai-delivery`in r)||r[`ai-delivery`]!==`./dist/cli.js`)throw new L(`Installed package CLI entry is not the supported ai-delivery executable.`);let i={capability:{cli:Wv,mcp:Wv},cliPath:e.cliPath,cliSha256:Kv(e.cliPath),configDigest:e.configuration.configDigest,mcpLauncherPath:e.mcpLauncherPath,mcpLauncherSha256:Kv(e.mcpLauncherPath),packageDistSha256:qv(t),packageManifestSha256:Kv(n),packageVersion:e.packageVersion,pluginManifestPath:e.pluginManifestPath,pluginManifestSha256:Kv(e.pluginManifestPath),repository:e.configuration.config.repository,schemaVersion:`ai-delivery.runtime-admission@2`,sourceArchiveSha256:e.sourceArchiveSha256,sourceCommit:e.sourceCommit};return Xv(Gv.parse({...i,admissionId:B(i)}),e.configuration,e.cliPath)}var Qv=E(((e,t)=>{var n=Me(`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`))}}})),$v=E(((e,t)=>{var n=Me(`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())}}})),ey=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}})),ty=E(((e,t)=>{var n=Me(`fs`),r=Qv(),i=$v(),a=ey(),o=Me(`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(`
|
|
283
|
+
`,{owner:e.repo.owner,name:e.repo.repo,number:t}),i=N({repository:N({issue:N({number:A().int().positive().safe(),repository:n,state:F([`OPEN`,`CLOSED`]),stateReason:F([`COMPLETED`,`NOT_PLANNED`,`DUPLICATE`,`REOPENED`]).nullable(),duplicateOf:N({number:A().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 L(`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 L(`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 Ov(e,t){if(e.clients.role!==`author`)throw new L(`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 L(`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 L(`A superseding issue must be a different positive issue number.`);let{clients:n,config:r,repo:i}=e,a=await Av(e,t.issueNumber),o=_v(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 gv(e,t.labels);if(t.issueType!==void 0&&!r.native.issueTypes.includes(t.issueType))throw new L(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!r.native.points.values.includes(String(t.points)))throw new L(`Unsupported configured Points value.`);if(t.priority!==void 0&&!r.native.priority.values.includes(t.priority))throw new L(`Unsupported configured Priority value.`);if(t.parentIssueNumber!==void 0||t.blockedBy!==void 0){let e=await f_({graphql:n.graphql,issueNumber:t.issueNumber,repo:i});await v_({blockers:e.blockers.map(e=>e.number),...e.parentNumber===null?{}:{parentIssueNumber:e.parentNumber},repo:i,rest:n.rest}),await v_({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 E_(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 L(`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 L(`Native closure readback disagrees with the requested reason or superseding issue.`)};if(l!==void 0){let n=await Dv(e,t.issueNumber);if(n.state===`closed`)try{d(n)}catch{throw new L(`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 L(`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=Ev(a.title,a.body),r=J_({title:a.title,legacyBody:a.body,draft:!0},!1);if(r.failures.length)throw new Y_(r.failures);if(n.length>65536)throw new L(`Complete issue history exceeds the supported comment body limit; issue was not rewritten.`);p=a,f=await pv(e,{issueNumber:t.issueNumber,body:n})}}let m;if(l!==void 0&&(m=await pv(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 L(`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":rg}},...l!==`duplicate`||u===void 0?{}:{duplicate_issue_id:u},...t.title===void 0?{}:{title:t.title}});let h=l===void 0?void 0:await Dv(e,t.issueNumber);h!==void 0&&d(h),(t.points!==void 0||t.priority!==void 0)&&await dg({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:ig(r)}),t.parentIssueNumber!==void 0&&await __({graphql:n.graphql,issueNumber:t.issueNumber,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&t.parentIssueNumber!==null&&await og({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:ig(r)});try{t.blockedBy!==void 0&&await g_({...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 m_({...c===void 0?{}:{beforeAdd:c},blockers:[t.issueNumber],graphql:n.graphql,issueNumber:e,repo:i,rest:n.rest})}catch(e){throw new L(`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 Av(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 Du({graphql:n.graphql,issueNodeId:v.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tu(r),status:_});let y=await Av(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 L(`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 kv(e,t){return Ov(e,t)}async function Av(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 L(`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:ig(r)}),f_({graphql:n.graphql,issueNumber:t,repo:i}),Su({graphql:n.graphql,issueNodeId:a.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tu(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 jv(e,t){if(`pull_request`in(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data)throw new L(`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 Mv(e,t){let n=await Av(e,t),r=await p_({issueNumber:t,repo:e.repo,rest:e.clients.rest});return nv({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 Nv(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 L(`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 L(`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 L(`GitHub linked branch pagination did not advance.`);r.add(o),i=o}throw new L(`GitHub linked issue branches exceed the bounded readback window.`)}async function Pv(e,t,n){let r=(await Nv(e,t)).filter(e=>n===void 0||e.name===n);if(r.length!==1)throw new L(`Select exactly one GitHub-linked issue branch; no local worktree or receipt fallback is available.`);return r[0].name}async function Fv(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 L(`Start requires the requested open GitHub issue.`);let i=await Nv(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 L(`Invalid issue branch name.`);let o=i.filter(e=>e.name===a);if(i.length>0&&o.length!==1)throw new L(`Select exactly one existing GitHub-linked issue branch before start.`);if(o.length>1)throw new L(`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 L(`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 Nv(e,t)).filter(e=>e.name===a);if(l.length!==1||l[0].sha!==c)throw new L(`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 Iv(e,t){let n=await Mv(e,t);if(!n.ready)throw new Y_(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 L(`Start requires the requested open GitHub issue before Project synchronization.`);return Du({graphql:e.clients.graphql,issueNodeId:r.node_id,org:e.config.native.organization,...e.projectConfiguration===void 0?{}:{configuration:e.projectConfiguration},settings:Tu(e.config),status:`In Progress`})}function Lv(e){Bv(e,448)}function Rv(e,t){Hv({directoryMode:511,mode:438,path:e,value:t})}function zv(e,t){Hv({directoryMode:448,mode:384,path:e,value:t})}function Bv(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.`)}Vv(C(e))}}function Vv(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function Hv({directoryMode:e,mode:t,path:r,value:i}){let a=C(r);Bv(a,e);let s=w(a,`.${String(process.pid)}.${me()}.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 Uv=k().regex(/^sha256:[a-f0-9]{64}$/u),Wv=2,Gv=N({admissionId:Uv,capability:N({cli:A().int().positive(),mcp:A().int().positive()}).strict(),cliPath:k().min(1),cliSha256:Uv,configDigest:Uv,mcpLauncherPath:k().min(1),mcpLauncherSha256:Uv,packageDistSha256:Uv,packageManifestSha256:Uv,packageVersion:k().min(1),pluginManifestPath:k().min(1),pluginManifestSha256:Uv,repository:k().min(1),schemaVersion:I(`ai-delivery.runtime-admission@2`),sourceArchiveSha256:Uv,sourceCommit:k().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 Kv(e){return`sha256:${fe(`sha256`).update(d(e)).digest(`hex`)}`}function qv(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:Kv(a)});else throw new L(`Runtime distribution contains an unsupported link or file type.`)}};if(n(e,``),t.length===0)throw new L(`Runtime distribution is empty.`);return B(t)}function Jv(e){let t=JSON.parse(d(e,`utf8`));if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`Runtime package or plugin manifest is invalid.`);return t}async function Yv(e){let t=id(e.repoRoot),n=e.configuration??await Mh(t,e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}),r=w(ad(t),`ai-delivery`,`runtime-admission.json`),i;try{i=Gv.parse(JSON.parse(H(r).toString(`utf8`)))}catch{throw new L(`Missing or invalid private ai-delivery runtime admission; refresh the installed binding before lifecycle mutation.`)}return Xv(i,n,e.runtimeEntryPath)}function Xv(e,t,n){let r=n??process.argv[1];if(!r)throw new L(`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=Jv(s),l=Jv(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`||Kv(n)!==e.cliSha256&&`cliSha256`||Kv(i)!==e.mcpLauncherSha256&&`mcpLauncherSha256`||Kv(a)!==e.pluginManifestSha256&&`pluginManifestSha256`||Kv(s)!==e.packageManifestSha256&&`packageManifestSha256`||qv(o)!==e.packageDistSha256&&`packageDistSha256`||e.configDigest!==t.configDigest&&`configDigest`||e.repository!==t.config.repository&&`repository`||e.capability.cli!==Wv&&`cliCapability`||e.capability.mcp!==Wv&&`mcpCapability`||c.name!==`@aviaratech/ai-delivery`&&`packageName`||c.version!==e.packageVersion&&`packageVersion`||l.name!==`ai-delivery`&&`pluginName`||l.packageVersion!==e.packageVersion&&`pluginPackageVersion`||l.deliveryCapabilityVersion!==Wv&&`pluginCapability`;if(u)throw new L(`Installed CLI/MCP source, capability or repository admission disagrees with the running delivery contract. Failed predicate: ${u}.`)}catch(e){throw e instanceof L?e:new L(`Installed CLI/MCP source or capability readback is unavailable.`)}return e}function Zv(e){for(let t of[e.cliPath,e.mcpLauncherPath,e.pluginManifestPath])if(h(t)!==t)throw new L(`Installed runtime paths must be canonical regular files.`);let t=C(e.cliPath),n=w(C(t),`package.json`),r=Jv(n).bin;if(typeof r!=`object`||!r||!(`ai-delivery`in r)||r[`ai-delivery`]!==`./dist/cli.js`)throw new L(`Installed package CLI entry is not the supported ai-delivery executable.`);let i={capability:{cli:Wv,mcp:Wv},cliPath:e.cliPath,cliSha256:Kv(e.cliPath),configDigest:e.configuration.configDigest,mcpLauncherPath:e.mcpLauncherPath,mcpLauncherSha256:Kv(e.mcpLauncherPath),packageDistSha256:qv(t),packageManifestSha256:Kv(n),packageVersion:e.packageVersion,pluginManifestPath:e.pluginManifestPath,pluginManifestSha256:Kv(e.pluginManifestPath),repository:e.configuration.config.repository,schemaVersion:`ai-delivery.runtime-admission@2`,sourceArchiveSha256:e.sourceArchiveSha256,sourceCommit:e.sourceCommit};return Xv(Gv.parse({...i,admissionId:B(i)}),e.configuration,e.cliPath)}var Qv=E(((e,t)=>{var n=Me(`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`))}}})),$v=E(((e,t)=>{var n=Me(`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())}}})),ey=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}})),ty=E(((e,t)=>{var n=Me(`fs`),r=Qv(),i=$v(),a=ey(),o=Me(`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
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]),Me(`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))}}})),ny=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}})),ry=E((e=>{var t=ny();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}}})),iy=E(((e,t)=>{t.exports=ry()})),ay=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`)})),oy=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=Me(`assert`),a=ay(),o=/^win/i.test(n.platform),s=Me(`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=Me(`path`),r=ty(),i=iy(),a=oy(),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})),ly=E(((e,t)=>{var n=ty();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}})),uy=Ae(E(((e,t)=>{var n=cy(),{toPromise:r,toSync:i,toSyncOptions:a}=ly();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),dy={realpath:!1,retries:0,stale:1e4},fy=200;async function py(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/fy),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,a_(`Acquiring lock on ${c}... (attempt ${d===null?String(f):`${String(f)}/${String(d)}`})`);try{l=await uy.lock(c,{...dy,...t===void 0?{}:{onCompromised:t}}),a_(`Lock acquired on ${c}`);break}catch(e){if(!hy(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 my(fy)}}return await i()}finally{if(l!==null)try{await l(),a_(`Lock released on ${c}`)}catch(e){n?.(e),a_(`Failed to release lock on ${c}: ${e instanceof Error?e.message:String(e)}`)}}}function my(e){return new Promise(t=>setTimeout(t,e))}function hy(e){return typeof e!=`object`||!e?!1:e.code===`ELOCKED`}var gy=P({bounds:P({maxAggregateRssBytes:A().int().positive().safe(),maxNewOutputBytes:A().int().positive().safe().optional(),minFreeDiskBytes:A().int().positive().safe(),outputRoots:M(k().min(1)).min(1).optional()}),maxSampledAggregateRssBytes:A().int().nonnegative().safe().nullable(),maxSampledNewOutputBytes:A().int().nonnegative().safe().nullable(),minSampledFreeDiskBytes:A().int().nonnegative().safe().nullable(),observation:I(`sampled`),outputBaselineId:k().regex(/^sha256:[a-f0-9]{64}$/u).optional(),processCoverage:I(`observed-processes-only`),sampleCount:A().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 _y(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 L(`Invalid ${e} resource bound.`);if(e.maxNewOutputBytes===void 0!=(e.outputRoots===void 0))throw new L(`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 L(`Filesystem output roots must be nonempty paths.`);if(process.platform===`win32`)throw new L(`Resource observation requires POSIX process support.`)}var vy=`AI_DELIVERY_OUTPUT_OBSERVATION_GATE`,yy=P({pid:A().int().positive(),identity:k().min(1)}),by=P({directory:k().min(1),id:il(),owner:yy}),xy=P({gateId:il(),id:il(),kind:F([`scan`,`fixture`]),owner:yy});function Sy(e=Vy()){let t=e.get(process.pid);if(!t)throw new L(`Filesystem observation gate owner is unavailable.`);return{pid:t.pid,identity:t.identity}}function Cy(e){let t=c(e);if(!t.isDirectory()||t.mode&63||h(e)!==e)throw new L(`Filesystem observation gate directory is invalid.`)}function wy(e){try{let t=by.parse(JSON.parse(e));return Ey(t),t}catch(e){throw new L(`Filesystem observation gate capability is invalid or stale: `+(e instanceof Error?e.message:String(e)))}}function Ty(e,t=Vy()){let n=t.get(e.pid);return n?.identity===e.identity&&!n.status.startsWith(`Z`)}function Ey(e,t=!1){Cy(e.directory);let n=by.parse(JSON.parse(H(w(e.directory,`gate.json`)).toString(`utf8`))),r=Vy(),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?Ty(e.owner,r):!Ty(e.owner,r)||i?.identity!==e.owner.identity))throw new L(`Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.`);return r}function Dy(e,t){let n=xy.parse(JSON.parse(H(t).toString(`utf8`)));if(n.gateId!==e.id)throw new L(`Filesystem observation gate claim belongs to another run.`);return n}function Oy(e,t){let n=w(e.directory,`requests`);Cy(n);let r=p(n);if(r.length>1024||r.some(e=>!/^[a-f0-9-]{36}\.json$/u.test(e)))throw new L(`Filesystem observation gate scan requests are invalid.`);let i=[],a=t??Vy();for(let t of r){let r;try{r=Dy(e,w(n,t))}catch(e){if(e.code===`ENOENT`)continue;throw e}if(r.kind!==`scan`||t!==r.id+`.json`||!Ty(r.owner,a))throw new L(`Filesystem observation gate scan request was abandoned.`);i.push(t)}return i}function ky(e,t,n){if(B(Dy(e,t))!==B(n))throw new L(`Filesystem observation gate claim changed before release.`);x(t)}async function Ay(e,t,n,r){if(!e)return n();let a=Ey(e),o={gateId:e.id,id:me(),kind:t,owner:Sy(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`);zv(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 L(`Filesystem observation gate lock changed before release.`);if(p(u).join(`,`)!==`owner.json`)throw new L(`Filesystem observation gate lock has unrelated metadata.`);ky(e,d,o),v(u),f=void 0};try{for(;;){if(r?.aborted)throw new L(`Filesystem observation gate wait cancelled.`);let a=Oy(e,Ey(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},zv(d,o),t===`scan`||Oy(e).length===0)return await n();_()}}if(i(u))try{Cy(u);let n=Dy(e,d);if(m=void 0,!Ty(n.owner))throw new L(`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 L(`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 L(`Filesystem observation gate owner publication is incomplete.`)}await new Promise(e=>setTimeout(e,100))}}finally{try{_()}finally{s&&ky(e,s,o)}}}function jy(e,t=!1){Ey(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 L(`Filesystem observation gate has unrelated or incomplete metadata.`);if(i(r)){if(Cy(r),p(r).join(`,`)!==`owner.json`)throw new L(`Filesystem observation gate lock has unrelated metadata.`);let t=Dy(e,w(r,`owner.json`));if(Ty(t.owner))throw new L(`Filesystem observation gate still has a live holder.`);ky(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 L(`Filesystem observation gate has unrelated metadata.`);let r=w(n,t),i=Dy(e,r);if(i.kind!==`scan`||t!==i.id+`.json`)throw new L(`Filesystem observation gate has unrelated scan metadata.`);if(Ty(i.owner))throw new L(`Filesystem observation gate still has a live scan request.`);ky(e,r,i)}if(v(n),B(JSON.parse(H(w(e.directory,`gate.json`)).toString(`utf8`)))!==B(e))throw new L(`Filesystem observation gate changed before retirement.`);x(w(e.directory,`gate.json`)),v(e.directory)}function My(e,t){try{jy(e)}catch(e){throw e instanceof By&&(e.message+=` Output-gate retirement: wrappedOperation=${t?`completed`:`failed`}.`),e}}async function Ny(e,t,n){let r=process.env[vy];if(r!==void 0)return n(wy(r));if(!t)return n(void 0);let i=me(),a=w(ad(e),`ai-delivery`,`output-observation`,$y(e).slice(7));Lv(a);for(let e of p(a)){il().parse(e);let t=w(a,e);Cy(t);let n=by.parse(JSON.parse(H(w(t,`gate.json`)).toString(`utf8`)));if(n.id!==e||n.directory!==t||Ty(n.owner))throw new L(`Prior filesystem observation gate is live or has conflicting ownership.`);jy(n,!0)}let o=w(a,i);Lv(w(o,`requests`));let s={directory:o,id:i,owner:Sy()};zv(w(o,`gate.json`),s);let c=!1;try{let e=await n(s);return c=!0,e}finally{My(s,c)}}var Py=class extends L{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 Fy(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 Py(`Filesystem output lstat failed.`,i,e)}if(l.isSymbolicLink()){let a;try{a=m(i)}catch(e){throw new Py(`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 Py(`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 L(`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 Py(`Filesystem output ancestor resolution failed.`,p,e);let n;try{n=c(p)}catch(e){if(e.code!==`ENOENT`)throw new Py(`Filesystem output ancestor lstat failed.`,p,e)}if(n?.isSymbolicLink()){let e,r;try{e=m(p),r=c(p)}catch(e){throw new Py(`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 L(`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 L(`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 L(`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(i)}.`);if(!e.some(e=>u===e||u.startsWith(`${e}${ce}`)))throw new L(`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 Py(`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 L(`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 Py(`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 L(`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 L(`Filesystem output observation exceeded its file limit.`)};for(let t of e){if(i(t)&&h(t)!==t)throw new L(`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 Iy(e,t,n=!1,r){let i,a,o,s,c=()=>{if(s!==void 0&&Date.now()-s>=1e3)throw new L(`Filesystem output observation remained unavailable for 1 second. First observation: ${a.message} Last observation: ${o.message}`)};for(;;){if(t?.aborted)throw new L(`Filesystem output observation cancelled.`);c();try{i=await Ay(e.gate,`scan`,()=>Fy(e.roots,e.links,n,r),t),c();break}catch(e){if(!n||!(e instanceof Py)||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 L(`Filesystem output observation overflowed.`);return l}function Ly(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 Ry(e,t){let n=(t===void 0?[e]:[e,...t.roots]).reduce((e,t)=>{let n=Ly(t);return n<e?n:e},BigInt(2**53-1));if(n>BigInt(2**53-1))throw new L(`Free disk observation overflowed.`);return Number(n)}function zy(e,t,n){if(Ry(e,n)<t.minFreeDiskBytes)throw new L(`Free disk fell below limit ${t.minFreeDiskBytes}.`)}var By=class extends L{};function Vy(){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
286
|
`)};throw new By(`Owned process resource observation failed. ${JSON.stringify(r)}`)}let n=new Map;for(let e of t.stdout.trim().split(`
|
|
@@ -307,5 +307,5 @@ GFS4: `),console.error(e)}),n[s]||(u(n,global[s]||[]),n.close=(function(e){funct
|
|
|
307
307
|
`}var Bj=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 Lj({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=zj(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}},Vj=JSON.parse(d(new URL(`../package.json`,import.meta.url),`utf8`));if(typeof Vj!=`object`||!Vj||!(`version`in Vj)||typeof Vj.version!=`string`||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(Vj.version))throw Error(`The adjacent ai-delivery package identity must contain a stable version.`);var Hj=Vj.version,Uj=[`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
308
|
`);function Wj(e,t){let n=new Dj({name:`ai-delivery`,version:Hj},{instructions:Uj}),r=BC;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=JC(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 Gj(e){i_(!0);let t=new AbortController,n=new Set,r=Wj({...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 Bj),process.stderr.write(`ai-delivery MCP server started
|
|
309
309
|
`),await new Promise(()=>{})}var Kj=e=>/^(?:area|risk):[^\s:]+$/u.test(e),qj=Kj,Jj=N({number:A().int().positive(),body:k(),labels:M(k()),trackingParent:j().optional(),resolvedLegacyBlockers:M(N({number:A().int().positive(),state:F([`OPEN`,`CLOSED`])}).strict()).optional(),existingNative:N({blockedBy:M(N({number:A().int().positive(),state:F([`OPEN`,`CLOSED`])}).strict()),issueType:k().optional(),points:A().int().positive().optional(),priority:k().optional(),projectStatus:F([`Todo`,`In Progress`,`Blocked`,`Done`]).optional()}).strict().optional()}).strict();function Yj(e){let t=N({issues:M(Jj),repositoryLabels:M(k()).optional()}).strict().parse(e),n=t.issues.map(e=>e.number);if(new Set(n).size!==n.length)throw new L(`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,...$j({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:eM(t.repositoryLabels??[]),schemaVersion:`ai-delivery.legacy-issue-migration@1`,validated:0}}var Xj=new Map([[`effort:l`,5],[`effort:m`,3],[`effort:medium`,3],[`effort:s`,2],[`effort:xl`,8],[`effort:xs`,1]]),Zj=new Map([[`priority:high`,`P1`],[`priority:p0`,`P0`],[`priority:p1`,`P1`],[`priority:p2`,`P2`],[`priority:p3`,`P3`],[`priority:p4`,`P4`]]),Qj=new Map([[`type:bug`,`Bug`],[`type:design`,`Task`],[`type:epic`,`Task`],[`type:feature`,`Feature`],[`type:spike`,`Task`],[`type:task`,`Task`],[`type:tracking`,`Task`]]);function $j(e){let t=[...new Set(e.labels.map(e=>e.trim()).filter(Boolean))],n=tM(e.body),r=aM(e.body,`executionContract`),i=aM(e.body,`dependencyDeclaration`),a=aM(e.body,`related`),o=rM([...e.existingNative?.blockedBy??[],...e.resolvedLegacyBlockers??[]]),s=sM({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 L(`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??uM({...n.points===void 0?{}:{bodyPoint:n.points},executionContract:r,labels:t}),f=e.existingNative?.priority??dM({label:`priority`,labels:t,mapping:Zj}),p=e.existingNative?.issueType??dM({label:`issue type`,labels:t,mapping:Qj});if(e.existingNative?.projectStatus===`Done`)throw new L(`An open issue cannot retain Project Done during legacy migration.`);let m=lM({existing:e.existingNative?.projectStatus,labels:t,unresolvedBlockers:l}),h=t.filter(Kj);h.sort();let g=t.filter(e=>!h.includes(e)).sort();return{body:oM(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 eM(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))].filter(e=>!qj(e)).sort((e,t)=>e.localeCompare(t))}function tM(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 L(`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 L(`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 nM(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function rM(e){let t=new Map;for(let n of e){if(!nM(n.number))throw new L(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new L(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function iM(e){if(nM(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 nM(n)?n:void 0}function aM(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 L(`Invalid legacy ${t} payload.`)}}function oM(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function sM({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=iM(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...cM(e?.blockedBy)),r.push(...cM(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function cM(e){return Array.isArray(e)?e.map(iM).filter(e=>e!==void 0):[]}function lM(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 uM(e){let t=[];for(let n of e.labels){let e=Xj.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=Xj.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 L(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new L(`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 L(`Found conflicting legacy ${e} values.`);return i[0]}var fM=class{constructor(e){this._client=e}async*callToolStream(e,t=PD,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 pM(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&&pM(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&pM(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&pM(n,t)}}function mM(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 hM=class extends Ak{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 pj,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,LD,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,OD,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,sD,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new fM(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Mk(this._capabilities,e)}setRequestHandler(e,t){let n=MT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=RT(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=AT(sO,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}=mM(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=AT(FE,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=AT(uO,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{pM(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=AT(ZD,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=AT(FE,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=AT(i.tools||i.toolChoice?$D:QD,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:zT,capabilities:this._capabilities,clientInfo:this._clientInfo}},wE,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!BT.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){hj(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&gj(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},_O,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},DD,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},_D,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},eD,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},nD,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},oD,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=PD,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},ND,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=RD.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`})}},gM=E(((e,t)=>{t.exports=a,a.sync=o;var n=Me(`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)}})),_M=E(((e,t)=>{t.exports=r,r.sync=i;var n=Me(`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}})),vM=E(((e,t)=>{Me(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?gM():_M();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}}})),yM=E(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=Me(`path`),i=n?`;`:`:`,a=vM(),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)}})),bM=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})),xM=E(((e,t)=>{var n=Me(`path`),r=yM(),i=bM();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})),SM=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})),CM=E(((e,t)=>{t.exports=/^#!(.*)/})),wM=E(((e,t)=>{var n=CM();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}})),TM=E(((e,t)=>{var n=Me(`fs`),r=wM();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})),EM=E(((e,t)=>{var n=Me(`path`),r=xM(),i=SM(),a=TM(),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})),DM=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}})),OM=Ae(E(((e,t)=>{var n=Me(`child_process`),r=EM(),i=DM();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),kM=le.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function AM(){let e={};for(let t of kM){let n=le.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var jM=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Lj({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new be)}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,OM.default)(this._serverParams.command,this._serverParams.args??[],{env:{...AM(),...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=zj(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}};async function MM(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 NM=k().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),PM=P({action:F([`install`,`doctor`,`update`,`rollback`,`remove`]),host:F([`codex`,`claude-code`]),scope:F([`user`,`project`,`local`]),version:NM.optional(),dryRun:j().default(!1),checkAuth:j().default(!1),repo:k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),repoRoot:k().min(1)}),FM=P({pid:A().int().positive(),birth:k().min(1)}),IM=P({action:PM.shape.action,targetVersion:NM.nullable(),owner:FM,producerDigest:k().regex(/^sha256:[a-f0-9]{64}$/u),staging:P({path:k(),device:A().int().nonnegative().optional(),inode:A().int().nonnegative().optional()}).optional(),command:Rl(`phase`,[P({phase:I(`idle`)}),P({phase:I(`starting`)}),P({phase:I(`running`),process:FM,tracked:M(FM.extend({pgid:A().int().positive()})).max(256)})])}),LM=P({owner:I(`@aviaratech/ai-delivery.plugin@1`),host:PM.shape.host,scope:PM.shape.scope,projectRoot:k().nullable(),nativeHome:k().min(1),marketplace:k(),currentVersion:NM.nullable(),previousVersion:NM.nullable(),installedPath:k().nullable(),nativeVersion:k().optional(),pending:IM.optional()}),RM=P({owner:I(`@aviaratech/ai-delivery.plugin-version@1`),version:NM,archiveSha256:k().regex(/^[a-f0-9]{64}$/u),files:Wl(k(),k().regex(/^[a-f0-9]{64}$/u))}),zM=e=>fe(`sha256`).update(e).digest(`hex`);function BM(){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 VM=N({routing:N({repository:PM.shape.repo.unwrap()}),reviewRoute:N({author:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),authSource:F([`app`,`personal`]),credentialSource:k().optional(),identity:k()}),reviewer:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),identity:k(),repositoryAccess:I(`readable`)}),rules:N({visibility:F([`complete`,`partial`,`unknown`]),observedRequiredApprovals:A().int().nonnegative().nullable()}),approvalEligibility:F([`unknown`,`insufficient-permission`])})});async function HM(e,t,n){let r;try{r=await jh(),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`&&Jm(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)||[...Ym,`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 Ym)process.env[e]!==void 0&&(l[e]=process.env[e]);try{a.authSource===`personal`&&qm(process.env);for(let e of[`author`,`reviewer`])r.roles[e].authSource!==`personal`&&Nh({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 MM(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=VM.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 UM(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 WM(e){let t=h(T(e.repoRoot)),n=T(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??w(de(),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}-${fe(`sha256`).update(t).digest(`hex`).slice(0,16)}`,s=w(de(),`.cache`,`ai-delivery`,`plugins`,e.host,o);if(UM(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 GM(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=LM.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 KM(e){let t=Vy().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function qM(e){if(KM(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:``}]))};Ky(t),await Gy(t)}async function JM(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?BM():{...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 YM(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function XM(e,t){return w(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function ZM(e,t){return w(e.catalog,`versions`,t)}function QM(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]=zM(d(s))}}};return r(e,``,0),t}function $M(e,t){let n=ZM(e,t);UM(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=RM.parse(JSON.parse(d(r,`utf8`)));if(l.version!==t||JSON.stringify(QM(XM(e,t)))!==JSON.stringify(l.files)||zM(d(o))!==l.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return l}function eN(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=ve(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 tN(e,t,n,r,a){let o=ZM(e,t);if(i(o)){$M(e,t);return}let s=C(o);Lv(s);let u=w(s,`.stage-${me()}`);a({path:u}),l(u,{mode:448});let f=c(u);YM(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 JM(`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=eN(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));Lv(C(n)),ee(n,t,{mode:384,flag:`wx`}),YM(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 JM(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`)),YM(w(u,`archive.tgz`)),zv(w(u,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:zM(i),files:QM(f)}),g(u,o),YM(s),a(void 0),$M(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}),YM(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 nN(e,t){$M(e,t);let n=`./versions/${t}/plugins/ai-delivery`;zv(w(e.catalog,`.agents/plugins/marketplace.json`),{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}),zv(w(e.catalog,`.claude-plugin/marketplace.json`),{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]})}async function rN(e,t,n,r){let i=JSON.parse(await JM(t.tool,[`plugin`,`list`,...e.host===`codex`?[`--marketplace`,t.marketplace,`--available`]:[],`--json`],t.projectRoot,n,r,e.action===`doctor`));if(e.host===`claude-code`)return M(Wl(k(),kl())).parse(i);let a=N({installed:M(Wl(k(),kl())),available:M(Wl(k(),kl()))}).parse(i);return[...a.installed.map(e=>({...e,installed:!0})),...a.available.map(e=>({...e,installed:!1}))]}function iN(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=Wl(k(),kl()).parse(JSON.parse(d(e,`utf8`)));if(n[t.marketplace]===void 0)return!1;let r=N({source:N({source:I(`directory`),path:k()}),installLocation:k()}).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=N({sourceType:I(`local`),source:k()}).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`?N({source:I(`local`),path:k()}).parse(i.source).path:void 0;return{version:NM.parse(i.version),enabled:j().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Wl(k(),kl()).parse(i.mcpServers)}:{}}}function oN(e){let t=w(e.catalog,`.claude-plugin/marketplace.json`);if(UM(t),!c(t).isFile()||c(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=N({name:I(e.marketplace),plugins:M(N({name:k(),version:NM,source:k()}))}).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)!==XM(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function sN(e,t,n,r,i=n.version){let a=$M(t,e.host===`claude-code`?i:n.version),o=XM(t,e.host===`claude-code`?i:n.version);if(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=e.host===`codex`?r:o;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`codex`&&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(UM(s),JSON.stringify(QM(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!N({command:I(`node`),args:Hl([I("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function cN(e,t,n){let r=new jM({command:process.execPath,args:[w(e,`dist/mcp-launcher.js`)],cwd:n,env:{...Object.fromEntries(kM.map(e=>[e,``])),NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new hM({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 lN(e){let t=PM.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=WM(t),r=GM(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)return a;if(t.action===`doctor`){if(!r||(a.recoveryRequired=r.pending!==void 0,r.pending||!r.currentVersion))return a;try{$M(n,r.currentVersion)}catch{return a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:`Managed archive integrity failed.`},a}let e=await rN(t,n,new AbortController().signal),i=iN(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)return a.mcp={configuration:`missing`,startup:`not_checked`},a;try{a.nativePluginRoot=sN(t,n,o,r.installedPath),a.sourceIntegrity=!0,a.skills=p(w(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await cN(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)}}return a.authProbe&&a.sourceIntegrity&&a.enabled&&a.mcp?.startup===`ready`&&(delete a.authProbe.reason,await HM(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 Lv(n.directory),py(n.statePath,{projectRoot:n.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{r=GM(t,n);let e=r?.pending!==void 0;if(r?.pending){if(await qM(r.pending),r.pending.producerDigest!==nb(C(ye(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(ZM(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.`);UM(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}),YM(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`||t.action===`rollback`)&&(!r||t.action===`update`&&!r.currentVersion))throw Error(`Install a managed plugin before updating or rolling it back.`);let o=t.action===`remove`?null:a.version;if(o===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let s=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 l=KM(process.pid);if(!l)throw Error(`Installer owner identity is unknown.`);r.pending={action:t.action,targetVersion:o,owner:{pid:process.pid,birth:l},producerDigest:nb(C(ye(import.meta.url))),command:{phase:`idle`}},zv(n.statePath,r);let u=new AbortController,d=()=>u.abort();process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let f=e=>{r.pending.command=e,zv(n.statePath,r)},m=e=>JM(n.tool,e,n.projectRoot,u.signal,f),h=`ai-delivery@${n.marketplace}`,g=t.host===`codex`?[`plugin`,`remove`,h,`--json`]:[`plugin`,`uninstall`,h,`--scope`,t.scope,`--keep-data`],v=t.host===`codex`?[`plugin`,`add`,h,`--json`]:[`plugin`,`install`,h,`--scope`,t.scope],y=!1;try{if(r.nativeVersion=(await m([`--version`])).trim(),t.host===`claude-code`&&!(await m([`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:o?`prepare_version`:`native_remove`,version:o})}\n`);let i=await rN(t,n,u.signal,f),c=iN(t,n,i),l=aN(t,n,i);if(l&&!s&&!(e&&l.version===o))throw Error(`Existing native plugin is not owned by managed state.`);let d=l?.version;if(l&&e&&t.host===`claude-code`&&(d=oN(n).version,d!==s&&d!==o))throw Error(`Interrupted native selection has an incompatible catalog version.`);l&&sN(t,n,l,l.version===s?r.installedPath:w(n.nativeHome,`plugins/cache`,n.marketplace,`ai-delivery`,l.version),d),o&&(await tN(n,o,u.signal,f,e=>{e?r.pending.staging=e:delete r.pending.staging,zv(n.statePath,r)}),y=!0,nN(n,o),c||await m([`plugin`,`marketplace`,`add`,n.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),l&&(l.version!==o||t.action===`remove`)&&(y=!0,await m(g));let p=r.installedPath;if(o){let e=await m(v);t.host===`codex`&&(p=N({installedPath:k()}).parse(JSON.parse(e)).installedPath)}let h=await rN(t,n,u.signal,f);if(!iN(t,n,h)&&o)throw Error(`Native marketplace registration is missing.`);let _=aN(t,n,h);if(o?_?.version!==o:_!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(o&&(sN(t,n,_,_?.installedPath??p),!_.enabled))throw Error(`Native plugin selection is disabled.`);return r.currentVersion=o,s!==o&&(r.previousVersion=s),r.installedPath=o?_?.installedPath??p:null,delete r.pending,zv(n.statePath,r),a.version=o,a.changed=s!==o,a.installed=o!==null,a.restartRequired=!0,o&&(a.nativePluginRoot=t.host===`codex`?r.installedPath??XM(n,o):XM(n,o)),a}catch(t){if(!e&&!u.signal.aborted&&!y&&r.pending?.command.phase===`idle`&&r.pending.staging===void 0){delete r.pending;try{zv(n.statePath,r)}catch(e){throw AggregateError([t,e],`Plugin preparation failed and pending-state cleanup also failed.`)}}if(y&&s)try{nN(n,s)}catch{}throw t}finally{process.removeListener(`SIGINT`,d),process.removeListener(`SIGTERM`,d)}}})}var uN=new Ke;uN.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(Hj).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=uN.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&uN.enablePositionalOptions();break}function dN(){let e=uN.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 fN(e){return e===void 0?void 0:Number(e)}function pN(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function mN(e){return pN(e)?.map(Number)}function hN(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 gN(e,t){let n=e===void 0?{}:JSON.parse(d(e,`utf8`));return{...G_.parse(n),...Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}}function _N(e,t){return JC(e,t,dN()).then(t=>Xe(e,t))}function vN(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var yN=uN.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`update`,`rollback`,`remove`]){let t=yN.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 lN({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&&dN().repo?{repo:dN().repo}:{},repoRoot:dN().repoRoot});if(t.json){vN(n);return}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.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`)})}uN.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=>_N(`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)}}:{}})),uN.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 _N(`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})}),uN.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=>_N(`issue_create`,gN(e.fieldsFile,{title:e.title,body:hN(e.body,e.bodyFile),issueType:e.type,points:fN(e.points),priority:e.priority,labels:pN(e.labels),blockedBy:mN(e.blockedBy),blocks:mN(e.blocks),overrideReason:e.overrideReason,milestone:fN(e.milestone),parentIssueNumber:fN(e.parent),...e.draft===!0?{draft:!0}:{}}))),uN.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 _N(`issue_start`,{issueNumber:fN(e.issue),investigationWorktree:e.investigationWorktree,expectedHeadSha:e.expectedHead})}return _N(`issue_start`,{issueNumber:fN(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:hN(e.body,e.bodyFile),issueType:e.type,points:fN(e.points),priority:e.priority,labels:pN(e.labels),blockedBy:mN(e.blockedBy),blocks:mN(e.blocks),overrideReason:e.overrideReason,milestone:fN(e.milestone),parentIssueNumber:fN(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0})});for(let e of[`list`,`search`])uN.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=>_N(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:pN(t.labels),parentIssueNumber:fN(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:fN(t.page),perPage:fN(t.perPage)}));uN.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=>_N(`issue_update`,gN(e.fieldsFile,{issueNumber:fN(e.issue),title:e.title,...e.draft===!0?{draft:!0}:{},body:hN(e.body,e.bodyFile),issueType:e.type,points:fN(e.points),priority:e.priority,labels:pN(e.labels),blockedBy:mN(e.blockedBy),blocks:mN(e.blocks),overrideReason:e.overrideReason,milestone:fN(e.milestone),parentIssueNumber:fN(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:fN(e.supersededBy),park:e.park===!0||void 0}))),uN.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=>_N(`delivery_health`,{repo:dN().repo,from:e.from,to:e.to,maxIssues:fN(e.maxIssues),maxTimelinePages:fN(e.maxTimelinePages),maxProjectPages:fN(e.maxProjectPages),oldestLimit:fN(e.oldestLimit)})),uN.command(`info`).requiredOption(`--issue <number>`).action(async e=>_N(`issue_info`,{issueNumber:fN(e.issue)})),uN.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>_N(`issue_ready_check`,{issueNumber:fN(e.issue)}));for(let e of[`parent`,`blockers`])uN.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await JC(`issue_info`,{issueNumber:fN(t.issue)},dN());vN(e===`parent`?{issueNumber:fN(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:fN(t.issue),blockedBy:n.blockedBy})});uN.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await KC(dN(),`subissues`);vN({issueNumber:fN(e.issue),subissues:await jv(t,Number(e.issue))})}),uN.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=>_N(`issue_pr_create`,{issueNumber:fN(e.issue),prNumber:fN(e.pr),nonClosing:e.nonClosing,title:e.title,body:hN(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),uN.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=>_N(`issue_pr_info`,{issueNumber:fN(e.issue),prNumber:fN(e.pr),nonClosing:e.nonClosing})),uN.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.`);vN(await WS(await KC(dN(),`pr:list`),e.state))}),uN.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{vN(await GS(await KC(dN(),`pr:checks`),Number(e.pr)))}),uN.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=>_N(`issue_pr_review`,{issueNumber:fN(e.issue),prNumber:fN(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=uN.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 _N(t,{issueNumber:fN(e.issue),investigation:!0,resultPath:e.result,authorityCommentId:fN(e.authorityComment),acceptanceCommentId:fN(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 _N(t,{issueNumber:fN(e.issue),prNumber:fN(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0,nonClosing:e.nonClosing})})}uN.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=>_N(`issue_worktree_transition_inspect`,{issueNumber:fN(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:fN(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:mN(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),uN.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=>_N(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),uN.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=Yj(JSON.parse(d(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),uN.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await KC(dN(),`config:resolve`);vN({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await JS(e,void 0,void 0,`development`)})}),uN.command(`mcp:serve`).action(async()=>Gj(dN())),uN.parseAsync(process.argv).catch(e=>{process.stderr.write(`ai-delivery: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1});export{};
|
|
310
|
+
`),points:Number(a[0])}}function nM(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function rM(e){let t=new Map;for(let n of e){if(!nM(n.number))throw new L(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new L(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function iM(e){if(nM(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 nM(n)?n:void 0}function aM(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 L(`Invalid legacy ${t} payload.`)}}function oM(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function sM({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=iM(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...cM(e?.blockedBy)),r.push(...cM(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function cM(e){return Array.isArray(e)?e.map(iM).filter(e=>e!==void 0):[]}function lM(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 uM(e){let t=[];for(let n of e.labels){let e=Xj.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=Xj.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 L(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new L(`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 L(`Found conflicting legacy ${e} values.`);return i[0]}var fM=class{constructor(e){this._client=e}async*callToolStream(e,t=PD,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 pM(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&&pM(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&pM(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&pM(n,t)}}function mM(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 hM=class extends Ak{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 pj,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,LD,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,OD,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,sD,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new fM(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Mk(this._capabilities,e)}setRequestHandler(e,t){let n=MT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=RT(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=AT(sO,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}=mM(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=AT(FE,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=AT(uO,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{pM(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=AT(ZD,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=AT(FE,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=AT(i.tools||i.toolChoice?$D:QD,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:zT,capabilities:this._capabilities,clientInfo:this._clientInfo}},wE,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!BT.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){hj(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&gj(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},_O,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},DD,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},_D,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},eD,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},nD,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},oD,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=PD,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},ND,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=RD.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`})}},gM=E(((e,t)=>{t.exports=a,a.sync=o;var n=Me(`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)}})),_M=E(((e,t)=>{t.exports=r,r.sync=i;var n=Me(`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}})),vM=E(((e,t)=>{Me(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?gM():_M();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}}})),yM=E(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=Me(`path`),i=n?`;`:`:`,a=vM(),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)}})),bM=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})),xM=E(((e,t)=>{var n=Me(`path`),r=yM(),i=bM();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})),SM=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})),CM=E(((e,t)=>{t.exports=/^#!(.*)/})),wM=E(((e,t)=>{var n=CM();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}})),TM=E(((e,t)=>{var n=Me(`fs`),r=wM();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})),EM=E(((e,t)=>{var n=Me(`path`),r=xM(),i=SM(),a=TM(),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})),DM=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}})),OM=Ae(E(((e,t)=>{var n=Me(`child_process`),r=EM(),i=DM();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),kM=le.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function AM(){let e={};for(let t of kM){let n=le.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var jM=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Lj({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new be)}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,OM.default)(this._serverParams.command,this._serverParams.args??[],{env:{...AM(),...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=zj(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}};async function MM(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 NM=k().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),PM=P({action:F([`install`,`doctor`,`preview`,`update`,`rollback`,`remove`]),host:F([`codex`,`claude-code`]),scope:F([`user`,`project`,`local`]),version:NM.optional(),dryRun:j().default(!1),checkAuth:j().default(!1),repo:k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),repoRoot:k().min(1)}),FM=P({pid:A().int().positive(),birth:k().min(1)}),IM=P({action:PM.shape.action,targetVersion:NM.nullable(),owner:FM,producerDigest:k().regex(/^sha256:[a-f0-9]{64}$/u),staging:P({path:k(),device:A().int().nonnegative().optional(),inode:A().int().nonnegative().optional()}).optional(),command:Rl(`phase`,[P({phase:I(`idle`)}),P({phase:I(`starting`)}),P({phase:I(`running`),process:FM,tracked:M(FM.extend({pgid:A().int().positive()})).max(256)})])}),LM=P({owner:I(`@aviaratech/ai-delivery.plugin@1`),host:PM.shape.host,scope:PM.shape.scope,projectRoot:k().nullable(),nativeHome:k().min(1),marketplace:k(),currentVersion:NM.nullable(),previousVersion:NM.nullable(),installedPath:k().nullable(),nativeVersion:k().optional(),pending:IM.optional()}),RM=P({owner:I(`@aviaratech/ai-delivery.plugin-version@1`),version:NM,archiveSha256:k().regex(/^[a-f0-9]{64}$/u),files:Wl(k(),k().regex(/^[a-f0-9]{64}$/u))}),zM=e=>fe(`sha256`).update(e).digest(`hex`);function BM(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(GM(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 Wl(k(),kl()).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(de()),`.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 VM(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=NM.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 HM(){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 UM=N({routing:N({repository:PM.shape.repo.unwrap()}),reviewRoute:N({author:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),authSource:F([`app`,`personal`]),credentialSource:k().optional(),identity:k()}),reviewer:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),identity:k(),repositoryAccess:I(`readable`)}),rules:N({visibility:F([`complete`,`partial`,`unknown`]),observedRequiredApprovals:A().int().nonnegative().nullable()}),approvalEligibility:F([`unknown`,`insufficient-permission`])})});async function WM(e,t,n){let r;try{r=await jh(),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`&&Jm(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)||[...Ym,`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 Ym)process.env[e]!==void 0&&(l[e]=process.env[e]);try{a.authSource===`personal`&&qm(process.env);for(let e of[`author`,`reviewer`])r.roles[e].authSource!==`personal`&&Nh({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 MM(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=UM.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 GM(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 KM(e){let t=h(T(e.repoRoot)),n=T(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??w(de(),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}-${fe(`sha256`).update(t).digest(`hex`).slice(0,16)}`,s=w(de(),`.cache`,`ai-delivery`,`plugins`,e.host,o);if(GM(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 qM(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=LM.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 JM(e){let t=Vy().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function YM(e){if(JM(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:``}]))};Ky(t),await Gy(t)}async function XM(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?HM():{...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 ZM(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function QM(e,t){return w(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function $M(e,t){return w(e.catalog,`versions`,t)}function eN(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]=zM(d(s))}}};return r(e,``,0),t}function tN(e,t){let n=$M(e,t);GM(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=RM.parse(JSON.parse(d(r,`utf8`)));if(l.version!==t||JSON.stringify(eN(QM(e,t)))!==JSON.stringify(l.files)||zM(d(o))!==l.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return l}function nN(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=ve(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 rN(e,t,n,r,a){let o=$M(e,t);if(i(o)){tN(e,t);return}let s=C(o);Lv(s);let u=w(s,`.stage-${me()}`);a({path:u}),l(u,{mode:448});let f=c(u);ZM(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 XM(`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=nN(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));Lv(C(n)),ee(n,t,{mode:384,flag:`wx`}),ZM(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 XM(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`)),ZM(w(u,`archive.tgz`)),zv(w(u,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:zM(i),files:eN(f)}),g(u,o),ZM(s),a(void 0),tN(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}),ZM(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 iN(e,t){tN(e,t);let n=`./versions/${t}/plugins/ai-delivery`;zv(w(e.catalog,`.agents/plugins/marketplace.json`),{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}),zv(w(e.catalog,`.claude-plugin/marketplace.json`),{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]})}async function aN(e,t,n,r,i=!1){let a=JSON.parse(await XM(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 M(Wl(k(),kl())).parse(a);let o=N({installed:M(Wl(k(),kl())),available:M(Wl(k(),kl()))}).parse(a);return[...o.installed.map(e=>({...e,installed:!0})),...o.available.map(e=>({...e,installed:!1}))]}function oN(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=Wl(k(),kl()).parse(JSON.parse(d(e,`utf8`)));if(n[t.marketplace]===void 0)return!1;let r=N({source:N({source:I(`directory`),path:k()}),installLocation:k()}).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=N({sourceType:I(`local`),source:k()}).parse(e.marketplaceSource);if(T(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return r.length>0}function sN(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`?N({source:I(`local`),path:k()}).parse(i.source).path:void 0;return{registration:i,version:NM.parse(i.version),enabled:j().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Wl(k(),kl()).parse(i.mcpServers)}:{}}}function cN(e){let t=w(e.catalog,`.claude-plugin/marketplace.json`);if(GM(t),!c(t).isFile()||c(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=N({name:I(e.marketplace),plugins:M(N({name:k(),version:NM,source:k()}))}).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)!==QM(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function lN(e,t,n,r,i=n.version){let a=tN(t,e.host===`claude-code`?i:n.version),o=QM(t,e.host===`claude-code`?i:n.version);if(e.host===`claude-code`&&cN(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=e.host===`codex`?r:o;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`codex`&&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(GM(s),JSON.stringify(eN(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!N({command:I(`node`),args:Hl([I("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function uN(e,t,n){let r=new jM({command:process.execPath,args:[w(e,`dist/mcp-launcher.js`)],cwd:n,env:{...Object.fromEntries(kM.map(e=>[e,``])),NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new hM({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 dN(e){let t=PM.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=KM(t),r=qM(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=BM(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{VM(a,t,n,await aN(t,n,new AbortController().signal,void 0,!0))}catch{a.diagnostics.nativeInventory=`unavailable`,a.diagnostics.findings.push(`native_inventory_unavailable`)}return a}try{tN(n,r.currentVersion)}catch{return a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:`Managed archive integrity failed.`},a}let e=await aN(t,n,new AbortController().signal),i=oN(t,n,e),o=sN(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{VM(a,t,n,await aN(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=lN(t,n,o,r.installedPath),a.sourceIntegrity=!0,a.skills=p(w(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await uN(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(VM(a,t,n,e,o.registration),t.host===`codex`)try{let r=await aN(t,n,new AbortController().signal,void 0,!0),i=new Set(e.flatMap(e=>typeof e.pluginId==`string`?[e.pluginId]:[]));VM(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 WM(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 Lv(n.directory),py(n.statePath,{projectRoot:n.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{r=qM(t,n);let e=r?.pending!==void 0;if(r?.pending){if(await YM(r.pending),r.pending.producerDigest!==nb(C(ye(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($M(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.`);GM(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}),ZM(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`||t.action===`rollback`)&&(!r||t.action===`update`&&!r.currentVersion))throw Error(`Install a managed plugin before updating or rolling it back.`);let o=t.action===`remove`?null:a.version;if(o===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let s=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 l=JM(process.pid);if(!l)throw Error(`Installer owner identity is unknown.`);r.pending={action:t.action,targetVersion:o,owner:{pid:process.pid,birth:l},producerDigest:nb(C(ye(import.meta.url))),command:{phase:`idle`}},zv(n.statePath,r);let u=new AbortController,d=()=>u.abort();process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let f=e=>{r.pending.command=e,zv(n.statePath,r)},m=e=>XM(n.tool,e,n.projectRoot,u.signal,f),h=`ai-delivery@${n.marketplace}`,g=t.host===`codex`?[`plugin`,`remove`,h,`--json`]:[`plugin`,`uninstall`,h,`--scope`,t.scope,`--keep-data`],v=t.host===`codex`?[`plugin`,`add`,h,`--json`]:[`plugin`,`install`,h,`--scope`,t.scope],y=!1;try{if(r.nativeVersion=(await m([`--version`])).trim(),t.host===`claude-code`&&!(await m([`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:o?`prepare_version`:`native_remove`,version:o})}\n`);let i=await aN(t,n,u.signal,f),c=oN(t,n,i),l=sN(t,n,i);if(l&&!s&&!(e&&l.version===o))throw Error(`Existing native plugin is not owned by managed state.`);let d=l?.version;if(l&&e&&t.host===`claude-code`&&(d=cN(n).version,d!==s&&d!==o))throw Error(`Interrupted native selection has an incompatible catalog version.`);l&&lN(t,n,l,l.version===s?r.installedPath:w(n.nativeHome,`plugins/cache`,n.marketplace,`ai-delivery`,l.version),d),o&&(await rN(n,o,u.signal,f,e=>{e?r.pending.staging=e:delete r.pending.staging,zv(n.statePath,r)}),y=!0,iN(n,o),c||await m([`plugin`,`marketplace`,`add`,n.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),l&&(l.version!==o||t.action===`remove`)&&(y=!0,await m(g));let p=r.installedPath;if(o){let e=await m(v);t.host===`codex`&&(p=N({installedPath:k()}).parse(JSON.parse(e)).installedPath)}let h=await aN(t,n,u.signal,f);if(!oN(t,n,h)&&o)throw Error(`Native marketplace registration is missing.`);let _=sN(t,n,h);if(o?_?.version!==o:_!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(o&&(lN(t,n,_,_?.installedPath??p),!_.enabled))throw Error(`Native plugin selection is disabled.`);return r.currentVersion=o,s!==o&&(r.previousVersion=s),r.installedPath=o?_?.installedPath??p:null,delete r.pending,zv(n.statePath,r),a.version=o,a.changed=s!==o,a.installed=o!==null,a.activation={installedVersion:o,startupVersion:null,loadedVersion:null},o&&(a.nativePluginRoot=t.host===`codex`?r.installedPath??QM(n,o):QM(n,o)),a}catch(t){if(!e&&!u.signal.aborted&&!y&&r.pending?.command.phase===`idle`&&r.pending.staging===void 0){delete r.pending;try{zv(n.statePath,r)}catch(e){throw AggregateError([t,e],`Plugin preparation failed and pending-state cleanup also failed.`)}}if(y&&s)try{iN(n,s)}catch{}throw t}finally{process.removeListener(`SIGINT`,d),process.removeListener(`SIGTERM`,d)}}})}var fN=new Ke;fN.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(Hj).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 pN(){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 mN(e){return e===void 0?void 0:Number(e)}function hN(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function gN(e){return hN(e)?.map(Number)}function _N(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 vN(e,t){let n=e===void 0?{}:JSON.parse(d(e,`utf8`));return{...G_.parse(n),...Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}}function yN(e,t){return JC(e,t,pN()).then(t=>Xe(e,t))}function bN(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var xN=fN.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`preview`,`update`,`rollback`,`remove`]){let t=xN.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 dN({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&&pN().repo?{repo:pN().repo}:{},repoRoot:pN().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`)})}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=>yN(`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 yN(`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=>yN(`issue_create`,vN(e.fieldsFile,{title:e.title,body:_N(e.body,e.bodyFile),issueType:e.type,points:mN(e.points),priority:e.priority,labels:hN(e.labels),blockedBy:gN(e.blockedBy),blocks:gN(e.blocks),overrideReason:e.overrideReason,milestone:mN(e.milestone),parentIssueNumber:mN(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 yN(`issue_start`,{issueNumber:mN(e.issue),investigationWorktree:e.investigationWorktree,expectedHeadSha:e.expectedHead})}return yN(`issue_start`,{issueNumber:mN(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:_N(e.body,e.bodyFile),issueType:e.type,points:mN(e.points),priority:e.priority,labels:hN(e.labels),blockedBy:gN(e.blockedBy),blocks:gN(e.blocks),overrideReason:e.overrideReason,milestone:mN(e.milestone),parentIssueNumber:mN(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=>yN(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:hN(t.labels),parentIssueNumber:mN(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:mN(t.page),perPage:mN(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=>yN(`issue_update`,vN(e.fieldsFile,{issueNumber:mN(e.issue),title:e.title,...e.draft===!0?{draft:!0}:{},body:_N(e.body,e.bodyFile),issueType:e.type,points:mN(e.points),priority:e.priority,labels:hN(e.labels),blockedBy:gN(e.blockedBy),blocks:gN(e.blocks),overrideReason:e.overrideReason,milestone:mN(e.milestone),parentIssueNumber:mN(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:mN(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=>yN(`delivery_health`,{repo:pN().repo,from:e.from,to:e.to,maxIssues:mN(e.maxIssues),maxTimelinePages:mN(e.maxTimelinePages),maxProjectPages:mN(e.maxProjectPages),oldestLimit:mN(e.oldestLimit)})),fN.command(`info`).requiredOption(`--issue <number>`).action(async e=>yN(`issue_info`,{issueNumber:mN(e.issue)})),fN.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>yN(`issue_ready_check`,{issueNumber:mN(e.issue)}));for(let e of[`parent`,`blockers`])fN.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await JC(`issue_info`,{issueNumber:mN(t.issue)},pN());bN(e===`parent`?{issueNumber:mN(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:mN(t.issue),blockedBy:n.blockedBy})});fN.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await KC(pN(),`subissues`);bN({issueNumber:mN(e.issue),subissues:await jv(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=>yN(`issue_pr_create`,{issueNumber:mN(e.issue),prNumber:mN(e.pr),nonClosing:e.nonClosing,title:e.title,body:_N(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=>yN(`issue_pr_info`,{issueNumber:mN(e.issue),prNumber:mN(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.`);bN(await WS(await KC(pN(),`pr:list`),e.state))}),fN.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{bN(await GS(await KC(pN(),`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=>yN(`issue_pr_review`,{issueNumber:mN(e.issue),prNumber:mN(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 yN(t,{issueNumber:mN(e.issue),investigation:!0,resultPath:e.result,authorityCommentId:mN(e.authorityComment),acceptanceCommentId:mN(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 yN(t,{issueNumber:mN(e.issue),prNumber:mN(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=>yN(`issue_worktree_transition_inspect`,{issueNumber:mN(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:mN(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:gN(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=>yN(`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=Yj(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 KC(pN(),`config:resolve`);bN({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await JS(e,void 0,void 0,`development`)})}),fN.command(`mcp:serve`).action(async()=>Gj(pN())),fN.parseAsync(process.argv).catch(e=>{process.stderr.write(`ai-delivery: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1});export{};
|