@runcanary/cli 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/canary.js +3 -3
  2. package/package.json +1 -1
package/dist/canary.js CHANGED
@@ -22,7 +22,7 @@ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
22
22
  `),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in f.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,f.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Wt(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(h=>h.negate&&a===h.attributeName()),u=this.options.find(h=>!h.negate&&a===h.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},i=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=Ne(e,i)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),t=Ne(e,i)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
23
23
  `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Lt(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=v.basename(e,v.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=i=>this._outputConfiguration.writeErr(i):n=i=>this._outputConfiguration.writeOut(i),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation(n);if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=f.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
24
24
  Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
25
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ie(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}Re.Command=le});var Te=S(b=>{var{Argument:je}=F(),{Command:ce}=Ve(),{CommanderError:qt,InvalidArgumentError:He}=V(),{Help:Dt}=ee(),{Option:Pe}=re();b.program=new ce;b.createCommand=r=>new ce(r);b.createOption=(r,e)=>new Pe(r,e);b.createArgument=(r,e)=>new je(r,e);b.Command=ce;b.Option=Pe;b.Argument=je;b.Help=Dt;b.CommanderError=qt;b.InvalidArgumentError=He;b.InvalidOptionArgumentError=He});var Fe=Nt(Te(),1),{program:di,createCommand:fi,createArgument:pi,createOption:mi,CommanderError:gi,InvalidArgumentError:yi,InvalidOptionArgumentError:_i,Command:Ue,Argument:bi,Option:wi,Help:Ci}=Fe.default;import{createHash as yn,randomBytes as Xe}from"node:crypto";import{spawn as _n}from"node:child_process";import{createServer as bn}from"node:http";import{existsSync as De,lstatSync as rn,mkdirSync as sn,readFileSync as on,writeFileSync as an}from"node:fs";import{homedir as fe}from"node:os";import{join as j}from"node:path";import{chmodSync as Bt,mkdirSync as Gt,readFileSync as Yt,renameSync as Kt,rmSync as zt,writeFileSync as Xt}from"node:fs";import{homedir as Qt}from"node:os";import{dirname as Zt,join as Je}from"node:path";var en="https://api.runcanary.ai",tn="https://app.runcanary.ai";function ue(){return process.env.CANARY_HOME||Je(Qt(),".canary")}function Le(){return Je(ue(),"config.json")}function m(){try{return JSON.parse(Yt(Le(),"utf8"))}catch{return{}}}function x(r){let e=Le();Gt(Zt(e),{recursive:!0,mode:448});let t=`${e}.${process.pid}.tmp`;try{Xt(t,JSON.stringify(r,null,2)+`
25
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ie(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}Re.Command=le});var Te=S(b=>{var{Argument:je}=F(),{Command:ce}=Ve(),{CommanderError:qt,InvalidArgumentError:He}=V(),{Help:Dt}=ee(),{Option:Pe}=re();b.program=new ce;b.createCommand=r=>new ce(r);b.createOption=(r,e)=>new Pe(r,e);b.createArgument=(r,e)=>new je(r,e);b.Command=ce;b.Option=Pe;b.Argument=je;b.Help=Dt;b.CommanderError=qt;b.InvalidArgumentError=He;b.InvalidOptionArgumentError=He});var Fe=Nt(Te(),1),{program:di,createCommand:fi,createArgument:pi,createOption:mi,CommanderError:gi,InvalidArgumentError:yi,InvalidOptionArgumentError:_i,Command:Ue,Argument:bi,Option:wi,Help:Ci}=Fe.default;import{createHash as yn,randomBytes as Xe}from"node:crypto";import{spawn as _n}from"node:child_process";import{createServer as bn}from"node:http";import{existsSync as De,lstatSync as rn,mkdirSync as sn,readFileSync as on,writeFileSync as an}from"node:fs";import{homedir as fe}from"node:os";import{join as j}from"node:path";import{chmodSync as Bt,mkdirSync as Gt,readFileSync as Yt,renameSync as Kt,rmSync as zt,writeFileSync as Xt}from"node:fs";import{homedir as Qt}from"node:os";import{dirname as Zt,join as Je}from"node:path";var en="https://api.runcanary.ai",tn="https://www.runcanary.ai";function ue(){return process.env.CANARY_HOME||Je(Qt(),".canary")}function Le(){return Je(ue(),"config.json")}function m(){try{return JSON.parse(Yt(Le(),"utf8"))}catch{return{}}}function x(r){let e=Le();Gt(Zt(e),{recursive:!0,mode:448});let t=`${e}.${process.pid}.tmp`;try{Xt(t,JSON.stringify(r,null,2)+`
26
26
  `,{mode:384}),Bt(t,384),Kt(t,e)}catch(n){throw zt(t,{force:!0}),n}}function he(r){let e={...m()};for(let[t,n]of Object.entries(r))n!==void 0&&(e[t]=n);x(e)}function Me(){let{apiUrl:r,webUrl:e}=m();x({...r?{apiUrl:r}:{},...e?{webUrl:e}:{}})}function k(){return process.env.CANARY_TOKEN||m().token}function U(){return process.env.CANARY_API_URL||m().apiUrl||en}function We(){return process.env.CANARY_WEB_URL||m().webUrl||tn}var de=`---
27
27
  name: canary
28
28
  description: >-
@@ -56,7 +56,7 @@ Rules that hold for every operation:
56
56
  If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then \`canary login\`, then start at step 1.
57
57
  Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
58
58
  you act on it.
59
- `;var ln="canary";function qe(r){try{return rn(r).isSymbolicLink()}catch{return!1}}function cn(){return[j(fe(),".claude"),j(fe(),".agents"),j(fe(),".codex")].filter(r=>De(r))}function J(){let r={installed:[],refreshed:[],current:[],skipped:[]};if(m().agentSkills===!1)return r;for(let e of cn()){let t=j(e,"skills",ln),n=j(t,"SKILL.md");try{if(qe(t)||qe(n)){r.skipped.push(n);continue}let i=De(n)?on(n,"utf8"):null;if(i===de){r.current.push(n);continue}sn(t,{recursive:!0}),an(n,de),(i===null?r.installed:r.refreshed).push(n)}catch{}}return r}var Be='Open your coding agent inside the repo you want to onboard and say: "Onboard this repo to Canary."';var g=class extends Error{constructor(t,n,i){super(n);this.status=t;this.fix=i;this.name="ApiError"}};async function y(r,e={}){let t=(e.baseUrl||U()).replace(/\/+$/,""),n={};e.token&&(n.authorization=`Bearer ${e.token}`),e.body!==void 0&&(n["content-type"]="application/json");let i;try{i=await fetch(t+r,{method:e.method??"GET",headers:n,body:e.body!==void 0?JSON.stringify(e.body):void 0})}catch(s){throw new g(0,`could not reach ${t} (${s instanceof Error?s.message:String(s)})`)}if(!i.ok){let s=i.statusText,o;try{let a=await i.json();s=a.error||a.message||s,typeof a.fix=="string"&&a.fix&&(o=a.fix)}catch{}throw new g(i.status,s,o)}return i.status===204?null:await i.json()}import{mkdirSync as un,readFileSync as hn,writeFileSync as dn}from"node:fs";import{homedir as fn}from"node:os";import{dirname as pn,join as Ge}from"node:path";var $="0.1.0",Ye="@runcanary/cli",mn=1440*60*1e3,pe=()=>Ge(process.env.CANARY_HOME||Ge(fn(),".canary"),"update-check.json");function Ke(){try{return JSON.parse(hn(pe(),"utf8"))}catch{return{}}}function gn(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i+=1){let s=(t[i]||0)-(n[i]||0);if(s!==0)return s>0}return!1}function ze(){if($==="0.0.0-dev")return;let{latest:r}=Ke();r&&gn(r,$)&&console.error(`A newer Canary CLI is available (${$} -> ${r}): npm install -g ${Ye}`)}function L(){if($==="0.0.0-dev")return;let r=Ke();r.checkedAt&&Date.now()-r.checkedAt<mn||(async()=>{let e=t=>{try{un(pn(pe()),{recursive:!0}),dn(pe(),JSON.stringify({checkedAt:Date.now(),latest:t??r.latest})+`
59
+ `;var ln="canary";function qe(r){try{return rn(r).isSymbolicLink()}catch{return!1}}function cn(){return[j(fe(),".claude"),j(fe(),".agents"),j(fe(),".codex")].filter(r=>De(r))}function J(){let r={installed:[],refreshed:[],current:[],skipped:[]};if(m().agentSkills===!1)return r;for(let e of cn()){let t=j(e,"skills",ln),n=j(t,"SKILL.md");try{if(qe(t)||qe(n)){r.skipped.push(n);continue}let i=De(n)?on(n,"utf8"):null;if(i===de){r.current.push(n);continue}sn(t,{recursive:!0}),an(n,de),(i===null?r.installed:r.refreshed).push(n)}catch{}}return r}var Be='Open your coding agent inside the repo you want to onboard and say: "Onboard this repo to Canary."';var g=class extends Error{constructor(t,n,i){super(n);this.status=t;this.fix=i;this.name="ApiError"}};async function y(r,e={}){let t=(e.baseUrl||U()).replace(/\/+$/,""),n={};e.token&&(n.authorization=`Bearer ${e.token}`),e.body!==void 0&&(n["content-type"]="application/json");let i;try{i=await fetch(t+r,{method:e.method??"GET",headers:n,body:e.body!==void 0?JSON.stringify(e.body):void 0})}catch(s){throw new g(0,`could not reach ${t} (${s instanceof Error?s.message:String(s)})`)}if(!i.ok){let s=i.statusText,o;try{let a=await i.json();s=a.error||a.message||s,typeof a.fix=="string"&&a.fix&&(o=a.fix)}catch{}throw new g(i.status,s,o)}return i.status===204?null:await i.json()}import{mkdirSync as un,readFileSync as hn,writeFileSync as dn}from"node:fs";import{homedir as fn}from"node:os";import{dirname as pn,join as Ge}from"node:path";var $="0.1.1",Ye="@runcanary/cli",mn=1440*60*1e3,pe=()=>Ge(process.env.CANARY_HOME||Ge(fn(),".canary"),"update-check.json");function Ke(){try{return JSON.parse(hn(pe(),"utf8"))}catch{return{}}}function gn(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i+=1){let s=(t[i]||0)-(n[i]||0);if(s!==0)return s>0}return!1}function ze(){if($==="0.0.0-dev")return;let{latest:r}=Ke();r&&gn(r,$)&&console.error(`A newer Canary CLI is available (${$} -> ${r}): npm install -g ${Ye}`)}function L(){if($==="0.0.0-dev")return;let r=Ke();r.checkedAt&&Date.now()-r.checkedAt<mn||(async()=>{let e=t=>{try{un(pn(pe()),{recursive:!0}),dn(pe(),JSON.stringify({checkedAt:Date.now(),latest:t??r.latest})+`
60
60
  `)}catch{}};try{let t=await fetch(`https://registry.npmjs.org/${Ye}/latest`,{signal:AbortSignal.timeout(1500)});if(!t.ok)return e();let{version:n}=await t.json();e(n||void 0)}catch{e()}})()}var wn=300*1e3,Qe=r=>r.toString("base64url");function Cn(r){let e=process.platform,[t,n]=e==="darwin"?["open",[r]]:e==="win32"?["explorer.exe",[r]]:["xdg-open",[r]];try{let i=_n(t,n,{stdio:"ignore",detached:!0});i.on("error",()=>{}),i.unref()}catch{}}function vn(r,e){return`<!doctype html><meta charset="utf-8"><title>${r}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${r}</h2><p style="color:#555">${e}</p></body>`}function kn(r){return new Promise((e,t)=>{let n,i,s=new Promise((c,u)=>{n=c,i=u}),o=bn((c,u)=>{let h=new URL(c.url??"/","http://127.0.0.1"),p=(C,I,kt)=>{u.writeHead(kt,{"content-type":"text/html",connection:"close"}),u.end(vn(C,I))};if(h.pathname!=="/callback"){u.writeHead(404,{connection:"close"}),u.end("not found");return}if(h.searchParams.get("state")!==r){p("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let w=h.searchParams.get("error");if(w){p("Authorization failed","You can close this tab and return to your terminal.",400),i(new Error(`authorization failed: ${w}`));return}let d=h.searchParams.get("code");if(!d){p("Authorization failed","No authorization code was returned. Please run canary login again.",400),i(new Error("callback returned no code"));return}p("You're all set","You can close this tab and return to your terminal.",200),n(d)}),a=setTimeout(()=>i(new Error("timed out waiting for browser authorization")),wn);a.unref?.();let l=()=>{clearTimeout(a),o.closeAllConnections?.(),o.close()};s.then(l,l),o.on("error",c=>{clearTimeout(a),t(c)}),o.listen(0,"127.0.0.1",()=>{e({port:o.address().port,code:s,close:l})})})}async function On(r,e){let t=Qe(Xe(32)),n=yn("sha256").update(t).digest("base64url"),i=Qe(Xe(16)),{port:s,code:o}=await kn(i),a=`http://127.0.0.1:${s}/callback`,c=`${(e.webUrl||We()).replace(/\/+$/,"")}/cli/authorize?challenge=${encodeURIComponent(n)}&state=${encodeURIComponent(i)}&redirect=${encodeURIComponent(a)}`;!e.open&&r?console.error(JSON.stringify({authorizeUrl:c})):r||(console.error(e.open?"Opening your browser to authorize the Canary CLI...":"Open this URL in your browser to authorize the Canary CLI:"),console.error((e.open?`If it doesn't open, visit:
61
61
  `:" ")+c+`
62
62
  `)),e.open&&Cn(c);let u=await o,h=await y("/api/v1/cli/auth/token",{method:"POST",body:{code:u,codeVerifier:t},baseUrl:e.apiUrl});he({token:h.token,user:h.user,team:h.team,apiUrl:e.apiUrl,webUrl:e.webUrl}),et(r,h.user.email,h.team)}async function Ze(r,e,t){let n=await y("/api/v1/cli/auth/whoami",{token:r,baseUrl:t});he({token:r,user:n.user,team:n.team,apiUrl:t}),et(e,n.user.email,n.team)}function et(r,e,t){console.log(r?JSON.stringify({ok:!0,user:{email:e},team:t}):`Logged in as ${e} (${t.name}).`)}function An(r){let e=J();if(r)return;let t=[...e.installed,...e.refreshed];t.length&&console.log(`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${t.join(", ")}).`),console.log(Be)}function tt(r){r.command("login").description("Authenticate the Canary CLI with your account").option("--json","output machine-readable JSON").option("--token <token>","log in with a token directly (CI / headless; else $CANARY_TOKEN)").option("--web-url <url>","override the authorization web URL").option("--api-url <url>","override the API base URL (moves with --web-url)").option("--no-open","print the authorization URL instead of opening a browser").option("--no-agent-skills","skip installing the Canary skill for your coding agents (written to ~/.claude, ~/.agents, ~/.codex when present)").action(async e=>{let t=e.json===!0;try{if(e.token!==void 0){let n=e.token.trim();if(!n)throw new Error("--token was provided but is empty");await Ze(n,t,e.apiUrl)}else{let n=(process.env.CANARY_TOKEN??"").trim();n?await Ze(n,t,e.apiUrl):await On(t,{webUrl:e.webUrl,apiUrl:e.apiUrl,open:e.open!==!1})}x({...m(),agentSkills:e.agentSkills!==!1}),e.agentSkills!==!1&&An(t),e.token===void 0&&!(process.env.CANARY_TOKEN??"").trim()&&L()}catch(n){let i=n instanceof g?`${n.message}`:n instanceof Error?n.message:String(n);t?console.log(JSON.stringify({ok:!1,error:i})):console.error(`Login failed: ${i}`),process.exitCode=1}})}function nt(r){r.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async e=>{let t=e.json===!0,n=k();if(n)try{await y("/api/v1/cli/auth/logout",{method:"POST",token:n})}catch{}Me();let i=!!process.env.CANARY_TOKEN;t?console.log(JSON.stringify({ok:!0,...i?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),i&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}import{readFileSync as jn,unlinkSync as Hn,writeFileSync as Pn}from"node:fs";import{join as Tn}from"node:path";import{execFileSync as Sn}from"node:child_process";import{existsSync as xn,mkdirSync as me,readFileSync as E,writeFileSync as M}from"node:fs";import{join as O}from"node:path";var _=class extends Error{constructor(t,n,i){super(n);this.code=t;this.fix=i;this.name="RecipeError"}};function N(r){return O(r,".canary")}function $n(r){let e=r.trim();if(!e)return null;if(!e.includes("://")){let t=e.match(/^[^@]+@([^:]+):(.+)$/);if(t){let n=t[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return n.length>=2?{host:t[1],owner:n[0],name:n.slice(1).join("/")}:null}}try{let t=new URL(e),n=t.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(n.length>=2)return{host:t.host,owner:n[0],name:n.slice(1).join("/")}}catch{}return null}function ge(r=process.cwd()){let e;try{e=Sn("git",["remote","get-url","origin"],{cwd:r,stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return null}return $n(e)}var En=new Set(["github.com","ssh.github.com"]);function ye(r){let e=r.host.toLowerCase().replace(/:\d+$/,"");if(!En.has(e))throw new _("unsupported_remote",`origin is on ${r.host}, but Canary connects GitHub repositories`,"run inside a checkout whose `origin` points at github.com")}function H(r){let e=N(r),t=O(e,".gitignore");try{let n=E(t,"utf8").split(`
@@ -81,4 +81,4 @@ Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}a
81
81
 
82
82
  ${r.body}${r.body.endsWith(`
83
83
  `)?"":`
84
- `}`,exit:0}}function Y(r){(r.stream==="stdout"?process.stdout:process.stderr).write(r.text),process.exit(r.exit)}function Oe(){return U().replace(/\/+$/,"")}function yt(r){r.command("skills").description("List the operations a coding agent can perform with Canary (hosted index)").option("--json","output machine-readable JSON").action(async e=>{let t=await mt({key:"index",url:`${Oe()}/llms.txt`,cliVersion:r.version()??"0.0.0",notFound:`this Canary server (${Oe()}) does not publish skills yet`});Y(G(t,!!e.json))}),r.command("skill <name>").description("Print the hosted instructions for one Canary operation").option("--json","output machine-readable JSON").action(async(e,t)=>{let n=!!t.json;Gn.test(e)||Y(G({ok:!1,error:`invalid operation name "${e.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},n));let i=r.version()??"0.0.0",s=await mt({key:e,url:`${Oe()}/skills/${e}.md`,cliVersion:i,notFound:`no such operation "${e}" \u2014 run \`canary skills\` to list the operations`});if(s.ok){let o=Zn(s.body);if(o&&Qn(i,o)<0){let a=`"${e}" needs Canary CLI ${o} or newer (you have ${i}). Update: ${Yn}`,l=G({ok:!1,error:a},n,{needsCli:o,cliVersion:i});Y({...l,exit:2})}}Y(G(s,n,{name:e}))})}function _t(r){r.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async e=>{let t=e.json===!0,n=k();if(!n){t?console.log(JSON.stringify({ok:!1,error:"not_logged_in"})):console.error("Not logged in. Run `canary login`."),process.exitCode=1;return}try{let i=await y("/api/v1/cli/auth/whoami",{token:n});console.log(t?JSON.stringify({ok:!0,user:i.user,team:i.team}):`${i.user.email} (${i.team.name})`)}catch(i){let s=i instanceof g&&i.status===401,o=s?"invalid_token":i instanceof Error?i.message:String(i);t?console.log(JSON.stringify({ok:!1,error:o})):console.error(s?"Your CLI session is no longer valid. Run `canary login`.":`Error: ${o}`),process.exitCode=1}})}async function Ct(){let r=k();if(!r)throw new g(401,"not logged in");let{workspaces:e}=await y("/api/v1/cli/workspaces",{token:r});return e}function P(r,e,t,n={}){r?console.log(JSON.stringify({ok:!1,error:e,message:t,...n})):console.error(t),process.exitCode=1}function bt(r,e){if(e instanceof g&&e.status===401){P(r,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}P(r,"workspace_error",e instanceof Error?e.message:String(e))}async function ti(r){let e=await Ct(),t=m().team?.id;if(r){console.log(JSON.stringify({workspaces:e,active:t??null}));return}if(e.length===0){console.error("You're not a member of any workspace yet. Set one up at app.runcanary.ai first.");return}let n=String(e.length).length;e.forEach((i,s)=>{let o=i.id===t?"*":" ",a=String(s+1).padStart(n," ");console.log(`${o} ${a} ${i.name}`)})}function wt(r,e){x({...m(),team:{id:r.id,name:r.name}}),console.log(e?JSON.stringify({ok:!0,workspace:{id:r.id,name:r.name}}):`Switched to ${r.name}.`)}async function ni(r,e){let t=await Ct(),n=r.trim();if(/^\d+$/.test(n)){let s=Number(n);if(s<1||s>t.length){P(e,"workspace_not_found",`No workspace #${s} \u2014 you have ${t.length}. Run: canary workspace list`,{available:t.map(o=>({id:o.id,name:o.name})),fix:"canary workspace list"});return}wt(t[s-1],e);return}let i=t.filter(s=>s.id===n||s.name.toLowerCase()===n.toLowerCase());if(i.length===0){P(e,"workspace_not_found",`No workspace matching "${r}".`,{available:t.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}if(i.length>1){P(e,"workspace_ambiguous",`"${r}" matches multiple workspaces \u2014 use the id.`,{matches:i.map(s=>({id:s.id,name:s.name})),fix:`canary workspace use ${i[0].id}`});return}wt(i[0],e)}function ii(r){let e=m().team;if(!e){r?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(r?JSON.stringify({workspace:e}):e.name)}function vt(r){let e=r.command("workspace").description("List and switch Canary workspaces");e.command("list").description("List the workspaces you belong to (the active one is marked with *)").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0;try{await ti(n)}catch(i){bt(n,i)}}),e.command("use <workspace>").description("Set the active workspace (by number from `list`, name, or id)").option("--json","output machine-readable JSON").action(async(t,n)=>{let i=n.json===!0;try{await ni(t,i)}catch(s){bt(i,s)}}),e.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(t=>ii(t.json===!0))}var A=new Ue;A.name("canary").description("Canary \u2014 break the code your AI writes.").version($);ze();tt(A);_t(A);nt(A);yt(A);vt(A);ht(A);A.parseAsync(process.argv).catch(r=>{console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)});
84
+ `}`,exit:0}}function Y(r){(r.stream==="stdout"?process.stdout:process.stderr).write(r.text),process.exit(r.exit)}function Oe(){return U().replace(/\/+$/,"")}function yt(r){r.command("skills").description("List the operations a coding agent can perform with Canary (hosted index)").option("--json","output machine-readable JSON").action(async e=>{let t=await mt({key:"index",url:`${Oe()}/llms.txt`,cliVersion:r.version()??"0.0.0",notFound:`this Canary server (${Oe()}) does not publish skills yet`});Y(G(t,!!e.json))}),r.command("skill <name>").description("Print the hosted instructions for one Canary operation").option("--json","output machine-readable JSON").action(async(e,t)=>{let n=!!t.json;Gn.test(e)||Y(G({ok:!1,error:`invalid operation name "${e.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},n));let i=r.version()??"0.0.0",s=await mt({key:e,url:`${Oe()}/skills/${e}.md`,cliVersion:i,notFound:`no such operation "${e}" \u2014 run \`canary skills\` to list the operations`});if(s.ok){let o=Zn(s.body);if(o&&Qn(i,o)<0){let a=`"${e}" needs Canary CLI ${o} or newer (you have ${i}). Update: ${Yn}`,l=G({ok:!1,error:a},n,{needsCli:o,cliVersion:i});Y({...l,exit:2})}}Y(G(s,n,{name:e}))})}function _t(r){r.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async e=>{let t=e.json===!0,n=k();if(!n){t?console.log(JSON.stringify({ok:!1,error:"not_logged_in"})):console.error("Not logged in. Run `canary login`."),process.exitCode=1;return}try{let i=await y("/api/v1/cli/auth/whoami",{token:n});console.log(t?JSON.stringify({ok:!0,user:i.user,team:i.team}):`${i.user.email} (${i.team.name})`)}catch(i){let s=i instanceof g&&i.status===401,o=s?"invalid_token":i instanceof Error?i.message:String(i);t?console.log(JSON.stringify({ok:!1,error:o})):console.error(s?"Your CLI session is no longer valid. Run `canary login`.":`Error: ${o}`),process.exitCode=1}})}async function Ct(){let r=k();if(!r)throw new g(401,"not logged in");let{workspaces:e}=await y("/api/v1/cli/workspaces",{token:r});return e}function P(r,e,t,n={}){r?console.log(JSON.stringify({ok:!1,error:e,message:t,...n})):console.error(t),process.exitCode=1}function bt(r,e){if(e instanceof g&&e.status===401){P(r,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}P(r,"workspace_error",e instanceof Error?e.message:String(e))}async function ti(r){let e=await Ct(),t=m().team?.id;if(r){console.log(JSON.stringify({workspaces:e,active:t??null}));return}if(e.length===0){console.error("You're not a member of any workspace yet. Set one up at www.runcanary.ai first.");return}let n=String(e.length).length;e.forEach((i,s)=>{let o=i.id===t?"*":" ",a=String(s+1).padStart(n," ");console.log(`${o} ${a} ${i.name}`)})}function wt(r,e){x({...m(),team:{id:r.id,name:r.name}}),console.log(e?JSON.stringify({ok:!0,workspace:{id:r.id,name:r.name}}):`Switched to ${r.name}.`)}async function ni(r,e){let t=await Ct(),n=r.trim();if(/^\d+$/.test(n)){let s=Number(n);if(s<1||s>t.length){P(e,"workspace_not_found",`No workspace #${s} \u2014 you have ${t.length}. Run: canary workspace list`,{available:t.map(o=>({id:o.id,name:o.name})),fix:"canary workspace list"});return}wt(t[s-1],e);return}let i=t.filter(s=>s.id===n||s.name.toLowerCase()===n.toLowerCase());if(i.length===0){P(e,"workspace_not_found",`No workspace matching "${r}".`,{available:t.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}if(i.length>1){P(e,"workspace_ambiguous",`"${r}" matches multiple workspaces \u2014 use the id.`,{matches:i.map(s=>({id:s.id,name:s.name})),fix:`canary workspace use ${i[0].id}`});return}wt(i[0],e)}function ii(r){let e=m().team;if(!e){r?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(r?JSON.stringify({workspace:e}):e.name)}function vt(r){let e=r.command("workspace").description("List and switch Canary workspaces");e.command("list").description("List the workspaces you belong to (the active one is marked with *)").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0;try{await ti(n)}catch(i){bt(n,i)}}),e.command("use <workspace>").description("Set the active workspace (by number from `list`, name, or id)").option("--json","output machine-readable JSON").action(async(t,n)=>{let i=n.json===!0;try{await ni(t,i)}catch(s){bt(i,s)}}),e.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(t=>ii(t.json===!0))}var A=new Ue;A.name("canary").description("Canary \u2014 break the code your AI writes.").version($);ze();tt(A);_t(A);nt(A);yt(A);vt(A);ht(A);A.parseAsync(process.argv).catch(r=>{console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runcanary/cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "private": false,
5
5
  "description": "Canary CLI — authenticate and onboard your repo to Canary from the terminal.",
6
6
  "license": "Apache-2.0",