@code-partner/codepipe 0.3.3 → 0.3.4-dev.101.g8c14361
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +33 -33
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var me="0.3.
|
|
2
|
+
var me="0.3.4-dev.101.g8c14361",Te="https://hub.dev.codepipe.dev";var Ie=4,yu=4;function Dr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=yu&&t<=Ie}var je=".codepipe-context.yaml",lr=".devpipe-context.yaml",li=[{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",je]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[je]}];function Br(t=2){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
|
-
`}function ui(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 pi(t,e=li){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 di(t,e=li){return e.filter(r=>r.version>t)}var fi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","backfill","analysis","chat"];function dt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ge="opus",Gr="sonnet",wu="haiku",Wn=[Ge,Gr,wu],mi={analyze:Ge,implement:Ge,"resolve-conflict":Ge,rework:Ge,estimate:Gr,build:Gr,draft:Gr,index:Ge,backfill:Ge,analysis:Ge,chat:Ge};var bu=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Wn],help:"Overrides the recommended defaults for every role not listed below."},...fi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Wn],help:`recommended: ${mi[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function gi(t=bu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...gi(r.groups));return e}function ku(t,e){let r=JSON.stringify(e);return gi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function hi(t){let e=ku(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var ft=/^[a-z][a-z0-9-]{1,30}$/,$u="-codepipe-ctx";function Me(t){return`${t}${$u}`}var vu=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Mr(t){for(let e of vu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ur={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Rt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var mt="x-bitbucket-api-token-auth";function Fr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var yi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as
|
|
5
|
+
`}function ui(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 pi(t,e=li){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 di(t,e=li){return e.filter(r=>r.version>t)}var fi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","backfill","analysis","chat"];function dt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ge="opus",Gr="sonnet",wu="haiku",Wn=[Ge,Gr,wu],mi={analyze:Ge,implement:Ge,"resolve-conflict":Ge,rework:Ge,estimate:Gr,build:Gr,draft:Gr,index:Ge,backfill:Ge,analysis:Ge,chat:Ge};var bu=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Wn],help:"Overrides the recommended defaults for every role not listed below."},...fi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Wn],help:`recommended: ${mi[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function gi(t=bu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...gi(r.groups));return e}function ku(t,e){let r=JSON.stringify(e);return gi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function hi(t){let e=ku(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var ft=/^[a-z][a-z0-9-]{1,30}$/,$u="-codepipe-ctx";function Me(t){return`${t}${$u}`}var vu=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Mr(t){for(let e of vu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ur={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Rt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var mt="x-bitbucket-api-token-auth";function Fr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var yi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as qh}from"commander";import{homedir as vi}from"node:os";import{mkdirSync as Au,readFileSync as _u,writeFileSync as Ou,existsSync as Yn}from"node:fs";import{dirname as Si,join as Wr,resolve as Nu}from"node:path";import{fileURLToPath as Uu}from"node:url";import{existsSync as Hr,readFileSync as bi,readdirSync as Su,writeFileSync as Ru}from"node:fs";import{dirname as Cu,join as Ve}from"node:path";import{parse as Tu}from"yaml";import{existsSync as wi,renameSync as xu}from"node:fs";function gt(t,e,r=n=>console.error(n)){if(wi(e)||!wi(t))return!1;try{return xu(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Pe=".codepipe",qn=".devpipe";function Iu(t=process.cwd()){let e=t;for(;;){if(Hr(Ve(e,Pe,"project.yaml")))return e;if(Hr(Ve(e,qn,"project.yaml")))return gt(Ve(e,qn),Ve(e,Pe))&&Pu(e),e;let r=Cu(e);if(r===e)return null;e=r}}function ju(t){let e=Ve(t,Pe);return Hr(e)?e:Ve(t,qn)}function Pu(t){let e=Ve(t,".gitignore");if(!Hr(e))return;let r=bi(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
6
6
|
`);n!==r&&Ru(e,n)}function ge(t=process.cwd()){let e=Iu(t);if(!e)return null;let r=ju(e),n=Eu(bi(Ve(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function ki(t,e,r){return Su(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function Kr(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Eu(t){let e=Tu(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,d=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:d,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function $i(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var xi=Nu(Si(Uu(import.meta.url)),"..");function Ri(t){let e=Wr(xi,".env");if(Yn(e)&&process.loadEnvFile(e),t){let r=Wr(xi,"profiles",t,".env");Yn(r)&&process.loadEnvFile(r)}}function Ct(t){let e=L("CONFIG");return e||(t?Wr(vi(),".codepipe","profiles",t,"config.json"):Wr(vi(),".codepipe","config.json"))}function $e(t){let e=Ct(t);if(!Yn(e))return null;let r=_u(e,"utf-8");return JSON.parse(r)}function Fe(t,e){let r=Ct(e);Au(Si(r),{recursive:!0}),Ou(r,JSON.stringify(t,null,2)+`
|
|
7
7
|
`,{mode:384})}function qr(t){if(t)return{cfg:he(t),profile:t};let e;try{e=ge()?.spec.projectId||void 0}catch{}if(e){let r=$e(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:he(void 0),profile:void 0}}function he(t){let e=$e(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Ct(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Ci}from"node:os";import{join as Ti}from"node:path";function Ii(){gt(Ti(Ci(),".devpipe"),Ti(Ci(),".codepipe"))}import{homedir as ji}from"node:os";import{existsSync as Pi,mkdirSync as Ei,readFileSync as Ai,writeFileSync as _i}from"node:fs";import{dirname as Oi,join as Ni}from"node:path";function Yr(t,e,r){let n=U(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,V(n),"pinned")}function Ui(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],V(r),!0):!1}function Ee(t){return Ni(ji(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Ee(t);return Pi(e)?JSON.parse(Ai(e,"utf-8")):null}function V(t){let e=Ee(t.projectId);Ei(Oi(e),{recursive:!0}),_i(e,JSON.stringify(t,null,2)+`
|
|
8
8
|
`,{mode:384})}function Vr(){return Ni(ji(),".codepipe","shared.json")}function Vn(){let t=Vr();return Pi(t)?JSON.parse(Ai(t,"utf-8")):null}function Li(t){let e=Vr();Ei(Oi(e),{recursive:!0}),_i(e,JSON.stringify(t,null,2)+`
|
|
@@ -452,7 +452,7 @@ ${h.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),w=d?["--force-with-leas
|
|
|
452
452
|
`)?e:e+`
|
|
453
453
|
`;return vf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Rf(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function Cf(t,e){return e?.contextWrite?.token?{user:Fr(t),secret:e.contextWrite.token}:t===ur.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ur.bitbucket?e?.bitbucket?.apiToken?{user:mt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function $n(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await M(e.hubUrl,e.cliToken,e.projectId)}catch(c){return o.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Cf(Rt(s.cloneUrl),r);if(a){let c=await Tf({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await If({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function Tf(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Rf(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Zn(r);await l.reset(["--hard",`origin/${s}`]),eo(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Va(Ja(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await za(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function If(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=qa(i,n),a=Wa(e.cloneUrl),c=e.branch;try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Zn(r);await l.reset(["--hard",`origin/${c}`]),eo(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Va(Ja(r),{recursive:!0}),await Ut().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ut(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await za(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function za(t){let e=Ut(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Xa(t={profile:void 0}){let{cfg:e,profile:r}=qr(t.profile),n=U(e.projectId);n&&pr(n),yr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),wr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),br(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=xr(To(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Jr("CLI_LOG",i,o);if(s.enabled){let p=new jt(s);zr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Kr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let p=xr(To(),".codepipe",r?xr("profiles",r,"context"):"context");if(await vo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await $n({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await vo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=xr(To(),".codepipe",r?xr("profiles",r,"context-config"):"context-config");Qr(a.contextDir,g,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=kn(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function d(p){u||(u=!0,console.log(`
|
|
454
454
|
[${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}import{hostname as Uf}from"node:os";import{spawnSync as jf}from"node:child_process";function Pf(){try{return jf("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Qa(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Pf(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Lt}from"node:os";import{mkdirSync as Ef,readFileSync as Za,writeFileSync as Af,existsSync as Io}from"node:fs";import{dirname as _f,join as rt}from"node:path";Io(".env")&&process.loadEnvFile(".env");function Of(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Re(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=rt(Lt(),".codepipe","worker");return t?rt(r,"profiles",t,"config.json"):rt(r,"config.json")}function ec(){return rt(Lt(),".devpipe-sandbox","config.json")}function vn(){gt(rt(Lt(),".devpipe"),rt(Lt(),".codepipe")),L("SANDBOX_CONFIG")||gt(rt(Lt(),".devpipe-sandbox"),rt(Lt(),".codepipe-sandbox"))}function ie(t){let e=Re(t),r=null;return Io(e)?r=JSON.parse(Za(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&Io(ec())&&(r=JSON.parse(Za(ec(),"utf-8"))),r?(r.planningLane=Of(),r):null}function tc(t,e){let r=Re(e);Ef(_f(r),{recursive:!0}),Af(r,JSON.stringify(t,null,2)+`
|
|
455
|
-
`,{mode:384})}import Nf from"ws";var Dt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Nf(e)}};async function wt(t){vn();let e=ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Re(t.profile)}.`),process.exit(1));let r=t.name??Uf(),n=Qa({projects:t.projects??[],llm:t.llm??null}),o=new Dt(t.hub.replace(/\/$/,"")),i=on(),s=ae(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});tc({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Re(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as
|
|
455
|
+
`,{mode:384})}import Nf from"ws";var Dt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Nf(e)}};async function wt(t){vn();let e=ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Re(t.profile)}.`),process.exit(1));let r=t.name??Uf(),n=Qa({projects:t.projects??[],llm:t.llm??null}),o=new Dt(t.hub.replace(/\/$/,"")),i=on(),s=ae(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});tc({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Re(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Im,readFileSync as Uo,readdirSync as jm,writeFileSync as Pm}from"node:fs";import{dirname as Em,join as Tr,resolve as Am}from"node:path";import{spawn as Ff}from"node:child_process";import{existsSync as Hf}from"node:fs";import{spawn as Lf}from"node:child_process";var rc=16e3,nc=5e3,oc=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Df="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function jo(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Bf(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function Gf(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function bt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Po(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
456
456
|
`}async function ic(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new qe;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let d=c.message;for(let p of d?.content??[]){let g=p.type;if(g==="text"){let f=String(p.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:jo(f,rc)})}else if(g==="tool_use"){let f=String(p.name??""),y=p.input?.file_path??p.input?.path,w=Bf(y,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...w?{file:w}:{}})}}return}if(u==="user"){let d=c.message;for(let p of d?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,f=g?jo(Gf(p.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...f?{text:f}:{}})}return}if(u==="result"){s=c;let d=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...d?{text:d}:{}});return}if(u==="system"){let d=String(c.subtype??"").trim();d&&o({ts:l,kind:"system",author:"agent",text:d})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=Lf(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let d=!1,p=!1,g=null,f=()=>{d=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)};e.signal?.addEventListener("abort",f,{once:!0});let y=null,w=()=>{y&&clearTimeout(y),y=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${oc}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)},oc)},b=()=>{g&&clearTimeout(g),y&&clearTimeout(y),e.signal?.removeEventListener("abort",f)},h=!0,v=I=>{if(!(!h||u.stdin.destroyed))try{u.stdin.write(I)}catch{}};v(Po(e.prompt)),w(),(async()=>{try{for await(let I of e.interactive.inbox){if(d||!h)break;if(w(),I.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:jo(I.text,rc)}),v(Po(I.text));else{v(Po(Df)),h=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let S="",N=I=>{let x;try{x=JSON.parse(I)}catch{return}a(x)};u.stdout.on("data",I=>{i.push(I),w(),S+=I;let x;for(;(x=S.indexOf(`
|
|
457
457
|
`))!==-1;){let m=S.slice(0,x).trim();S=S.slice(x+1),m&&N(m)}}),u.stderr.on("data",I=>{i.push(I);for(let x of I.split(`
|
|
458
458
|
`)){let m=x.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",I=>{b(),l(I)}),u.on("close",I=>{if(b(),d){l(new qe);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}S.trim()&&N(S.trim()),console.log(`[claude:chat] exit code=${I}`),c({artifactPaths:[],log:i.join(""),usage:Mf(s)})})})}function Mf(t){let e=dt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=bt(r.input_tokens),e.outputTokens=bt(r.output_tokens),e.cacheReadInputTokens=bt(r.cache_read_input_tokens),e.cacheCreationInputTokens=bt(r.cache_creation_input_tokens)),e.totalCostUsd=bt(t.total_cost_usd),e.numTurns=bt(t.num_turns),e.durationMs=bt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},qe=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Kf=5e3,Sr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ic(this.binary,e);if(e.signal?.aborted)throw new qe;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let y=Vf(f.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(f.type==="assistant"){let y=f.message;typeof y?.model=="string"&&(c=y.model);let w=y?.usage;w&&(a+=1,s.input+=ce(w.input_tokens),s.output+=ce(w.output_tokens),s.cacheRead+=ce(w.cache_read_input_tokens),s.cacheCreate+=ce(w.cache_creation_input_tokens))}}},d=e.role,p=e.onActivity,g=f=>{if(p)for(let y of zf(f,e.workspaceDir))try{p(y)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,y)=>{let w=Ff(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let b=!1,h=null,v=()=>{b=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},Kf)};e.signal?.addEventListener("abort",v,{once:!0});let S=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",v)},N="";w.stdout.on("data",I=>{n.push(I),N+=I;let x;for(;(x=N.indexOf(`
|
|
@@ -545,17 +545,17 @@ ${r?`
|
|
|
545
545
|
`)+`
|
|
546
546
|
`,{mode:384}),hc(o,`[credential]
|
|
547
547
|
helper = store --file=${n}
|
|
548
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{pm(r,{recursive:!0,force:!0})}catch{}}}}function Ao(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(fm)),t.bitbucket?.apiToken&&(e.push(`https://${mt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(mm)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(gm)),yc(e,r)}function wc(t,e){if(t.contextWrite?.token){let r=Rt(e)??"github.com",n=Fr(r);return yc([`https://${n}:${t.contextWrite.token}@${r}`],[Sn(r)])}return Ao(t)}import{spawn as kc}from"node:child_process";import{existsSync as Rn,mkdirSync as Cn,readFileSync as hm,rmSync as _o,symlinkSync as ym}from"node:fs";import{homedir as wm}from"node:os";import{dirname as Tn,join as kt}from"node:path";function $c(){return kt(wm(),".codepipe-sandbox","repos")}var Ft=new Map;function vc(t,e){let n=(Ft.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ft.get(t)===o&&Ft.delete(t)},()=>{Ft.get(t)===o&&Ft.delete(t)});return Ft.set(t,o),n}function bc(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}async function xc(t,e,r,n,o){
|
|
548
|
+
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{pm(r,{recursive:!0,force:!0})}catch{}}}}function Ao(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(fm)),t.bitbucket?.apiToken&&(e.push(`https://${mt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(mm)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(gm)),yc(e,r)}function wc(t,e){if(t.contextWrite?.token){let r=Rt(e)??"github.com",n=Fr(r);return yc([`https://${n}:${t.contextWrite.token}@${r}`],[Sn(r)])}return Ao(t)}import{spawn as kc}from"node:child_process";import{existsSync as Rn,mkdirSync as Cn,readFileSync as hm,rmSync as _o,symlinkSync as ym}from"node:fs";import{homedir as wm}from"node:os";import{dirname as Tn,join as kt}from"node:path";function $c(){return kt(wm(),".codepipe-sandbox","repos")}var Ft=new Map;function vc(t,e){let n=(Ft.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ft.get(t)===o&&Ft.delete(t)},()=>{Ft.get(t)===o&&Ft.delete(t)});return Ft.set(t,o),n}function bc(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}function bm(t){let e=t instanceof Error?t.message:String(t);return/invalid index-pack output/i.test(e)||/index-pack failed/i.test(e)||/fetch-pack/i.test(e)||/objects[\/\\]pack/i.test(e)||/(loose object .* is corrupt|corrupt loose object|object file .* is empty)/i.test(e)||/did not send all necessary objects/i.test(e)||/(bad object|bad tree object|unable to read (tree|sha1))/i.test(e)||/not a git repository/i.test(e)||/unable to read .*(pack|object)/i.test(e)}async function xc(t,e,r,n,o){let i=async c=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await Y(t,["reset","--hard",`origin/${c}`],o),await Y(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!bc(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Rn(t)&&_o(t,{recursive:!0,force:!0}),Cn(Tn(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!bc(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Rn(t)&&_o(t,{recursive:!0,force:!0}),Cn(Tn(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Rn(kt(t,".git")))try{return await s()}catch(c){if(!bm(c))throw c;let l=c instanceof Error?c.message:String(c);console.warn(`[git] cache at ${t} looks corrupt (${l}) \u2014 discarding and re-cloning`)}return a()}async function Sc(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Ht="CodePipe Agent",Kt="codepipe@codepartner.ee";async function Rc(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let n=(await oe(r,["write-tree"])).trim(),o=(await oe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};return(await oe(r,["commit-tree",n,"-m",e],i)).trim()}async function Cc(t,e,r,n,o){try{await Y(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Rt(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Tc(t,e){return oe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ic(t,e,r,n,o){await Y(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await Y(t.workspacePath,["checkout","--force",r])}async function jc(t,e,r,n,o,i){let s=t.workspacePath;await Y(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await oe(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>oe(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await oe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),await c(n)||await Y(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt},u=(await oe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),d=(await oe(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await Y(s,["cherry-pick","--quit"],l).catch(()=>{});let p=null;try{await Y(s,["cherry-pick","--no-commit",d],l)}catch(f){p=f instanceof Error?f.message:String(f)}let g=(await oe(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
549
549
|
`).map(f=>f.trim()).filter(f=>f.length>0);if(p&&g.length===0)throw await Y(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${p}`);return g}async function Oo(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};(await oe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await Y(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Y(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await oe(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
550
550
|
`).map(l=>l.trim()).filter(l=>l.length>0),c=await oe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Y(t,e,r){return new Promise((n,o)=>{let i=kc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
|
|
551
551
|
${s.join("").trim()||"(no stderr)"}`))})})}function oe(t,e,r){return new Promise((n,o)=>{let i=kc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
|
|
552
552
|
${a.join("").trim()||"(no stderr)"}`))})})}function Pc(t,e){Rn(t)&&_o(t,{recursive:!0,force:!0}),Cn(Tn(t),{recursive:!0}),ym(e,t,"dir")}async function Ec(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Cn(Tn(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ac(t,e,r,n="worktree",o){return r.length===0?[]:vc(e,async()=>{let i=[];for(let s of r){let a=kt($c(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await xc(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let l=(await oe(a,["rev-parse","HEAD"])).trim(),u=kt(t,"code",s.name);n==="direct"?(Pc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Ec(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i})}async function _c(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return vc(e,async()=>{let s=kt($c(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await xc(s,i.cloneUrl,i.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=kt(t,"context");n==="direct"?(Pc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Ec(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await oe(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Oc(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await Y(r,["add","-A",...n]).catch(()=>{});let o;try{o=await oe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
553
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=hm(kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as
|
|
554
|
-
`+e.subarray(e.length-No).toString("utf-8")}import{lstatSync as
|
|
553
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=hm(kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as km}from"node:fs";import{join as $m}from"node:path";var No=8*1024,Wt=class extends Error{},Cr="meta/build-result.json";function Nc(t){let e=$m(t,Cr),r;try{r=km(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${Cr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Wt(`${Cr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Wt(`${Cr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Wt(`${Cr}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let d=u,p=typeof d.name=="string"?d.name:null,g=typeof d.exitCode=="number"?d.exitCode:null;if(p===null||g===null)return[];let f={name:p,exitCode:g};return typeof d.durationMs=="number"&&(f.durationMs=d.durationMs),[f]}),c=typeof o.logTail=="string"?vm(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(d=>d.exitCode!==0);u&&(l.failedStep=u.name)}return l}function vm(t){let e=Buffer.from(t,"utf-8");return e.length<=No?t:`\u2026 [${e.length-No} bytes elided] \u2026
|
|
554
|
+
`+e.subarray(e.length-No).toString("utf-8")}import{lstatSync as xm,mkdtempSync as Sm,readFileSync as Rm,readdirSync as Lc,rmSync as Uc}from"node:fs";import{tmpdir as Cm}from"node:os";import{join as In,relative as Tm}from"node:path";var Dc=new Set(["code","context"]);function Bc(t){let e=Sm(In(Cm(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Uc(e,{recursive:!0,force:!0}),listFiles:()=>Gc(e,e),readFile:r=>Rm(In(e,r),"utf-8"),clean:()=>{for(let r of Lc(e))Dc.has(r)||Uc(In(e,r),{recursive:!0,force:!0})}}}function Gc(t,e){let r=[];for(let n of Lc(e)){let o=In(e,n),i=xm(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Dc.has(n))continue;r.push(...Gc(t,o))}else r.push(Tm(t,o))}return r}var jn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),_m=new Set(["implement","resolve-conflict"]);function Om(t){let e=Buffer.from(t,"utf-8");if(e.length<=jn)return t;let r=Math.floor(jn/4),n=jn-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
|
|
555
555
|
|
|
556
556
|
\u2026 [${s} bytes elided \u2014 log capped at ${jn} bytes for upload] \u2026
|
|
557
557
|
|
|
558
|
-
${i}`}function
|
|
558
|
+
${i}`}function Nm(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Ir(t={}){vn();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Jr("SANDBOX_LOG","sandbox",Am("./logs"));if(n.enabled){let x=new jt(n);zr(x),console.log(`[log] file logging \u2192 ${x.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${me} (protocol ${Ie})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=uc(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=fc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,d=null,p=!1,g=()=>{let x=s.openControlSocket();return u=x,x.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Ie};x.send(JSON.stringify(m))}),x.on("message",m=>{let T=m.toString("utf-8"),k=null;try{let R=JSON.parse(T);R&&typeof R=="object"&&(k=R)}catch{}if(k&&k.type==="hello"){let R=k;d=Dr(R.protocolVersion);let P=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${P}`),d&&(p=!1);return}if(k&&k.type==="pause_job"){let R=typeof k.jobId=="string"?k.jobId:"",P=R?l.get(R):void 0;P?(console.warn(`[ws] pause_job ${R} \u2014 aborting agent`),P.paused=!0,P.abort.abort()):console.log(`[ws] pause_job ${R} \u2014 not a running job, ignoring`),R&&x.send(JSON.stringify({type:"job_paused",jobId:R}));return}if(k&&(k.type==="chat_user_message"||k.type==="chat_finalize")){let R=typeof k.jobId=="string"?k.jobId:"",P=R?l.get(R):void 0;if(P?.chatInbox)if(k.type==="chat_user_message"){let $=typeof k.text=="string"?k.text:"";$.trim()&&P.chatInbox.push({kind:"user",text:$})}else P.chatInbox.finalize();else console.log(`[ws] ${String(k.type)} ${R} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${T}`)}),x.on("close",(m,T)=>{console.log(`[ws] closed code=${m} reason=${T?.toString()||""}`),u===x&&(u=null),!a&&setTimeout(g,2e3)}),x.on("error",m=>console.warn(`[ws] error: ${m.message}`)),x},f=g(),y=async x=>{for(;!a;){if(d===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${me}, protocol ${Ie}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,x);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${x}] ${m.status} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3));continue}let T=await m.json();await w(s,T)}catch(m){if(c.signal.aborted)break;let T=m instanceof Error?m.message:String(m);console.warn(`[claim:${x}] error: ${T} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function w(x,m){let T={abort:new AbortController,paused:!1};m.role==="chat"&&(T.chatInbox=Nm()),l.set(m.jobId,T);let k=!1,R=null,P=null,$=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),j=async()=>{try{await x.heartbeat(m.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(F){let ke=F instanceof Error?F.message:String(F);console.warn(`[job] ${m.jobId} heartbeat error: ${ke}`)}};j();let D=setInterval(()=>{j()},$),K=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(h(m.prompt," \u2502 "));let Ce=[],lt=null,E=400,de=25,Ye=500,Ue=()=>{if(lt&&(clearTimeout(lt),lt=null),Ce.length===0)return;let F=Ce.splice(0,Ce.length),ke=u;if(!ke||ke.readyState!==ke.OPEN)return;let Le={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:F};try{ke.send(JSON.stringify(Le))}catch{}},Dn=F=>{Ce.push(F),Ce.length>Ye&&Ce.shift(),Ce.length>=de?Ue():lt||(lt=setTimeout(Ue,E))},ut=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,te=new Set,Bn=null;try{if(!o){k||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:K,finishedAt:new Date().toISOString()});return}let F=Bc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let ke=b(m,r);R=ke.gitCreds,P=ke.contextGitCreds;let Le=R?.env,ni=ke.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ke.claudeOauthToken}:void 0,De=[],ir=null,Gn=null;try{let _="worktree";De=await Ac(F.dir,m.projectId,m.projectRepos,_,Le);let O=await _c(F.dir,m.projectId,m.contextRepo,_,Le);Gn=O,ir=O?.workspacePath??null}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} materialize failed: ${O}`),k||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let oi=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let _=m.contextRepo?.cloneUrl;if(!_||!Le)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let B of m.deliveries){let H=De.find(fe=>fe.name===B.name);if(H){if(m.role==="implement"&&B.baseSha&&B.baseSha!==H.baseSha){let fe=await jc(H,B.deliveryRef,B.deliverySha,B.baseSha,_,Le);console.log(`[job] ${m.jobId} ${H.name}: base moved ${B.baseSha.slice(0,10)} \u2192 ${H.baseSha.slice(0,10)} \u2014 re-applied delivery ${B.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&O.push(`- **${H.name}**:`,...fe.map(sr=>` - \`${sr}\``));continue}await Ic(H,B.deliveryRef,B.deliverySha,_,Le),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${B.deliverySha.slice(0,10)} for ${m.role}`)}}return O},Mn=[];if(m.role==="build"||m.role==="implement")try{Mn=await oi()}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} delivery checkout failed: ${O}`),k||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let Fn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},ii="";if(m.role==="resolve-conflict"){if(!De.some(_=>Fn[_.name])){let _="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${m.jobId} ${_}`),k||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}try{let _=[];for(let O of De){let B=Fn[O.name];if(!B)continue;let H=await Oo(O,B,Le);console.log(`[job] ${m.jobId} ${O.name}: merged ${B} into ${O.ref} \u2014 ${H.length} conflicted file(s)`),H.length>0?_.push(`- **${O.name}**:`,...H.map(fe=>` - \`${fe}\``)):_.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}ii=`
|
|
559
559
|
|
|
560
560
|
## Conflicts to resolve
|
|
561
561
|
|
|
@@ -569,22 +569,22 @@ The base branch advanced since the previous iteration; its delivery was re-appli
|
|
|
569
569
|
|
|
570
570
|
`+Mn.join(`
|
|
571
571
|
`)+`
|
|
572
|
-
`:"",mu=S(v(m.prompt,De,ir),ir,m.taskId)+ii+fu,Hn=[...De.map(_=>_.workspacePath),...ir?[ir]:[]];Hn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Hn.join(", ")}`),ut&&(Bn=setInterval(()=>{let O=u;if(!O||O.readyState!==O.OPEN)return;let B;try{B=
|
|
572
|
+
`:"",mu=S(v(m.prompt,De,ir),ir,m.taskId)+ii+fu,Hn=[...De.map(_=>_.workspacePath),...ir?[ir]:[]];Hn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Hn.join(", ")}`),ut&&(Bn=setInterval(()=>{let O=u;if(!O||O.readyState!==O.OPEN)return;let B;try{B=jm(Tr(F.dir,"drafts")).filter(H=>H.endsWith(".json")).sort()}catch{return}for(let H of B){if(te.has(H))continue;if(te.size>=yi)break;let fe;try{let le=JSON.parse(Uo(Tr(F.dir,"drafts",H),"utf-8")),pt=typeof le.localRef=="string"?le.localRef:"",G=typeof le.title=="string"?le.title:"",z=typeof le.body=="string"?le.body:"";if(!pt||!G)continue;fe={localRef:pt,title:G,body:z,...le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(le.links)?{links:le.links}:{}}}catch{continue}te.add(H);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:ut,child:fe};try{O.send(JSON.stringify(sr))}catch{}}},1500));try{let _={workspaceDir:F.dir,role:m.role,prompt:mu,addDirs:Hn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...ni?{env:ni}:{},signal:T.abort.signal,onActivity:Dn},O=T.chatInbox?await o.run({..._,interactive:{inbox:T.chatInbox.iterable}}):await gc(o,_,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let G of De)try{await Sc(G);let z=Fn[G.name];m.role==="resolve-conflict"&&z&&await Oo(G,z,Le)}catch(z){let ar=z instanceof Error?z.message:String(z);console.warn(`[job] ${m.jobId} worktree reset failed (${G.name}): ${ar}`)}try{await oi()}catch(G){let z=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${z}`)}},aborted:()=>k||T.paused}),B=[];if(_m.has(m.role)&&De.length>0){let G=m.metadata??{},z=typeof G.commitMessage=="string"?G.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,si=P?.env;if(!ar||!si)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let gu=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Be of De){let cr=await Rc(Be,z);if(!cr){console.log(`[job] ${m.jobId} ${Be.name}: no changes \u2014 no delivery`);continue}let Kn=`codepipe/deliveries/${gu}/${m.jobId}/${Be.name}`;await Cc(Be,cr,Kn,ar,si),B.push({name:Be.name,deliveryRef:Kn,deliverySha:cr,baseSha:Be.baseSha}),console.log(`[job] ${m.jobId} ${Be.name}: delivered ${cr.slice(0,10)} \u2192 ${Kn}`);let ai=await Tc(Be,cr);if(ai.trim().length>0){let hu=Tr("display",`${Be.name}.diff`),ci=Tr(F.dir,hu);Im(Em(ci),{recursive:!0}),Pm(ci,ai)}}}if(m.role==="resolve-conflict"&&B.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let H;m.role==="build"&&(H=Nc(F.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let fe=O.artifactPaths.length>0?O.artifactPaths:F.listFiles(),sr=Array.from(new Set(fe)),le;if(Gn)try{let G=m.role==="index"?["adr/SOURCES.md"]:m.role==="backfill"?["adr"]:[],z=await Oc(Gn,G);z.length>0&&(le=z,console.log(`[job] ${m.jobId} captured ${z.length} knowledge file(s) for Context Repo`))}catch(G){let z=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${z}`)}let pt={jobId:m.jobId,status:"succeeded",artifacts:sr.map(G=>({path:G,contentBase64:Uo(`${F.dir}/${G}`).toString("base64")})),...le?{contextWrites:le}:{},...B.length>0?{deliveries:B}:{},log:Om(O.log),startedAt:K,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...H?{build:H}:{}};if(k||T.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${T.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await x.submitResult(pt),console.log(`[job] ${m.jobId} done \u2014 uploaded ${pt.artifacts.length} artifact(s):`);for(let G of pt.artifacts){let z=Buffer.from(G.contentBase64,"base64").length;console.log(` \xB7 ${G.path} (${z} bytes)`)}pt.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(_){let O=_ instanceof Error?_.message:String(_);if(T.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${m.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let B=mc(_);console.warn(B?`[job] ${m.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${O}`),await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:K,finishedAt:new Date().toISOString(),...B?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(D),Bn&&clearInterval(Bn),Ue(),T.chatInbox?.close(),l.delete(m.jobId),R?.cleanup(),P?.cleanup()}}function b(x,m){if(!x.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${x.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let T;try{T=JSON.parse(sn(m,x.credBundle).toString("utf-8"))}catch($){return console.warn(`[job] ${x.jobId} failed to open credBundle: ${$ instanceof Error?$.message:String($)}`),{gitCreds:null,contextGitCreds:null}}let k=Ao(T);k&&console.log(`[job] ${x.jobId} cred bundle opened \u2014 git creds configured`);let R=wc(T,x.contextRepo.cloneUrl),P={gitCreds:k,contextGitCreds:R};return T.claudeOauthToken&&(P.claudeOauthToken=T.claudeOauthToken),P}function h(x,m){return x.split(`
|
|
573
573
|
`).map(T=>m+T).join(`
|
|
574
574
|
`)}function v(x,m,T){let k=m[0]?.workspacePath??"";return x.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,T??"")}function S(x,m,T){let k=x,R=T.includes("::")?"":T.split(":",2)[1]??"",P=$=>{if(!m||!R)return"";try{return Uo(Tr(m,"tasks",R,$),"utf-8").trim()}catch{return""}};if(k.includes("{{solutionMd}}")){let $=P("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";k=k.replace(/\{\{solutionMd\}\}/g,()=>$)}if(k.includes("{{taskDescription}}")){let $=P("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";k=k.replace(/\{\{taskDescription\}\}/g,()=>$)}return k}let N=x=>{if(a)return;a=!0,console.log(`
|
|
575
|
-
[${x}] shutting down`),c.abort();let m=[...l.keys()];for(let R of l.values())R.abort.abort();let T=new AbortController,k=setTimeout(()=>T.abort(),3e3);(async()=>(await Promise.all(m.map(async R=>{try{await s.releaseJob(R,`sandbox ${x}`,T.signal),console.log(`[${x}] released job ${R}`)}catch(P){let $=P instanceof Error?P.message:String(P);console.warn(`[${x}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),f.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let I=[y("implementation")];e.planningLane!==!1?I.push(y("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(I)}async function Mc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gn(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let d=JSON.parse(u);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ie(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as pg}from"node:child_process";import{existsSync as Jt,mkdirSync as ll,readFileSync as ul,readdirSync as dg,writeFileSync as pl}from"node:fs";import{join as $t,resolve as dl}from"node:path";import{setTimeout as Go}from"node:timers/promises";import{cancel as fg,confirm as zt,intro as fl,isCancel as En,log as C,outro as Mo,password as Xt,select as st,spinner as ml,text as Z}from"@clack/prompts";import{simpleGit as _n}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Um(t,e,r):e.host==="gitlab"?Hm(t,e,r):Wm(t,e,r)}async function Fc(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 it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Hc(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 s=encodeURIComponent(`${t.owner}/${t.name}`);return(await ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Kc(e.gitlabToken,t):o}}return e.bitbucket?(await qt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wc(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Hc(t,e){let r=!1;try{r=(await it(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 Kc(t,e){let r=!1;try{r=(await ot(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 Wc(t,e){let r=!1;try{r=(await qt(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`}var Nm="https://api.github.com";async function it(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 i=await fetch(Nm+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Um(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 Lm(n,e,r),i=await Bm(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ot(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Gm(n,o.owner,o.name,a.path,i)||await Mm(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function Lm(t,e,r){let n=await it(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 Hc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Dm(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await it(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Dm(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Bm(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Gm(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Mm(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Fm="https://gitlab.com/api/v4";async function ot(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 i=await fetch(Fm+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Hm(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}`),i,s=await ot(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Kc(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await ot(n,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(d.data?.username!==e.owner){let f=await ot(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`);p.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await ot(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let g=(await ot(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of g)l.add(f.path);if(g.length<100)break}let u=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return u.length>0?await ot(n,"POST",`/projects/${i.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:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Km="https://api.bitbucket.org/2.0";async function qt(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 i=await fetch(Km+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function Wm(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)}`,i,s=await qt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Wc(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await qt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.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`);i=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await qt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let g of l)d.set(g.path,g.content);if((await qt(n,"POST",`${o}/src`,{form:d})).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=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var qm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function we(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=qm[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as Ym}from"node:crypto";import{existsSync as qc,mkdirSync as Vm,readFileSync as Yc,readdirSync as Jm,rmSync as Pn,writeFileSync as zm}from"node:fs";import{homedir as Xm}from"node:os";import{dirname as Qm,join as Lo}from"node:path";var Zm=24*60*60*1e3;function Vc(){return Lo(Xm(),".codepipe","init-drafts")}function Do(t){let e=Ym("sha256").update(t).digest("hex").slice(0,16);return Lo(Vc(),`${e}.json`)}function Jc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Zm)}function zc(t){let e=Do(t);if(!qc(e))return null;try{let r=JSON.parse(Yc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Jc(r.savedAt)?(Pn(e,{force:!0}),null):r}catch{return null}}function Bo(t){Pn(Do(t),{force:!0})}function Xc(){let t=Vc();if(qc(t))for(let e of Jm(t)){let r=Lo(t,e);try{let n=JSON.parse(Yc(r,"utf-8"));Jc(n.savedAt)&&Pn(r,{force:!0})}catch{Pn(r,{force:!0})}}}var Vt=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(){Bo(this.cwd)}persist(){let e=Do(this.cwd);Vm(Qm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};zm(e,JSON.stringify(r,null,2)+`
|
|
576
|
-
`,{mode:384})}};function Qc(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}function Zc(){return{message:"Reconstruct architecture decisions from the existing code first? (deep one-off analysis \u2014 proposes decision drafts you review before they become canonical)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes \u2014 analyse and propose decision drafts"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function el(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}}import{existsSync as
|
|
577
|
-
`).map(n=>n.trim()).filter(Boolean);return tl(r)}catch{return!1}}async function cg(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 i=await o.json();return Array.isArray(i)?tl(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function rl(t,e){for(let r of t)try{let n=e.localRoot!=null?tg(e.localRoot,r.mountAs??r.name):null;if(n&&eg(n)?await ag(n):await cg(r,e.tokens))return!0}catch{}return!1}import{existsSync as nl}from"node:fs";import{join as ol}from"node:path";import{simpleGit as il}from"simple-git";var lg={info:t=>console.log(t),warn:t=>console.warn(t)};async function jr(t,e,r={}){let n=r.log??lg,o=[];for(let i of e){let s=ol(t,i.mountAs),a=$i(i);if(!nl(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await il().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let d=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!nl(ol(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=il(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!ug(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let d=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}}return o}function ug(t,e){return sl(t)===sl(e)}function sl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function al(t={}){let e=ge();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 jr(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 cl=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){fg(t),process.exit(1)}function be(t){return En(t)&&J("aborted"),t}function W(t){return En(t)&&J("aborted"),typeof t=="string"?t:""}async function gl(t={}){fl("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Xc();let r=zc(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await zt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Bo(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Ho(e),s=await n.ask("target",async()=>be(await st({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||yl(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await Z({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??Te,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qt()),{cliToken:u,accountEmail:d}=await n.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await mg(c,u));let g=a?hg(a.parsed.repoName):"",f=await n.ask("projectId",async()=>W(await Z({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>ft.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>W(await Z({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),w=await n.ask("automationLevel",async()=>be(await st({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),b=await n.ask("youtrack",()=>Sl()),h=await n.ask("youtrackProjectKey",async()=>W(await Z({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),v=await n.ask("youtrackWrites",async()=>be(await zt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),S=n.get("tokens")??{},N=()=>n.set("tokens",S),I=await n.ask("repos",()=>kg(S,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let x=await $g(await n.ask("contextRepo",()=>$l(f,I,S,l)),f,I,S,l,N,E=>n.set("contextRepo",E)),{spec:m,mode:T}=x;C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await n.ask("assigneeLogin",async()=>W(await Z({message:"your YouTrack login (the assignee value)",...b.login?{initialValue:b.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),R=await n.ask("claudeToken",()=>Ig(s==="farm")),P={projectId:f,name:y,automationLevel:w,repos:I,youtrackProjectKey:h};C.step(`${T==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Yt(P,m,{...vl(S),youtrackWrites:v,trackerUrl:b.url,mode:T,log:{info:E=>C.message(E),warn:E=>C.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}P.contextRepo=$,C.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),C.step(`registering project on ${c}\u2026`);let j;try{j=await tt(c,u,P)}catch(E){if(E instanceof A&&E.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{j=await M(c,u,f)}catch(de){throw de instanceof A&&J(`HUB \u2192 ${de.status} ${de.message}`),de}}else if(E instanceof A&&E.status===401)n.delete("cliToken"),J("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)J(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let D=j.contextRepo??$;C.success(`project ${j.projectId} ready (${j.provisioningStatus})`);let K=await Cg(D),Ce={url:b.url,token:b.token};if(s==="farm"){let E=p,de={...S,...K?{contextWrite:K}:{},...R?{claude:{oauthToken:R}}:{},youtrack:Ce},Ye=S.github?.token;if(D.host==="github"&&Ye)try{let te=Ha(`devpipe-${f}`);await Ka(D,Ye,te.publicKey,`devpipe-${f}`),de.contextSsh={privateKey:te.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(te){C.warn(`could not set up Context Repo SSH deploy key (${te instanceof Error?te.message:String(te)}); the farm will fall back to the token path.`)}let Ue={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:de,contextRepo:D,projectConfig:_e(P,v,b.url,k||void 0)},Dn=We(E.farm.publicKey,JSON.stringify(Ue));C.step(`handing project ${f} to farm ${E.farm.name}\u2026`);let ut;try{ut=await hn(c,u,E.farm.farmId,{projectId:f,sealedBundle:Dn})}catch(te){throw te instanceof A&&J(te.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:te.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${te.status} ${te.message}`),te}ut.ok||J(`farm rejected provisioning: ${ut.error??"unknown error"}`),await Fo(c,u,f,D,Ye,j.repos,null,S),n.clear(),Mo(`done. project ${f} is now hosted on farm ${E.farm.name} (daemon ${ut.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}xl(S),await wl(e,D.cloneUrl,D.branch),kl(e),a&&await wg(e);{let E=$t(e,Pe);At(E);let de=_e(P,v,b.url,k||void 0),Ye=dr(E,de);Ye.length>0&&C.success(`local project config \u2192 .codepipe/{${Ye.join(", ")}}`),ht(f,de,{info:Ue=>C.message(Ue),warn:Ue=>C.warn(Ue)})}await bl(e,j.repos);let lt={hubUrl:c,cliToken:u,projectId:f,...S,...K?{contextWrite:K}:{},...R?{claude:{oauthToken:R}}:{},youtrack:Ce};V(lt),Fe({hubUrl:c,cliToken:u,projectId:f,accountEmail:d},f),C.success(`secrets \u2192 ${Ee(f)}`),await Fo(c,u,f,D,S.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,j.repos,e,S),n.clear(),Mo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Fo(t,e,r,n,o,i=[],s=null,a={}){let c=await el(n,o);if(!c){let d=!1;try{d=await rl(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let p=Zc(),g=await st({message:p.message,options:p.options,initialValue:p.initialValue});if(!En(g)&&g===p.proceedValue)try{let{jobId:f}=await $r(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){C.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=Qc(c),u=await st({message:l.message,options:l.options,initialValue:l.initialValue});if(!(En(u)||u!==l.proceedValue))try{let{jobId:d}=await $r(t,e,r,{reindex:l.reindex});C.success(`indexing queued (job ${d}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(d){C.warn(`could not start indexing: ${d instanceof Error?d.message:String(d)}. You can retry later \u2014 registration is not affected.`)}}async function mg(t,e){let r;try{r=await ua(t,e)}catch(c){throw c instanceof A&&J(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&J("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=be(await st({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=mn(i.farmId,i.publicKey)}catch(c){J(c instanceof Error?c.message:String(c))}return be(await zt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
575
|
+
[${x}] shutting down`),c.abort();let m=[...l.keys()];for(let R of l.values())R.abort.abort();let T=new AbortController,k=setTimeout(()=>T.abort(),3e3);(async()=>(await Promise.all(m.map(async R=>{try{await s.releaseJob(R,`sandbox ${x}`,T.signal),console.log(`[${x}] released job ${R}`)}catch(P){let $=P instanceof Error?P.message:String(P);console.warn(`[${x}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),f.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let I=[y("implementation")];e.planningLane!==!1?I.push(y("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(I)}async function Mc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gn(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let d=JSON.parse(u);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ie(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as dg}from"node:child_process";import{existsSync as Jt,mkdirSync as ll,readFileSync as ul,readdirSync as fg,writeFileSync as pl}from"node:fs";import{join as $t,resolve as dl}from"node:path";import{setTimeout as Go}from"node:timers/promises";import{cancel as mg,confirm as zt,intro as fl,isCancel as En,log as C,outro as Mo,password as Xt,select as st,spinner as ml,text as Z}from"@clack/prompts";import{simpleGit as _n}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Lm(t,e,r):e.host==="gitlab"?Km(t,e,r):qm(t,e,r)}async function Fc(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 it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Hc(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 s=encodeURIComponent(`${t.owner}/${t.name}`);return(await ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Kc(e.gitlabToken,t):o}}return e.bitbucket?(await qt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wc(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Hc(t,e){let r=!1;try{r=(await it(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 Kc(t,e){let r=!1;try{r=(await ot(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 Wc(t,e){let r=!1;try{r=(await qt(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`}var Um="https://api.github.com";async function it(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 i=await fetch(Um+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Lm(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 Dm(n,e,r),i=await Gm(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ot(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Mm(n,o.owner,o.name,a.path,i)||await Fm(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function Dm(t,e,r){let n=await it(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 Hc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Bm(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await it(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Bm(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Gm(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Mm(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Fm(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Hm="https://gitlab.com/api/v4";async function ot(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 i=await fetch(Hm+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Km(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}`),i,s=await ot(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Kc(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await ot(n,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(d.data?.username!==e.owner){let f=await ot(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`);p.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await ot(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let g=(await ot(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of g)l.add(f.path);if(g.length<100)break}let u=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return u.length>0?await ot(n,"POST",`/projects/${i.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:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Wm="https://api.bitbucket.org/2.0";async function qt(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 i=await fetch(Wm+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function qm(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)}`,i,s=await qt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Wc(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await qt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.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`);i=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await qt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let g of l)d.set(g.path,g.content);if((await qt(n,"POST",`${o}/src`,{form:d})).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=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Ym={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function we(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=Ym[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as Vm}from"node:crypto";import{existsSync as qc,mkdirSync as Jm,readFileSync as Yc,readdirSync as zm,rmSync as Pn,writeFileSync as Xm}from"node:fs";import{homedir as Qm}from"node:os";import{dirname as Zm,join as Lo}from"node:path";var eg=24*60*60*1e3;function Vc(){return Lo(Qm(),".codepipe","init-drafts")}function Do(t){let e=Vm("sha256").update(t).digest("hex").slice(0,16);return Lo(Vc(),`${e}.json`)}function Jc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=eg)}function zc(t){let e=Do(t);if(!qc(e))return null;try{let r=JSON.parse(Yc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Jc(r.savedAt)?(Pn(e,{force:!0}),null):r}catch{return null}}function Bo(t){Pn(Do(t),{force:!0})}function Xc(){let t=Vc();if(qc(t))for(let e of zm(t)){let r=Lo(t,e);try{let n=JSON.parse(Yc(r,"utf-8"));Jc(n.savedAt)&&Pn(r,{force:!0})}catch{Pn(r,{force:!0})}}}var Vt=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(){Bo(this.cwd)}persist(){let e=Do(this.cwd);Jm(Zm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Xm(e,JSON.stringify(r,null,2)+`
|
|
576
|
+
`,{mode:384})}};function Qc(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}function Zc(){return{message:"Reconstruct architecture decisions from the existing code first? (deep one-off analysis \u2014 proposes decision drafts you review before they become canonical)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes \u2014 analyse and propose decision drafts"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function el(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}}import{existsSync as tg}from"node:fs";import{join as rg}from"node:path";import{simpleGit as ng}from"simple-git";var og=3,ig=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,sg=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"]);function ag(t){let e=t.split("/");return e[e.length-1]??t}function tl(t){if(t.filter(r=>!ig.test(ag(r))).length>og)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(sg.has(n))return!0}return!1}async function cg(t){try{let r=(await ng(t).raw(["ls-files"])).split(`
|
|
577
|
+
`).map(n=>n.trim()).filter(Boolean);return tl(r)}catch{return!1}}async function lg(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 i=await o.json();return Array.isArray(i)?tl(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function rl(t,e){for(let r of t)try{let n=e.localRoot!=null?rg(e.localRoot,r.mountAs??r.name):null;if(n&&tg(n)?await cg(n):await lg(r,e.tokens))return!0}catch{}return!1}import{existsSync as nl}from"node:fs";import{join as ol}from"node:path";import{simpleGit as il}from"simple-git";var ug={info:t=>console.log(t),warn:t=>console.warn(t)};async function jr(t,e,r={}){let n=r.log??ug,o=[];for(let i of e){let s=ol(t,i.mountAs),a=$i(i);if(!nl(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await il().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let d=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!nl(ol(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=il(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!pg(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let d=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}}return o}function pg(t,e){return sl(t)===sl(e)}function sl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function al(t={}){let e=ge();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 jr(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 cl=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){mg(t),process.exit(1)}function be(t){return En(t)&&J("aborted"),t}function W(t){return En(t)&&J("aborted"),typeof t=="string"?t:""}async function gl(t={}){fl("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Xc();let r=zc(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await zt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Bo(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Ho(e),s=await n.ask("target",async()=>be(await st({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||yl(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await Z({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??Te,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qt()),{cliToken:u,accountEmail:d}=await n.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await gg(c,u));let g=a?yg(a.parsed.repoName):"",f=await n.ask("projectId",async()=>W(await Z({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>ft.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>W(await Z({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),w=await n.ask("automationLevel",async()=>be(await st({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),b=await n.ask("youtrack",()=>Sl()),h=await n.ask("youtrackProjectKey",async()=>W(await Z({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),v=await n.ask("youtrackWrites",async()=>be(await zt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),S=n.get("tokens")??{},N=()=>n.set("tokens",S),I=await n.ask("repos",()=>$g(S,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let x=await vg(await n.ask("contextRepo",()=>$l(f,I,S,l)),f,I,S,l,N,E=>n.set("contextRepo",E)),{spec:m,mode:T}=x;C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await n.ask("assigneeLogin",async()=>W(await Z({message:"your YouTrack login (the assignee value)",...b.login?{initialValue:b.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),R=await n.ask("claudeToken",()=>jg(s==="farm")),P={projectId:f,name:y,automationLevel:w,repos:I,youtrackProjectKey:h};C.step(`${T==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Yt(P,m,{...vl(S),youtrackWrites:v,trackerUrl:b.url,mode:T,log:{info:E=>C.message(E),warn:E=>C.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}P.contextRepo=$,C.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),C.step(`registering project on ${c}\u2026`);let j;try{j=await tt(c,u,P)}catch(E){if(E instanceof A&&E.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{j=await M(c,u,f)}catch(de){throw de instanceof A&&J(`HUB \u2192 ${de.status} ${de.message}`),de}}else if(E instanceof A&&E.status===401)n.delete("cliToken"),J("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)J(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let D=j.contextRepo??$;C.success(`project ${j.projectId} ready (${j.provisioningStatus})`);let K=await Tg(D),Ce={url:b.url,token:b.token};if(s==="farm"){let E=p,de={...S,...K?{contextWrite:K}:{},...R?{claude:{oauthToken:R}}:{},youtrack:Ce},Ye=S.github?.token;if(D.host==="github"&&Ye)try{let te=Ha(`devpipe-${f}`);await Ka(D,Ye,te.publicKey,`devpipe-${f}`),de.contextSsh={privateKey:te.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(te){C.warn(`could not set up Context Repo SSH deploy key (${te instanceof Error?te.message:String(te)}); the farm will fall back to the token path.`)}let Ue={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:de,contextRepo:D,projectConfig:_e(P,v,b.url,k||void 0)},Dn=We(E.farm.publicKey,JSON.stringify(Ue));C.step(`handing project ${f} to farm ${E.farm.name}\u2026`);let ut;try{ut=await hn(c,u,E.farm.farmId,{projectId:f,sealedBundle:Dn})}catch(te){throw te instanceof A&&J(te.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:te.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${te.status} ${te.message}`),te}ut.ok||J(`farm rejected provisioning: ${ut.error??"unknown error"}`),await Fo(c,u,f,D,Ye,j.repos,null,S),n.clear(),Mo(`done. project ${f} is now hosted on farm ${E.farm.name} (daemon ${ut.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}xl(S),await wl(e,D.cloneUrl,D.branch),kl(e),a&&await bg(e);{let E=$t(e,Pe);At(E);let de=_e(P,v,b.url,k||void 0),Ye=dr(E,de);Ye.length>0&&C.success(`local project config \u2192 .codepipe/{${Ye.join(", ")}}`),ht(f,de,{info:Ue=>C.message(Ue),warn:Ue=>C.warn(Ue)})}await bl(e,j.repos);let lt={hubUrl:c,cliToken:u,projectId:f,...S,...K?{contextWrite:K}:{},...R?{claude:{oauthToken:R}}:{},youtrack:Ce};V(lt),Fe({hubUrl:c,cliToken:u,projectId:f,accountEmail:d},f),C.success(`secrets \u2192 ${Ee(f)}`),await Fo(c,u,f,D,S.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,j.repos,e,S),n.clear(),Mo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Fo(t,e,r,n,o,i=[],s=null,a={}){let c=await el(n,o);if(!c){let d=!1;try{d=await rl(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let p=Zc(),g=await st({message:p.message,options:p.options,initialValue:p.initialValue});if(!En(g)&&g===p.proceedValue)try{let{jobId:f}=await $r(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){C.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=Qc(c),u=await st({message:l.message,options:l.options,initialValue:l.initialValue});if(!(En(u)||u!==l.proceedValue))try{let{jobId:d}=await $r(t,e,r,{reindex:l.reindex});C.success(`indexing queued (job ${d}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(d){C.warn(`could not start indexing: ${d instanceof Error?d.message:String(d)}. You can retry later \u2014 registration is not affected.`)}}async function gg(t,e){let r;try{r=await ua(t,e)}catch(c){throw c instanceof A&&J(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&J("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=be(await st({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=mn(i.farmId,i.publicKey)}catch(c){J(c instanceof Error?c.message:String(c))}return be(await zt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
578
578
|
${s}
|
|
579
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),fn(i.farmId,s),{farm:i,fingerprint:s}}async function hl(t){fl(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();yl(e,t.force===!0);let r=W(await Z({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,o,t.projectId)}catch(d){throw d instanceof A&&J(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await Sl(),c={},l=new Set(s.repos.map(d=>d.host));l.add(s.contextRepo.host);for(let d of l)await An(d,c,d===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===d)?.owner,n);xl(c),await wl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),kl(e);{let d=$t(e,Pe);At(d);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=_e(p,!0,a.url),f=dr(d,g);f.length>0&&C.success(`local project config \u2192 .codepipe/{${f.join(", ")}} (defaults \u2014 review and adjust)`),ht(t.projectId,g,{info:y=>C.message(y),warn:y=>C.warn(y)})}await bl(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Fe({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Ee(t.projectId)}`),await Fo(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,c),Mo("done.")}function yl(t,e){if(!Jt(t)){ll(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=
|
|
579
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),fn(i.farmId,s),{farm:i,fingerprint:s}}async function hl(t){fl(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();yl(e,t.force===!0);let r=W(await Z({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,o,t.projectId)}catch(d){throw d instanceof A&&J(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await Sl(),c={},l=new Set(s.repos.map(d=>d.host));l.add(s.contextRepo.host);for(let d of l)await An(d,c,d===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===d)?.owner,n);xl(c),await wl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),kl(e);{let d=$t(e,Pe);At(d);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=_e(p,!0,a.url),f=dr(d,g);f.length>0&&C.success(`local project config \u2192 .codepipe/{${f.join(", ")}} (defaults \u2014 review and adjust)`),ht(t.projectId,g,{info:y=>C.message(y),warn:y=>C.warn(y)})}await bl(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Fe({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Ee(t.projectId)}`),await Fo(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,c),Mo("done.")}function yl(t,e){if(!Jt(t)){ll(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=fg(t).filter(o=>!r.has(o));n.length!==0&&(e||J(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Ho(t){if(!Jt($t(t,".git")))return null;try{let r=(await _n(t).remote(["get-url","origin"])||"").toString().trim(),n=r?we(r):null;return n?{parsed:n,defaultBranch:await hg(t)}:null}catch{return null}}async function hg(t){let e=_n(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function yg(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ft.test(e)?e:""}function wg(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function bg(t){let e=$t(t,".gitignore"),r=Jt(e)?ul(e,"utf-8"):"";if(wg(r))return;if(!be(await zt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
580
580
|
`)?"":`
|
|
581
581
|
`;pl(e,r+o+`
|
|
582
582
|
# codepipe workspace (added by \`codepipe init\`)
|
|
583
583
|
.codepipe/
|
|
584
|
-
`),C.success(`.codepipe/ added to ${dl(e)}`)}function
|
|
584
|
+
`),C.success(`.codepipe/ added to ${dl(e)}`)}function kg(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=dg(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Qt(){let t="";try{t=(await _n().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Z({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Zt(t,e){C.step(`connecting account ${e}`);let r;try{r=await ga(t,e)}catch(s){throw s instanceof kr&&J(`${e} is not authorized on this HUB yet.
|
|
585
585
|
Sign up at ${t} (registration form on the login screen),
|
|
586
586
|
wait for the operator to approve it by email, then re-run
|
|
587
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(
|
|
587
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(kg(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
|
|
588
588
|
${r.authorizeUrl}
|
|
589
589
|
`+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
|
|
590
590
|
otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await ha(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Go(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&J("the HUB rejected this account"),s.status==="expired"&&J("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
@@ -593,43 +593,43 @@ The base branch advanced since the previous iteration; its delivery was re-appli
|
|
|
593
593
|
`,i=cl.join(`
|
|
594
594
|
`)+`
|
|
595
595
|
`;pl(e,r+o+(r?`
|
|
596
|
-
`:"")+i),C.message(`appended runtime entries to ${dl(e)}`)}async function
|
|
596
|
+
`:"")+i),C.message(`appended runtime entries to ${dl(e)}`)}async function $g(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;C.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await An(s.host,t,s.owner,e),i?.();let c=W(await Z({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=W(await Z({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;be(await zt({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=W(await Z({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||we(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=we(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await An(c.host,t,c.owner,e),i?.();let l=W(await Z({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=W(await Z({message:"default branch (optional)",placeholder:"main"})).trim(),d=W(await Z({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),d&&d!==l&&(p.mountAs=d),o.push(p),n.onProgress?.(o)}return o}async function $l(t,e,r,n){C.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=be(await st({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=W(await Z({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Me(t),validate:u=>{let d=(u??"").trim();if(!d)return"required";if(!we(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await xg(),l=W(await Z({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=W(await Z({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function vl(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??It()}}async function vg(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await An(c.host,n,c.owner,o),i?.();let u=ml();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await Fc(c,vl(n),{explain:l==="attach"});if(d.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(d.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${d.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(d.detail,1);let p=be(await st({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&J("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await $l(e,r,n,o),s(a)}}async function xg(){return be(await st({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Pr(t,e){let r=ml();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function xl(t){yr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),wr(t.gitlab?.token??process.env.GITLAB_TOKEN),br(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function An(t,e,r,n){if(!e[t])if(t==="github"){let o=await Sg(r);o?e.github=o:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await Rg(r,n);o?e.bitbucket=o:C.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let o=await Cg();o?e.gitlab=o:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Sg(t){for(;;){let e=W(await Xt({message:`GitHub PAT \u2014 blank to skip
|
|
597
597
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
598
598
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
599
599
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
600
600
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
601
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Pr("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function
|
|
601
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Pr("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Rg(t,e){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
602
602
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
603
603
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
604
604
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
605
605
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
606
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Z({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=W(await Xt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Pr("Bitbucket",()=>Xe(r,n,t)))return{email:r,apiToken:n};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function
|
|
607
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Pr("GitLab",()=>Qe(t))){let e=await is(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function
|
|
606
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Z({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=W(await Xt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Pr("Bitbucket",()=>Xe(r,n,t)))return{email:r,apiToken:n};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Cg(){for(;;){let t=W(await Xt({message:`GitLab PAT \u2014 blank to skip
|
|
607
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Pr("GitLab",()=>Qe(t))){let e=await is(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Tg(t){if(be(await zt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
608
608
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
609
609
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
610
610
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?C.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
611
611
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
612
612
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):C.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
613
|
-
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=W(await Xt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Pr("contextWrite",()=>
|
|
614
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Xt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||C.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`."),r):(C.warn(t?"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`."),"")}async function Sl(){for(;;){let t=W(await Z({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=W(await Xt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Pr("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await Ns({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as jg}from"node:fs";function ee(t){throw new Error(t)}function ne(t,e){return(typeof t!="string"||t.trim().length===0)&&ee(`config: '${e}' must be a non-empty string`),t.trim()}function Er(t,e){if(t==null)return;typeof t!="string"&&ee(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Pg(t){(!t||typeof t!="object")&&ee("config: expected a JSON object");let e=t,r=ne(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ee("config: 'hubUrl' must start with http(s)://");let n=ne(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ee("config: 'project' is required");let i=o,s=ne(i.id,"project.id");ft.test(s)||ee("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ne(i.name,"project.name"),c=ne(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ee("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ee("config: 'project.repos' must be an array");let u=l.map((h,v)=>{(!h||typeof h!="object")&&ee(`config: project.repos[${v}] must be an object`);let S=h,N=ne(S.host,`project.repos[${v}].host`);N!=="github"&&N!=="bitbucket"&&N!=="gitlab"&&ee(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let I={name:ne(S.name,`project.repos[${v}].name`),host:N,owner:ne(S.owner,`project.repos[${v}].owner`),repoName:ne(S.repoName,`project.repos[${v}].repoName`)},x=Er(S.defaultBranch,`project.repos[${v}].defaultBranch`);x&&(I.defaultBranch=x);let m=Er(S.mountAs,`project.repos[${v}].mountAs`);return m&&(I.mountAs=m),I}),d=i.contextRepo;(!d||typeof d!="object")&&ee("config: 'project.contextRepo' is required");let p=d,g=Er(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&ee("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:g,owner:ne(p.owner,"project.contextRepo.owner"),name:Er(p.name,"project.contextRepo.name")??Me(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},w=Er(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&ee("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ee("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&ee("config: 'secrets' must be an object");let h=b,v={};if(h.github){let S=h.github;v.github={token:ne(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;v.bitbucket={email:ne(S.email,"secrets.bitbucket.email"),apiToken:ne(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;v.gitlab={token:ne(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;v.youtrack={url:ne(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:ne(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;v.contextWrite={token:ne(S.token,"secrets.contextWrite.token")}}y.secrets=v}return y}async function Eg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Ag(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Xe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Qe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Rl(t){let e=!t.configPath||t.configPath==="-"?await Eg():jg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){ee(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=Pg(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Ag(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Yt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??It(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){ee(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await tt(o,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(o,i,s.id);else if(p instanceof A)ee(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let d={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(V(d),Fe({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),ht(s.id,_e(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await $r(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Cl,intro as Tl,isCancel as Il,log as Ko,outro as _g,password as jl}from"@clack/prompts";async function Og(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Pl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Og(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Tl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ko.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await jl({message:"Claude OAuth token"});Il(i)&&(Cl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Li({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Vr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){Tl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ko.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await jl({message:"Claude OAuth token"});Il(i)&&(Cl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},V(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ko.success("Claude OAuth token saved."),_g("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Ng,confirm as Ug,intro as Lg,isCancel as El,log as se,outro as Dg,select as Al,text as at}from"@clack/prompts";function _l(t){Ng(t),process.exit(1)}function er(t){return El(t)&&_l("aborted"),t}function Ar(t){return El(t)&&_l("aborted"),typeof t=="string"?t:""}async function Bg(t,e){let r=er(await Al({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Ar(await at({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Ar(await at({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Ol(t={profile:void 0}){let e=he(t.profile);Lg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await at({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>ft.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await at({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=er(await Al({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=er(await at({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await Ug({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Ar(await at({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||we(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let f=Ar(await at({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),y=Ar(await at({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:g.host,owner:g.owner,repoName:g.repoName};y&&(w.defaultBranch=y),a.push(w)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Bg(r,a),u=U(e.projectId);se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await Yt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??It(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=d,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await tt(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),ht(r,_e(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),Dg("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as Gg,rmSync as Mg}from"node:fs";import{confirm as Fg,intro as Hg,isCancel as Kg,log as ct,outro as Wg,spinner as qg}from"@clack/prompts";function Ne(t){ct.error(t),process.exit(1)}var Nl=t=>t.trim().replace(/\/+$/,"");async function Ul(t){Hg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||Ne("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Ne(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Nl(r.hubUrl),o=r.projectId,i=Nl(t.hub);i.startsWith("http")||Ne("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ne(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=qg();b.start(`reading project ${o} from ${n}\u2026`);try{l=await M(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(h){throw b.stop("could not read the source project",1),h instanceof A&&Ne(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||Ne(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(o),d=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(ct.message(`move project '${o}'
|
|
613
|
+
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=W(await Xt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Pr("contextWrite",()=>Ig(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ig(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function jg(t){if(Vn()?.claude?.oauthToken&&!t)return C.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";C.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
|
|
614
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Xt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||C.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`."),r):(C.warn(t?"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`."),"")}async function Sl(){for(;;){let t=W(await Z({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=W(await Xt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Pr("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await Ns({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Pg}from"node:fs";function ee(t){throw new Error(t)}function ne(t,e){return(typeof t!="string"||t.trim().length===0)&&ee(`config: '${e}' must be a non-empty string`),t.trim()}function Er(t,e){if(t==null)return;typeof t!="string"&&ee(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Eg(t){(!t||typeof t!="object")&&ee("config: expected a JSON object");let e=t,r=ne(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ee("config: 'hubUrl' must start with http(s)://");let n=ne(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ee("config: 'project' is required");let i=o,s=ne(i.id,"project.id");ft.test(s)||ee("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ne(i.name,"project.name"),c=ne(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ee("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ee("config: 'project.repos' must be an array");let u=l.map((h,v)=>{(!h||typeof h!="object")&&ee(`config: project.repos[${v}] must be an object`);let S=h,N=ne(S.host,`project.repos[${v}].host`);N!=="github"&&N!=="bitbucket"&&N!=="gitlab"&&ee(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let I={name:ne(S.name,`project.repos[${v}].name`),host:N,owner:ne(S.owner,`project.repos[${v}].owner`),repoName:ne(S.repoName,`project.repos[${v}].repoName`)},x=Er(S.defaultBranch,`project.repos[${v}].defaultBranch`);x&&(I.defaultBranch=x);let m=Er(S.mountAs,`project.repos[${v}].mountAs`);return m&&(I.mountAs=m),I}),d=i.contextRepo;(!d||typeof d!="object")&&ee("config: 'project.contextRepo' is required");let p=d,g=Er(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&ee("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:g,owner:ne(p.owner,"project.contextRepo.owner"),name:Er(p.name,"project.contextRepo.name")??Me(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},w=Er(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&ee("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ee("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&ee("config: 'secrets' must be an object");let h=b,v={};if(h.github){let S=h.github;v.github={token:ne(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;v.bitbucket={email:ne(S.email,"secrets.bitbucket.email"),apiToken:ne(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;v.gitlab={token:ne(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;v.youtrack={url:ne(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:ne(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;v.contextWrite={token:ne(S.token,"secrets.contextWrite.token")}}y.secrets=v}return y}async function Ag(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function _g(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Xe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Qe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Rl(t){let e=!t.configPath||t.configPath==="-"?await Ag():Pg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){ee(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=Eg(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await _g(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Yt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??It(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){ee(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await tt(o,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(o,i,s.id);else if(p instanceof A)ee(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let d={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(V(d),Fe({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),ht(s.id,_e(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await $r(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Cl,intro as Tl,isCancel as Il,log as Ko,outro as Og,password as jl}from"@clack/prompts";async function Ng(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Pl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Ng(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Tl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ko.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await jl({message:"Claude OAuth token"});Il(i)&&(Cl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Li({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Vr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){Tl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ko.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await jl({message:"Claude OAuth token"});Il(i)&&(Cl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},V(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ko.success("Claude OAuth token saved."),Og("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Ug,confirm as Lg,intro as Dg,isCancel as El,log as se,outro as Bg,select as Al,text as at}from"@clack/prompts";function _l(t){Ug(t),process.exit(1)}function er(t){return El(t)&&_l("aborted"),t}function Ar(t){return El(t)&&_l("aborted"),typeof t=="string"?t:""}async function Gg(t,e){let r=er(await Al({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Ar(await at({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Ar(await at({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Ol(t={profile:void 0}){let e=he(t.profile);Dg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await at({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>ft.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await at({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=er(await Al({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=er(await at({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await Lg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Ar(await at({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||we(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let f=Ar(await at({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),y=Ar(await at({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:g.host,owner:g.owner,repoName:g.repoName};y&&(w.defaultBranch=y),a.push(w)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Gg(r,a),u=U(e.projectId);se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await Yt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??It(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=d,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await tt(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),ht(r,_e(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),Bg("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as Mg,rmSync as Fg}from"node:fs";import{confirm as Hg,intro as Kg,isCancel as Wg,log as ct,outro as qg,spinner as Yg}from"@clack/prompts";function Ne(t){ct.error(t),process.exit(1)}var Nl=t=>t.trim().replace(/\/+$/,"");async function Ul(t){Kg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||Ne("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Ne(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Nl(r.hubUrl),o=r.projectId,i=Nl(t.hub);i.startsWith("http")||Ne("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ne(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=Yg();b.start(`reading project ${o} from ${n}\u2026`);try{l=await M(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(h){throw b.stop("could not read the source project",1),h instanceof A&&Ne(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||Ne(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(o),d=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(ct.message(`move project '${o}'
|
|
615
615
|
from : ${n} (profile ${e})
|
|
616
616
|
to : ${i} (profile ${s}, project ${a}, account ${d})
|
|
617
617
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
618
618
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
619
|
-
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let b=await
|
|
620
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await xa(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof A&&ue(`HUB \u2192 ${h.status} ${h.message}`),ue(h instanceof Error?h.message:String(h))}let{updated:w,errors:b}=fr(e.projectId,y.repos,r?.contextDir);for(let h of w)X.message(`updated ${h}`);for(let h of b)X.warn(`could not update ${h.path}: ${h.error}`);X.success(`added "${u}" \u2014 project now has ${y.repos.length} repo(s)`),Bl("done")}async function Fl(t){let e=he(t.profile);Dl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{let c=(await M(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Sa(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&ue(`no repo named "${t.name}" in this project`),ue(`HUB \u2192 ${a.status} ${a.message}`)),ue(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=fr(e.projectId,o.repos,r?.contextDir);for(let a of i)X.message(`updated ${a}`);for(let a of s)X.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")X.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?On(r.root,n):ve(e.projectId,t.name);if(Wo(On(a,".git")))try{
|
|
621
|
-
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`),Ui(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function
|
|
619
|
+
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let b=await Hg({message:"Continue?",initialValue:!0});(Wg(b)||!b)&&Ne("aborted")}!c&&a===o&&ct.warn(`source and destination share the same project id, so they share one secrets file (${Ee(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Zt(i,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};ct.step(`registering project on ${i}\u2026`);let y;try{y=await tt(i,p,f)}catch(b){if(b instanceof A&&b.status===409){ct.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await M(i,p,a)}catch(h){throw h instanceof A&&Ne(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(b instanceof A&&b.status===403)Ne(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(b instanceof A)Ne(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}ct.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),Fe({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let w={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete w.sandboxPins,V(w),ct.success(`profile '${s}' \u2192 ${Ee(a)}`),c){let b=Re(s);Mg(b)&&(Fg(b),ct.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}qg(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Wo,rmSync as Vg,statSync as Jg}from"node:fs";import{join as On,relative as zg,resolve as Xg}from"node:path";import{cancel as Qg,intro as Dl,isCancel as Zg,log as X,outro as Bl,text as vt}from"@clack/prompts";import{simpleGit as Gl}from"simple-git";function ue(t){Qg(t),process.exit(1)}function xt(t){return Zg(t)&&ue("aborted"),typeof t=="string"?t:""}async function Ll(t){try{let e=await Gl(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function eh(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function th(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(eh(r,e)){X.message(`reusing existing ${e} credentials`);return}if(X.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=xt(await vt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=xt(await vt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=xt(await vt({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}V(r),X.success(`saved ${e} credentials`)}async function Ml(t){let e=he(t.profile);Dl(`codepipe repo add \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{n=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){ue(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Ll(process.cwd());h?(o=process.cwd(),X.message(`using the current directory (${h})`)):o=xt(await vt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Wo(o)&&Jg(o).isDirectory()){i=Xg(o);let h=await Ll(i);h||ue(`${i} is not a git repository (no origin remote)`);let v=we(h);v||ue(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=h,X.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=we(o);h||ue(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,X.message(`${a}: ${c}/${l}`)}let u=xt(await vt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===u)&&ue(`a repo named "${u}" is already registered`);let d=xt(await vt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=zg(r.root,i);p=h===""?".":h}let g=xt(await vt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;n.some(h=>(h.mountAs??h.name)===g)&&ue(`mount_as "${g}" is already used by another repo`),await th(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:g,...d?{defaultBranch:d}:{}};if(!i){let h=r?On(r.root,g):ve(e.projectId,u);if(Wo(On(h,".git")))X.message(`already cloned at ${h}`);else{X.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Gl().clone(s,h),X.success(`cloned into ${h}`)}catch(v){ue(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
|
|
620
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await xa(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof A&&ue(`HUB \u2192 ${h.status} ${h.message}`),ue(h instanceof Error?h.message:String(h))}let{updated:w,errors:b}=fr(e.projectId,y.repos,r?.contextDir);for(let h of w)X.message(`updated ${h}`);for(let h of b)X.warn(`could not update ${h.path}: ${h.error}`);X.success(`added "${u}" \u2014 project now has ${y.repos.length} repo(s)`),Bl("done")}async function Fl(t){let e=he(t.profile);Dl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{let c=(await M(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Sa(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&ue(`no repo named "${t.name}" in this project`),ue(`HUB \u2192 ${a.status} ${a.message}`)),ue(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=fr(e.projectId,o.repos,r?.contextDir);for(let a of i)X.message(`updated ${a}`);for(let a of s)X.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")X.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?On(r.root,n):ve(e.projectId,t.name);if(Wo(On(a,".git")))try{Vg(a,{recursive:!0,force:!0}),X.message(`deleted local clone ${a}`)}catch(c){X.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else X.message(`no local clone found to purge (${a})`)}X.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Bl("done")}async function Hl(t){let e=he(t.profile),r;try{r=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}import{spawn as rh}from"node:child_process";import{existsSync as Kl}from"node:fs";import{homedir as nh,hostname as oh}from"node:os";import{join as Nn}from"node:path";async function ih(t,e,r){let n=ie(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Re(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 fa(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \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 ${Re(e)} still holds its token.
|
|
621
|
+
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`),Ui(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function sh(t,e,r){let n=ie(e)!==null;if(!await ih(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 yn(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.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"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await wt({hub:t.hubUrl,token:o,name:r.name??`${oh()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function ah(t,e){let r=ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ae(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Yr(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 ch(t,e){let r=process.cwd(),n=Nn(r,Pe);if(Kr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Kl(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await M(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Ho(r);if(!ki(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await $n({cfg:t,secrets:s,contextDir:n,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=Nn(nh(),".codepipe",e?Nn("profiles",e,"context-config"):"context-config");if(Qr(c.contextDir,l,a),!Kl(Nn(c.contextDir,"project.yaml"))){At(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};dr(c.contextDir,_e(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Wl(t){let{cfg:e,profile:r}=qr(t.profile);await ch(e,r),await sh(e,r,t),ah(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,f)=>{let y=w=>b=>{for(let h of b.toString("utf-8").split(`
|
|
622
622
|
`))h.length>0&&w.write(`${f} ${h}
|
|
623
|
-
`)};g.stdout?.on("data",y(process.stdout)),g.stderr?.on("data",y(process.stderr))},i=(g,f)=>{let y=
|
|
624
|
-
[up] ${g} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(g);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let d=c.map(({name:g,child:f})=>new Promise(y=>{f.on("exit",(w,b)=>y({name:g,code:w??(b?1:0)}))})),p=await Promise.race(d);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(d),process.exit(p.code)}import{existsSync as nu,mkdirSync as
|
|
625
|
-
`)}async function Jl(t,e,r,n,o){let i;try{i=await ba(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(b=>b.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let f=Or(t.root,g.mountAs);if(!Vo(Or(f,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Yo(f).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:f})}let a=[];for(let p of s){let g=Yo(p.dir),f=await
|
|
623
|
+
`)};g.stdout?.on("data",y(process.stdout)),g.stderr?.on("data",y(process.stderr))},i=(g,f)=>{let y=rh(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,g),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
|
|
624
|
+
[up] ${g} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(g);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let d=c.map(({name:g,child:f})=>new Promise(y=>{f.on("exit",(w,b)=>y({name:g,code:w??(b?1:0)}))})),p=await Promise.race(d);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(d),process.exit(p.code)}import{existsSync as nu,mkdirSync as fh,readFileSync as mh,writeFileSync as gh}from"node:fs";import{homedir as hh}from"node:os";import{dirname as yh,join as ou}from"node:path";import*as rr from"node:readline";import{existsSync as Vo,readFileSync as lh,writeFileSync as uh}from"node:fs";import{join as Or}from"node:path";import{simpleGit as Yo}from"simple-git";var ql=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],ph="apply-queue.json";function Yl(t){return Or(t,ph)}function tr(t){let e=Yl(t);if(!Vo(e))return{};try{return JSON.parse(lh(e,"utf-8"))}catch{return{}}}function Vl(t,e){uh(Yl(t),JSON.stringify(e,null,2)+`
|
|
625
|
+
`)}async function Jl(t,e,r,n,o){let i;try{i=await ba(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(b=>b.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let f=Or(t.root,g.mountAs);if(!Vo(Or(f,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Yo(f).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:f})}let a=[];for(let p of s){let g=Yo(p.dir),f=await dh(g),y=p.claimRepo;try{await g.fetch()}catch(h){return await qo(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${_r(h)}`}}let w=`origin/${y.baseRef}`,b;try{b=await nn(g,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(h){return await qo(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${_r(h)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:f,branch:y.branchName,baseSha:w,deliveryCommit:b,startPoint:w})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...ql,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([...ql,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await qo(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${_r(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Vl(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),d=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
|
|
626
626
|
${d}
|
|
627
|
-
or: /abort ${r} --reason "..."`}}function Jo(t,e){let r=tr(t);r[e]&&(delete r[e],Vl(t,r))}async function qo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${_r(n)} \u2014 check manually`)}}async function zl(t,e,r){let o=tr(t.contextDir)[e];if(o){for(let i of o.repos){let s=Or(t.root,i.mountAs);if(!Vo(Or(s,".git")))continue;let a=Yo(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${_r(u)} \u2014 check manually`)}}Jo(t.contextDir,e)}}async function
|
|
627
|
+
or: /abort ${r} --reason "..."`}}function Jo(t,e){let r=tr(t);r[e]&&(delete r[e],Vl(t,r))}async function qo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${_r(n)} \u2014 check manually`)}}async function zl(t,e,r){let o=tr(t.contextDir)[e];if(o){for(let i of o.repos){let s=Or(t.root,i.mountAs);if(!Vo(Or(s,".git")))continue;let a=Yo(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${_r(u)} \u2014 check manually`)}}Jo(t.contextDir,e)}}async function dh(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function _r(t){return t instanceof Error?t.message.trim():String(t)}var Un=ou(hh(),".codepipe","history"),Xl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],iu=500,Ql=40;async function su(){let t=ge();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),pr(e),console.log(`connected to ${e.hubUrl} as project ${t.spec.projectId}`),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let r=tr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
628
628
|
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
629
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:
|
|
630
|
-
`))}async function
|
|
631
|
-
`)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}
|
|
632
|
-
`),t.unread+=1,Xo(t),t.rl.prompt(!0)}function Xo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var tu=!1;function ru(t){tu||(tu=!0,
|
|
633
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
629
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:wh,history:Dh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ds(s=>St(i,s)),i.daemon=kn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>St(i,s),warn:s=>St(i,s)},onEvent:s=>Ah(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Xo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await bh(i,a)){ru(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Xo(i),o.prompt()}),o.on("close",()=>{ru(i)})}function wh(t){let e=Xl.filter(r=>r.startsWith(t));return[e.length?e:Xl,t]}async function bh(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return kh(),!1;case"/status":return await $h(t),!1;case"/tasks":return await vh(t,n),!1;case"/task":return await xh(t,n),!1;case"/sync":return await Sh(t),!1;case"/logs":return _h(t,n),!1;case"/monitor":return Oh(t),!1;case"/apply":return await Zl(t,n,"apply"),!1;case"/unstash":return await Zl(t,n,"unstash"),!1;case"/applied":return await Rh(t,n),!1;case"/abort":return await Ch(t,n),!1;case"/approve":return await eu(t,n,"approve"),!1;case"/merge":return await eu(t,n,"merge"),!1;case"/login":return Ih(t,n),!1;case"/secret":return jh(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function kh(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
|
|
630
|
+
`))}async function $h(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=nu(ou(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function vh(t,e){let r=Nh(e,"--phase");try{let n=await ya(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){Ur(n)}}async function xh(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await wa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){Ur(n)}}async function Sh(t){let e=await jr(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function Zl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Jl(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Rh(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=tr(t.ws.contextDir)[r],i=Uh(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,d;if(l>0?(u=c.slice(0,l),d=c.slice(l+1)):(d=c,u=o?.repos.length===1?Th(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${d}`);return}let p=d.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${d}`);return}a.push({repoName:u,url:d,number:Number(p[1])})}try{let c=await ka(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Jo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Ur(c)}}async function eu(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await va(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Ur(o)}}async function Ch(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Lh(e,"--reason")||"local apply aborted";await zl(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await $a(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Ur(o)}}function Th(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Ih(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},V(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function jh(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
|
|
631
|
+
`)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}Ph(t.secrets,n,i),V(t.secrets),pr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Eh(t.secrets,n),V(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Ph(t,e,r){switch(e){case"GH_TOKEN":t.github={token:r};break;case"YOUTRACK_URL":t.youtrack={url:r,token:t.youtrack?.token??""};break;case"YOUTRACK_TOKEN":t.youtrack={url:t.youtrack?.url??"",token:r};break;case"BITBUCKET_EMAIL":t.bitbucket={email:r,apiToken:t.bitbucket?.apiToken??""};break;case"BITBUCKET_API_TOKEN":t.bitbucket={email:t.bitbucket?.email??"",apiToken:r};break;default:console.log(`unknown secret key: ${e}`)}}function Eh(t,e){e.startsWith("GH")||e==="github"?delete t.github:e.toUpperCase().startsWith("YOUTRACK")||e==="youtrack"?delete t.youtrack:(e.toUpperCase().startsWith("BITBUCKET")||e==="bitbucket")&&delete t.bitbucket}function Ah(t,e){switch(e.kind){case"connected":t.connection="connecting",St(t,"[hub] connected");break;case"registered":t.connection="registered",St(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Nr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",St(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Nr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Nr(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?St(t,`[hub] action ${e.actionType} done`):Nr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function St(t,e){t.logBuffer.push(e),t.logBuffer.length>iu&&t.logBuffer.shift(),t.follow&&Nr(t,e)}function _h(t,e){let r=e[0];if(r==="follow"||r==="on"){zo(t,!0);return}if(r==="off"){zo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(iu,Number(r)||Ql)):Ql,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function Oh(t){zo(t,!t.follow)}function zo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Nr(t,e){rr.cursorTo(process.stdout,0),rr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
632
|
+
`),t.unread+=1,Xo(t),t.rl.prompt(!0)}function Xo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var tu=!1;function ru(t){tu||(tu=!0,Bh(t.rl),t.daemon.stop(),console.log(`
|
|
633
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Nh(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Uh(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function Lh(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Ur(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Dh(){if(!nu(Un))return[];try{return mh(Un,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Bh(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{fh(yh(Un),{recursive:!0}),gh(Un,r.slice().reverse().join(`
|
|
634
634
|
`)+`
|
|
635
|
-
`)}catch{}}import{hostname as Bh}from"node:os";import{cancel as Gh,confirm as au,intro as Mh,isCancel as uu,log as nr,multiselect as Fh,outro as cu,password as Hh,select as Qo,text as Zo}from"@clack/prompts";function Lr(t){Gh(t),process.exit(1)}function or(t){return uu(t)&&Lr("aborted"),t}function Ln(t){return uu(t)&&Lr("aborted"),typeof t=="string"?t:""}function ei(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function lu(t,e){try{let{secret:r}=await yn(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Lr("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Kh(t,e){if(or(await Qo({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await ma(t,e);if(o.length>0)return or(await Fh({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));nr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){nr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ln(await Zo({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function ti(t){Mh("codepipe worker \u2014 set up this machine as a runner");let e=ie(t.profile);e&&(nr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),or(await au({message:"re-register this worker?",initialValue:!1}))||Lr("keeping the existing registration"));let r=$e(t.profile)??$e(),n=Ln(await Zo({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??r?.hubUrl??Te,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=or(await Qo({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await lu(n,a),nr.success("account-issued registration token minted");else if(i==="login"){let p=await Qt();a=(await Zt(n,p)).cliToken,s=await lu(n,a),nr.success("account-issued registration token minted")}else s=Ln(await Hh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Lr("a registration token is required");let c=await Kh(n,a),l=Ln(await Zo({message:"worker name",initialValue:Bh(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=or(await Qo({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await wt({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),nr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!or(await au({message:"start the claim-loop now?",initialValue:!0}))){cu("registered. start later with `codepipe worker`.");return}cu("starting the claim-loop\u2026"),await Ir(t.profile?{profile:t.profile}:{})}function qh(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return L("PROFILE")}var Q=qh();Ri(Q);Ii();var pe=new Wh;pe.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(me).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await su()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Rl({configPath:t.config,skipVerify:t.skipVerify===!0}):await gl({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Di({...t,profile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await hl({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});pe.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Xa({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await al({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Pl({profile:Q,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Mc({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Wl({profile:Q,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var pu=pe.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");pu.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??L("HUB_URL")??$e(Q)?.hubUrl??Te,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ei()){await ti({profile:Q});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await wt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...Q?{profile:Q}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ie(Q)&&ei()){await ti({profile:Q});return}await Ir(Q?{profile:Q}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var du=pe.command("project").description("Manage CodePipe projects");du.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ol({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});du.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await Ul({...t,cliProfile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ri=pe.command("repo").description("Manage the project's git repositories");ri.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Ml({profile:Q,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ri.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Fl({profile:Q,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ri.command("list").description("List the project's repos").action(async()=>{try{await Hl({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.parseAsync();
|
|
635
|
+
`)}catch{}}import{hostname as Gh}from"node:os";import{cancel as Mh,confirm as au,intro as Fh,isCancel as uu,log as nr,multiselect as Hh,outro as cu,password as Kh,select as Qo,text as Zo}from"@clack/prompts";function Lr(t){Mh(t),process.exit(1)}function or(t){return uu(t)&&Lr("aborted"),t}function Ln(t){return uu(t)&&Lr("aborted"),typeof t=="string"?t:""}function ei(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function lu(t,e){try{let{secret:r}=await yn(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Lr("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Wh(t,e){if(or(await Qo({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await ma(t,e);if(o.length>0)return or(await Hh({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));nr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){nr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ln(await Zo({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function ti(t){Fh("codepipe worker \u2014 set up this machine as a runner");let e=ie(t.profile);e&&(nr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),or(await au({message:"re-register this worker?",initialValue:!1}))||Lr("keeping the existing registration"));let r=$e(t.profile)??$e(),n=Ln(await Zo({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??r?.hubUrl??Te,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=or(await Qo({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await lu(n,a),nr.success("account-issued registration token minted");else if(i==="login"){let p=await Qt();a=(await Zt(n,p)).cliToken,s=await lu(n,a),nr.success("account-issued registration token minted")}else s=Ln(await Kh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Lr("a registration token is required");let c=await Wh(n,a),l=Ln(await Zo({message:"worker name",initialValue:Gh(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=or(await Qo({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await wt({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),nr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!or(await au({message:"start the claim-loop now?",initialValue:!0}))){cu("registered. start later with `codepipe worker`.");return}cu("starting the claim-loop\u2026"),await Ir(t.profile?{profile:t.profile}:{})}function Yh(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return L("PROFILE")}var Q=Yh();Ri(Q);Ii();var pe=new qh;pe.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(me).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await su()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Rl({configPath:t.config,skipVerify:t.skipVerify===!0}):await gl({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Di({...t,profile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await hl({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});pe.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Xa({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await al({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Pl({profile:Q,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Mc({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Wl({profile:Q,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var pu=pe.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");pu.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??L("HUB_URL")??$e(Q)?.hubUrl??Te,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ei()){await ti({profile:Q});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await wt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...Q?{profile:Q}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ie(Q)&&ei()){await ti({profile:Q});return}await Ir(Q?{profile:Q}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var du=pe.command("project").description("Manage CodePipe projects");du.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ol({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});du.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await Ul({...t,cliProfile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ri=pe.command("repo").description("Manage the project's git repositories");ri.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Ml({profile:Q,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ri.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Fl({profile:Q,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ri.command("list").description("List the project's repos").action(async()=>{try{await Hl({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.parseAsync();
|