@code-partner/codepipe 0.11.1-dev.229.g86cd22a → 0.12.0

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.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Kw=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fe=(t,e)=>{for(var r in e)Kw(t,r,{get:e[r],enumerable:!0})};var Ke,at,Hi=S(()=>{"use strict";Ke="0.11.1-dev.229.g86cd22a",at="https://hub.dev.codepipe.dev"});function Yn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=mu&&t<=ct}var ct,mu,hu=S(()=>{"use strict";Hi();ct=4,mu=4});var gu=S(()=>{"use strict";Hi()});function Vn(t=6){return`# CodePipe Context Repo format version.
2
+ var Kw=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fe=(t,e)=>{for(var r in e)Kw(t,r,{get:e[r],enumerable:!0})};var Ke,at,Hi=S(()=>{"use strict";Ke="0.12.0",at="https://hub.codepipe.dev"});function Yn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=mu&&t<=ct}var ct,mu,hu=S(()=>{"use strict";Hi();ct=4,mu=4});var gu=S(()=>{"use strict";Hi()});function Vn(t=6){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
5
  `}function qi(t){if(!t)return 0;let e=/^\s*template_version:\s*(\d+)\s*$/m.exec(t),r=e?parseInt(e[1]??"",10):NaN;return Number.isFinite(r)&&r>=0?r:0}function Yi(t,e=Wi){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function Vi(t,e=Wi){return e.filter(r=>r.version>t)}var yu,lt,Hr,Wi,ku=S(()=>{"use strict";yu=6,lt=".codepipe-context.yaml",Hr=".devpipe-context.yaml",Wi=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",lt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[lt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function Xn(t){return`model/facts/identity/${t}.yaml`}function pr(t){return`model/facts/events/${t}.yaml`}function Ji(t){return`model/facts/annotations/${t}.md`}function Zi(t){return`model/derived/correlates/${t}.yaml`}function Qi(t){return`model/derived/touched/${t}.yaml`}function wu(t){return t===""?"root":t.replace(/\//g,"-")}function ea(t,e){return`model/derived/structure/${t}/${wu(e)}.yaml`}function Vo(t){return typeof t=="string"&&$u.test(t)}function re(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!bu.includes(n))return null;let o=t.slice(e+1,r),s=t.slice(r+1);return o===""&&!Yw.includes(n)||s===""?null:{level:n,repo:o,path:s}}function ge(t){return`task::${t}`}function fe(t,e,r){return`${t}:${e}:${r}`}function Jn(t){let e=[];return kt(t)?(Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!kt(r)){e.push(`edges[${n}]: not an object`);return}ta.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),re(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),re(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function vu(t){return{...t,edges:Wr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function fr(t){return hr(vu(t))}function kt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function ut(t){return typeof t=="string"&&t.length>0}function zw(t){return t.modelFormatVersion!==2}function Ct(t){let e=[];if(!kt(t))return{ok:!1,errors:["shard: not an object"]};Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.repo)||e.push("repo: missing or empty"),ut(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,s)=>{if(!kt(o)){e.push(`nodes[${s}]: not an object`);return}let i=re(o.key);if(!i){e.push(`nodes[${s}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==i.level&&e.push(`nodes[${s}]: level "${String(o.level)}" does not match key prefix "${i.level}"`),r&&i.repo!==r&&e.push(`nodes[${s}].key: repo "${i.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${s}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Vo(o.entityId)&&e.push(`nodes[${s}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,s)=>{if(!kt(o)){e.push(`edges[${s}]: not an object`);return}ta.includes(o.kind)||e.push(`edges[${s}].kind: unknown "${String(o.kind)}"`),(!ut(o.to)||!re(o.to))&&e.push(`edges[${s}].to: malformed nodeKey`),(!ut(o.from)||!n.has(o.from))&&e.push(`edges[${s}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${s}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Zn(t){let e=[];if(!kt(t))return{ok:!1,errors:["identity: not an object"]};if(Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!ut(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!kt(n)){e.push(`entities[${o}]: not an object`);return}Vo(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),ut(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),ut(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((s,i)=>{(!kt(s)||!re(s.key)||!ut(s.until))&&e.push(`entities[${o}].aliases[${i}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function At(t){let e=[];return kt(t)?(Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.taskKey)||e.push("taskKey: missing or empty"),t.origin!=="bootstrap"&&t.origin!=="pipeline"&&e.push("origin: expected bootstrap|pipeline"),t.date!==void 0&&!(typeof t.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.date))&&e.push("date: expected YYYY-MM-DD"),(!Array.isArray(t.commits)||t.commits.some(r=>!ut(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!kt(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Vo(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function Wr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function xu(t){return{...t,nodes:Wr(t.nodes,e=>e.key),edges:Wr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Su(t){return{...t,entities:Wr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Wr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Eu(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:Wr(t.files,r=>r.key),...e?{links:e}:{}}}function zn(t){return Xw.test(t)?t:JSON.stringify(t)}function Ru(t){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`model yaml: non-finite number ${t}`);return JSON.stringify(t)}if(typeof t=="string")return JSON.stringify(t);throw new Error(`model yaml: unsupported scalar ${typeof t}`)}function Iu(t){return t===null||["boolean","number","string"].includes(typeof t)}function zi(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Tu(t,e,r){if(Array.isArray(t)){for(let n of t)if(Iu(n))r.push(`${e}- ${Ru(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=zi(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([s,i],a)=>{let c=a===0?`${e}- `:`${e} `;Xi(s,i,c,`${e} `,r)})}}return}for(let[n,o]of zi(t))Xi(n,o,e,e,r)}function Xi(t,e,r,n,o){if(Iu(e))o.push(`${r}${zn(t)}: ${Ru(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${zn(t)}: []`):(o.push(`${r}${zn(t)}:`),Tu(e,`${n} `,o));else{let s=zi(e);if(s.length===0)o.push(`${r}${zn(t)}: {}`);else{o.push(`${r}${zn(t)}:`);for(let[i,a]of s)Xi(i,a,`${n} `,`${n} `,o)}}}function hr(t){let e=[];return Tu(t,"",e),e.join(`
@@ -21,7 +21,7 @@ ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}fu
21
21
  ${Jd(h,8e3)}`)}}return u.length===0?void 0:Jd(u.join(`
22
22
 
23
23
  `),16e3)}catch{return}}async mergePR(e,r,n,o){let s=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!s.ok)throw new Error(`github merge PR #${r}: ${s.status} ${await s.text()}`);let i=await s.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return i?.sha?{mergedSha:i.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},tc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let s=(await n.json())[0];return s?{url:s.web_url??"",number:s.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new br(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let s=await o.json();if(s.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed"||s.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=b$(s.head_pipeline?.status??s.pipeline?.status),a=s.merge_status==="cannot_be_merged"||s.has_conflicts===!0?"conflict":s.merge_status==="can_be_merged"&&s.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:i,mergeable:a}}async mergePR(e,r,n,o){let s=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,i,a=await fetch(s,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);i=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${s}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...i?{sha:i}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};rc=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Za(e,r,"merge"))}async closePR(e,r,n){throw new Error(Za(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Za(e,r,"comment"))}}});import{X509Certificate as rp}from"node:crypto";import{readFileSync as $$}from"node:fs";import Vt from"node:tls";function v$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function sp(t=op){if(ep)return;ep=!0;let e=X("EXTRA_CA_FILE");if(!(!e||!np))try{let r=v$($$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Vt.setDefaultCACertificates([...Vt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function ip(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function x$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
24
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function S$(t,e,r){return new Promise((n,o)=>{let s=Vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate(!0),a=new Set;for(;i?.issuerCertificate&&i.issuerCertificate!==i&&i.fingerprint256&&!a.has(i.fingerprint256);)a.add(i.fingerprint256),i=i.issuerCertificate;let c=i?.raw?new rp(i.raw):null;s.end(),n(c)});s.on("error",o),s.setTimeout(r,()=>{s.destroy(),o(new Error("tls connect timeout"))})})}function nc(t,e,r){return new Promise(n=>{let o=Vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function E$(t){try{let e=await fetch(t);return e.ok?new rp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ap(t,e=443,r=op){let n=`${t}:${e}`,o=tp.get(n);if(o)return o;let s=R$(t,e,r).catch(i=>(r(`[tls] chain repair for ${t} failed: ${i instanceof Error?i.message:String(i)}`),!1));return tp.set(n,s),s}async function R$(t,e,r){if(!np)return!1;let n=8e3;if(await nc(t,e,n))return!0;let o=await S$(t,e,n),s=Vt.getCACertificates(),i=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=x$(o);if(!c)break;let l=await E$(c);if(!l)break;if(i.push(l.toString()),Vt.setDefaultCACertificates([...s,...i]),await nc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${i.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return nc(t,e,n)}var np,ep,tp,op,cp=S(()=>{"use strict";Le();np=typeof Vt.getCACertificates=="function"&&typeof Vt.setDefaultCACertificates=="function",ep=!1,tp=new Map,op=t=>console.warn(t)});function pp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function rt(t,e,r){sp();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,s={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,s)}catch(i){if(ip(i)&&await ap(new URL(t.baseUrl).host))return await fetch(o,s);throw i}}function I$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function T$(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function oc(t,e,r,n){let{attempts:o,baseMs:s,capMs:i}=T$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await rt(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&I$(l.status,u)){await lp(Math.min(i,s*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await lp(Math.min(i,s*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function zt(t){let e;try{e=await rt(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function fp(t){try{let e=await rt(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function C$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,s=up.get(o);if(s)return s;let i=await rt(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let c=(await i.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return up.set(o,l.id),l.id}async function mp(t,e,r,n=ao){let o=await C$(t,e,r,n);await oc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function hp(t,e,r){return await(await oc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await oc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function yp(t,e){let r=dp.get(e);if(r)return r;let n=await rt(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let s=(await n.json()).find(i=>i.shortName===e);if(!s)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return dp.set(e,s.id),s.id}async function kp(t,e,r,n,o,s=ao){let i=await yp(t,e),a=await rt(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:s,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function wp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,s=await rt(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!s.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${s.status} ${await s.text()}`)}function vp(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function xp(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Sp(t,e){let r=e.stageField??ao,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),s=`/api/issues?query=${encodeURIComponent(o)}&fields=${$p}&$top=200`,i=await rt(t,s);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);let a=await i.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Ip(c,r))}async function Ep(t,e,r=ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${$p}`,o=await rt(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ip(await o.json(),r)}async function Rp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${P$}&$top=500`,o=await rt(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(i=>i.created>r).map(i=>{let a={id:i.id,issueId:e,author:i.author?.login??"unknown",body:i.text??"",createdAt:new Date(i.created).toISOString()},c=vp(i.attachments);return c&&(a.attachments=c),a})}function _$(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Ip(t,e=ao){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),s=r.find(l=>l.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),s?.value?.name&&(i.issueType=s.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(l=>l.name));let a=vp(t.attachments);a&&(i.attachments=a);let c=_$(t.links);return c&&(i.links=c),i}async function Tp(t,e){let r=await j$(t,e);return r.length>0?r:N$(t,e)}async function j$(t,e){let r=await yp(t,e),n=await rt(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),s=[];for(let i of o)i.$type==="StateProjectCustomField"&&i.field?.name&&s.push({name:i.field.name,values:Cp(i.bundle)});return s}async function N$(t,e){let r=`project: ${e}`,n=await rt(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),s=[];for(let i of o[0]?.customFields??[])i.$type==="StateIssueCustomField"&&i.name&&s.push({name:i.name,values:Cp(i.projectCustomField?.bundle)});return s}function Cp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var lp,ao,up,dp,bp,A$,$p,P$,$r=S(()=>{"use strict";cp();lp=t=>new Promise(e=>setTimeout(e,t));ao="Stage",up=new Map;dp=new Map;bp="attachments(id,name,url,size,mimeType)",A$="links(direction,linkType(name),issues(idReadable))",$p=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${bp},${A$}`,P$=`id,text,created,author(login),${bp}`});function ft(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function rn(t){return t instanceof tt}async function Ap(t,e){let r=q(t),n=[],o=[],s=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await zt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"youtrack",ok:!1,detail:ft(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ft(c),checkedAt:s()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:s()});let i=!1;if(r?.github?.token){i=!0;try{let c=await Ht(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"github",ok:!1,detail:ft(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"github",present:!1,checkedAt:s()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){i=!0;try{let c=await Wt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"bitbucket",ok:!1,detail:ft(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:s()});if(r?.gitlab?.token){i=!0;try{let c=await qt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"gitlab",ok:!1,detail:ft(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:s()});if(i||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await ps(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){rn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:ft(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ps(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){rn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:ft(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ps(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:s()})}catch(l){rn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:s()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:ft(l),checkedAt:s()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:s()})}else o.push({kind:"contextWrite",present:!1,checkedAt:s()});let a=Qr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:s()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:s()});else{let c=await Nt(a);if(c==="invalid"){let l="Claude token cannot run a job (rejected or missing the inference scope) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:s()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:s()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Nt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:O$,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Pp(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let s=(await n.json())?.data;if(!Array.isArray(s))return null;let i=[];for(let a of s){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;i.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return i}catch{return null}finally{clearTimeout(r)}}var O$,nn=S(()=>{"use strict";de();Yt();$r();O$="claude-haiku-4-5-20251001"});import L$ from"node:http";import sc from"node:crypto";function ms(){let t=ic(sc.randomBytes(32)),e=ic(sc.createHash("sha256").update(t).digest()),r=ic(sc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function cc(t){let e=new URL(D$);return e.search=new URLSearchParams({response_type:"code",client_id:_p,redirect_uri:t.redirectUri,scope:U$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function F$(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function jp(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function K$(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function lc(t){let e=await fetch(M$,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:_p,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return K$(await e.json())}async function uc(t){let e=t.timeoutMs??B$,r=L$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,s=cc({redirectUri:o,challenge:t.challenge,state:t.state}),i,a=new Promise((l,u)=>{i=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(i),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(F$(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:s,redirectUri:o,waitForToken(){return c||(c=a.then(l=>lc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(i),r.close()}}}async function Np(t){let e=await uc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
24
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function S$(t,e,r){return new Promise((n,o)=>{let s=Vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate(!0),a=new Set;for(;i?.issuerCertificate&&i.issuerCertificate!==i&&i.fingerprint256&&!a.has(i.fingerprint256);)a.add(i.fingerprint256),i=i.issuerCertificate;let c=i?.raw?new rp(i.raw):null;s.end(),n(c)});s.on("error",o),s.setTimeout(r,()=>{s.destroy(),o(new Error("tls connect timeout"))})})}function nc(t,e,r){return new Promise(n=>{let o=Vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function E$(t){try{let e=await fetch(t);return e.ok?new rp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ap(t,e=443,r=op){let n=`${t}:${e}`,o=tp.get(n);if(o)return o;let s=R$(t,e,r).catch(i=>(r(`[tls] chain repair for ${t} failed: ${i instanceof Error?i.message:String(i)}`),!1));return tp.set(n,s),s}async function R$(t,e,r){if(!np)return!1;let n=8e3;if(await nc(t,e,n))return!0;let o=await S$(t,e,n),s=Vt.getCACertificates(),i=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=x$(o);if(!c)break;let l=await E$(c);if(!l)break;if(i.push(l.toString()),Vt.setDefaultCACertificates([...s,...i]),await nc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${i.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return nc(t,e,n)}var np,ep,tp,op,cp=S(()=>{"use strict";Le();np=typeof Vt.getCACertificates=="function"&&typeof Vt.setDefaultCACertificates=="function",ep=!1,tp=new Map,op=t=>console.warn(t)});function pp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function rt(t,e,r){sp();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,s={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,s)}catch(i){if(ip(i)&&await ap(new URL(t.baseUrl).host))return await fetch(o,s);throw i}}function I$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function T$(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function oc(t,e,r,n){let{attempts:o,baseMs:s,capMs:i}=T$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await rt(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&I$(l.status,u)){await lp(Math.min(i,s*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await lp(Math.min(i,s*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function zt(t){let e;try{e=await rt(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function fp(t){try{let e=await rt(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function C$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,s=up.get(o);if(s)return s;let i=await rt(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let c=(await i.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return up.set(o,l.id),l.id}async function mp(t,e,r,n=ao){let o=await C$(t,e,r,n);await oc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function hp(t,e,r){return await(await oc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await oc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function yp(t,e){let r=dp.get(e);if(r)return r;let n=await rt(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let s=(await n.json()).find(i=>i.shortName===e);if(!s)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return dp.set(e,s.id),s.id}async function kp(t,e,r,n,o,s=ao){let i=await yp(t,e),a=await rt(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:s,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function wp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,s=await rt(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!s.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${s.status} ${await s.text()}`)}function vp(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function xp(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Sp(t,e){let r=e.stageField??ao,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),s=`/api/issues?query=${encodeURIComponent(o)}&fields=${$p}&$top=200`,i=await rt(t,s);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);let a=await i.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Ip(c,r))}async function Ep(t,e,r=ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${$p}`,o=await rt(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ip(await o.json(),r)}async function Rp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${P$}&$top=500`,o=await rt(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(i=>i.created>r).map(i=>{let a={id:i.id,issueId:e,author:i.author?.login??"unknown",body:i.text??"",createdAt:new Date(i.created).toISOString()},c=vp(i.attachments);return c&&(a.attachments=c),a})}function _$(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Ip(t,e=ao){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),s=r.find(l=>l.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),s?.value?.name&&(i.issueType=s.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(l=>l.name));let a=vp(t.attachments);a&&(i.attachments=a);let c=_$(t.links);return c&&(i.links=c),i}async function Tp(t,e){let r=await j$(t,e);return r.length>0?r:N$(t,e)}async function j$(t,e){let r=await yp(t,e),n=await rt(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),s=[];for(let i of o)i.$type==="StateProjectCustomField"&&i.field?.name&&s.push({name:i.field.name,values:Cp(i.bundle)});return s}async function N$(t,e){let r=`project: ${e}`,n=await rt(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),s=[];for(let i of o[0]?.customFields??[])i.$type==="StateIssueCustomField"&&i.name&&s.push({name:i.name,values:Cp(i.projectCustomField?.bundle)});return s}function Cp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var lp,ao,up,dp,bp,A$,$p,P$,$r=S(()=>{"use strict";cp();lp=t=>new Promise(e=>setTimeout(e,t));ao="Stage",up=new Map;dp=new Map;bp="attachments(id,name,url,size,mimeType)",A$="links(direction,linkType(name),issues(idReadable))",$p=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${bp},${A$}`,P$=`id,text,created,author(login),${bp}`});function ft(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function rn(t){return t instanceof tt}async function Ap(t,e){let r=q(t),n=[],o=[],s=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await zt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"youtrack",ok:!1,detail:ft(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ft(c),checkedAt:s()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:s()});let i=!1;if(r?.github?.token){i=!0;try{let c=await Ht(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"github",ok:!1,detail:ft(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"github",present:!1,checkedAt:s()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){i=!0;try{let c=await Wt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"bitbucket",ok:!1,detail:ft(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:s()});if(r?.gitlab?.token){i=!0;try{let c=await qt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"gitlab",ok:!1,detail:ft(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:s()});if(i||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await ps(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){rn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:ft(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ps(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){rn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:ft(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ps(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:s()})}catch(l){rn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:s()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:ft(l),checkedAt:s()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:s()})}else o.push({kind:"contextWrite",present:!1,checkedAt:s()});let a=Qr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:s()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:s()});else{let c=await Nt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:s()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:s()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Nt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:O$,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Pp(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let s=(await n.json())?.data;if(!Array.isArray(s))return null;let i=[];for(let a of s){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;i.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return i}catch{return null}finally{clearTimeout(r)}}var O$,nn=S(()=>{"use strict";de();Yt();$r();O$="claude-haiku-4-5-20251001"});import L$ from"node:http";import sc from"node:crypto";function ms(){let t=ic(sc.randomBytes(32)),e=ic(sc.createHash("sha256").update(t).digest()),r=ic(sc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function cc(t){let e=new URL(D$);return e.search=new URLSearchParams({response_type:"code",client_id:_p,redirect_uri:t.redirectUri,scope:U$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function F$(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function jp(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function K$(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function lc(t){let e=await fetch(M$,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:_p,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return K$(await e.json())}async function uc(t){let e=t.timeoutMs??B$,r=L$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,s=cc({redirectUri:o,challenge:t.challenge,state:t.state}),i,a=new Promise((l,u)=>{i=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(i),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(F$(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:s,redirectUri:o,waitForToken(){return c||(c=a.then(l=>lc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(i),r.close()}}}async function Np(t){let e=await uc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
25
25
  ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var _p,D$,M$,ac,U$,B$,ic,dc=S(()=>{"use strict";_p="9d1c250a-e61b-44d9-88ed-5944d1962f5e",D$="https://platform.claude.com/oauth/authorize",M$="https://platform.claude.com/v1/oauth/token",ac="https://platform.claude.com/oauth/code/callback",U$="org:create_api_key user:profile user:inference",B$=12e4,ic=t=>Buffer.from(t).toString("base64url")});import{spawn as G$}from"node:child_process";function vr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=G$(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var hs=S(()=>{"use strict"});import{setTimeout as H$}from"node:timers/promises";import W$ from"ws";function gs(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new W$(r)}async function Xt(t,e,r){return mt(t,e,"/projects",r)}async function Mp(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ys(t,e,r,n){return mt(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Up(t,e,r,n){return mt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Bp(t,e,r,n){return mt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Fp(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new W(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function ks(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function pc(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Kp(t,e,r={}){let n=r.attempts??3,o;for(let s=0;s<n;s++)try{let i=await pc(t,e),a=new Set;for(let c of i)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(i){o=i,s<n-1&&await H$(r.delayMs??1500)}throw o}async function Gp(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new co(e)}if(!r.ok)throw new W(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Hp(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new W(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Wp(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function qp(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new W(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function fc(t,e,r,n){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Yp(t,e,r,n,o){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Vp(t,e,r,n,o){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function zp(t,e,r,n,o){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function lo(t,e,r,n){return mt(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function mc(t,e,r,n){await mt(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Xp(t,e,r,n){return mt(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Jp(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new W(o.status,i,a)}return i}async function ne(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function mt(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new W(o.status,i,a)}return i}var W,co,Te=S(()=>{"use strict";W=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};co=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function Qp(t){Zp=t}function xr(t,e="info"){Zp(t,e)}var Zp,ws=S(()=>{"use strict";Zp=t=>console.log(t)});import{homedir as q$,tmpdir as Y$}from"node:os";import{existsSync as V$,mkdirSync as z$,mkdtempSync as X$,rmSync as J$}from"node:fs";import{join as uo}from"node:path";import{simpleGit as bs}from"simple-git";function Ie(t,e,r){let n=r??uo(q$(),".codepipe","repos");return uo(n,t,e)}async function Ot(t,e,r={}){let n=Ie(t,e.name,r.baseDir),o=r.cloneUrlOverride??fo(e);if(!V$(uo(n,".git"))){z$(n,{recursive:!0});let a=bs();xr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
26
26
  ${l.trim()}`)}}let s=bs(n);try{await s.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
27
27
  ${c.trim()}`)}let i=e.defaultBranch??"main";return await s.checkout(["-B",i,`origin/${i}`]).catch(()=>{}),s}async function Sr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Er(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:s,commitMessage:i}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&xr(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Sr(t,s)||await t.fetch(["origin",s]).catch(()=>{}),!await Sr(t,s))throw new Error(`apply_delivery: base commit ${s.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...$s,"commit-tree",c,"-p",s,"-m",i])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function po(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Sr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Sr(t,o)){let i=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}let s=await r();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}async function ef(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await po(t,s,()=>Er(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await Sr(t,m)||(m=`origin/${u??c}`),(await t.revparse([m])).trim()===i)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...$s,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${s.slice(0,10)} onto ${c} hit conflicts
@@ -891,7 +891,7 @@ ${e}`);let r=await ET({message:"Authorization code \u2014 blank to skip"});if(sk
891
891
  1. install Claude Code \u2014 https://claude.com/claude-code
892
892
  2. run \`claude setup-token\`
893
893
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
894
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=RT(await ST({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return qe.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||qe.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Nt(e);return r==="invalid"?(qe.warn("Claude refused this token \u2014 it cannot run a job (expired, or minted without the inference scope). Run `claude setup-token` again and paste the new one."),ak(t)):(qe.success(`Claude: ${ik(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var ck,lk=S(()=>{"use strict";hs();nn();de();dc();ck={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:TT,promptManual:ak,validate:Nt}});function uk(t){return ck}async function dk(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var pk=S(()=>{"use strict";lk()});async function Nn(t,e,r){return e.host==="github"?AT(t,e,r):e.host==="gitlab"?DT(t,e,r):UT(t,e,r)}async function fk(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await sr(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await mk(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let i=encodeURIComponent(`${t.owner}/${t.name}`);return(await or(e.gitlabToken,"GET",`/projects/${i}`)).status!==404?{found:!0}:{found:!1,detail:n?await hk(e.gitlabToken,t):o}}return e.bitbucket?(await jn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await gk(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(s){return{found:"unknown",detail:s instanceof Error?s.message:String(s)}}}async function mk(t,e){let r=!1;try{r=(await sr(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function hk(t,e){let r=!1;try{r=(await or(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function gk(t,e){let r=!1;try{r=(await jn(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function sr(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let s=await fetch(CT+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:i;throw new Error(`GitHub ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function AT(t,e,r){let n=r.githubToken;if(!n)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let o=await PT(n,e,r),s=await jT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${s}`);let i=ln(t,e,r.youtrackWrites,r.trackerUrl);for(let a of i)await NT(n,o.owner,o.name,a.path,s)||await OT(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,s);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:s}}async function PT(t,e,r){let n=await sr(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await mk(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await _T(t,e.owner),s=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let i=await sr(t,"POST",s,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!i.data)throw new Error("GitHub createRepo: empty response");return{owner:i.data.owner.login,name:i.data.name,sshUrl:i.data.ssh_url}}async function _T(t,e){let{status:r,data:n}=await sr(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function jT(t,e,r){let{data:n}=await sr(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function NT(t,e,r,n,o){let{status:s,data:i}=await sr(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return s===404||!i?null:i.sha}async function OT(t,e,r,n,o,s,i,a){let c={message:s,content:Buffer.from(o,"utf-8").toString("base64"),branch:i};a&&(c.sha=a),await sr(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function or(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let s=await fetch(LT+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):i;throw new Error(`GitLab ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function DT(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),s,i=await or(n,"GET",`/projects/${o}`);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await hk(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await or(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await or(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await or(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");s=m.data}let a=s.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await or(n,"GET",`/projects/${s.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await or(n,"POST",`/projects/${s.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:s.path,cloneUrl:s.ssh_url_to_repo,branch:a}}async function jn(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let s=await fetch(MT+r,o),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status>=400&&s.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${s.status} ${i}`);return{status:s.status,data:a}}async function UT(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,s,i=await jn(n,"GET",o);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await gk(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await jn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);s=p.data}let a=s.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await jn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await jn(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=s.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:s.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var CT,LT,MT,$i=S(()=>{"use strict";Pr();CT="https://api.github.com";LT="https://gitlab.com/api/v4";MT="https://api.bitbucket.org/2.0"});function Ue(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=BT[r];if(!o)return null;let s=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(s.length<2)return null;let i=s[s.length-1].replace(/\.git$/,"");return i?{host:o,owner:s.slice(0,-1).join("/"),repoName:i}:null}var BT,vi=S(()=>{"use strict";BT={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as FT}from"node:crypto";import{existsSync as yk,mkdirSync as KT,readFileSync as kk,readdirSync as GT,rmSync as xi,writeFileSync as HT}from"node:fs";import{homedir as WT}from"node:os";import{dirname as qT,join as Fl}from"node:path";function wk(){return Fl(WT(),".codepipe","init-drafts")}function Kl(t){let e=FT("sha256").update(t).digest("hex").slice(0,16);return Fl(wk(),`${e}.json`)}function bk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=YT)}function $k(t){let e=Kl(t);if(!yk(e))return null;try{let r=JSON.parse(kk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:bk(r.savedAt)?(xi(e,{force:!0}),null):r}catch{return null}}function Gl(t){xi(Kl(t),{force:!0})}function vk(){let t=wk();if(yk(t))for(let e of GT(t)){let r=Fl(t,e);try{let n=JSON.parse(kk(r,"utf-8"));bk(n.savedAt)&&xi(r,{force:!0})}catch{xi(r,{force:!0})}}}var YT,On,xk=S(()=>{"use strict";YT=24*60*60*1e3;On=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Gl(this.cwd)}persist(){let e=Kl(this.cwd);KT(qT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};HT(e,JSON.stringify(r,null,2)+`
894
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=RT(await ST({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return qe.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||qe.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Nt(e);return r==="invalid"?(qe.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),ak(t)):(qe.success(`Claude: ${ik(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var ck,lk=S(()=>{"use strict";hs();nn();de();dc();ck={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:TT,promptManual:ak,validate:Nt}});function uk(t){return ck}async function dk(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var pk=S(()=>{"use strict";lk()});async function Nn(t,e,r){return e.host==="github"?AT(t,e,r):e.host==="gitlab"?DT(t,e,r):UT(t,e,r)}async function fk(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await sr(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await mk(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let i=encodeURIComponent(`${t.owner}/${t.name}`);return(await or(e.gitlabToken,"GET",`/projects/${i}`)).status!==404?{found:!0}:{found:!1,detail:n?await hk(e.gitlabToken,t):o}}return e.bitbucket?(await jn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await gk(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(s){return{found:"unknown",detail:s instanceof Error?s.message:String(s)}}}async function mk(t,e){let r=!1;try{r=(await sr(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function hk(t,e){let r=!1;try{r=(await or(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function gk(t,e){let r=!1;try{r=(await jn(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function sr(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let s=await fetch(CT+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:i;throw new Error(`GitHub ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function AT(t,e,r){let n=r.githubToken;if(!n)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let o=await PT(n,e,r),s=await jT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${s}`);let i=ln(t,e,r.youtrackWrites,r.trackerUrl);for(let a of i)await NT(n,o.owner,o.name,a.path,s)||await OT(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,s);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:s}}async function PT(t,e,r){let n=await sr(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await mk(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await _T(t,e.owner),s=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let i=await sr(t,"POST",s,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!i.data)throw new Error("GitHub createRepo: empty response");return{owner:i.data.owner.login,name:i.data.name,sshUrl:i.data.ssh_url}}async function _T(t,e){let{status:r,data:n}=await sr(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function jT(t,e,r){let{data:n}=await sr(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function NT(t,e,r,n,o){let{status:s,data:i}=await sr(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return s===404||!i?null:i.sha}async function OT(t,e,r,n,o,s,i,a){let c={message:s,content:Buffer.from(o,"utf-8").toString("base64"),branch:i};a&&(c.sha=a),await sr(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function or(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let s=await fetch(LT+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):i;throw new Error(`GitLab ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function DT(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),s,i=await or(n,"GET",`/projects/${o}`);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await hk(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await or(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await or(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await or(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");s=m.data}let a=s.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await or(n,"GET",`/projects/${s.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await or(n,"POST",`/projects/${s.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:s.path,cloneUrl:s.ssh_url_to_repo,branch:a}}async function jn(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let s=await fetch(MT+r,o),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status>=400&&s.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${s.status} ${i}`);return{status:s.status,data:a}}async function UT(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,s,i=await jn(n,"GET",o);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await gk(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await jn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);s=p.data}let a=s.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await jn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await jn(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=s.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:s.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var CT,LT,MT,$i=S(()=>{"use strict";Pr();CT="https://api.github.com";LT="https://gitlab.com/api/v4";MT="https://api.bitbucket.org/2.0"});function Ue(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=BT[r];if(!o)return null;let s=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(s.length<2)return null;let i=s[s.length-1].replace(/\.git$/,"");return i?{host:o,owner:s.slice(0,-1).join("/"),repoName:i}:null}var BT,vi=S(()=>{"use strict";BT={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as FT}from"node:crypto";import{existsSync as yk,mkdirSync as KT,readFileSync as kk,readdirSync as GT,rmSync as xi,writeFileSync as HT}from"node:fs";import{homedir as WT}from"node:os";import{dirname as qT,join as Fl}from"node:path";function wk(){return Fl(WT(),".codepipe","init-drafts")}function Kl(t){let e=FT("sha256").update(t).digest("hex").slice(0,16);return Fl(wk(),`${e}.json`)}function bk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=YT)}function $k(t){let e=Kl(t);if(!yk(e))return null;try{let r=JSON.parse(kk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:bk(r.savedAt)?(xi(e,{force:!0}),null):r}catch{return null}}function Gl(t){xi(Kl(t),{force:!0})}function vk(){let t=wk();if(yk(t))for(let e of GT(t)){let r=Fl(t,e);try{let n=JSON.parse(kk(r,"utf-8"));bk(n.savedAt)&&xi(r,{force:!0})}catch{xi(r,{force:!0})}}}var YT,On,xk=S(()=>{"use strict";YT=24*60*60*1e3;On=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Gl(this.cwd)}persist(){let e=Kl(this.cwd);KT(qT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};HT(e,JSON.stringify(r,null,2)+`
895
895
  `,{mode:384})}}});function Sk(t){let e=[],r=[];return t.localClones&&(e.push({value:"map",label:"Project map from git history",hint:"local, a few seconds \u2014 a graph of files, tasks and their connections for the AI agent"}),r.push("map")),e.push(t.indexExists?{value:"index",label:"Re-index the context (an index already exists)",hint:"background job; keeps nothing if skipped"}:{value:"index",label:"Context index \u2014 knowledge and docs map",hint:"background job, recommended on first run"}),t.indexExists||r.push("index"),!t.indexExists&&t.reposNonEmpty&&(e.push({value:"backfill",label:"Reconstruct architecture decisions from the existing code",hint:"deep one-off AI analysis \u2014 proposes decision drafts you review before they become canonical"}),r.push("backfill")),{message:"Analyze the project? Pick what to run (space to toggle, enter to confirm):",options:e,initialValues:r,reindex:t.indexExists}}async function Ek(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}var Rk=S(()=>{"use strict"});import{existsSync as VT}from"node:fs";import{join as zT}from"node:path";import{simpleGit as XT}from"simple-git";function eC(t){let e=t.split("/");return e[e.length-1]??t}function Ik(t){if(t.filter(r=>!ZT.test(eC(r))).length>JT)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(QT.has(n))return!0}return!1}async function tC(t){try{let r=(await XT(t).raw(["ls-files"])).split(`
896
896
  `).map(n=>n.trim()).filter(Boolean);return Ik(r)}catch{return!1}}async function rC(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let s=await o.json();return Array.isArray(s)?Ik(s.map(i=>i.name??"").filter(Boolean)):!1}catch{return!1}}async function Tk(t,e){for(let r of t)try{let n=e.localRoot!=null?zT(e.localRoot,r.mountAs??r.name):null;if(n&&VT(n)?await tC(n):await rC(r,e.tokens))return!0}catch{}return!1}var JT,ZT,QT,Ck=S(()=>{"use strict";JT=3,ZT=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,QT=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Ak}from"node:fs";import{join as Pk}from"node:path";import{simpleGit as _k}from"simple-git";async function Uo(t,e,r={}){let n=r.log??nC,o=[];for(let s of e){let i=Pk(t,s.mountAs),a=Td(s);if(!Ak(i)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${s.mountAs}/`),await _k().clone(a,i),o.push({mountAs:s.mountAs,status:"cloned"})}catch(u){let p=Mo(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${s.mountAs}: ${p}`),o.push({mountAs:s.mountAs,status:"error",detail:p})}continue}if(!Ak(Pk(i,".git"))){n.warn(`${s.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-not-git"});continue}let c=_k(i),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!oC(l,a)){n.warn(`${s.mountAs}/ origin (${Mo(l)||"none"}) != expected (${Mo(a)}) \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-origin-mismatch",detail:Mo(l)});continue}if(r.dryRun){n.info(`would fetch ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:s.mountAs,status:"fetched"})}catch(u){let p=Mo(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${s.mountAs}: ${p}`),o.push({mountAs:s.mountAs,status:"error",detail:p})}}return o}function oC(t,e){return jk(t)===jk(e)}function jk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Mo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Nk(t={}){let e=Re();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Uo(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var nC,Si=S(()=>{"use strict";bt();nC={info:t=>console.log(t),warn:t=>console.warn(t)}});var Uk={};Fe(Uk,{ensureEmbeddedWorker:()=>Ri,spawnWorkerProcess:()=>Ii,upCommand:()=>Ti,workerChildEnv:()=>Mk,workerStartArgs:()=>Dk});import{spawn as Lk}from"node:child_process";import{existsSync as Ok}from"node:fs";import{homedir as sC,hostname as iC}from"node:os";import{join as Ei}from"node:path";async function aC(t,e,r){let n=je(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${gt(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await Fp(t.hubUrl.replace(/\/$/,""),n.token)}catch(s){return console.warn(`[up] could not verify the worker registration (${s instanceof Error?s.message:String(s)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${gt(e)} still holds its token.
897
897
  Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),Gd(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function cC(t,e,r){let n=je(e)!==null;if(!await aC(t,e,r))return;console.log(n?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await ks(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(s){throw s instanceof W&&s.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):s instanceof W&&s.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):s instanceof W?s:new Error(`cannot reach the HUB at ${t.hubUrl} (${s instanceof Error?s.message:String(s)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Nr({hub:t.hubUrl,token:o,name:r.name??`${iC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function lC(t,e){let r=je(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=De(r.sealPublicKey);if(!q(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=is(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Ri(t,e,r){await cC(t,e,r),lC(t.projectId,e)}function Dk(t){return[...t?["--profile",t]:[],"worker","start"]}function Mk(t){let e={...t};for(let r of za)delete e[r];return e}function Ii(t){let e=Lk(process.execPath,[t.entry,...Dk(t.profile)],{stdio:["ignore","pipe","pipe"],env:Mk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-partner/codepipe",
3
- "version": "0.11.1-dev.229.g86cd22a",
3
+ "version": "0.12.0",
4
4
  "description": "CodePipe turns tasks into reviewed pull requests: an AI agent analyzes, implements, and opens a PR under your control.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",