@runcanary/cli 0.1.9 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -17
- package/dist/canary.js +97 -74
- package/package.json +1 -1
package/dist/canary.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __canaryCreateRequire } from 'node:module';
|
|
3
3
|
const require = __canaryCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${t.commandUsage(e)}`,""],
|
|
6
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i
|
|
4
|
+
var us=Object.create;var Gn=Object.defineProperty;var ds=Object.getOwnPropertyDescriptor;var ps=Object.getOwnPropertyNames;var fs=Object.getPrototypeOf,hs=Object.prototype.hasOwnProperty;var ze=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Re=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var gs=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ps(e))!hs.call(n,i)&&i!==t&&Gn(n,i,{get:()=>e[i],enumerable:!(r=ds(e,i))||r.enumerable});return n};var ms=(n,e,t)=>(t=n!=null?us(fs(n)):{},gs(e||!n||!n.__esModule?Gn(t,"default",{value:n,enumerable:!0}):t,n));var Ke=Re(Yt=>{var bt=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},qt=class extends bt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Yt.CommanderError=bt;Yt.InvalidArgumentError=qt});var St=Re(Kt=>{var{InvalidArgumentError:ys}=Ke(),zt=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new ys(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ws(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Kt.Argument=zt;Kt.humanReadableArgName=ws});var Qt=Re(Bn=>{var{humanReadableArgName:bs}=St(),Xt=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(i=>!i._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((i,s)=>i.name().localeCompare(s.name())),t}compareOptions(e,t){let r=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),r=e._getHelpOption();if(r&&!r.hidden){let i=r.short&&e._findOption(r.short),s=r.long&&e._findOption(r.long);!i&&!s?t.push(r):r.long&&!s?t.push(e.createOption(r.long,r.description)):r.short&&!i&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let i=r.options.filter(s=>!s.hidden);t.push(...i)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>bs(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,i)=>Math.max(r,t.subcommandTerm(i).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,i)=>Math.max(r,t.optionTerm(i).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,i)=>Math.max(r,t.optionTerm(i).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,i)=>Math.max(r,t.argumentTerm(i).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let i=e.parent;i;i=i.parent)r=i.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),i=t.helpWidth||80,s=2,o=2;function a(p,g){if(g){let y=`${p.padEnd(r+o)}${g}`;return t.wrap(y,i-s,r+o)}return p}function c(p){return p.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,i,0),""]));let u=t.visibleArguments(e).map(p=>a(t.argumentTerm(p),t.argumentDescription(p)));u.length>0&&(l=l.concat(["Arguments:",c(u),""]));let h=t.visibleOptions(e).map(p=>a(t.optionTerm(p),t.optionDescription(p)));if(h.length>0&&(l=l.concat(["Options:",c(h),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));p.length>0&&(l=l.concat(["Global Options:",c(p),""]))}let f=t.visibleCommands(e).map(p=>a(t.subcommandTerm(p),t.subcommandDescription(p)));return f.length>0&&(l=l.concat(["Commands:",c(f),""])),l.join(`
|
|
6
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,i=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${s}]+`);if(e.match(o))return e;let a=t-r;if(a<i)return e;let c=e.slice(0,r),l=e.slice(r).replace(`\r
|
|
7
7
|
`,`
|
|
8
|
-
`),
|
|
9
|
-
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),
|
|
10
|
-
`?"":(
|
|
11
|
-
`)}};
|
|
12
|
-
(Did you mean one of ${
|
|
13
|
-
(Did you mean ${
|
|
14
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
15
|
-
Expecting one of '${
|
|
16
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=
|
|
8
|
+
`),d=" ".repeat(r),h="\\s\u200B",f=new RegExp(`
|
|
9
|
+
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=l.match(f)||[];return c+p.map((g,y)=>g===`
|
|
10
|
+
`?"":(y>0?d:"")+g.trimEnd()).join(`
|
|
11
|
+
`)}};Bn.Help=Xt});var nn=Re(tn=>{var{InvalidArgumentError:Ss}=Ke(),Zt=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=_s(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Ss(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ks(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},en=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let i=this.negativeOptions.get(r).presetArg,s=i!==void 0?i:!1;return t.negate===(s===e)}};function ks(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function _s(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}tn.Option=Zt;tn.DualOptions=en});var Wn=Re(Vn=>{function vs(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let i=1;i<=n.length;i++){let s=1;n[i-1]===e[r-1]?s=0:s=1,t[i][r]=Math.min(t[i-1][r]+1,t[i][r-1]+1,t[i-1][r-1]+s),i>1&&r>1&&n[i-1]===e[r-2]&&n[i-2]===e[r-1]&&(t[i][r]=Math.min(t[i][r],t[i-2][r-2]+1))}return t[n.length][e.length]}function xs(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let r=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=vs(n,o),c=Math.max(n.length,o.length);(c-a)/c>s&&(a<i?(i=a,r=[o]):a===i&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),t&&(r=r.map(o=>`--${o}`)),r.length>1?`
|
|
12
|
+
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
13
|
+
(Did you mean ${r[0]}?)`:""}Vn.suggestSimilar=xs});var Kn=Re(zn=>{var Cs=ze("node:events").EventEmitter,rn=ze("node:child_process"),pe=ze("node:path"),sn=ze("node:fs"),M=ze("node:process"),{Argument:Is,humanReadableArgName:Rs}=St(),{CommanderError:on}=Ke(),{Help:$s}=Qt(),{Option:Jn,DualOptions:Os}=nn(),{suggestSimilar:qn}=Wn(),an=class n extends Cs{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>M.stdout.write(t),writeErr:t=>M.stderr.write(t),getOutHelpWidth:()=>M.stdout.isTTY?M.stdout.columns:void 0,getErrHelpWidth:()=>M.stderr.isTTY?M.stderr.columns:void 0,outputError:(t,r)=>r(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let i=t,s=r;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new n(e)}createHelp(){return Object.assign(new $s,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Is(e,t)}argument(e,t,r,i){let s=this.createArgument(e,t);return typeof r=="function"?s.default(i).argParser(r):s.default(r),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,i]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(r);return o.helpOption(!1),i&&o.arguments(i),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
15
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new on(e,t,r)),M.exit(e)}action(e){let t=r=>{let i=this.registeredArguments.length,s=r.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new Jn(e,t)}_callParseArg(e,t,r,i){try{return e.parseArg(t,r)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
16
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),r=t(e).find(i=>this._findCommand(i));if(r){let i=t(this._findCommand(r)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(r);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,o):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(r,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,t,r,i,s){if(typeof t=="object"&&t instanceof Jn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,l)=>{let d=a.exec(c);return d?d[0]:l},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,r,i){return this._optionEx({},e,t,r,i)}requiredOption(e,t,r,i){return this._optionEx({mandatory:!0},e,t,r,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){M.versions?.electron&&(t.from="electron");let i=M.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=M.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":M.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(d,u){let h=pe.resolve(d,u);if(sn.existsSync(h))return h;if(i.includes(pe.extname(u)))return;let f=i.find(p=>sn.existsSync(`${h}${p}`));if(f)return`${h}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=sn.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=pe.resolve(pe.dirname(d),a)}if(a){let d=s(a,o);if(!d&&!e._executableFile&&this._scriptPath){let u=pe.basename(this._scriptPath,pe.extname(this._scriptPath));u!==this._name&&(d=s(a,`${u}-${e._name}`))}o=d||o}r=i.includes(pe.extname(o));let c;M.platform!=="win32"?r?(t.unshift(o),t=Yn(M.execArgv).concat(t),c=rn.spawn(M.argv[0],t,{stdio:"inherit"})):c=rn.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Yn(M.execArgv).concat(t),c=rn.spawn(M.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{M.on(u,()=>{c.killed===!1&&c.exitCode===null&&c.kill(u)})});let l=this._exitCallback;c.on("close",d=>{d=d??1,l?l(new on(d,"commander.executeSubCommandAsync","(close)")):M.exit(d)}),c.on("error",d=>{if(d.code==="ENOENT"){let u=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
|
|
17
17
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
18
18
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
19
|
-
- ${
|
|
19
|
+
- ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)M.exit(1);else{let u=new on(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=c}_dispatchSubcommand(e,t,r){let i=this._findCommand(e);i||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(r));else return i._parseCommand(t,r)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,i,s)=>{let o=i;if(i!==null&&r.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,i,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,i)=>{let s=r.defaultValue;r.variadic?i<this.args.length?(s=this.args.slice(i),r.parseArg&&(s=s.reduce((o,a)=>e(r,a,o),r.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],r.parseArg&&(s=e(r,s,r.defaultValue))),t[i]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),t==="postAction"&&i.reverse(),i.forEach(s=>{r=this._chainOrCall(r,()=>s.callback(s.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let i=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(s=>{i=this._chainOrCall(i,()=>s(this,t))}),i}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let i=r.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let i=e.find(s=>r.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(r,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],i=t,s=e.slice();function o(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){i===r&&i.push(c),i.push(...s);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let l=this._findOption(c);if(l){if(l.required){let d=s.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;s.length>0&&!o(s[0])&&(d=s.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),d=this._findOption(c.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,c.slice(l+1));continue}}if(o(c)&&(i=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(c)){t.push(c),s.length>0&&r.push(...s);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){r.push(c),s.length>0&&r.push(...s);break}}if(this._passThroughOptions){i.push(c),s.length>0&&i.push(...s);break}i.push(c)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let i=this.options[r].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
20
20
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
21
21
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
22
|
-
`),this.outputHelp({error:!0}));let
|
|
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
|
|
24
|
-
Expecting one of '${
|
|
25
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(
|
|
26
|
-
`,{mode:384}),
|
|
22
|
+
`),this.outputHelp({error:!0}));let r=t||{},i=r.exitCode||1,s=r.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in M.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()}`,M.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Os(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,r.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 r=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(u=>u.negate&&a===u.attributeName()),d=this.options.find(u=>!u.negate&&a===u.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:d||o},i=o=>{let a=r(o),c=a.attributeName();return this.getOptionValueSource(c)==="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=qn(e,i)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} 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=qn(e,i)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let i=this.createOption(t,r);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
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 r=this.parent?._findCommand(e);if(r){let i=[r.name()].concat(r.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(r=>Rs(r));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=pe.basename(e,pe.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},r;return t.error?r=i=>this._outputConfiguration.writeErr(i):r=i=>this._outputConfiguration.writeOut(i),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let i=this.helpInformation(r);if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}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=M.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
24
|
+
Expecting one of '${r.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 Yn(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="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]:r=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],r=s[3],i=s[4]),t&&i!=="0"?`${t}=${r}:${parseInt(i)+1}`:e})}zn.Command=an});var er=Re(X=>{var{Argument:Xn}=St(),{Command:cn}=Kn(),{CommanderError:As,InvalidArgumentError:Qn}=Ke(),{Help:Es}=Qt(),{Option:Zn}=nn();X.program=new cn;X.createCommand=n=>new cn(n);X.createOption=(n,e)=>new Zn(n,e);X.createArgument=(n,e)=>new Xn(n,e);X.Command=cn;X.Option=Zn;X.Argument=Xn;X.Help=Es;X.CommanderError=As;X.InvalidArgumentError=Qn;X.InvalidOptionArgumentError=Qn});var tr=ms(er(),1),{program:Kc,createCommand:Xc,createArgument:Qc,createOption:Zc,CommanderError:el,InvalidArgumentError:tl,InvalidOptionArgumentError:nl,Command:nr,Argument:rl,Option:il,Help:sl}=tr.default;import{createHash as Wo,randomBytes as qr}from"node:crypto";import{spawn as Jo}from"node:child_process";import{createServer as qo}from"node:http";import{existsSync as pn,lstatSync as Ws,mkdirSync as Js,readFileSync as lr,rmSync as qs,rmdirSync as Ys,writeFileSync as zs}from"node:fs";import{homedir as dn}from"node:os";import{join as Oe}from"node:path";import{randomUUID as Ts}from"node:crypto";import{chmodSync as Ns,mkdirSync as Ps,readFileSync as Ls,renameSync as Ms,rmSync as js,writeFileSync as Fs}from"node:fs";import{homedir as Us}from"node:os";import{dirname as Hs,join as rr}from"node:path";var Ds="https://api.runcanary.ai",Gs="https://www.runcanary.ai";function Le(){return process.env.CANARY_HOME||rr(Us(),".canary")}function ir(){return rr(Le(),"config.json")}var Bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ln=null;function sr(){let{config:n,unreadable:e}=kt();if(n.installId&&Bs.test(n.installId))return n.installId;if(ln??=Ts(),!e)try{fe({...n,installId:ln})}catch{}return ln}function P(){return kt().config}function or(n){return P().repoFingerprints?.[n]}function ar(n,e){let{config:t,unreadable:r}=kt();if(!r)try{fe({...t,repoFingerprints:{...t.repoFingerprints,[n]:e}})}catch{}}function kt(){let n;try{n=Ls(ir(),"utf8")}catch(e){return{config:{},unreadable:e.code!=="ENOENT"}}try{let e=JSON.parse(n);return!e||typeof e!="object"||Array.isArray(e)?{config:{},unreadable:!0}:{config:e,unreadable:!1}}catch{return{config:{},unreadable:!0}}}function fe(n){let e=ir();Ps(Hs(e),{recursive:!0,mode:448});let t=`${e}.${process.pid}.tmp`;try{Fs(t,JSON.stringify(n,null,2)+`
|
|
26
|
+
`,{mode:384}),Ns(t,384),Ms(t,e)}catch(r){throw js(t,{force:!0}),r}}function cr(){let{config:n,unreadable:e}=kt();if(e)return;let{apiUrl:t,webUrl:r,installId:i,agentSkills:s,repoFingerprints:o}=n;fe({...t?{apiUrl:t}:{},...r?{webUrl:r}:{},...i?{installId:i}:{},...s!==void 0?{agentSkills:s}:{},...o?{repoFingerprints:o}:{}})}function V(){return process.env.CANARY_TOKEN||P().token}function W(){return process.env.CANARY_API_URL||P().apiUrl||Ds}function $e(){let n=process.env.CANARY_WEB_URL||P().webUrl;if(n)return n;let e=process.env.CANARY_API_URL||P().apiUrl;return e?e.replace("//api.","//www."):Gs}var Me="Onboard this repository to Canary.",_t="Verify my changes with Canary.";var un=`---
|
|
27
27
|
name: canary
|
|
28
28
|
description: >-
|
|
29
29
|
Use whenever you finish a code change and are about to report it done, or whenever a change
|
|
@@ -62,78 +62,101 @@ If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then start at step
|
|
|
62
62
|
"Getting started" section covers logging in.
|
|
63
63
|
Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
|
|
64
64
|
you act on it.
|
|
65
|
-
`;var
|
|
66
|
-
`)}catch{}};try{let t=await fetch(`https://registry.npmjs.org/${
|
|
67
|
-
`);if(!t)return{};let s={worktreeId:
|
|
68
|
-
`).filter(Boolean).sort()[0]:void 0;
|
|
69
|
-
`).map(
|
|
70
|
-
`)&&(
|
|
71
|
-
`)}catch{}
|
|
72
|
-
`)}catch{}}function
|
|
73
|
-
`),
|
|
74
|
-
`}catch{}
|
|
65
|
+
`;var Ks="canary",Xs="canary-setup";function Qs(n){let e=Oe(n,"skills",Xs),t=Oe(e,"SKILL.md");if(vt(e)||vt(t)||!pn(t))return;let r;try{r=lr(t,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{qs(t,{force:!1})}catch{return}try{Ys(e)}catch{}}}function vt(n){try{return Ws(n).isSymbolicLink()}catch{return!1}}function Zs(){return[Oe(dn(),".claude"),Oe(dn(),".agents"),Oe(dn(),".codex")].filter(n=>pn(n))}function xt(){let n={installed:[],refreshed:[],current:[],skipped:[]};if(P().agentSkills===!1)return n;for(let e of Zs()){Qs(e);let t=Oe(e,"skills",Ks),r=Oe(t,"SKILL.md");try{if(vt(t)||vt(r)){n.skipped.push(r);continue}let i=pn(r)?lr(r,"utf8"):null;if(i===un){n.current.push(r);continue}Js(t,{recursive:!0}),zs(r,un),(i===null?n.installed:n.refreshed).push(r)}catch{}}return n}var ur=`Open your coding agent inside the repo you want to onboard and say: "${Me}"`;import{createHash as ao}from"node:crypto";import{execFileSync as co,spawn as lo}from"node:child_process";import{mkdirSync as eo,readFileSync as to,writeFileSync as no}from"node:fs";import{homedir as ro}from"node:os";import{dirname as io,join as dr}from"node:path";var Se="0.1.10",pr="@runcanary/cli",so=1440*60*1e3,fn=()=>dr(process.env.CANARY_HOME||dr(ro(),".canary"),"update-check.json");function fr(){try{return JSON.parse(to(fn(),"utf8"))}catch{return{}}}function oo(n,e){let t=n.split(".").map(Number),r=e.split(".").map(Number);for(let i=0;i<3;i+=1){let s=(t[i]||0)-(r[i]||0);if(s!==0)return s>0}return!1}function hr(){if(Se==="0.0.0-dev")return;let{latest:n}=fr();n&&oo(n,Se)&&console.error(`A newer Canary CLI is available (${Se} -> ${n}): npm install -g ${pr}`)}function je(){if(Se==="0.0.0-dev")return;let n=fr();n.checkedAt&&Date.now()-n.checkedAt<so||(async()=>{let e=t=>{try{eo(io(fn()),{recursive:!0}),no(fn(),JSON.stringify({checkedAt:Date.now(),latest:t??n.latest})+`
|
|
66
|
+
`)}catch{}};try{let t=await fetch(`https://registry.npmjs.org/${pr}/latest`,{signal:AbortSignal.timeout(1500)});if(!t.ok)return e();let{version:r}=await t.json();e(r||void 0)}catch{e()}})()}var J={cli:"x-canary-cli",command:"x-canary-command",install:"x-canary-install",worktree:"x-canary-worktree",repo:"x-canary-repo",branch:"x-canary-branch",harness:"x-canary-harness",chat:"x-canary-chat",agent:"x-canary-agent",mode:"x-canary-mode"},Ae={},Xe=null;function Ct(n){Ae={...Ae,...n},Xe=null}function uo(n=process.env){if(n.CLAUDECODE==="1"||n.CLAUDE_CODE_SESSION_ID){let e=n.CLAUDE_CODE_SESSION_ID??n.CLAUDE_CODE_HOST_SESSION_ID;return{harness:"claude-code",...e?{chatId:e}:{}}}return n.CODEX_SANDBOX||n.CODEX_SANDBOX_NETWORK_DISABLED==="1"?{harness:"codex"}:n.CURSOR_AGENT==="1"?{harness:"cursor"}:{harness:"unknown"}}function po(n,e){return ao("sha256").update(`${e}\0${n}`).digest("hex").slice(0,24)}function yr(){return{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(n))),GIT_OPTIONAL_LOCKS:"0",GIT_NO_LAZY_FETCH:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_TERMINAL_PROMPT:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"}}function gr(n,e){try{let t=yr();return co("git",n,{cwd:e,env:t,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function fo(n,e){let[t,r,i]=(gr(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],n)??"").split(`
|
|
67
|
+
`);if(!t)return{};let s={worktreeId:po(t,e)};if(i!=="true"){let o=or(s.worktreeId);o&&gr(["cat-file","-e",`${o}^{commit}`],t)!==null?s.repoFingerprint=o:ho(t,s.worktreeId)}return s.branch=r&&r!=="HEAD"?r:"HEAD",s}var mr=new Map;function ho(n,e){mr.has(e)||mr.set(e,new Promise(t=>{try{let r=yr(),i=lo("git",["rev-list","--max-parents=0","HEAD"],{cwd:n,env:r,stdio:["ignore","pipe","ignore"],timeout:6e4}),s="";i.stdout.on("data",o=>{s+=o.toString("utf8")}),i.on("error",()=>t()),i.on("close",o=>{let a=o===0?s.trim().split(`
|
|
68
|
+
`).filter(Boolean).sort()[0]:void 0;a&&ar(e,a),t()}),i.unref(),i.stdout.unref?.()}catch{t()}}))}function go(){if(Xe)return Xe;let n=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",{harness:e,chatId:t}=uo(),r="",i={};try{r=sr(),i=fo(Ae.cwd??process.cwd(),r)}catch{}return Xe={cliVersion:Se,command:n,installId:r,...i,harness:e,...t?{chatId:t}:{},...Ae.agent!==void 0?{agent:Ae.agent}:{},...Ae.mode?{mode:Ae.mode}:{}},Xe}function ke(){let n=go(),e=r=>r.replace(/[^\x20-\x7e]/g,"?").slice(0,200),t={[J.cli]:n.cliVersion,[J.harness]:n.harness};return n.installId&&(t[J.install]=n.installId),n.command&&(t[J.command]=e(n.command)),n.worktreeId&&(t[J.worktree]=n.worktreeId),n.repoFingerprint&&(t[J.repo]=n.repoFingerprint),n.branch&&(t[J.branch]=e(n.branch)),n.chatId&&(t[J.chat]=e(n.chatId)),n.agent!==void 0&&(t[J.agent]=n.agent?"1":"0"),n.mode&&(t[J.mode]=n.mode),t}var O=class extends Error{constructor(t,r,i,s){super(r);this.status=t;this.fix=i;this.runId=s;this.name="ApiError"}},ie=n=>n instanceof O&&(n.status===0||n.status===408||n.status===429||n.status===502||n.status===503||n.status===504);async function I(n,e={}){let t=(e.baseUrl||W()).replace(/\/+$/,""),r=ke();e.token&&(r.authorization=`Bearer ${e.token}`),e.body!==void 0&&(r["content-type"]="application/json");let i;try{i=await fetch(t+n,{method:e.method??"GET",headers:r,body:e.body!==void 0?JSON.stringify(e.body):void 0,signal:e.signal})}catch(s){throw new O(0,`could not reach ${t} (${s instanceof Error?s.message:String(s)})`)}if(!i.ok){let s=i.statusText,o,a;try{let c=await i.json();s=c.error||c.message||s,typeof c.fix=="string"&&c.fix&&(o=c.fix),typeof c.runId=="string"&&c.runId&&(a=c.runId)}catch{}throw new O(i.status,s,o,a)}return i.status===204?null:await i.json()}import{execFileSync as _o}from"node:child_process";import{createHash as vo,randomUUID as wn}from"node:crypto";import{linkSync as xo,lstatSync as Co,mkdirSync as bn,readFileSync as Io,realpathSync as Rt,renameSync as Ro,rmSync as $o,writeFileSync as Rr}from"node:fs";import{basename as Sn,dirname as $r,isAbsolute as Oo,join as ge,relative as Ao,resolve as Or,sep as Eo}from"node:path";import{createHash as mo}from"node:crypto";import{existsSync as yo,mkdirSync as hn,readFileSync as Fe,writeFileSync as It}from"node:fs";import{join as he}from"node:path";var z=class extends Error{constructor(t,r,i){super(r);this.code=t;this.fix=i;this.name="RecipeError"}};function Ue(n){return he(n,".canary")}function Sr(n){let e=n.trim();if(!e)return null;if(!e.includes("://")){let t=e.match(/^[^@]+@([^:]+):(.+)$/);if(t){let r=t[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return r.length>=2?{host:t[1],owner:r[0],name:r.slice(1).join("/")}:null}}try{let t=new URL(e),r=t.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(r.length>=2)return{host:t.host,owner:r[0],name:r.slice(1).join("/")}}catch{}return null}var kr=new Set(["github.com","ssh.github.com"]);function Qe(n){let e=Ue(n),t=he(e,".gitignore");try{let r=Fe(t,"utf8").split(`
|
|
69
|
+
`).map(i=>i.trim()).filter(i=>i.length>0);if(r[r.length-1]==="*")return}catch{}try{hn(e,{recursive:!0});let r="";try{r=Fe(t,"utf8"),r&&!r.endsWith(`
|
|
70
|
+
`)&&(r+=`
|
|
71
|
+
`)}catch{}It(t,`${r}*
|
|
72
|
+
`)}catch{}}function _e(n){let e=Ue(n),t;try{t=Fe(he(e,"setup.sh"),"utf8")}catch{throw new z("recipe_missing","No .canary/setup.sh found. Produce the recipe first (run the Canary setup skill in your coding agent).","canary setup skill")}if(!t.trim())throw new z("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(Fe(he(e,"run.json"),"utf8"))}catch(a){throw new z("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let i=[],s={},o=he(e,"env.json");if(yo(o)){let a;try{a=JSON.parse(Fe(o,"utf8"))}catch(l){throw new z("recipe_invalid",`Cannot read .canary/env.json: ${l instanceof Error?l.message:String(l)}`)}if(a===null||typeof a!="object"||Array.isArray(a))throw new z("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let c=a;i=_r(c.manifest),s=vr(c.values),bo(i)}return{setupSh:t,runJson:r,envManifest:i,envValues:s}}function Ee(n){return mo("sha256").update(JSON.stringify([n.setupSh,n.runJson,n.envManifest,n.envValues])).digest("hex")}function gn(n,e){let t=n.filter(r=>r.neededAt==="boot").map(r=>r.name).filter(r=>!Object.prototype.hasOwnProperty.call(e,r)||e[r]==="");return{missing:[...new Set(t)]}}function _r(n){return Array.isArray(n)?n.filter(e=>!!e&&typeof e=="object"&&typeof e.name=="string"):[]}var wr=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),wo=new Set(["boot","runtime"]);function bo(n){for(let e of n){if(!wr.has(String(e.class)))throw new z("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has unknown class "${String(e.class)}"`,`use one of: ${[...wr].join(", ")}`);if(!wo.has(String(e.neededAt)))throw new z("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has invalid neededAt "${String(e.neededAt)}"`,'use "boot" or "runtime"')}}function vr(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function So(n){try{let e=JSON.parse(Fe(he(Ue(n),"env.json"),"utf8"));return{manifest:_r(e.manifest),values:vr(e.values)}}catch{return{manifest:[],values:{}}}}function ko(n,e){hn(Ue(n),{recursive:!0}),It(he(Ue(n),"env.json"),JSON.stringify(e,null,2)+`
|
|
73
|
+
`),Qe(n)}var br=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"]);function mn(n,e){if(e.length===0)return;let t=So(n),r=new Map(t.manifest.map(i=>[i.name,i]));for(let i of e){t.values[i.name]=i.value;let s=r.get(i.name);if(s)i.class&&br.has(i.class)&&!br.has(s.class??"")&&(s.class=i.class,s.neededAt="boot");else{let o={name:i.name,class:i.class??"config",neededAt:"boot",why:i.why??"added during cloud verification"};r.set(i.name,o),t.manifest.push(o)}}ko(n,t)}function xr(n,e){let t=[],r=Ue(n);if(hn(r,{recursive:!0}),typeof e.setupSh=="string"&&e.setupSh.trim()&&(It(he(r,"setup.sh"),e.setupSh),t.push(".canary/setup.sh")),typeof e.runJson=="string"&&e.runJson.trim()){let s=e.runJson;try{s=JSON.stringify(JSON.parse(e.runJson),null,2)+`
|
|
74
|
+
`}catch{}It(he(r,"run.json"),s),t.push(".canary/run.json")}let i=Object.entries(e.envOverrides??{});return i.length>0&&(mn(n,i.map(([s,o])=>({name:s,value:o,why:"authored by the cloud verifier while fixing the boot"}))),t.push(".canary/env.json")),Qe(n),t}var Ze=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,$t=2,Cr=/^[A-Za-z0-9_.-]+$/,E=class extends Error{constructor(t,r){super(r);this.code=t;this.name="LocalRepositoryError"}};function To(n){let e=Sr(n);if(!(!e||!kr.has(e.host.toLowerCase().replace(/:\d+$/,"")))&&!(!Cr.test(e.owner)||!Cr.test(e.name)))return`${e.owner}/${e.name}`}function tt(n=process.cwd()){let e={...Object.fromEntries(Object.entries(process.env).filter(([a])=>!a.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(a))),GIT_OPTIONAL_LOCKS:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"},t=a=>_o("git",a,{cwd:n,env:e,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").replace(/\r?\n$/,""),r,i;try{r=Rt(t(["rev-parse","--show-toplevel"])),i=Rt(Or(Rt(n),t(["rev-parse","--git-common-dir"])))}catch{throw new E("not_a_git_repository","Run this command inside the Git repository you want Canary to use.")}let s;try{s=To(t(["remote","get-url","origin"]))}catch{}if(s)return{root:r,commonDirectory:i,name:s,githubFullName:s};let o=Sn(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:i,name:o}}function No(n){let e;try{e=new URL(n)}catch{throw new E("invalid_api_url","The Canary API URL is invalid.")}if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new E("invalid_api_url","The Canary API URL must be HTTP(S) without credentials, a query, or a fragment.");return e.href.replace(/\/+$/,"")}function kn(n){try{return Rt(n)}catch(e){if(e.code!=="ENOENT")throw e;if(Co(n,{throwIfNoEntry:!1})?.isSymbolicLink())throw new E("cache_path_unresolvable","A symlink under CANARY_HOME/local-repositories points at a missing target. Remove or fix that link, then run the command again.");let t=$r(n);if(t===n)throw e;return ge(kn(t),Sn(n))}}function yn(n,e){let t=Ao(n,e);return t===""||!Oo(t)&&t!==".."&&!t.startsWith(`..${Eo}`)}function _n(n,e){let t=kn(e);if(!yn(n,t))throw new E("cache_outside_home","Something under CANARY_HOME/local-repositories links outside CANARY_HOME. Remove that link, then run the command again.");return t}function nt(n){if(!Ze.test(n.userId)||!Ze.test(n.workspaceId))throw new E("invalid_account_context","Sign in with canary login and select a workspace with canary workspace use <id>, then run the command again.");let e=tt(n.directory),t=No(n.apiUrl),r=kn(Or(Le())),i=Sn(e.commonDirectory)===".git"?$r(e.commonDirectory):e.commonDirectory,s=vo("sha256").update(JSON.stringify([$t,t,n.userId,n.workspaceId,e.githubFullName?`github:${e.githubFullName.toLowerCase()}`:e.commonDirectory])).digest("hex"),o=ge(r,"local-repositories"),a=_n(o,ge(o,s));if([e.root,e.commonDirectory,i].some(c=>yn(c,r)||yn(c,a)))throw new E("cache_inside_checkout","CANARY_HOME is inside this repository. Point it at a directory outside the checkout, then run the command again.");return{...e,apiUrl:t,scope:s,cacheRoot:o,cacheDirectory:a}}function Ir(n,e){let t=_n(n.cacheRoot,ge(n.cacheDirectory,e)),r;try{r=Io(t,"utf8")}catch(o){if(o.code==="ENOENT")return null;throw new E("binding_unreadable","Could not read Canary's saved record for this repository under CANARY_HOME/local-repositories. Check its permissions, then run the command again.")}let i;try{i=JSON.parse(r)}catch{}let s=e==="identity.json"?["version","scope","localKey"]:["version","scope","localKey","repositoryId"];if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(o=>!s.includes(o))||i.version!==$t||i.scope!==n.scope||typeof i.localKey!="string"||!Ze.test(i.localKey)||e==="repository.json"&&(typeof i.repositoryId!="string"||!Ze.test(i.repositoryId)))throw new E("invalid_binding","Canary's saved record for this repository under CANARY_HOME/local-repositories is damaged. Canary left it in place: restore it, or remove it to register this repository as new.");return i}function et(n){let e=Ir(n,"identity.json"),t=Ir(n,"repository.json");if(!e&&!t)return null;if(!e||t&&t.localKey!==e.localKey)throw new E("invalid_binding","Canary's saved records for this repository under CANARY_HOME/local-repositories disagree with each other. Canary left them in place: restore them, or remove them to register this repository as new.");return{localKey:e.localKey,...t?{repositoryId:t.repositoryId}:{}}}function Ar(n,e,t){bn(n.cacheDirectory,{recursive:!0,mode:448});let r=ge(n.cacheDirectory,`${e}.${wn()}.tmp`);try{Rr(r,JSON.stringify({version:$t,scope:n.scope,...t})+`
|
|
75
|
+
`,{flag:"wx",mode:384});try{xo(r,ge(n.cacheDirectory,e))}catch(i){if(i.code!=="EEXIST")throw i}}finally{$o(r,{force:!0})}}function Er(n,e){bn(n.cacheDirectory,{recursive:!0,mode:448});let t=ge(n.cacheDirectory,`repository.json.${wn()}.tmp`);Rr(t,JSON.stringify({version:$t,scope:n.scope,...e})+`
|
|
76
|
+
`,{flag:"wx",mode:384}),Ro(t,ge(n.cacheDirectory,"repository.json"))}function Tr(n){return et(nt(n))}function Nr(n,e){let t=nt(n),r=et(t);!r?.repositoryId||r.repositoryId===e||Er(t,{localKey:r.localKey,repositoryId:e})}function Pr(n,e){if(!/^[a-z0-9-]+\.json$/.test(e))throw new E("invalid_receipt_name","Invalid cache file name.");let t=nt(n);return bn(t.cacheDirectory,{recursive:!0,mode:448}),_n(t.cacheRoot,ge(t.cacheDirectory,e))}function Po(n){let e=nt(n),t=et(e);return t||(Ar(e,"identity.json",{localKey:wn()}),et(e))}function Lo(n,e,t,r){let i=n,s=t.githubFullName?"github":"local";if(!i||typeof i.repositoryId!="string"||!Ze.test(i.repositoryId)||i.provider!==s||e.repositoryId&&i.repositoryId!==e.repositoryId&&s!=="github"||(s==="local"?i.localKey!==e.localKey:i.localKey!==void 0)||typeof i.name!="string"||!i.name.trim()||i.name.length>512||/[\u0000-\u001f\u007f]/.test(i.name)||!i.workspace||i.workspace.id!==r||typeof i.workspace.name!="string")throw new E("invalid_repository_response","Canary returned an unexpected answer while looking up this repository. Run the command again; if it repeats, update the CLI.");return i}async function rt(n,e=I){if(!n.token)throw new E("not_logged_in","Run canary login first.");let t=nt(n),r=Po(n),i={token:n.token,baseUrl:t.apiUrl},s=r.repositoryId?await e(`/api/v1/cli/local-repositories/${r.repositoryId}?workspaceId=${encodeURIComponent(n.workspaceId)}`,i):await e("/api/v1/cli/local-repositories",{...i,method:"POST",body:{workspaceId:n.workspaceId,localKey:r.localKey,name:t.name,...t.githubFullName?{githubFullName:t.githubFullName}:{}}}),o=Lo(s,r,t,n.workspaceId);r.repositoryId&&r.repositoryId!==o.repositoryId?Er(t,{localKey:r.localKey,repositoryId:o.repositoryId}):Ar(t,"repository.json",{localKey:r.localKey,repositoryId:o.repositoryId});let a=et(t);if(a?.repositoryId!==o.repositoryId||a.localKey!==r.localKey)throw new E("binding_conflict","Another canary process registered this repository at the same time. Run the command again.");return o}async function it(n,e,t=W()){let r=P().team?.id;if(!r)throw new E("workspace_selection_required","Select a workspace with canary workspace list and canary workspace use <id>, then run the command again.");let i=await I("/api/v1/cli/auth/whoami",{token:e,baseUrl:t});if(!i?.user?.id)throw new E("invalid_identity_response","Canary could not tell which account this token belongs to. Run canary login again.");return{apiUrl:t,userId:i.user.id,workspaceId:r,directory:n}}async function Ot(n,e,t){let r=Tr(n);if(!r?.repositoryId)return;let i=await I(`/api/v1/cli/local-repositories/${r.repositoryId}/status?workspaceId=${encodeURIComponent(n.workspaceId)}`,{token:e,baseUrl:n.apiUrl,signal:t});if(typeof i?.repositoryId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(i.repositoryId)||!["setup_required","ready"].includes(i.state))throw new E("invalid_readiness_response","Canary returned an unexpected answer about this repository's setup. Run the command again.");return i.repositoryId!==r.repositoryId&&Nr(n,i.repositoryId),i}function Lr(n=process.cwd()){try{return tt(n).name}catch{return}}function Mr(n){try{return new URL(n).href.replace(/\/+$/,"")}catch{return}}var vn=Lr;async function jr(n,e,t,r){let i=await I("/api/v1/cli/workspaces",{token:n.token,baseUrl:r,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(i?.workspaces)||i.workspaces.some(u=>!u||typeof u.id!="string"||!u.id||typeof u.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let s=[...new Map(i.workspaces.map(({id:u,name:h})=>[u,{id:u,name:h}])).values()],a=e.user?.id===n.user.id&&Mr(t)===Mr(r)?s.find(u=>u.id===e.team?.id):void 0,c=s.length===1?s[0]:void 0,l=a??c??s.find(u=>u.id===n.team.id)??s[0]??{id:"",name:"No workspace selected"},d=vn();return{workspace:l,workspaces:s,source:a?"saved in CLI":c?"only workspace":"active on platform",selectionRequired:!a&&!c,...d?{repository:d}:{},...s.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function At(n,e,t,r=AbortSignal.timeout(3e3)){try{let i=await Ot({apiUrl:n.apiUrl,userId:n.userId,workspaceId:t},n.token,r);return i?{state:i.state}:void 0}catch{return}}function Et(n,e){let t=/^\d+$/.test(e)?Number(e)-1:-1,r=t>=0?n.workspaces.filter((i,s)=>s===t):n.workspaces.filter(i=>i.id===e||i.name.toLowerCase()===e.toLowerCase());if(r.length!==1)throw new Error(r.length?"Workspace name is ambiguous. Use its ID.":"Workspace not found. Run canary workspace list.");return r[0]}import{stripVTControlCharacters as Fr}from"node:util";var U="\x1B[";function ot(n,e,t){let r={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[e];return t?`${U}${r}m${n}${U}0m`:n}function N(n){return Fr(n).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var xn=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Ur(n){if(/^[\p{Mark}\u200d\ufe0f]+$/u.test(n))return 0;if(new RegExp("\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\u20e3","u").test(n))return 2;let e=n.codePointAt(0);return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072)?2:1}function st(n){return[...xn.segment(Fr(n))].reduce((e,t)=>e+Ur(t.segment),0)}function Tt(n,e){let t=0,r="";for(let i of n.split(/(\x1b\[[0-9;]*m)/)){if(i.startsWith(U)){r+=i;continue}for(let{segment:s}of xn.segment(i))t+=Ur(s),t<=e&&(r+=s)}return r}function ve(n,e){let t=[],r="";for(let i of N(n).split(/\s+/)){r&&st(r+" "+i)>e&&(t.push(r),r="");for(let{segment:s}of xn.segment((r?" ":"")+i))st(r+s)>e&&r&&(t.push(r),r=""),r+=s}return r&&t.push(r),t}function He(n){let e=[];return{render(t){if(t.join(`
|
|
75
77
|
`)===e.join(`
|
|
76
|
-
`))return;let
|
|
78
|
+
`))return;let r=Math.max(2,n.columns||80),i=Math.max(3,n.rows||24),s=Math.min(i-1,e.reduce((o,a)=>o+Math.max(1,Math.ceil(st(a)/r)),0));n.write((s?`\r${U}${s}A`:"")+`${U}0J`+(t.length?t.join(`\r
|
|
77
79
|
`)+`\r
|
|
78
|
-
`:"")),e=t}}}function
|
|
80
|
+
`:"")),e=t}}}function Hr(n,e,t){return n?[JSON.stringify({authorizeUrl:t})]:[e?"Opening your browser to authorize the Canary CLI...":"Open this URL in your browser to authorize the Canary CLI:",(e?`If it doesn't open, visit:
|
|
79
81
|
`:" ")+t+`
|
|
80
|
-
`]}function qn(n,e){return n?JSON.stringify({waiting:!0,elapsedSeconds:e}):`Still waiting for the sign-in to finish in your browser (${Math.max(1,Math.round(e/60))} min). The link above is still valid.`}function ut(n,e,t,i=[]){let r=S(n);switch(e){case"connected_elsewhere":return i.length===1?`Repository ${r} \xB7 connected in your workspace "${S(i[0].name)}", not the selected one`:`Repository ${r} \xB7 connected in ${i.length||"other"} of your workspaces, not the selected one`;case"onboarded":return`Repository ${r} \xB7 set up on Canary`;case"connected":return`Repository ${r} \xB7 connected \xB7 not set up yet`;case"not_connected":return`Repository ${r} \xB7 not connected to Canary \u2014 connect it at ${S(t)}`;case"no_access":return`Repository ${r} \xB7 connected in a workspace you're not a member of`;default:return`Repository ${r} \xB7 detected locally`}}function Je(n,e,t,i=[]){switch(n){case"connected_elsewhere":return i.length===1?`Next: switch the CLI to that workspace: canary workspace use ${S(i[0].id)}, then in your coding agent say "${te}"`:`Next: switch the CLI to the workspace it is connected in: ${ss(i)}; then in your coding agent say "${te}"`;case"onboarded":return`Next: in your coding agent, say "${rt}"`;case"not_connected":{let r=t?` (choose "${S(t)}" as the workspace there)`:"";return`Next: connect this repository at ${S(e)}${r}, then in your coding agent say "${te}"`}case"no_access":return"Next: ask an admin of the workspace where this repository is connected to add you, then run canary setup.";default:return`Next: in your coding agent, say "${te}"`}}import{stripVTControlCharacters as os}from"node:util";var Ae=[[" "," \u2880\u28F4\u28F6\u28FF\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F\u2801 "," \u28B0\u28FF\u2841\u28B8\u28FF\u28FF\u2801 "," \u2838\u28FF\u28E7\u2818\u28BF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F "," \u28B0\u28FF\u2840\u28BA\u28FF\u28FF "," \u2838\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280F "," \u28B0\u28FF \u28FF\u28FF\u28FF "," \u28B8\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u281F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280B "," \u28B0\u28FF \u28FF\u28FF\u285F "," \u28B8\u28FF\u28C7\u2839\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FF\u281F\u2809 "," \u28E0\u2802\u28FC\u28FF\u28FF\u2803 "," \u28B0\u28FF \u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u283B\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28F7\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E4\u28F6\u28FF\u281B\u2801 "," \u28E0\u2802\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28E6\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u287F\u280B\u2801 "," \u28E0\u2882\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28BB\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28BF\u28E6\u28D9\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B "," \u28E0\u28A0\u28FF\u28FF\u285F "," \u28F8\u28FF\u28B8\u28FF\u28FF\u2843 "," \u28BB\u28FF\u284C\u28BF\u28FF\u2847 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28E6\u28D9\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u281F\u2809 "," \u28F4\u28A0\u28FF\u28FF\u284F "," \u28F8\u28C7\u28B8\u28FF\u28FF "," \u28BF\u28FF\u285C\u28BF\u28FF\u2846 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u28DB\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28A0\u28F4\u28FE\u281F\u2801 "," \u2874\u28B0\u28FF\u28FF\u2807 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28BF\u28FF\u285C\u28FF\u28FF\u2844 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u287B\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u280B\u2801 "," \u2874\u28F0\u28FF\u28FF\u2803 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u283F\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2874\u28FC\u28FF\u28FF\u2801 "," \u28FC\u2847\u28FF\u28FF\u28CF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2854\u28FC\u28FF\u287F "," \u28FC\u2867\u28FF\u28FF\u2847 "," \u28FF\u28F7\u28FB\u28FF\u28F7\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28FF\u287B\u28F7\u2844 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u285F\u2801 "," \u2880\u2854\u28FE\u28FF\u285F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28E7\u28FF\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28FD\u287F\u28F7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u281F\u2801 "," \u2880\u28D4\u28FE\u28FF\u284F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28EF\u28BF\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28DD\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2807 "," \u28FE\u28F8\u28FF\u28FF "," \u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28BF\u28FF\u28DF\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2803 "," \u28FE\u28BC\u28FF\u28FF "," \u2818\u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28FF\u28FF\u28DF\u28FF\u28E6\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "]];var Be="\x1B[",as={gold:"33",text:"39",muted:"90",green:"32"};function cs(n,e,t){if(!t)return n;let i=e==="gold"?"38;2;255;212;0":as[e];return`${Be}${i}m${n}${Be}0m`}function Yn(n){return os(n).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var zn=1.4;function ls(n){let{phase:e,seconds:t,columns:i,rows:r,color:s,open:o}=n,a=n.phaseSeconds??t,c=1.4,u=t%(c+.2),f=v=>Math.sin(v/c*Math.PI*2)*Math.sin(v/c*Math.PI),h=e==="waiting"&&u<c?f(u):e==="success"&&a<zn?f(a):0,g=Ae[Math.max(0,Math.min(16,Math.round(h*10)+8))],d=e==="success"?"You're signed in.":e==="failed"?"Sign-in didn't finish.":e==="saving"?"Securing your CLI session":t<1.5?"Let's get you connected.":"Waiting for browser approval",m=e==="success"?"Your terminal is ready for the next step.":e==="failed"?"Run canary login to try again.":e==="saving"?"Exchanging authorization and saving credentials.":o&&t<1.5?"Opening your browser...":"Finish signing in at the link above.",p=(v,b="text")=>cs(v,b,s),_=e==="success"?"green":e==="failed"?"muted":"gold",k;if(r<5)k=[p(d)];else if(i>=72&&r>=18){let v={1:p("CANARY","gold"),3:p(d,e==="success"?"green":"text"),5:p(m,"muted")};k=["",...g.map((b,w)=>` ${p(b,_)} ${v[w]??""}`)]}else i>=42&&r>=23?k=["",...g.map(v=>` ${p(v,_)}`),` ${p("CANARY","gold")}`,"",` ${p(d)}`,` ${p(m,"muted")}`]:k=["",` ${p("CANARY","gold")}`,` ${p(d)}`];return r>=10&&(k.push("",` ${p("\u2500".repeat(Math.max(1,Math.min(54,i-5))),"gold")}`),(e==="waiting"||e==="saving")&&k.push(` ${p("Ctrl+C","muted")} ${p("cancel sign-in","muted")}`),k.push("")),k.slice(0,Math.max(1,r-2)).map(v=>{let b=0;return v.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,w=>w.startsWith("\x1B")||++b<i?w:"")})}function Kn(n){if(n.json||!n.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let e=process.stderr,t=!process.env.NO_COLOR,i=performance.now(),r="waiting",s=i,o=p=>{r=p,s=performance.now()},a=Re(e),c=!1;function l(){if(c)return;let p=Math.max(2,e.columns||80),_=Math.max(3,e.rows||24),k=performance.now(),v=ls({phase:r,seconds:(k-i)/1e3,phaseSeconds:(k-s)/1e3,columns:p,rows:_,color:t,open:n.open});a.render(v)}let u=()=>e.write(`${Be}0m${Be}?25h`);function f(){c||(c=!0,clearInterval(m),e.removeListener("resize",l),process.removeListener("SIGINT",g),process.removeListener("SIGTERM",d),process.removeListener("exit",u),u())}function h(p){o("failed"),l(),f(),e.write(`Sign-in cancelled.
|
|
81
|
-
`),process.exit(
|
|
82
|
-
Workspace ${
|
|
82
|
+
`]}function Dr(n,e){return n?JSON.stringify({waiting:!0,elapsedSeconds:e}):`Still waiting for the sign-in to finish in your browser (${Math.max(1,Math.round(e/60))} min). The link above is still valid.`}function Nt(n,e){let t=e==="ready"?"your setup is ready":e==="setup_required"?"not set up yet":"detected locally";return`Repository ${N(n)} \xB7 ${t}`}function De(n){return`Next: in your coding agent, say "${n==="ready"?_t:Me}"`}import{stripVTControlCharacters as Mo}from"node:util";var Ge=[[" "," \u2880\u28F4\u28F6\u28FF\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F\u2801 "," \u28B0\u28FF\u2841\u28B8\u28FF\u28FF\u2801 "," \u2838\u28FF\u28E7\u2818\u28BF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F "," \u28B0\u28FF\u2840\u28BA\u28FF\u28FF "," \u2838\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280F "," \u28B0\u28FF \u28FF\u28FF\u28FF "," \u28B8\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u281F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280B "," \u28B0\u28FF \u28FF\u28FF\u285F "," \u28B8\u28FF\u28C7\u2839\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FF\u281F\u2809 "," \u28E0\u2802\u28FC\u28FF\u28FF\u2803 "," \u28B0\u28FF \u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u283B\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28F7\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E4\u28F6\u28FF\u281B\u2801 "," \u28E0\u2802\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28E6\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u287F\u280B\u2801 "," \u28E0\u2882\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28BB\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28BF\u28E6\u28D9\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B "," \u28E0\u28A0\u28FF\u28FF\u285F "," \u28F8\u28FF\u28B8\u28FF\u28FF\u2843 "," \u28BB\u28FF\u284C\u28BF\u28FF\u2847 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28E6\u28D9\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u281F\u2809 "," \u28F4\u28A0\u28FF\u28FF\u284F "," \u28F8\u28C7\u28B8\u28FF\u28FF "," \u28BF\u28FF\u285C\u28BF\u28FF\u2846 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u28DB\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28A0\u28F4\u28FE\u281F\u2801 "," \u2874\u28B0\u28FF\u28FF\u2807 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28BF\u28FF\u285C\u28FF\u28FF\u2844 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u287B\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u280B\u2801 "," \u2874\u28F0\u28FF\u28FF\u2803 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u283F\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2874\u28FC\u28FF\u28FF\u2801 "," \u28FC\u2847\u28FF\u28FF\u28CF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2854\u28FC\u28FF\u287F "," \u28FC\u2867\u28FF\u28FF\u2847 "," \u28FF\u28F7\u28FB\u28FF\u28F7\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28FF\u287B\u28F7\u2844 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u285F\u2801 "," \u2880\u2854\u28FE\u28FF\u285F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28E7\u28FF\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28FD\u287F\u28F7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u281F\u2801 "," \u2880\u28D4\u28FE\u28FF\u284F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28EF\u28BF\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28DD\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2807 "," \u28FE\u28F8\u28FF\u28FF "," \u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28BF\u28FF\u28DF\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2803 "," \u28FE\u28BC\u28FF\u28FF "," \u2818\u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28FF\u28FF\u28DF\u28FF\u28E6\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "]];var at="\x1B[",jo={gold:"33",text:"39",muted:"90",green:"32"};function Fo(n,e,t){if(!t)return n;let r=e==="gold"?"38;2;255;212;0":jo[e];return`${at}${r}m${n}${at}0m`}function Gr(n){return Mo(n).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Br=1.4;function Uo(n){let{phase:e,seconds:t,columns:r,rows:i,color:s,open:o}=n,a=n.phaseSeconds??t,c=1.4,d=t%(c+.2),u=C=>Math.sin(C/c*Math.PI*2)*Math.sin(C/c*Math.PI),h=e==="waiting"&&d<c?u(d):e==="success"&&a<Br?u(a):0,f=Ge[Math.max(0,Math.min(16,Math.round(h*10)+8))],p=e==="success"?"You're signed in.":e==="failed"?"Sign-in didn't finish.":e==="saving"?"Securing your CLI session":t<1.5?"Let's get you connected.":"Waiting for browser approval",g=e==="success"?"Your terminal is ready for the next step.":e==="failed"?"Run canary login to try again.":e==="saving"?"Exchanging authorization and saving credentials.":o&&t<1.5?"Opening your browser...":"Finish signing in at the link above.",y=(C,x="text")=>Fo(C,x,s),S=e==="success"?"green":e==="failed"?"muted":"gold",m;if(i<5)m=[y(p)];else if(r>=72&&i>=18){let C={1:y("CANARY","gold"),3:y(p,e==="success"?"green":"text"),5:y(g,"muted")};m=["",...f.map((x,R)=>` ${y(x,S)} ${C[R]??""}`)]}else r>=42&&i>=23?m=["",...f.map(C=>` ${y(C,S)}`),` ${y("CANARY","gold")}`,"",` ${y(p)}`,` ${y(g,"muted")}`]:m=["",` ${y("CANARY","gold")}`,` ${y(p)}`];return i>=10&&(m.push("",` ${y("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(e==="waiting"||e==="saving")&&m.push(` ${y("Ctrl+C","muted")} ${y("cancel sign-in","muted")}`),m.push("")),m.slice(0,Math.max(1,i-2)).map(C=>{let x=0;return C.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,R=>R.startsWith("\x1B")||++x<r?R:"")})}function Vr(n){if(n.json||!n.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let e=process.stderr,t=!process.env.NO_COLOR,r=performance.now(),i="waiting",s=r,o=y=>{i=y,s=performance.now()},a=He(e),c=!1;function l(){if(c)return;let y=Math.max(2,e.columns||80),S=Math.max(3,e.rows||24),m=performance.now(),C=Uo({phase:i,seconds:(m-r)/1e3,phaseSeconds:(m-s)/1e3,columns:y,rows:S,color:t,open:n.open});a.render(C)}let d=()=>e.write(`${at}0m${at}?25h`);function u(){c||(c=!0,clearInterval(g),e.removeListener("resize",l),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",p),process.removeListener("exit",d),d())}function h(y){o("failed"),l(),u(),e.write(`Sign-in cancelled.
|
|
83
|
+
`),process.exit(y)}let f=()=>h(130),p=()=>h(143),g=setInterval(l,80);return g.unref(),e.on("resize",l),process.once("SIGINT",f),process.once("SIGTERM",p),process.once("exit",d),e.write(`${at}?25l`),l(),{saving(){o("saving"),l()},celebrate(){return o("success"),l(),new Promise(y=>setTimeout(y,Br*1e3+100))},succeed(y,S){o("success"),l(),u(),process.stdout.write(` Account ${Gr(y)}
|
|
84
|
+
Workspace ${Gr(S)}
|
|
83
85
|
|
|
84
|
-
`)},fail(){o("failed"),l(),
|
|
85
|
-
${
|
|
86
|
-
`);
|
|
87
|
-
${
|
|
86
|
+
`)},fail(){o("failed"),l(),u()},clear(){a.render([]),u()},stop:u}}import{spawn as Ho}from"node:child_process";import{createInterface as Do,emitKeypressEvents as Go}from"node:readline";function Cn(n){return n?n.installed.length+n.refreshed.length+n.current.length?`Installed \xB7 available to your coding agent${n.skipped.length?" (some locations skipped)":""}`:"Not installed \xB7 no writable agent location found":"Skipped \xB7 --no-agent-skills"}function In(n){return n.workspaces.length>1}function ct(n){return n.repositoryState==="ready"?_t:Me}async function Wr(n){let e=process.stdin,t=process.stderr,r=e.readableFlowing===!0;t.write(`Choose a workspace:
|
|
87
|
+
`),n.workspaces.forEach((o,a)=>{let c=n.workspaces.some(l=>l.id!==o.id&&l.name===o.name);t.write(` ${a+1}. ${N(o.name)}${c?` (${N(o.id)})`:""}
|
|
88
|
+
`)});let i=Do({input:e,output:t,terminal:!1}),s=()=>i.close();process.once("SIGINT",s);try{t.write("Workspace (number or name): ");for await(let o of i)try{return Et(n,o.trim())}catch(a){t.write(`${a instanceof Error?a.message:"Choose a listed workspace."}
|
|
89
|
+
Workspace (number or name): `)}}finally{process.off("SIGINT",s),i.close(),r||e.pause()}}function Bo(n,e,t,r){let{context:i}=n,s=Math.max(1,e-5),o=(h,f="text")=>ot(N(h),f,r),a=(h="",f="text")=>` ${o(h,f)}`,c=[];if(e>=90&&t>=36&&!n.picker){let h={1:o("CANARY","gold"),3:o("You're connected."),5:o("Let's give your agent the next step.","muted")};c.push("",...Ge[8].map((f,p)=>` ${o(f,"green")} ${h[p]??""}`),"")}else c.push(a("CANARY","gold"),a("You're connected."),"");if(c.push(a(`Account ${N(n.email)}`)),c.push(a(`Workspace ${i.selectionRequired?"Choose below":N(i.workspace.name)}`)),c.push(a(` ${i.source}${!n.done&&In(i)?" \xB7 [w] Change":""}`,"muted")),n.picker){c.push("",a("Choose a workspace","gold"));let h=Math.max(1,Math.min(8,t-c.length-5)),f=Math.max(0,Math.min(n.highlighted-Math.floor(h/2),i.workspaces.length-h));for(let p=f;p<Math.min(f+h,i.workspaces.length);p++){let g=i.workspaces[p],S=i.workspaces.some(C=>C.id!==g.id&&C.name===g.name)?` \xB7 ${N(g.id)}`:"",m=!i.selectionRequired&&g.id===i.workspace.id?" \xB7 current":"";c.push(a(`${p===n.highlighted?"\u203A":" "} ${p+1}. ${N(g.name)}${S}${m}`,p===n.highlighted?"gold":"text"))}c.push(a(`${n.highlighted+1} of ${i.workspaces.length}`,"muted"),"",a("\u2191 \u2193 choose \xB7 number highlight \xB7 Enter select \xB7 Esc back","muted"))}else{let h=i.repositoryState==="ready",f=i.repository?N(i.repository):void 0;f?h?c.push(a(`Repository ${f} \xB7 your setup is ready`,"green")):i.repositoryState==="setup_required"?c.push(a(`Repository ${f} \xB7 not set up yet`)):c.push(a(`Repository ${f} \xB7 detected locally`)):c.push(a("Repository Open a local Git repository to continue")),c.push(a(`Agent skill ${Cn(n.skill)}`,n.skill&&Cn(n.skill).startsWith("Installed")?"green":"muted")),i.workspaceNotice&&c.push(...ve(i.workspaceNotice,s).map(g=>a(g,"muted"))),c.push("",a("\u2500".repeat(Math.min(68,s)),"muted"),a(h?"NEXT \xB7 VERIFY A CHANGE":"NEXT \xB7 SET UP THIS REPOSITORY","gold"));let p=!!n.skill&&Cn(n.skill).startsWith("Installed");c.push(a(p?"Open your coding agent in this repository and say:":"In your coding agent, run canary skills, then say:","muted")),c.push(...ve(ct(i),s-2).map(g=>a(`\u2502 ${g}`))),n.done||c.push("",a(`${In(i)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),n.message&&c.push(...ve(n.message,s).map(g=>a(g,"muted"))),c.push("",a(h?"Signed in \xB7 Ready to verify":i.repositoryState==="setup_required"?"Signed in \xB7 This repo isn't set up yet":"Signed in \xB7 Couldn't check this repo's setup",h?"green":"muted"))}let d=Math.max(1,t-2);return(d<=3?c.slice(0,d):c.length>d?[...c.slice(0,Math.max(0,d-3)),...c.slice(-3)]:c).map(h=>Tt(h,Math.max(1,e-1)))}async function Vo(n,e){let t=process.platform==="darwin"?[["pbcopy"]]:process.platform==="win32"?[["clip.exe"]]:[["wl-copy"],["xclip","-selection","clipboard"],["xsel","--clipboard","--input"]];for(let[r,...i]of t){if(e.aborted)return!1;if(await new Promise(o=>{let a=Ho(r,i,{stdio:["pipe","ignore","ignore"],signal:e}),c=setTimeout(()=>{a.kill(),o(!1)},1e3),l=d=>{clearTimeout(c),o(d)};a.on("error",()=>l(!1)),a.on("close",d=>l(d===0)),a.stdin.on("error",()=>{}),a.stdin.end(n)}))return!0}return!1}async function Jr(n){let e=process.stdin,t=process.stderr,r={...n,picker:n.context.workspaces.length>1,highlighted:Math.max(0,n.context.workspaces.findIndex(f=>f.id===n.context.workspace.id))},i=!process.env.NO_COLOR,s=He(t),o=()=>s.render(Bo(r,t.columns||80,t.rows||24,i));if(!e.isTTY||!t.isTTY||(t.rows||24)<16||(t.columns||80)<30){r.done=!0,o(),t.write(`
|
|
90
|
+
${ct(r.context)}
|
|
91
|
+
`);return}let a=e.isRaw,c=e.readableFlowing===!0,l=new AbortController,d=!1,u,h=0;await new Promise(f=>{function p(){if(d)return;d=!0,l.abort(),e.off("keypress",m),e.off("end",p),t.off("resize",S),process.off("SIGINT",p),process.off("SIGTERM",y),process.off("exit",g),r.picker=!1,r.done=!0,r.message=void 0;let C=n.sessionCurrent();C?o():s.render(["CLI session changed in another process. Run canary whoami to check the active account."]),g(),C&&!r.context.selectionRequired&&t.write(`
|
|
92
|
+
${ct(r.context)}
|
|
88
93
|
|
|
89
|
-
`),g()}function m(){e.setRawMode(a),c||e.pause(),t.write(`${L}0m${L}?25h`)}function p(){process.exitCode=143,d()}function _(){(t.rows||24)<16||(t.columns||80)<30?d():o()}function k(v,b){if(!(!b||u)){if(!n.sessionCurrent()){d();return}if(b.ctrl&&["c","d"].includes(b.name??"")){d();return}if(!(b.ctrl||b.meta)){if(i.picker){let w=i.context.workspaces.length;if(b.name==="escape")i.picker=!1;else if(b.name==="up")i.highlighted=(i.highlighted+w-1)%w;else if(b.name==="down")i.highlighted=(i.highlighted+1)%w;else if(b.name==="return"){let x=i.context.workspaces[i.highlighted];try{n.selectWorkspace(x);let A=x.id!==i.context.workspace.id;if(i.context={...i.context,workspace:x,source:"selected in CLI",...A?{repositoryState:void 0}:{}},i.picker=!1,i.message="Workspace saved for future CLI commands.",A&&(f?.abort(),n.repositoryState&&i.context.repository)){let N=++h;n.repositoryState(x.id).then(j=>{if(!u){if(!n.sessionCurrent()){d();return}N!==h||i.context.workspace.id!==x.id||(i.context={...i.context,repositoryState:j?.state,connectUrl:j?.connectUrl??i.context.connectUrlDefault,repositoryWorkspaces:j?.workspaces},o())}})}}catch{if(!n.sessionCurrent()){d();return}i.picker=!1,i.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(b.name??"")){d();return}else if(b.name==="w"&&dt(i.context))i.picker=!0,i.highlighted=Math.max(0,i.context.workspaces.findIndex(w=>w.id===i.context.workspace.id));else if(b.name==="c"&&!f){let w=qe(i.context),x=new AbortController;f=x,l.signal.addEventListener("abort",()=>x.abort(),{once:!0}),ps(w,x.signal).then(A=>{f===x&&(f=void 0),!u&&(i.message=x.signal.aborted||w!==qe(i.context)?"The next step changed while copying. Press [c] to copy the current one.":A?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",o())})}o()}}}ds(e),e.setRawMode(!0),e.resume(),e.on("keypress",k),e.once("end",d),t.on("resize",_),process.once("SIGINT",d),process.once("SIGTERM",p),process.once("exit",m),t.write(`${L}?25l`),o()})}var ys=900*1e3,ws=6e4,bs=3e3,Zn=n=>n.toString("base64url");function ks(n){let e=process.platform,[t,i]=e==="darwin"?["open",[n]]:e==="win32"?["explorer.exe",[n]]:["xdg-open",[n]];try{let r=gs(t,i,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}function _s(n,e){return`<!doctype html><meta charset="utf-8"><title>${n}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${n}</h2><p style="color:#555">${e}</p></body>`}function vs(n){return new Promise((e,t)=>{let i,r,s=new Promise((l,u)=>{i=l,r=u}),o=ms((l,u)=>{let f=new URL(l.url??"/","http://127.0.0.1"),h=(m,p,_)=>{u.writeHead(_,{"content-type":"text/html",connection:"close"}),u.end(_s(m,p))};if(f.pathname!=="/callback"){u.writeHead(404,{connection:"close"}),u.end("not found");return}if(f.searchParams.get("state")!==n){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let g=f.searchParams.get("error");if(g){h("Authorization failed","You can close this tab and return to your terminal.",400),r(new Error(`authorization failed: ${g}`));return}let d=f.searchParams.get("code");if(!d){h("Authorization failed","No authorization code was returned. Please run canary login again.",400),r(new Error("callback returned no code"));return}h("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),i(d)}),a=setTimeout(()=>r(new Error("timed out waiting for browser authorization")),ys);a.unref?.();let c=()=>{clearTimeout(a),o.closeAllConnections?.(),o.close()};s.then(c,c),o.on("error",l=>{clearTimeout(a),t(l)}),o.listen(0,"127.0.0.1",()=>{e({port:o.address().port,code:s,close:c})})})}async function Cs(n,e){let t=O(),i=t.apiUrl||"",r=(e.apiUrl||ce()).replace(/\/+$/,""),s=Zn(Qn(32)),o=hs("sha256").update(s).digest("base64url"),a=Zn(Qn(16)),{port:c,code:l,close:u}=await vs(a),f=`http://127.0.0.1:${c}/callback`,h=(e.webUrl||ee()).replace(/\/+$/,""),g=`${h}/cli/authorize?challenge=${encodeURIComponent(o)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(f)}`;for(let _ of Bn(n,e.open,g))console.error(_);let d=Kn({json:n,animation:e.animation,open:e.open}),m=Date.now(),p=d?void 0:setInterval(()=>console.error(qn(n,Math.round((Date.now()-m)/1e3))),ws);p?.unref?.();try{e.open&&ks(g);let _=await l;p&&clearInterval(p),d?.saving();let k=await I("/api/v1/cli/auth/token",{method:"POST",body:{code:_,codeVerifier:s},baseUrl:r});jt({token:k.token,user:k.user,team:k.team,apiUrl:r,webUrl:h,agentSkills:e.agentSkills});let v=e.agentSkills?Ue():void 0;if(d){let[b]=await Promise.all([Vn(k,t,i,r),d.celebrate()]),w=()=>{let N=O();return N.token===k.token&&N.apiUrl===r};if(!w()){d.clear(),console.error("CLI session changed in another process. Run canary whoami to check the active account.");return}let x=N=>{let j=O();if(j.token!==k.token||j.apiUrl!==r)throw new Error("CLI session changed");X({...j,team:N})};try{x(b.workspace)}catch{b.workspace=k.team,b.source="active on platform",b.workspaceNotice="Couldn't save the workspace preference. Run canary workspace current to check your CLI selection."}d.clear(),b.connectUrlDefault=`${h}/integrations`,b.connectUrl??=b.connectUrlDefault;let A=b.repository?N=>ie({token:k.token,apiUrl:r},b.repository,N):void 0;await Xn({email:k.user.email,context:b,skill:v,selectWorkspace:x,sessionCurrent:w,repositoryState:A})}else{let b=$e(),w={token:k.token,apiUrl:r},x=AbortSignal.timeout(bs),A=b&&!n?await ie(w,b,k.team.id,x):void 0,N,j=A?.state==="connected_elsewhere"&&A.workspaces?.length===1?A.workspaces[0]:void 0;if(j&&b){let z=O();if(z.token===k.token&&z.apiUrl===r)try{X({...z,team:j}),N=j,A=await ie(w,b,j.id,x)??{state:"connected"}}catch{}}let C=A?.connectUrl??`${h}/integrations`,P=N?.name??k.team.name;ti(n,k.user.email,k.team,b?{name:b,state:A?.state,connectUrl:C,workspaces:A?.workspaces}:void 0,N);let $=b?Je(A?.state,C,P,A?.workspaces):void 0;v?ni(n,v,$):n||console.log($??st)}}catch(_){throw d?.fail(),_}finally{p&&clearInterval(p),d?.stop(),u()}}async function ei(n,e,t){let i=await I("/api/v1/cli/auth/whoami",{token:n,baseUrl:t});jt({token:n,user:i.user,team:i.team,apiUrl:t});let r=$e(),s=`${ee().replace(/\/+$/,"")}/integrations`;return ti(e,i.user.email,i.team,r?{name:r,connectUrl:s}:void 0),r?Je(void 0,s):void 0}function ti(n,e,t,i,r){if(n){console.log(JSON.stringify({ok:!0,user:{email:e},team:t,...i?{repository:i}:{},...r?{workspace:r}:{}}));return}console.log(`Logged in as ${S(e)} (${S(t.name)}).`),r&&console.log(Jn(r)),i&&console.log(ut(i.name,i.state,i.connectUrl,i.workspaces))}function xs(n,e){let t=Ue();ni(n,t,e)}function ni(n,e,t=st){if(n)return;let i=[...e.installed,...e.refreshed];i.length&&console.log(`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${i.join(", ")}).`),console.log(t)}function ii(n){n.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-animation","use plain login output without the animated Canary").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{let i;if(e.token!==void 0){let r=e.token.trim();if(!r)throw new Error("--token was provided but is empty");i=await ei(r,t,e.apiUrl)}else{let r=(process.env.CANARY_TOKEN??"").trim();if(r)i=await ei(r,t,e.apiUrl);else{await Cs(t,{webUrl:e.webUrl,apiUrl:e.apiUrl,open:e.open!==!1,animation:e.animation!==!1,agentSkills:e.agentSkills!==!1}),me();return}}X({...O(),agentSkills:e.agentSkills!==!1}),e.agentSkills!==!1?xs(t,i):t||console.log(i??st),e.token===void 0&&!(process.env.CANARY_TOKEN??"").trim()&&me()}catch(i){let r=i instanceof E?`${i.message}`:i instanceof Error?i.message:String(i);t?console.log(JSON.stringify({ok:!1,error:r})):console.error(`Login failed: ${r}`),process.exitCode=1}})}var Ss={[D.install]:"(random, minted once into ~/.canary/config.json)",[D.worktree]:"(hash of this checkout's path, salted by the install id; the path never leaves)",[D.repo]:"(root commit of the history; absent on a shallow clone)"};function ri(n){n.command("identity").description("Show what this CLI sends about where it runs (ids and hashes only; no request is made)").option("--json","print the headers as JSON").action(e=>{let t=Ce();if(e.json===!0)return void console.log(JSON.stringify(t));for(let[i,r]of Object.entries(t)){let s=i===D.harness&&r==="unknown"?"(no running coding-agent session detected)":Ss[i]??"";console.log(`${i.padEnd(18)} ${r}${s?` ${s}`:""}`)}})}function si(n){n.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,i=U();if(i)try{await I("/api/v1/cli/auth/logout",{method:"POST",token:i})}catch{}Rn();let r=!!process.env.CANARY_TOKEN;t?console.log(JSON.stringify({ok:!0,...r?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),r&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}import{readFileSync as fi}from"node:fs";import{execFileSync as $s}from"node:child_process";import{copyFileSync as Rs,existsSync as oi,mkdirSync as As,mkdtempSync as Os,rmSync as ai,statSync as Is,utimesSync as Es,writeFileSync as Ts}from"node:fs";import{tmpdir as ci}from"node:os";import{join as Oe,resolve as li}from"node:path";var M=class extends Error{constructor(t,i,r){super(i);this.code=t;this.fix=r;this.name="SnapshotError"}},be=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:n=>`canary verify: tree ${n}`});function Ns(n,e){return{args:["-c","i18n.commitEncoding=utf-8","-c","commit.gpgsign=false","commit-tree",n,"-p",e,"--no-gpg-sign","-m",be.message(n)],env:{GIT_AUTHOR_NAME:be.name,GIT_AUTHOR_EMAIL:be.email,GIT_AUTHOR_DATE:be.date,GIT_COMMITTER_NAME:be.name,GIT_COMMITTER_EMAIL:be.email,GIT_COMMITTER_DATE:be.date}}}var Ps=["apply","--binary","--whitespace=nowarn"],ft=n=>`tree:${n.slice(0,12)}`;function Ms(n){let e=0,t=0,i=0;for(let r of n.split(`
|
|
90
|
-
`)
|
|
91
|
-
`)
|
|
92
|
-
`)
|
|
93
|
-
`);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
94
|
+
`),f()}function g(){e.setRawMode(a),c||e.pause(),t.write(`${U}0m${U}?25h`)}function y(){process.exitCode=143,p()}function S(){(t.rows||24)<16||(t.columns||80)<30?p():o()}function m(C,x){if(!(!x||d)){if(!n.sessionCurrent()){p();return}if(x.ctrl&&["c","d"].includes(x.name??"")){p();return}if(!(x.ctrl||x.meta)){if(r.picker){let R=r.context.workspaces.length;if(x.name==="escape"){if(r.context.selectionRequired){p();return}r.picker=!1}else if(/^[1-9]$/.test(x.sequence??"")&&Number(x.sequence)<=R)r.highlighted=Number(x.sequence)-1;else if(x.name==="up")r.highlighted=(r.highlighted+R-1)%R;else if(x.name==="down")r.highlighted=(r.highlighted+1)%R;else if(x.name==="return"){let _=r.context.workspaces[r.highlighted];try{n.selectWorkspace(_);let F=_.id!==r.context.workspace.id;if(r.context={...r.context,workspace:_,source:"selected in CLI",selectionRequired:!1,...F?{repositoryState:void 0}:{}},r.picker=!1,r.message="Workspace saved for future CLI commands.",(F||!r.context.repositoryState)&&(u?.abort(),n.repositoryState&&r.context.repository)){let D=++h;n.repositoryState(_.id).then(ye=>{if(!d){if(!n.sessionCurrent()){p();return}D!==h||r.context.workspace.id!==_.id||(r.context={...r.context,repositoryState:ye?.state},o())}})}}catch{if(!n.sessionCurrent()){p();return}r.picker=!1,r.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(x.name??"")){p();return}else if(x.name==="w"&&In(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(R=>R.id===r.context.workspace.id));else if(x.name==="c"&&!u){let R=ct(r.context),_=new AbortController;u=_,l.signal.addEventListener("abort",()=>_.abort(),{once:!0}),Vo(R,_.signal).then(F=>{u===_&&(u=void 0),!d&&(r.message=_.signal.aborted||R!==ct(r.context)?"The next step changed while copying. Press [c] to copy the current one.":F?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",o())})}o()}}}Go(e),e.setRawMode(!0),e.resume(),e.on("keypress",m),e.once("end",p),t.on("resize",S),process.once("SIGINT",p),process.once("SIGTERM",y),process.once("exit",g),t.write(`${U}?25l`),o()})}var Yo=900*1e3,zo=6e4;var Yr=n=>n.toString("base64url");function Ko(n){let e=process.platform,[t,r]=e==="darwin"?["open",[n]]:e==="win32"?["explorer.exe",[n]]:["xdg-open",[n]];try{let i=Jo(t,r,{stdio:"ignore",detached:!0});i.on("error",()=>{}),i.unref()}catch{}}function Xo(n,e){return`<!doctype html><meta charset="utf-8"><title>${n}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${n}</h2><p style="color:#555">${e}</p></body>`}function Qo(n){return new Promise((e,t)=>{let r,i,s=new Promise((l,d)=>{r=l,i=d}),o=qo((l,d)=>{let u=new URL(l.url??"/","http://127.0.0.1"),h=(g,y,S)=>{d.writeHead(S,{"content-type":"text/html",connection:"close"}),d.end(Xo(g,y))};if(u.pathname!=="/callback"){d.writeHead(404,{connection:"close"}),d.end("not found");return}if(u.searchParams.get("state")!==n){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let f=u.searchParams.get("error");if(f){h("Authorization failed","You can close this tab and return to your terminal.",400),i(new Error(`authorization failed: ${f}`));return}let p=u.searchParams.get("code");if(!p){h("Authorization failed","No authorization code was returned. Please run canary login again.",400),i(new Error("callback returned no code"));return}h("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),r(p)}),a=setTimeout(()=>i(new Error("timed out waiting for browser authorization")),Yo);a.unref?.();let c=()=>{clearTimeout(a),o.closeAllConnections?.(),o.close()};s.then(c,c),o.on("error",l=>{clearTimeout(a),t(l)}),o.listen(0,"127.0.0.1",()=>{e({port:o.address().port,code:s,close:c})})})}async function Zo(n,e){let t=P(),r=t.apiUrl||W(),i=(e.apiUrl||W()).replace(/\/+$/,""),s=Yr(qr(32)),o=Wo("sha256").update(s).digest("base64url"),a=Yr(qr(16)),{port:c,code:l,close:d}=await Qo(a),u=`http://127.0.0.1:${c}/callback`,h=(e.webUrl||$e()).replace(/\/+$/,""),f=`${h}/cli/authorize?challenge=${encodeURIComponent(o)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(u)}`;for(let S of Hr(n,e.open,f))console.error(S);let p=Vr({json:n,animation:e.animation,open:e.open}),g=Date.now(),y=p?void 0:setInterval(()=>console.error(Dr(n,Math.round((Date.now()-g)/1e3))),zo);y?.unref?.();try{e.open&&Ko(f);let S=await l;y&&clearInterval(y),p?.saving();let m=await I("/api/v1/cli/auth/token",{method:"POST",body:{code:S,codeVerifier:s},baseUrl:i});p&&await p.celebrate(),p?.clear(),await Kr(m,t,r,i,n,{webUrl:h,agentSkills:e.agentSkills,workspace:e.workspace,interactive:!!p&&!!process.stdin.isTTY&&(process.stderr.rows||24)>=16&&(process.stderr.columns||80)>=30,promptWorkspace:!n&&!process.env.CI&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&!!process.stderr.isTTY})}catch(S){throw p?.fail(),S}finally{y&&clearInterval(y),p?.stop(),d()}}async function Kr(n,e,t,r,i,s){let{team:o,...a}=P();fe({...a,token:n.token,user:n.user,apiUrl:r,...s.webUrl?{webUrl:s.webUrl}:{},agentSkills:s.agentSkills});let c=await jr(n,e,t,r);s.workspace!==void 0&&(c.workspace=Et(c,s.workspace),c.source="selected in CLI",c.selectionRequired=!1),c.selectionRequired||fe({...P(),team:c.workspace});let l=s.agentSkills?xt():void 0,d=()=>{let g=P();return g.token===n.token&&g.apiUrl===r},u=g=>{let y=P();if(!d())throw new Error("CLI session changed");fe({...y,team:g}),c.selectionRequired=!1},h=c.repository?g=>At({token:n.token,apiUrl:r,userId:n.user.id},c.repository,g):void 0;if(!c.selectionRequired&&h&&(c.repositoryState=(await h(c.workspace.id))?.state),s.interactive&&c.workspaces.length)await Jr({email:n.user.email,context:c,skill:l,selectWorkspace:u,sessionCurrent:d,repositoryState:h});else if(s.promptWorkspace&&c.selectionRequired&&c.workspaces.length){console.error(`Signed in as ${N(n.user.email)}.`);let g=await Wr(c);g&&(u(g),c.workspace=g,c.source="selected in CLI",h&&(c.repositoryState=(await h(g.id))?.state))}if(!d())throw new Error("CLI session changed in another process. Run canary whoami.");let f=P().team;if(!f){let g=c.workspaces.length?"workspace_selection_required":"workspace_required",y=c.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${$e()}, then run canary login.`;i?console.log(JSON.stringify({ok:!1,authenticated:!0,error:g,user:n.user,workspaces:c.workspaces,fix:y})):(console.log(`Signed in as ${N(n.user.email)}. Select a workspace to continue.`),c.workspaces.forEach((S,m)=>console.log(` ${m+1}. ${N(S.name)} (${N(S.id)})`)),console.log(y)),process.exitCode=1;return}let p=c.repository?{name:c.repository,state:c.repositoryState}:void 0;return i?console.log(JSON.stringify({ok:!0,user:n.user,team:f,workspace:f,...p?{repository:p}:{}})):s.interactive||(console.log(`Logged in as ${N(n.user.email)} (${N(f.name??f.id)}).`),p&&console.log(Nt(p.name,p.state)),l?ea(!1,l,De(p?.state)):console.log(De(p?.state))),De(p?.state)}async function zr(n,e,t){let r=P(),i=r.apiUrl||W(),s=(t.apiUrl||W()).replace(/\/+$/,""),o=await I("/api/v1/cli/auth/whoami",{token:n,baseUrl:s});await Kr({...o,token:n,tokenType:"Bearer",expiresAt:null},r,i,s,e,{agentSkills:t.agentSkills,workspace:t.workspace,interactive:!1})}function ea(n,e,t=ur){if(n)return;let r=[...e.installed,...e.refreshed];r.length&&console.log(`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${r.join(", ")}).`),console.log(t)}function Xr(n){n.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("--workspace <id-or-name>","select a workspace from your memberships (required for an unselected headless login)").option("--no-open","print the authorization URL instead of opening a browser").option("--no-animation","use plain login output without the animated Canary").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 r=e.token.trim();if(!r)throw new Error("--token was provided but is empty");await zr(r,t,{...e,agentSkills:e.agentSkills!==!1})}else{let r=(process.env.CANARY_TOKEN??"").trim();if(r)await zr(r,t,{...e,agentSkills:e.agentSkills!==!1});else{await Zo(t,{webUrl:e.webUrl,apiUrl:e.apiUrl,workspace:e.workspace,open:e.open!==!1,animation:e.animation!==!1,agentSkills:e.agentSkills!==!1}),je();return}}}catch(r){let i=r instanceof O?`${r.message}`:r instanceof Error?r.message:String(r);t?console.log(JSON.stringify({ok:!1,error:i})):console.error(`Login failed: ${i}`),process.exitCode=1}})}var ta={[J.install]:"(random, minted once into ~/.canary/config.json)",[J.worktree]:"(hash of this checkout's path, salted by the install id; the path never leaves)",[J.repo]:"(root commit of the history; absent on a shallow clone)"};function Qr(n){n.command("identity").description("Show what this CLI sends about where it runs (ids and hashes only; no request is made)").option("--json","print the headers as JSON").action(e=>{let t=ke();if(e.json===!0)return void console.log(JSON.stringify(t));for(let[r,i]of Object.entries(t)){let s=r===J.harness&&i==="unknown"?"(no running coding-agent session detected)":ta[r]??"";console.log(`${r.padEnd(18)} ${i}${s?` ${s}`:""}`)}})}function Zr(n){n.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,r=V();if(r)try{await I("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}cr();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 Ii}from"node:fs";var Nu=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:n=>`canary verify: tree ${n}`});var Pt=n=>`tree:${n.slice(0,12)}`;var na=[["core.fsmonitor","false"],["core.splitIndex","false"],["gc.auto","0"],["commit.gpgsign","false"],["i18n.commitEncoding","utf-8"],["log.showSignature","false"],["diff.noprefix","false"],["diff.mnemonicPrefix","false"],["diff.relative","false"],["diff.context","3"],["diff.interHunkContext","0"],["diff.submodule","short"],["apply.ignoreWhitespace","no"],["apply.whitespace","nowarn"]],Pu=na.flatMap(([n,e])=>["-c",`${n}=${e}`]);import{spawn as ra}from"node:child_process";import{createHash as Tn}from"node:crypto";import{constants as ei}from"node:fs";import{lstat as ia,mkdir as ai,mkdtemp as sa,open as ci,readFile as oa,readdir as aa,readlink as ca,realpath as Lt,rm as la,writeFile as ua}from"node:fs/promises";import{tmpdir as da}from"node:os";import{isAbsolute as pa,join as se,relative as fa,resolve as ti,sep as ha}from"node:path";import{promisify as ga}from"node:util";import{deflate as ma}from"node:zlib";var ut={maxBundleBytes:4*1024*1024*1024,maxObjectBytes:1024*1024*1024,maxExpandedBytes:16*1024*1024*1024,maxObjects:1e6,maxTreeFiles:5e5,maxTreeBytes:16*1024*1024*1024,maxDepth:64,maxPathBytes:4096,maxSymlinkBytes:4096},me=class extends Error{constructor(t,r,i){super(r);this.code=t;this.fix=i;this.name="SourceSnapshotError"}},k=(n,e)=>{throw new me(n,e)},ya=ga(ma),wa=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),$n=/^[a-f0-9]{40}$/,Mt="Canary Snapshot <snapshot@runcanary.ai> 0 +0000",ni=(n,e)=>{let t=fa(n,e);return t===""||!t.startsWith(`..${ha}`)&&t!==".."&&!pa(t)},li=n=>{try{return wa.decode(n)}catch{return k("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},dt=n=>n.length?li(n).split("\0").filter(Boolean):[],ui=n=>{let e=n.normalize("NFC").replace(/[\u200c-\u200f\u202a-\u202e\u206a-\u206f\ufeff]/g,"").toLowerCase().replace(/[ .]+$/g,"");return e===".git"||e.startsWith(".git:")||/^git~[0-9]+(?:\.|$)/.test(e)};function On(n,e){let t=n.split("/");(!n||Buffer.byteLength(n)>e.maxPathBytes||t.length>e.maxDepth||t.some(r=>!r||Buffer.byteLength(r)>255||r==="."||r===".."||ui(r)||r.includes("\0")||r.includes("\\")))&&k("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(n)}.`)}function ba(n){return{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_")||!n&&["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(t))),GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_NO_LAZY_FETCH:"1",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0",...n?{GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"}:{}}}var Sa=["-c","core.fsmonitor=false","-c","core.untrackedCache=false","-c","core.hooksPath=/dev/null","-c","gc.auto=0","-c","maintenance.auto=false","-c","protocol.allow=never"],Ve=class{constructor(e,t,r=!1,i={}){this.cwd=e;this.signal=t;this.isolated=r;this.extra=i}child(e){return this.signal?.throwIfAborted(),ra("git",[...Sa,...e],{cwd:this.cwd,env:{...ba(this.isolated),...this.extra},signal:this.signal,stdio:"pipe"})}async run(e,t={}){let r=this.child(e),i=[],s=0,o="",a;r.on("error",l=>{a=l}),r.stdout.on("data",l=>{s+=l.length,s>(t.maxBytes??256*1024*1024)?(a=new me("snapshot_limit","This repository's Git metadata is too large to upload."),r.kill()):i.push(l)}),r.stderr.on("data",l=>{o.length<8192&&(o+=l.toString("utf8"))}),r.stdin.on("error",()=>{}),r.stdin.end(t.input);let c=await new Promise(l=>r.on("close",l));if(a)throw a;return c!==0&&!(t.optional&&c===1)&&k("git_source_error",`Cannot read local Git source: ${o.trim()||`git ${e[0]} failed`}`),c===1?Buffer.alloc(0):Buffer.concat(i)}async text(e,t=!1){return(await this.run(e,{optional:t})).toString("utf8").trim()}};function ri(n,e){return dt(n).map(t=>{let r=t.indexOf(" "),[i,s,o]=t.slice(0,r).split(" ");return r<0||!(e?$n.test(s):$n.test(o))?k("git_source_error","Git returned an invalid source entry."):(e&&o!=="0"&&k("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:t.slice(r+1),mode:i,oid:e?s:o})})}async function ii(n,e){let t=await n.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await n.text(["symbolic-ref","--quiet","--short","HEAD"],!0)||null,i={headSha:t,branch:r,baseRef:null,baseSha:null,baselineMode:"whole-project"};if(e!==void 0){(!e||e.startsWith("-")||e.length>1024||/[\x00-\x1f\x7f]/.test(e))&&k("invalid_base","--base must name a local Git commit or ref.");let a=await n.text(["rev-parse","--verify","--quiet",`${e}^{commit}`],!0);return $n.test(a)||k("invalid_base",`--base ${JSON.stringify(e)} is not a local commit or ref. Canary does not fetch; pass one that exists locally.`),{...i,baseRef:e,baseSha:a,baselineMode:"explicit"}}if(!t)return i;let s=await n.text(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"],!0),o;for(let a of[[s],["refs/remotes/origin/main","refs/remotes/origin/master"],["main","master"].filter(c=>c!==r).map(c=>`refs/heads/${c}`)]){for(let c of[...new Set(a.filter(Boolean))]){let l=await n.text(["rev-parse","--verify","--quiet",`${c}^{commit}`],!0);if(!l)continue;let d=await n.text(["merge-base",t,l],!0);if(!d)continue;let u=Number(await n.text(["rev-list","--count",`${d}..${t}`]));(!o||u<o.distance)&&(o={ref:c,base:d,distance:u})}if(o)break}return o?{...i,baseRef:o.ref,baseSha:o.base,baselineMode:"merge-base"}:i}async function Rn(n){return new Set(dt(await n.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function lt(n,e,t){if(!e.length)return;let r=dt(await n.run(["check-attr",...t?["--cached"]:[],"-z","--stdin","filter"],{input:`${e.join("\0")}\0`}));for(let i=0;i<r.length;i+=3)r[i+2]==="lfs"&&k("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[i])}. Remove the LFS attribute for it, or ignore the file.`)}function ka(n,e){(n.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
|
|
95
|
+
`)||n.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
|
|
96
|
+
`))&&k("unsupported_lfs",`${JSON.stringify(e)} is a Git LFS pointer. Canary needs the real file contents.`)}var An=class{constructor(e,t){this.limits=t;this.child=e.child(["cat-file","--batch"]),this.child.on("error",r=>{this.error=r}),this.child.stdin.on("error",()=>{}),this.child.stderr.resume(),this.iterator=this.child.stdout[Symbol.asyncIterator]()}child;iterator;pending=Buffer.alloc(0);error;async read(e){let t=[],r=e;for(;r;){if(!this.pending.length){let s=await this.iterator.next();if(s.done)throw this.error??new me("missing_source_object","A Git object this repository needs is missing on disk. Canary does not fetch; restore it, then run the command again.");this.pending=s.value}let i=Math.min(r,this.pending.length);t.push(this.pending.subarray(0,i)),this.pending=this.pending.subarray(i),r-=i}return Buffer.concat(t,e)}async get(e){this.child.stdin.write(`${e}
|
|
97
|
+
`);let t="";for(;!t.endsWith(`
|
|
98
|
+
`)&&t.length<128;)t+=(await this.read(1)).toString("ascii");let[r,i,s]=t.trim().split(" "),o=Number(s);(r!==e||i!=="blob"||!Number.isSafeInteger(o)||o<0)&&k("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),o>this.limits.maxObjectBytes&&k("snapshot_limit","A file in this repository is too large to upload.");let a=await this.read(o);return(await this.read(1))[0]!==10&&k("git_source_error","Invalid Git object framing."),a}async close(){this.child.exitCode!==null||this.child.signalCode!==null||(this.child.stdin.end(),this.child.kill(),await new Promise(e=>this.child.on("close",()=>e())))}},En=class{constructor(e,t,r){this.directory=e;this.limits=t;this.signal=r}sizes=new Map;expanded=0;async put(e,t){this.signal?.throwIfAborted(),t.length>this.limits.maxObjectBytes&&k("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.concat([Buffer.from(`${e} ${t.length}\0`),t]),i=Tn("sha1").update(r).digest("hex");if(!this.sizes.has(i)){(this.sizes.size+1>this.limits.maxObjects||this.expanded+t.length>this.limits.maxExpandedBytes)&&k("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(i,t.length),this.expanded+=t.length;let s=se(this.directory,"objects",i.slice(0,2));await ai(s,{recursive:!0}),await ua(se(s,i.slice(2)),await ya(r,{level:6}),{mode:384,flag:"wx"})}return i}};function si(n,e){(n.length>e.maxTreeFiles||n.reduce((s,o)=>s+o.size,0)>e.maxTreeBytes)&&k("snapshot_limit","This repository has too many files, or too many bytes, to upload.");let t=new Map,r=new Map,i=new Map;for(let s of n){On(s.path,e),s.link!==void 0&&i.set(s.path,s.link);let o=s.path.split("/");for(let a=1;a<=o.length;a++){let c=o.slice(0,a).join("/"),l=c.normalize("NFC").toLowerCase();t.has(l)&&t.get(l)!==c&&k("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(c)}.`),t.set(l,c);let d=a<o.length;r.has(c)&&r.get(c)!==d&&k("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(c)}.`),r.set(c,d)}}[...r.values()].filter(Boolean).length+1>e.maxObjects&&k("snapshot_limit","This repository has too many directories to upload.");for(let[s,o]of i){(!o||Buffer.byteLength(o)>e.maxSymlinkBytes||o.startsWith("/")||o.includes("\0")||o.includes("\\")||/^[a-z]:/i.test(o))&&k("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(s)}.`);let a=o.split("/"),c=s.split("/").slice(0,-1),l=0;for(;a.length;){let d=a.shift();if(!d||d===".")continue;if(d===".."){c.length||k("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(s)}.`),c.pop();continue}ui(d)&&k("unsafe_symlink",`Symlink enters Git metadata: ${JSON.stringify(s)}.`),c.push(d);let u=t.get(c.join("/").normalize("NFC").toLowerCase());if(u!==void 0&&i.has(u)){++l>e.maxDepth&&k("unsafe_symlink",`Symlink cycle or excessive chain depth at ${JSON.stringify(s)}.`);let h=i.get(u);(h.startsWith("/")||h.includes("\\")||/^[a-z]:/i.test(h))&&k("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(s)}.`),c.pop(),a.unshift(...h.split("/"))}a.length+c.length>e.maxPathBytes&&k("unsafe_symlink","Symlink expansion exceeds the source limit.")}}}async function oi(n,e){let t=new Map;for(let i of n){let s=i.path.split("/"),o=t;for(let a of s.slice(0,-1))o.has(a)||o.set(a,new Map),o=o.get(a);o.set(s.at(-1),i)}let r=async i=>{let s=[];for(let[o,a]of i)s.push(a instanceof Map?{name:o,mode:"40000",oid:await r(a)}:{name:o,mode:a.mode,oid:a.oid});return s.sort((o,a)=>Buffer.compare(Buffer.from(o.name+(o.mode==="40000"?"/":"")),Buffer.from(a.name+(a.mode==="40000"?"/":"")))),e.put("tree",Buffer.concat(s.map(o=>Buffer.concat([Buffer.from(`${o.mode} ${o.name}\0`),Buffer.from(o.oid,"hex")]))))};return r(t)}var Be=n=>`${n.dev}:${n.ino}:${n.mode}:${n.size}:${n.mtimeMs}:${n.ctimeMs}`;async function di(n,e){let t=e.split("/");for(let r=1;r<=t.length;r++)try{let i=await ia(se(n,...t.slice(0,r)));if(r===t.length)return i;if(!i.isDirectory())return null}catch(i){if(["ENOENT","ENOTDIR"].includes(i.code??""))return null;throw i}return null}async function _a(n,e,t,r){let i=await di(n,e);if(t.set(e,i?Be(i):null),!i||i.isDirectory())return null;if(!i.isFile()&&!i.isSymbolicLink()&&k("unsupported_file",`This is not a regular file or symlink and cannot be uploaded: ${JSON.stringify(e)}.`),i.size>(i.isSymbolicLink()?r.maxSymlinkBytes:r.maxObjectBytes)&&k("snapshot_limit",`This file is too large to upload: ${JSON.stringify(e)}.`),i.isSymbolicLink())return{data:await ca(se(n,e),{encoding:"buffer"}),mode:"120000"};let s=await ci(se(n,e),ei.O_RDONLY|ei.O_NOFOLLOW);try{Be(await s.stat())!==Be(i)&&k("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.");let o=Buffer.alloc(i.size+1),a=0;for(;a<o.length;){let l=await s.read(o,a,o.length-a);if(!l.bytesRead)break;a+=l.bytesRead}return(a!==i.size||Be(await s.stat())!==Be(i))&&k("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped."),{data:o.subarray(0,a),mode:i.mode&73?"100755":"100644"}}finally{await s.close()}}async function va(n,e,t,r,i){let s=Buffer.from(`# v2 git bundle
|
|
99
|
+
${t} refs/canary/base
|
|
100
|
+
${r} refs/canary/head
|
|
101
|
+
|
|
102
|
+
`),o=await ci(e,"wx",384);try{let a=n.child(["pack-objects","--stdout","--revs","--no-reuse-delta","--no-reuse-object","--window=0","--threads=1","--compression=6"]),c=Tn("sha256"),l=0,d="";a.stderr.on("data",f=>{d.length<8192&&(d+=f.toString())}),a.stdin.on("error",()=>{});let u=new Promise((f,p)=>{a.on("close",f),a.on("error",p)});u.catch(()=>{});let h=async f=>{l+=f.length,l>i.maxBundleBytes&&k("snapshot_limit","This repository is too large to upload, even compressed."),c.update(f),await o.writeFile(f)};try{await h(s),a.stdin.end(`${r}
|
|
103
|
+
`);for await(let f of a.stdout)await h(f);return await u!==0&&k("git_source_error",`Cannot package source: ${d.trim()}`),{bytes:l,sha256:c.digest("hex")}}finally{a.kill(),await u.catch(()=>{})}}finally{await o.close()}}async function pt(n,e={}){let t={...ut,...e.limits};for(let[f,p]of Object.entries(t))(!Object.hasOwn(ut,f)||!Number.isSafeInteger(p)||p<=0||p>ut[f])&&k("invalid_limit",`Invalid source snapshot limit ${f}.`);let r=await Lt(n),i=new Ve(r,e.signal),s;try{s=await Lt(await i.text(["rev-parse","--show-toplevel"]))}catch(f){if(e.signal?.aborted)throw f;return k("not_a_git_repository","Run this command inside a Git repository.")}let o=new Ve(s,e.signal),a=await Lt(ti(s,await o.text(["rev-parse","--git-common-dir"]))),c=await o.text(["config","--get-regexp","^(extensions\\.partialclone|remote\\..*\\.promisor|extensions\\.objectformat)$"],!0);c.split(`
|
|
104
|
+
`).some(f=>/^extensions\.objectformat\s+(?!sha1$)/i.test(f))&&k("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(c.split(`
|
|
105
|
+
`).some(f=>/^extensions\.partialclone\s/i.test(f)||/^remote\..*\.promisor(?:\s|$)/i.test(f)&&!/\s(false|no|off|0)$/i.test(f))||(await aa(se(a,"objects","pack")).catch(()=>[])).some(f=>f.endsWith(".promisor")))&&k("partial_clone","This is a partial clone. Canary needs every Git object on disk and will not fetch them; use a full clone.");let l=await Lt(da());(ni(s,l)||ni(a,l))&&k("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let d=await sa(se(l,"canary-source-")),u,h=()=>la(d,{recursive:!0,force:!0});try{let f=await ii(o,e.baseRef),p=ti(s,await o.text(["rev-parse","--git-path","index"])),g=async()=>{try{return Tn("sha256").update(await oa(p)).digest("hex")}catch(w){if(w.code==="ENOENT")return"missing";throw w}},y=await g(),S=new Ve(s,e.signal,!1,{GIT_INDEX_FILE:se(d,"baseline-index")});await S.run(["read-tree",f.baseSha??"--empty"]);let m=f.baseSha?ri(await o.run(["ls-tree","-r","-z","--full-tree",f.baseSha]),!1):[],C=await Rn(S),x=w=>w.split("/").some(A=>A.toLowerCase()===".git"),R=(w,A)=>!A.has(w.path)&&!x(w.path),_=m.filter(w=>R(w,C)),F=async()=>{let w=ri(await o.run(["ls-files","--stage","-z"]),!0),A=await Rn(o),T=w.filter(v=>R(v,A)),de=dt(await o.run(["ls-files","--others","--exclude-standard","-z"])).filter(v=>!x(v)),L=new Set(dt(await o.run(["ls-files","-t","-z"])).filter(v=>v.startsWith("S ")).map(v=>v.slice(2)));return{tracked:T,paths:[...new Set([...T.map(v=>v.path),...de])].sort(),skip:L}},D=await F(),ye=await o.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(_.length>t.maxTreeFiles||D.paths.length>t.maxTreeFiles)&&k("snapshot_limit","This repository has too many files to upload.");for(let w of[..._,...D.tracked])On(w.path,t),w.mode==="160000"&&k("unsupported_submodule",`Submodules cannot be uploaded: ${JSON.stringify(w.path)}.`),["100644","100755","120000"].includes(w.mode)||k("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(w.path)}.`);for(let w of D.paths)w.endsWith("/")&&k("unsupported_submodule",`Nested Git repositories cannot be uploaded: ${JSON.stringify(w)}.`),On(w,t);await lt(S,_.map(w=>w.path),!0),await lt(o,D.paths,!1);let $=se(d,"repository.git");await ai($);let j=new Ve($,e.signal,!0);await j.run(["init","--bare","--quiet","--template="]);let Z=new En($,t,e.signal);u=new An(o,t);let Ce=[],we=[],Y=new Map,ee=async(w,A,T)=>{ka(A,w.path);let de=await Z.put("blob",A);w.oid&&w.oid!==de&&k("invalid_source_object",`Git blob contents do not match their hash: ${JSON.stringify(w.path)}.`);let L=(Y.get(T)??0)+A.length;Y.set(T,L),L>t.maxTreeBytes&&k("snapshot_limit","This repository has too many bytes to upload."),T.push({...w,oid:de,size:A.length,...w.mode==="120000"?{link:li(A)}:{}})};for(let w of _)await ee(w,await u.get(w.oid),Ce);let K=new Map,re=new Map(D.tracked.map(w=>[w.path,w]));for(let w of D.paths){e.signal?.throwIfAborted();let A=await _a(s,w,K,t);if(A){let T=re.get(w),de=!ye&&A.mode!=="120000"&&T&&["100644","100755"].includes(T.mode)?T.mode:A.mode;await ee({path:w,mode:de,oid:""},A.data,we)}else if(K.get(w)===null&&D.skip.has(w)){let T=re.get(w);await ee(T,await u.get(T.oid),we)}}si(Ce,t),si(we,t);let B=await oi(Ce,Z),ae=await oi(we,Z);for(let[w,A]of[[B,Ce],[ae,we]])await j.run(["read-tree",w]),await lt(j,A.map(T=>T.path),!0);let ce=await Z.put("commit",Buffer.from(`tree ${B}
|
|
106
|
+
author ${Mt}
|
|
107
|
+
committer ${Mt}
|
|
108
|
+
|
|
109
|
+
Canary snapshot baseline
|
|
110
|
+
`)),be=await Z.put("commit",Buffer.from(`tree ${ae}
|
|
111
|
+
parent ${ce}
|
|
112
|
+
author ${Mt}
|
|
113
|
+
committer ${Mt}
|
|
114
|
+
|
|
115
|
+
Canary snapshot current
|
|
116
|
+
`)),Ie=se(d,"source.bundle"),le=await va(j,Ie,ce,be,t),Te=await F();(y!==await g()||JSON.stringify(D.paths)!==JSON.stringify(Te.paths)||JSON.stringify([...C].sort())!==JSON.stringify([...await Rn(S)].sort())||JSON.stringify(f)!==JSON.stringify(await ii(o,e.baseRef)))&&k("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped.");for(let[w,A]of K){let T=await di(s,w);(T?Be(T):null)!==A&&k("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}await lt(S,_.map(w=>w.path),!0),await lt(o,D.paths,!1);let Ne=new Map(Ce.map(w=>[w.path,w])),ue=new Map(we.map(w=>[w.path,w])),te=[];for(let w of[...new Set([...Ne.keys(),...ue.keys()])].sort()){let A=Ne.get(w),T=ue.get(w);A?T?(A.oid!==T.oid||A.mode!==T.mode)&&te.push({path:w,status:A.mode==="120000"!=(T.mode==="120000")?"T":"M"}):te.push({path:w,status:"D"}):te.push({path:w,status:"A"})}return await u.close(),u=void 0,{bundlePath:Ie,manifest:{kind:"local_snapshot",version:2,...le,baseTreeHash:B,treeHash:ae,baseSha:ce,headSha:be,provenance:f},files:te,dispose:h}}catch(f){throw await u?.close(),await h(),f}}import{createHash as Oa,randomUUID as Aa}from"node:crypto";import{readFileSync as Ea,renameSync as Ta,rmSync as vi,writeFileSync as Na}from"node:fs";import{createHash as xa}from"node:crypto";import{constants as pi}from"node:fs";import{open as Ca}from"node:fs/promises";import{Readable as Ia}from"node:stream";var H=class extends O{constructor(t,r,i,s,o){super(t,i,s);this.code=r;this.uploadId=o;this.name="SourceUploadError"}},yi="/api/v1/cli/source-uploads",Ft=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,fi=/^[a-f0-9]{40}$/,wi=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],bi=["headSha","branch","baseRef","baseSha","baselineMode"],Nn=(n,e)=>!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===e.length&&e.every(t=>Object.hasOwn(n,t));function Ut(n){if(!Nn(n,wi))return!1;let e=n.provenance;return n.kind==="local_snapshot"&&n.version===2&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&typeof n.bytes=="number"&&Number.isSafeInteger(n.bytes)&&n.bytes>0&&n.bytes<=ut.maxBundleBytes&&[n.baseTreeHash,n.treeHash,n.baseSha,n.headSha].every(t=>typeof t=="string"&&fi.test(t))&&Nn(e,bi)&&[e.headSha,e.baseSha].every(t=>t===null||typeof t=="string"&&fi.test(t))&&[e.branch,e.baseRef].every(t=>t===null||typeof t=="string"&&t.length>0&&t.length<=1024&&!/[\x00-\x1f\x7f]/.test(t))&&["explicit","merge-base","whole-project"].includes(e.baselineMode)}function Ra(n,e){return wi.filter(t=>t!=="provenance").every(t=>n[t]===e[t])&&bi.every(t=>n.provenance[t]===e.provenance[t])}function ft(n,e){if(!Nn(n,["uploadId","expiresAt","status","source"])||typeof n.uploadId!="string"||!Ft.test(n.uploadId)||typeof n.expiresAt!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(n.expiresAt)||!Number.isFinite(Date.parse(n.expiresAt))||!["pending","uploading","completed","cancelled"].includes(n.status)||!Ut(n.source)||e?.uploadId!==void 0&&e.uploadId!==n.uploadId||e?.manifest!==void 0&&!Ra(e.manifest,n.source))throw new H(502,"invalid_upload_response","Canary's answer does not match the upload in progress.","Run the command again to continue the upload.",e?.uploadId);return n}function Si(n){if(!Ft.test(n))throw new H(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${yi}/${n}`}function $a(n,e){return n instanceof H?new H(n.status,n.code,n.message,n.fix,e):n instanceof O?new H(n.status,"source_upload_failed",n.message,n.fix,e):new H(0,"source_upload_failed",n instanceof Error?n.message:"The source upload failed.","Run the command again to continue the upload.",e)}function jt(n){if(n.status==="completed")return n;throw n.status==="cancelled"?new H(410,"source_upload_cancelled","This upload was cancelled.",void 0,n.uploadId):new H(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",n.uploadId)}async function hi(n,e,t={}){let r=await(t.request??I)(Si(n),{...e});return ft(r,{uploadId:n})}async function*ki(n,e,t){let r=0;for(;r<e;){t?.throwIfAborted();let i=Buffer.allocUnsafe(Math.min(64*1024,e-r)),s=await n.read(i,0,i.length,r);if(!s.bytesRead)throw new H(0,"source_changed","The source changed while it was being uploaded. Run the command again.");r+=s.bytesRead,yield i.subarray(0,s.bytesRead)}}async function gi(n,e,t){let r=await n.stat();if(!r.isFile()||r.size!==e.bytes)throw new H(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let i=xa("sha256");for await(let o of ki(n,e.bytes,t))i.update(o);let s=await n.stat();if(i.digest("hex")!==e.sha256||s.size!==r.size||s.mtimeMs!==r.mtimeMs||s.ctimeMs!==r.ctimeMs)throw new H(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function mi(n,e,t,r){let i=Ia.from(ki(n,e.manifest.bytes,e.signal));try{let s=await(r.fetch??fetch)(`${e.baseUrl.replace(/\/+$/,"")}${Si(t)}/content`,{method:"PUT",headers:{...(r.headers??ke)(),authorization:`Bearer ${e.token}`,"content-type":"application/octet-stream","content-length":String(e.manifest.bytes)},body:i,duplex:"half",signal:e.signal,redirect:"error"});if(!s.ok){let o={};try{o=await s.json()}catch{}throw new H(s.status,typeof o.code=="string"?o.code:"source_upload_failed",typeof o.error=="string"?o.error:s.statusText,typeof o.fix=="string"?o.fix:void 0,t)}return jt(ft(await s.json(),{uploadId:t,manifest:e.manifest}))}catch(s){throw s instanceof H?s:new H(0,"source_upload_uncertain","The connection dropped before Canary confirmed the upload.","An earlier upload is still in progress. Run the command again to continue it.",t)}finally{i.destroy()}}async function _i(n,e={}){if(!Ut(n.manifest)||!Ft.test(n.workspaceId)||!Ft.test(n.repositoryId))throw new H(0,"invalid_source_receipt","A captured source, a workspace, and a repository are required before uploading.");let t={token:n.token,baseUrl:n.baseUrl,signal:n.signal},r;if(n.uploadId&&(r=ft(await hi(n.uploadId,t,e),{uploadId:n.uploadId,manifest:n.manifest}),r.status!=="pending"))return jt(r);let i=await Ca(n.bundlePath,pi.O_RDONLY|pi.O_NOFOLLOW);try{if(await gi(i,n.manifest,n.signal),r||(r=ft(await(e.request??I)(yi,{...t,method:"POST",body:{workspaceId:n.workspaceId,repositoryId:n.repositoryId,source:n.manifest}}),{manifest:n.manifest})),n.onReceipt?.(r),r.status!=="pending")return jt(r);try{return await mi(i,n,r.uploadId,e)}catch(s){if(n.signal?.aborted||!(ie(s)||s instanceof O&&s.status===409))throw s;let o=ft(await hi(r.uploadId,t,e),{uploadId:r.uploadId,manifest:n.manifest});return o.status!=="pending"?jt(o):(await gi(i,n.manifest,n.signal),await mi(i,n,r.uploadId,e))}}catch(s){throw r?$a(s,r.uploadId):s}finally{await i.close()}}function xi(n,e,t,r="verify"){let i=Oa("sha256").update(JSON.stringify([t,n,r])).digest("hex");return Pr(e,`source-upload-${i}.json`)}function Ci(n){try{let e=JSON.parse(Ea(n,"utf8"));if(typeof e.uploadId!="string"||!/^[a-f0-9-]{36}$/i.test(e.uploadId)||typeof e.expiresAt!="string"||!Number.isFinite(Date.parse(e.expiresAt)))throw new Error("invalid upload record");return{uploadId:e.uploadId,expiresAt:e.expiresAt}}catch(e){if(e.code!=="ENOENT")throw new H(0,"invalid_upload_receipt","Canary's record of an earlier upload under CANARY_HOME/local-repositories is unreadable.","Fix or remove that file, then run the command again.")}}function Pn(n,e,t,r){let i=xi(n,e,t,r.requestKey),s=Ci(i);s&&(!r.uploadId||s.uploadId===r.uploadId)&&vi(i,{force:!0})}async function Ht(n,e,t,r,i={}){let s=xi(n.manifest,e,t,i.requestKey),o=i.fresh?void 0:Ci(s),a=o&&Date.parse(o.expiresAt)>Date.now()?o.uploadId:void 0,c=await _i({bundlePath:n.bundlePath,manifest:n.manifest,workspaceId:e.workspaceId,repositoryId:t,token:r,baseUrl:e.apiUrl,...a?{uploadId:a}:{},onReceipt:({uploadId:l,expiresAt:d})=>{let u=`${s}.${Aa()}.tmp`;try{Na(u,JSON.stringify({uploadId:l,expiresAt:d})+`
|
|
117
|
+
`,{flag:"wx",mode:384}),Ta(u,s)}finally{vi(u,{force:!0})}}});return{...c.source,uploadId:c.uploadId}}var Ln=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,Pa=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Ri=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,Mn=new Set(["completed","failed","cancelled"]),xe=class extends Error{constructor(t,r,i){super(r);this.code=t;this.fix=i;this.name="VerifyError"}},b=n=>(n??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g," ").trim(),We=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Dt=n=>new Promise(e=>setTimeout(e,n)),$i=3,La=1e3;function Ma(n){if(n===void 0)return;let e=n;try{n==="-"?e=Ii(0,"utf8"):n.startsWith("@")&&(e=Ii(n.slice(1),"utf8"))}catch(t){throw new xe("brief_unreadable",`could not read the brief from ${n==="-"?"stdin":n.slice(1)}: ${t instanceof Error?t.message:String(t)}`,"pass the brief as text, @<file>, or - (stdin)")}return e.trim()===""?void 0:e}function oe(n){return n==="P3"?null:n==="P0"||n==="P1"?n:"P2"}var Oi=n=>n?n.startLine?`${n.file}:${n.startLine}`:n.file:null;function ja(n,e){if(oe(n.materiality)===null)return null;let r=e??null;return n.result==="fail"?{checkRunId:n.checkRunId,kind:"fail",proof:r?.isStatic===!1?"runtime":"source",headline:b(r?.finding?.headline)||b(n.title),summary:b(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:Oi(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:b(r?.finding?.reproduce)||null}:n.result==="blocked"?{checkRunId:n.checkRunId,kind:"blocked",proof:"none",headline:b(n.title),summary:b(r?.verdict?.reasonOneLiner)||(ht[n.blockedReason??""]??""),location:Oi(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}var Ai={P0:0,P1:1,P2:2},ht={setup_install_failure:"the app's dependencies could not be installed in the sandbox",setup_boot_failure:"the app failed to start in the sandbox",health_timeout:"the app never became healthy in the sandbox",runtime_precondition:"a runtime precondition for this check could not be reached",missing_capability:"the sandbox lacks a capability this check needs",missing_required_secret:"a required secret is not configured for this repository"};function Ei(n,e,t){let r=V();I("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...t?{baseUrl:t}:{},body:{outcome:n,...e?{runId:e}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function Ti(n){if(n.status!=="completed"||n.stageB.status==="failed")return 2;let e=n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns;return e>0&&n.stageC.checks.length===e?2:0}async function Fa(n,e,t={}){let r=u=>I(u,{token:e,...t.baseUrl?{baseUrl:t.baseUrl}:{}}),i=new Map,s="",o=new Set,a=!1,c=!1,l=null,d=Date.now();for(;;){let u;try{u=(await r(`/api/v1/red-team/runs/${n}`)).run,l=null}catch(p){if(ie(p)&&(l??=Date.now(),Date.now()-l<Pa)){t.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await Dt(Ln);continue}throw p}for(let p of u.stageC.checks)if(!(!(p.status==="completed"&&(p.result==="fail"||p.result==="blocked"))||i.has(p.checkRunId))){if(!We.test(p.checkRunId)){i.set(p.checkRunId,null);continue}try{i.set(p.checkRunId,await r(`/api/v1/red-team/runs/${n}/checks/${p.checkRunId}/finding`))}catch(y){ie(y)||i.set(p.checkRunId,null)}}for(let p of u.stageC.checks){if(o.has(p.checkRunId)||!(p.status==="completed"||p.status==="failed"||p.status==="cancelled")||oe(p.materiality)===null)continue;o.add(p.checkRunId);let y=i.get(p.checkRunId),S=p.status!=="completed"?"!":p.result==="pass"?"\u2713":p.result==="fail"?"\u2717":"\u23F8",m=p.status!=="completed"?"errored":p.result==="pass"?"passed":p.result==="fail"?y?.isStatic===!1?"verified failure":"finding from the code":"could not verify";t.onProgress?.(`${S} ${m}: ${b(p.title)}`)}u.stageB.status!=="completed"&&(c=!0);let h=u.stageC.checks.length>0||u.stageB.finalChecksCount===0||Mn.has(u.status);!a&&u.stageB.status==="completed"&&h&&(a=!0,t.onProgress?.(Ha(u,c?Date.now()-d:null,i)));let f=Ua(u);if(f!==s&&(t.onProgress?.(f),s=f),Mn.has(u.status)){for(let g=0;g<3;g++){let y=u.stageC.checks.filter(S=>S.status==="completed"&&(S.result==="fail"||S.result==="blocked")&&!i.has(S.checkRunId));if(y.length===0)break;await Dt(Math.min(Ln,1e3));for(let S of y)try{i.set(S.checkRunId,await r(`/api/v1/red-team/runs/${n}/checks/${S.checkRunId}/finding`))}catch(m){(!ie(m)||g===2)&&i.set(S.checkRunId,null)}}let p=u.stageC.checks.filter(g=>g.status==="completed"&&(g.result==="fail"||g.result==="blocked")).sort((g,y)=>Ai[oe(g.materiality)??"P2"]-Ai[oe(y.materiality)??"P2"]).map(g=>ja(g,i.get(g.checkRunId)??null)).filter(g=>g!==null);return{run:u,findings:p}}if(Date.now()-d>Ri)throw new xe("still_running",`run ${n} is still ${u.status} after ${Math.round(Ri/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await Dt(Ln)}}function Ua(n){if(n.status==="queued")return"\u2026 queued";if(n.phase==="stage_b"||n.stageC.checks.length===0){let t=n.stageB.risksFound??0;return`\u2026 analyzing the change${t?` \xB7 ${t} risk${t===1?"":"s"} found`:""}`}return`\u2026 ${n.stageC.completedCheckRuns+n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns}/${n.stageC.checks.length} checks done \xB7 ${n.stageC.results.fail} failed`}function Ha(n,e,t=new Map){let r=n.stageC.checks.filter(u=>oe(u.materiality)!==null),i=u=>u.result==="fail"&&t.get(u.checkRunId)?.isStatic!==!1,s=r.filter(i).length,o=n.stageC.checks.filter(u=>u.status==="failed"||u.status==="cancelled").length,a=r.filter(u=>!i(u)&&u.status!=="failed"&&u.status!=="cancelled").length,c=n.stageC.results.pass+n.stageC.results.blocked+r.filter(u=>u.result==="fail"&&t.get(u.checkRunId)?.isStatic===!1).length,l=Mn.has(n.status)?c>0?"verified in sandboxes":"not run":"verifying in sandboxes";return`${e===null?"analysis done":`analysis done in ${Math.max(1,Math.round(e/6e4))} min`} \xB7 ${Q(s,"finding")} from the code \xB7 ${a} runtime check${a===1?"":"s"}${o?` \xB7 ${o} errored`:""} \xB7 ${l}`}function Da(n,e,t){let r=n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns;if(Ti(n)===2)return`Verification did not complete (${n.status})${r?`: ${Q(r,"check")} errored`:""}; nothing was verified.`;let i=e.filter(d=>d.kind==="fail"&&d.proof==="runtime").length,s=e.filter(d=>d.kind==="fail"&&d.proof==="source").length,o=e.filter(d=>d.kind==="blocked").length,a=n.stageC.results.pass,c=[`${Q(i,"verified failure")}`,`${Q(a,"check")} passed`,`${Q(s,"finding")} from the code (source-reasoned, not run)`,...o?[`${o} could not be verified`]:[],`${Q(r,"check")} errored`],l=a===0&&i===0&&o===0&&r===0;return`${c.join("; ")}.${l?" Nothing in this change was executed.":""}${Ga(t)}`}function Ga(n){let e=n?n.reverifiable-n.carried:0;return!n||e<=0?"":` ${e} of run ${n.sourceRunId.slice(0,8)}'s ${Q(n.reverifiable,"failed check")} ${e===1?"was":"were"} not re-run (reported disputed or skipped).`}function Ba(n,e){let t=n.slice(0,8);if(!e)return`re-checking the failed set of run ${t} \u2014`;let r=`of run ${t}'s ${Q(e.reverifiable,"failed check")}`;return e.excludedReported>0?`re-checking ${e.carried} ${r} (${e.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${e.reverifiable} failed checks of run ${t} \u2014`}function Va(n,e,t,r){return{ok:!0,runId:n.runId,treeHash:e,status:n.status,findings:t,summary:Da(n,t,r),failed:t.filter(i=>i.kind==="fail").length,passed:n.stageC.results.pass,blocked:t.filter(i=>i.kind==="blocked").length,errored:n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns,exitCode:Ti(n),failureMessage:n.failure?.publicMessage??null,...r?{reverify:r}:{}}}var Wa={fail:"\u2717",blocked:"\u23F8"},Ja={fail:"",blocked:" (could not be verified)"},Q=(n,e)=>`${n} ${e}${n===1?"":"s"}`;function qa(n){let e=[];if(e.push(`Receipt ${Pt(n.treeHash)} \xB7 run ${b(n.runId)}`),n.exitCode===2)return e.push(`\u2717 Verification did not complete (${b(n.status)})${n.failureMessage?`: ${b(n.failureMessage)}`:""}`),n.errored>0&&e.push(` ${Q(n.errored,"check")} errored \u2014 nothing was verified; this is not a clean result.`),e.push(` Run \`canary verify\` again; if it repeats, report run ${b(n.runId)}.`),e.join(`
|
|
118
|
+
`);let t=[n.failed?`\u2717 ${Q(n.failed,"finding")}`:"",n.passed?`\u2713 ${n.passed} passed`:"",n.blocked?`\u23F8 ${n.blocked} could not be verified`:""].filter(Boolean);n.findings.length===0&&n.errored===0?e.push(`\u2713 Clean \u2014 no findings in this change${n.passed?` \xB7 ${n.passed} passed`:""}.`):e.push(`${n.failed?"":"\u2713 No verified findings"}${n.failed||t.length===0?"":" \xB7 "}${t.join(" \xB7 ")}`);for(let r of n.findings)e.push(""),e.push(`${Wa[r.kind]} ${b(r.headline)}${Ja[r.kind]}`),r.summary&&e.push(` ${b(r.summary)}`),r.location&&e.push(` \u2192 ${b(r.location)}`),r.fix&&e.push(` reproduce: ${b(r.fix)}`);return n.errored>0&&e.push(`
|
|
119
|
+
(${Q(n.errored,"check")} errored and could not be verified.)`),e.push(`
|
|
97
120
|
${n.summary}`),e.join(`
|
|
98
|
-
`)}function
|
|
99
|
-
fix: ${
|
|
100
|
-
run: ${y(o)}`:""}`)}process.exitCode=r}async function oo(n,e,t,i,r={}){let s=r.baseUrl?{baseUrl:r.baseUrl}:{};ot({cwd:n,agent:t,mode:i!==void 0?"reverify_failed":"full"});let o=(p,_,k,v=3,b={})=>{W(t,p,_,k,v,b),yi(`exit${v}:${p}`,b.runId,r.baseUrl)},a=U();if(!a)return o("not_logged_in","Not logged in","run `canary login` first");if(i!==void 0&&!Ye.test(i))return o("bad_run_id",`"${i}" is not a run id`,"pass the run id from your last `canary verify` (see the receipt line), e.g. `canary verify --failed <run-id>`");let c,l;try{c=Ys(e),l=di(n)}catch(p){if(p instanceof M||p instanceof Ie)return o(p.code,p.message,p.fix);throw p}let u=de(l.root);if(!u)return o("no_git_remote","no GitHub origin found","run inside the checkout you want verified");try{we(u)}catch(p){if(p instanceof V)return o(p.code,p.message,p.fix);throw p}c===void 0&&i===void 0&&console.error("! No --brief given \u2014 Canary will attack the change using only the commit messages. A brief with acceptance criteria and must-not-break finds more."),me();let f=p=>{t?console.error(` ${p}`):console.log(` ${p}`)},h,g;{let p,_=O().team?.id,k=l.branch.replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256),v=()=>I("/api/v1/cli/runs",{method:"POST",token:a,...s,body:{repoFullName:`${u.owner}/${u.name}`,..._?{workspaceId:_}:{},baseSha:l.baseSha,treeHash:l.treeHash,headSha:l.headSha,patchBase64:l.patch.toString("base64"),...c!==void 0?{brief:c}:{},commitMessages:l.commitMessages,diffStats:l.diffStats,...k?{branch:k}:{},...i!==void 0?{reverifySourceRunId:i}:{}}});try{for(let w=1;;w+=1)try{p=await v();break}catch(x){if(w>=hi||!ue(x))throw x;f(`${x.message} \u2014 retrying (${w}/${hi-1})`),await pt(qs*w)}}catch(w){if(w instanceof E){let x=!ue(w)&&w.status>=400&&w.status<500,A=w.fix??(w.status===401||w.status===403?"run `canary login`":x?void 0:"run `canary verify` again in a minute"),N={httpStatus:w.status,...w.runId?{runId:w.runId}:{}};return x?W(t,"api_error",w.message,A,3,N):o("api_error",w.message,A,2,N)}throw w}if(!Ye.test(p.runId))return W(t,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);h=p.runId;let b=i?to(i,p.reverify):p.created?"submitted":"same tree as an existing run \u2014 following it:";f(`${b} ${ft(l.treeHash)} \xB7 run ${h} \xB7 ${J(l.files.length,"file")}`),g=p.reverify}let d;try{d=await Ks(h,a,{...s,onProgress:f})}catch(p){if(p instanceof Ie)return o(p.code,p.message,p.fix,2,{runId:h});if(p instanceof E){let _=p.status===401||p.status===403;return o("api_error",`${p.message} \u2014 run ${h} may still be running`,p.fix??(_?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:h,httpStatus:p.status})}throw p}let m=no(d.run,l.treeHash,d.findings,g);console.log(t?JSON.stringify(m):so(m)),process.exitCode=m.exitCode}function bi(n){n.command("verify").description("Pressure-test your local change set with Canary (no commit or PR needed)").option("--brief <text>","what the change intends and must not break (text, @file, or - for stdin)").option("--failed <runId>","re-check only the failed checks of an earlier run, against your current (fixed) code").option("--json","output one JSON document").option("--dir <path>","repo directory (default: current directory)").action(async e=>{try{await oo(e.dir??process.cwd(),e.brief,e.json===!0,e.failed)}catch(t){W(e.json===!0,"internal_error",t instanceof Error?t.message:String(t),void 0,2),yi("exit2:internal_error")}})}var ao={happy_path:"Core flow",boundary:"Edge case",failure:"Failure handling",security:"Security",parity:"Old-vs-new behavior",performance:"Performance",compatibility:"Compatibility",lifecycle:"Lifecycle",modality:"Interface"},co=15e3;function lo(n){return n&&ao[n]||"Other"}var uo=n=>{let e=n?.finding?.nextActionCodeRef??n?.codeRefs?.[0]??n?.checkReadback?.codeRefs?.[0]??null;return e?{file:e.file,line:e.startLine??null}:null},fo=n=>(Array.isArray(n?.evidence)?n.evidence:[]).filter(e=>e&&e.media&&typeof e.media.url=="string").map(e=>({kind:y(e.modality)||"evidence",caption:y(e.caption),url:e.media.url,expiresAt:e.media.expiresAt??null}));function po(n,e,t){if(n.status!=="completed"||Q(n.materiality)===null)return null;let i=e??null,r=i?.isStatic===!0?"source":"runtime",s=n.result==="pass"?"passed":n.result==="fail"?"failed":"could_not_run",o=y(i?.assertion)||null;return{checkRunId:n.checkRunId,checkUrl:`${t}/checks/${n.checkRunId}`,scenarioId:n.stageBCheckId??n.checkRunId,category:lo(i?.lane),title:y(n.title),proof:r,status:s,whatWasTried:r==="source"?y(i?.finding?.whatWasTested)||null:y(i?.finding?.reproduce??i?.finding?.whatWasTested)||null,expected:o||y(i?.finding?.whatWasTested)||null,observed:y(i?.finding?.headline??i?.verdict?.reasonOneLiner)||null,assertion:o,location:uo(i),evidence:fo(i),fix:r==="source"&&y(i?.finding?.reproduce)||null,reason:s==="could_not_run"&&(y(i?.verdict?.reasonOneLiner)||ze[n.blockedReason??""])||null}}async function ki(n,e,t){let i=new Map,r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;for(let s of e)if(!(s.status!=="completed"||i.has(s.checkRunId)||!r.test(s.checkRunId)))try{i.set(s.checkRunId,await I(`/api/v1/red-team/runs/${n}/checks/${s.checkRunId}/finding`,{token:t.token,signal:AbortSignal.timeout(co),...t.baseUrl?{baseUrl:t.baseUrl}:{}}))}catch{i.set(s.checkRunId,null)}return i}function _i(n,e,t){let i=n.stageC.checks.map(r=>po(r,e.get(r.checkRunId)??null,t.runUrl)).filter(r=>r!==null);return{runId:n.runId,runUrl:t.runUrl,repo:t.repo,treeHash:n.target.treeHash??"",files:t.files,reverifySourceRunId:n.reverifySourceRunId??null,startedAt:n.startedAt??null,completedAt:n.completedAt??null,checks:i,passed:i.filter(r=>r.status==="passed").length,failed:i.filter(r=>r.status==="failed").length,couldNotRun:i.filter(r=>r.status==="could_not_run").length,errored:n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns}}var Si=new Set(["completed","failed","cancelled"]);function vi(n){return Si.has(n.status)?null:n.status==="queued"?"queued":n.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function Ci(n){return n.status==="failed"||n.status==="cancelled"?"errored":n.status!=="completed"?n.status==="running"?"running":"pending":n.result==="pass"?"passed":n.result==="fail"?"failed":"could_not_run"}async function Kt(n,e,t,i,r={}){let s=U();if(!s)return W(n,"not_logged_in","Not logged in","run `canary login` first",3),null;if(e.some(o=>!Ye.test(o)))return W(n,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await I(t,{token:s,...i?{baseUrl:i}:{},...r})}catch(o){if(o instanceof E){if(o.status===404)return W(n,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let a=!ue(o)&&o.status>=400&&o.status<500,c=o.fix??(o.status===401?"run `canary login`":a?void 0:"run the command again in a minute");return W(n,"api_error",o.message,c,a?3:2,{httpStatus:o.status}),null}throw o}}var xi=n=>{if(!n?.file)return"";let e=n.startLine?`:${n.startLine}`:"",t=n.startLine&&n.endLine&&n.endLine>n.startLine?`-${n.endLine}`:"";return`${y(n.file)}${e}${t}`};async function ho(n,e,t){let i=await Kt(e,[n],`/api/v1/red-team/runs/${n}`,t);if(!i)return;let r=i.run,s=i.repository?.fullName??"";if(e){let l=r.stageC.checks.filter(g=>Q(g.materiality)!==null).map(g=>({checkRunId:g.checkRunId,scenarioId:g.stageBCheckId??g.checkRunId,title:y(g.title),status:Ci(g)})),u={runId:r.runId,status:r.status,progress:vi(r),treeHash:r.target.treeHash??"",repo:s,reverifySourceRunId:r.reverifySourceRunId??null,startedAt:r.startedAt??null,completedAt:r.completedAt??null,failureMessage:r.failure?.publicMessage??null,checks:l,passed:l.filter(g=>g.status==="passed").length,failed:l.filter(g=>g.status==="failed").length,couldNotRun:l.filter(g=>g.status==="could_not_run").length,errored:r.stageC.failedCheckRuns+r.stageC.cancelledCheckRuns},f={},h=U();if(Si.has(r.status)&&h){let g=await ki(n,r.stageC.checks,{token:h,...t?{baseUrl:t}:{}});f=_i(r,g,{runUrl:`${ee().replace(/\/+$/,"")}/runs/${n}`,repo:s,files:null})}return void console.log(JSON.stringify({ok:!0,...u,...f}))}let o=vi(r),a=[`run ${y(r.runId)} \xB7 ${y(r.status)}${o?` \xB7 ${o}`:""}${r.target.treeHash?` \xB7 tree ${y(r.target.treeHash).slice(0,12)}`:""}`];r.failure?.publicMessage&&a.push(` ${y(r.failure.publicMessage)}`);let c=r.stageC;a.push(`checks ${c.checks.length} \xB7 ${c.results.pass} passed \xB7 ${c.results.fail} failed \xB7 ${c.results.blocked} could not verify \xB7 ${c.failedCheckRuns+c.cancelledCheckRuns} errored`);for(let l of c.checks){let u=Ci(l),f=u==="could_not_run"?"could not verify":u,h=l.result==="blocked"?ze[l.blockedReason??""]:void 0;a.push(` ${Q(l.materiality)??"P3"} ${f.padEnd(16)} ${y(l.title)} ${y(l.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
|
|
101
|
-
`))}async function
|
|
102
|
-
`))}async function
|
|
103
|
-
Input needed: ${
|
|
104
|
-
${
|
|
121
|
+
`)}function q(n,e,t,r,i,s={}){if(n)console.log(JSON.stringify({ok:!1,error:e,message:t,...r?{fix:r}:{},exitCode:i,...s}));else{let o=typeof s.runId=="string"?s.runId:null;console.error(`\u2717 ${b(t)}${r?`
|
|
122
|
+
fix: ${b(r)}`:""}${o?`
|
|
123
|
+
run: ${b(o)}`:""}`)}process.exitCode=i}async function Ya(n,e,t,r,i={}){let s={baseUrl:i.baseUrl??W()};Ct({cwd:n,agent:t,mode:r!==void 0?"reverify_failed":"full"});let o=(m,C,x,R=3,_={})=>{q(t,m,C,x,R,_),Ei(`exit${R}:${m}`,_.runId,s.baseUrl)},a=V();if(!a)return o("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!We.test(r))return o("bad_run_id",`"${r}" is not a run id`,"pass the run id from your last `canary verify` (see the receipt line), e.g. `canary verify --failed <run-id>`");let c,l;try{c=Ma(e),l=await pt(n,{baseRef:i.baseRef})}catch(m){if(m instanceof me||m instanceof xe)return o(m.code,m.message,m.fix);throw m}if(l.manifest.treeHash===l.manifest.baseTreeHash&&r===void 0)return await l.dispose(),o("nothing_to_verify","The current source matches the selected baseline","make a change, or choose a different baseline with --base <ref>");let d,u,h;try{d=await it(n,a,s.baseUrl),u=await rt({...d,token:a});let m=AbortSignal.timeout(3e3);if((await Ot(d,a,m).catch(x=>{throw m.aborted?new O(0,"Checking this repository's setup timed out","run `canary verify` again"):x}))?.state!=="ready")throw new xe("setup_required",`This repository isn't set up for you in ${b(u.workspace.name)} yet`,"run `canary setup`");h=await Ht(l,d,u.repositoryId,a,{fresh:!0})}catch(m){if(m instanceof E||m instanceof xe)return o(m.code,m.message,"fix"in m?m.fix:void 0);if(m instanceof O)return o("api_error",m.message,m.fix,m.status>=400&&m.status<500?3:2);throw m}finally{await l.dispose()}c===void 0&&r===void 0&&console.error("! No --brief given \u2014 Canary will attack the change using the submitted source and baseline. A brief with acceptance criteria and must-not-break finds more."),je();let f=m=>{t?console.error(` ${m}`):console.log(` ${m}`)};l.manifest.provenance.baselineMode==="whole-project"?f("No comparison branch found: reviewing the whole eligible project against an empty baseline."):f(`Baseline: ${b(l.manifest.provenance.baseRef)} \xB7 source ${Pt(l.manifest.treeHash)}`);let p,g;{let m,C=(l.manifest.provenance.branch??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256),x=()=>I("/api/v1/cli/runs",{method:"POST",token:a,...s,body:{repositoryId:u.repositoryId,workspaceId:d.workspaceId,source:h,...c!==void 0?{brief:c}:{},...C?{branch:C}:{},...r!==void 0?{reverifySourceRunId:r}:{}}});try{for(let _=1;;_+=1)try{m=await x();break}catch(F){if(_>=$i||!ie(F)||F instanceof O&&F.runId&&We.test(F.runId))throw F;f(`${F.message} \u2014 retrying (${_}/${$i-1})`),await Dt(La*_)}}catch(_){if(_ instanceof O){let F=!ie(_)&&_.status>=400&&_.status<500,D=_.fix??(_.status===401||_.status===403?"run `canary login`":F?void 0:"run `canary verify` again in a minute"),ye={httpStatus:_.status,..._.runId?{runId:_.runId}:{}};return F?q(t,"api_error",_.message,D,3,ye):o("api_error",_.message,D,2,ye)}throw _}if(m.treeHash!==l.manifest.treeHash||m.headSha!==l.manifest.headSha)return q(t,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!We.test(m.runId))return q(t,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);p=m.runId;let R=r?Ba(r,m.reverify):m.created?"submitted":"same verification inputs as an existing run \u2014 following it:";f(`${R} ${Pt(l.manifest.treeHash)} \xB7 run ${p} \xB7 ${Q(l.files.length,"file")}`),g=m.reverify}let y;try{y=await Fa(p,a,{...s,onProgress:f})}catch(m){if(m instanceof xe)return o(m.code,m.message,m.fix,2,{runId:p});if(m instanceof O){let C=m.status===401||m.status===403;return o("api_error",`${m.message} \u2014 run ${p} may still be running`,m.fix??(C?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:p,httpStatus:m.status})}throw m}let S={...Va(y.run,l.manifest.treeHash,y.findings,g),source:l.manifest,repositoryId:u.repositoryId};console.log(t?JSON.stringify(S):qa(S)),process.exitCode=S.exitCode}function Ni(n){n.command("verify").description("Pressure-test your local change set with Canary (no commit or PR needed)").option("--brief <text>","what the change intends and must not break (text, @file, or - for stdin)").option("--failed <runId>","re-check only the failed checks of an earlier run, against your current (fixed) code").option("--json","output one JSON document").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","compare directly with a local commit (use HEAD for worktree changes only)").action(async e=>{try{await Ya(e.dir??process.cwd(),e.brief,e.json===!0,e.failed,{baseRef:e.base})}catch(t){q(e.json===!0,"internal_error",t instanceof Error?t.message:String(t),void 0,2),Ei("exit2:internal_error")}})}var za={happy_path:"Core flow",boundary:"Edge case",failure:"Failure handling",security:"Security",parity:"Old-vs-new behavior",performance:"Performance",compatibility:"Compatibility",lifecycle:"Lifecycle",modality:"Interface"},Ka=15e3;function Xa(n){return n&&za[n]||"Other"}var Qa=n=>{let e=n?.finding?.nextActionCodeRef??n?.codeRefs?.[0]??n?.checkReadback?.codeRefs?.[0]??null;return e?{file:e.file,line:e.startLine??null}:null},Za=n=>(Array.isArray(n?.evidence)?n.evidence:[]).filter(e=>e&&e.media&&typeof e.media.url=="string").map(e=>({kind:b(e.modality)||"evidence",caption:b(e.caption),url:e.media.url,expiresAt:e.media.expiresAt??null}));function ec(n,e,t){if(n.status!=="completed"||oe(n.materiality)===null)return null;let r=e??null,i=r?.isStatic===!0?"source":"runtime",s=n.result==="pass"?"passed":n.result==="fail"?"failed":"could_not_run",o=b(r?.assertion)||null;return{checkRunId:n.checkRunId,checkUrl:`${t}/checks/${n.checkRunId}`,scenarioId:n.stageBCheckId??n.checkRunId,category:Xa(r?.lane),title:b(n.title),proof:i,status:s,whatWasTried:i==="source"?b(r?.finding?.whatWasTested)||null:b(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:o||b(r?.finding?.whatWasTested)||null,observed:b(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:o,location:Qa(r),evidence:Za(r),fix:i==="source"&&b(r?.finding?.reproduce)||null,reason:s==="could_not_run"&&(b(r?.verdict?.reasonOneLiner)||ht[n.blockedReason??""])||null}}async function Pi(n,e,t){let r=new Map,i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;for(let s of e)if(!(s.status!=="completed"||r.has(s.checkRunId)||!i.test(s.checkRunId)))try{r.set(s.checkRunId,await I(`/api/v1/red-team/runs/${n}/checks/${s.checkRunId}/finding`,{token:t.token,signal:AbortSignal.timeout(Ka),...t.baseUrl?{baseUrl:t.baseUrl}:{}}))}catch{r.set(s.checkRunId,null)}return r}function Li(n,e,t){let r=n.stageC.checks.map(i=>ec(i,e.get(i.checkRunId)??null,t.runUrl)).filter(i=>i!==null);return{runId:n.runId,runUrl:t.runUrl,repo:t.repo,treeHash:n.target.treeHash??"",files:t.files,reverifySourceRunId:n.reverifySourceRunId??null,startedAt:n.startedAt??null,completedAt:n.completedAt??null,checks:r,passed:r.filter(i=>i.status==="passed").length,failed:r.filter(i=>i.status==="failed").length,couldNotRun:r.filter(i=>i.status==="could_not_run").length,errored:n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns}}var Ui=new Set(["completed","failed","cancelled"]);function Mi(n){return Ui.has(n.status)?null:n.status==="queued"?"queued":n.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function ji(n){return n.status==="failed"||n.status==="cancelled"?"errored":n.status!=="completed"?n.status==="running"?"running":"pending":n.result==="pass"?"passed":n.result==="fail"?"failed":"could_not_run"}async function jn(n,e,t,r,i={}){let s=V();if(!s)return q(n,"not_logged_in","Not logged in","run `canary login` first",3),null;if(e.some(o=>!We.test(o)))return q(n,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await I(t,{token:s,...r?{baseUrl:r}:{},...i})}catch(o){if(o instanceof O){if(o.status===404)return q(n,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let a=!ie(o)&&o.status>=400&&o.status<500,c=o.fix??(o.status===401?"run `canary login`":a?void 0:"run the command again in a minute");return q(n,"api_error",o.message,c,a?3:2,{httpStatus:o.status}),null}throw o}}var Fi=n=>{if(!n?.file)return"";let e=n.startLine?`:${n.startLine}`:"",t=n.startLine&&n.endLine&&n.endLine>n.startLine?`-${n.endLine}`:"";return`${b(n.file)}${e}${t}`};async function tc(n,e,t){let r=await jn(e,[n],`/api/v1/red-team/runs/${n}`,t);if(!r)return;let i=r.run,s=r.repository?.fullName??"";if(e){let l=i.stageC.checks.filter(f=>oe(f.materiality)!==null).map(f=>({checkRunId:f.checkRunId,scenarioId:f.stageBCheckId??f.checkRunId,title:b(f.title),status:ji(f)})),d={runId:i.runId,status:i.status,progress:Mi(i),treeHash:i.target.treeHash??"",repo:s,reverifySourceRunId:i.reverifySourceRunId??null,startedAt:i.startedAt??null,completedAt:i.completedAt??null,failureMessage:i.failure?.publicMessage??null,checks:l,passed:l.filter(f=>f.status==="passed").length,failed:l.filter(f=>f.status==="failed").length,couldNotRun:l.filter(f=>f.status==="could_not_run").length,errored:i.stageC.failedCheckRuns+i.stageC.cancelledCheckRuns},u={},h=V();if(Ui.has(i.status)&&h){let f=await Pi(n,i.stageC.checks,{token:h,...t?{baseUrl:t}:{}});u=Li(i,f,{runUrl:`${$e().replace(/\/+$/,"")}/runs/${n}`,repo:s,files:null})}return void console.log(JSON.stringify({ok:!0,...d,...u}))}let o=Mi(i),a=[`run ${b(i.runId)} \xB7 ${b(i.status)}${o?` \xB7 ${o}`:""}${i.target.treeHash?` \xB7 tree ${b(i.target.treeHash).slice(0,12)}`:""}`];i.failure?.publicMessage&&a.push(` ${b(i.failure.publicMessage)}`);let c=i.stageC;a.push(`checks ${c.checks.length} \xB7 ${c.results.pass} passed \xB7 ${c.results.fail} failed \xB7 ${c.results.blocked} could not verify \xB7 ${c.failedCheckRuns+c.cancelledCheckRuns} errored`);for(let l of c.checks){let d=ji(l),u=d==="could_not_run"?"could not verify":d,h=l.result==="blocked"?ht[l.blockedReason??""]:void 0;a.push(` ${oe(l.materiality)??"P3"} ${u.padEnd(16)} ${b(l.title)} ${b(l.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
|
|
124
|
+
`))}async function nc(n,e,t,r){let i=await jn(t,[n,e],`/api/v1/red-team/runs/${n}/checks/${e}/finding`,r);if(!i)return;if(t)return void console.log(JSON.stringify({ok:!0,runId:n,checkRunId:e,...i}));let s=[];s.push(b(i.finding?.headline)||"(no finding written for this check yet)"),i.verdict&&s.push(`verdict: ${b(i.verdict.result)}${i.verdict.reasonOneLiner?` \u2014 ${b(i.verdict.reasonOneLiner)}`:""}${i.isStatic?" (reasoned from the code, not run)":""}`),i.assertion&&s.push(`assertion: ${b(i.assertion)}`),i.observable&&s.push(`observable: ${b(i.observable)}`),i.checkReadback?.whyThisCheck&&s.push(`why this check: ${b(i.checkReadback.whyThisCheck)}`),i.finding?.whatWasTested&&s.push(`tested: ${b(i.finding.whatWasTested)}`),i.finding?.reproduce&&s.push(`reproduce: ${b(i.finding.reproduce)}`),i.finding?.nextActionCodeRef&&s.push(`\u2192 ${Fi(i.finding.nextActionCodeRef)}`);for(let o of i.codeRefs??[])s.push(` ref ${Fi(o)}${o.reason?` \u2014 ${b(o.reason)}`:""}`);for(let o of i.evidence??[])s.push(` evidence ${b(o.modality)}: ${b(o.caption)}${o.media?` ${b(o.media.url)}`:o.failureReason?` (${b(o.failureReason)})`:""}`);for(let o of i.verdict?.limitations??[])s.push(` limitation: ${b(o)}`);i.network?.failures?.length&&s.push(` network failures: ${i.network.failures.length}`),console.log(s.join(`
|
|
125
|
+
`))}async function rc(n,e,t,r,i,s){if(await jn(i,[n,e],`/api/v1/red-team/runs/${n}/checks/${e}/report`,s,{method:"POST",body:{reported:t,...r?{note:r}:{}}})){if(i)return void console.log(JSON.stringify({ok:!0,runId:n,checkRunId:e,reported:t}));console.log(`reported ${t}${r?`: ${b(r)}`:""}`)}}function Hi(n){n.command("run <runId>").description("Show a verify run: status and every check with its verdict").option("--json","print one JSON document: status, progress, every check with its verdict, and the report fields once the run has finished").action(async(e,t)=>{try{await tc(e,t.json===!0)}catch(r){q(t.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),n.command("check <runId> <checkRunId>").description("Show one check in full: verdict, what was tested, reproduce steps, code refs, evidence \u2014 or report what you did with it").option("--json","print the server's finding body, unchanged, under an ok:true envelope with runId and checkRunId").option("--fixed","report: you fixed the behaviour this finding describes").option("--disputed <why>","report: the finding is not a real problem, and why").option("--skipped <why>","report: you did not act on it, and why").action(async(e,t,r)=>{try{let i=[r.fixed?"fixed":null,r.disputed!==void 0?"disputed":null,r.skipped!==void 0?"skipped":null].filter(Boolean);if(i.length>1)return q(r.json===!0,"bad_report","report exactly one of --fixed, --disputed, --skipped",void 0,3);if(i.length===1){let s=(i[0]==="disputed"?r.disputed:i[0]==="skipped"?r.skipped:void 0)?.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").trim();return s!==void 0&&!s?q(r.json===!0,"bad_report",`--${i[0]} needs a reason`,void 0,3):await rc(e,t,i[0],s,r.json===!0)}await nc(e,t,r.json===!0)}catch(i){q(r.json===!0,"internal_error",i instanceof Error?i.message:String(i),void 0,2)}})}import{readFileSync as dc,unlinkSync as pc,writeFileSync as fc}from"node:fs";import{basename as hc,join as gc}from"node:path";import{setTimeout as mc}from"node:timers/promises";import{emitKeypressEvents as ic}from"node:readline";var sc=36,oc=12,Di=64*1024,Fn=new Intl.Segmenter(void 0,{granularity:"grapheme"}),ac={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},cc={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function Gt(n){let e=Math.max(0,Math.floor(n));return e<60?`${e}s`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`}function lc(n,e){let t="";for(let{segment:r}of[...Fn.segment(N(n))].reverse()){if(st(r+t)>e)break;t=r+t}return t}function Gi(n,e,t){let r=n.question,i=Math.max(1,e-5),s=(c,l="text")=>` ${ot(N(c),l,t)}`,o=0;if(r.secret){for(let c of Fn.segment(n.input??""))if(++o===24)break}let a=r.secret?"\u2022".repeat(o):lc(n.input??"",Math.max(1,i-2));return[s("CANARY \xB7 SETUP","gold"),s(`${n.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${Gt(n.seconds)}`),s(`CLI workspace ${n.workspace}`,"muted"),"",s(r.key,"gold"),...ve(r.prompt,i).map(c=>s(c)),s(n.inputActive?`\u203A ${a||(r.secret?"(hidden)":"")}`:n.inputSubmitted?"Value captured locally.":"Input deferred","muted"),s(n.inputNotice??(r.secret?"Your value stays hidden.":""),"muted"),s(n.inputActive?"Enter submit \xB7 Esc/Ctrl+C later":n.inputSubmitted?"Waiting for verification to continue.":"Run canary setup to resume.","muted")]}function uc(n,e,t,r){let i=Math.max(1,e-5),s=Math.max(1,t-2),o=n.outcome?cc[n.outcome.status]:n.question?"Your input is needed":ac[n.status],a=n.outcome?.status==="green"?"green":"gold",c=(u,h="text")=>ot(N(u),h,r),l;if(s<=3)l=[c(o,a),c(`Elapsed ${Gt(n.seconds)}`,"muted")].slice(0,s);else if(n.question&&!n.outcome)l=Gi(n,e,r);else{let u=n.seconds%1.6,h=!n.outcome&&["pending","running"].includes(n.status)&&u<1.4?Math.sin(u/1.4*Math.PI*2)*Math.sin(u/1.4*Math.PI):0,f=Ge[Math.max(0,Math.min(16,Math.round(h*10)+8))];if(e>=76&&t>=23){let p={1:c("CANARY \xB7 SETUP","gold"),3:c(o,a),5:c(`Elapsed ${Gt(n.seconds)}`,"muted")};l=["",...f.map((g,y)=>` ${c(g,a)} ${p[y]??""}`)]}else l=[` ${c("CANARY \xB7 SETUP","gold")}`,` ${c(o,a)}`,` ${c(`Elapsed ${Gt(n.seconds)}`,"muted")}`];l.push("",` ${c(`Repository ${n.repository}`)}`,` ${c(`CLI workspace ${n.workspace}`)}`),n.detail&&!n.outcome&&l.push(...ve(n.detail,i).map(p=>` ${c(p,"muted")}`)),n.outcome||l.push("",` ${c("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(l.length>s?[...l.slice(0,Math.max(0,s-2)),...l.slice(-2)]:l).map(u=>Tt(u,Math.max(1,e-1)))}function Bi(n){if(n.json||!n.animation||!process.stdin.isTTY||!process.stdout.isTTY||!process.stderr.isTTY||process.env.CI||process.env.TERM==="dumb"||process.env.CANARY_NO_ANIMATION)return;let e=process.stderr,t=process.stdin,r=!process.env.NO_COLOR,i=He(e),s=performance.now(),o={...n,status:"submitting",seconds:0},a=!1,c=!1,l,d=!1,u,h,f=()=>({columns:e.columns||80,rows:e.rows||24}),p=$=>{try{e.write($)}catch{}},g=()=>p(`${U}0m${U}?25h`);function y(){if(a||d)return;o.seconds=(performance.now()-s)/1e3;let{columns:$,rows:j}=f();try{i.render(uc(o,$,j,r))}catch{R()}}function S(){let{columns:$,rows:j}=f();return t.isTTY&&$>=sc&&j>=oc&&Gi(o,$,!1).length<=j-2}function m(){let $=o.question;if(!$)return;d=!0;try{i.render([])}catch{}let j=Math.max(1,f().columns-3);p(`
|
|
126
|
+
Input needed: ${N($.key)}
|
|
127
|
+
${ve($.prompt,j).join(`
|
|
105
128
|
`)}
|
|
106
129
|
|
|
107
130
|
Answer with: canary setup --answer '<value>'
|
|
108
|
-
`)}function
|
|
131
|
+
`)}function C(){h&&!S()?h.settle(null,!0):y()}function x(){!a||h||c||(c=!0,process.off("SIGINT",F),process.off("SIGTERM",D),process.off("exit",R),g(),l!==void 0&&(p(`
|
|
109
132
|
Stopped watching. Run canary setup to resume verification.
|
|
110
|
-
`),process.exit(l)))}function
|
|
111
|
-
`)),
|
|
112
|
-
Warning: ${
|
|
133
|
+
`),process.exit(l)))}function R(){a||(a=!0,clearInterval(u),e.off("resize",C),h?.settle(null),x())}function _($){l=$,R(),x()}function F(){h?h.settle(null):_(130)}function D(){_(143)}async function ye($,j){return a||h||j?.aborted?null:(o.question={...$},o.input="",o.inputActive=!0,o.inputSubmitted=!1,o.inputNotice=void 0,d=!1,S()?new Promise(Z=>{let Ce=t.isRaw,we=t.readableFlowing===!0,Y="",ee="",K=!1,re=!1,B="",ae=!1,ce=!1,be=!1,Ie=!1,le;function Te(L,v=!1){Ie||(le={answer:le&&L!==null?le.answer:L,showStatic:v||le?.showStatic||!1},ce||=!!B&&!re,Y=ee="",o.input="",(K||re||B||ce)&&(o.inputNotice="Finishing clipboard input.",y()),Ne())}function Ne(){if(Ie||!le||ae||K||re||B||ce)return;let{answer:L,showStatic:v}=le;Ie=!0,t.off("keypress",de),t.off("data",w),t.off("data",A),t.off("end",te),t.off("error",te),t.off("close",te),j?.removeEventListener("abort",ue);try{t.setRawMode(Ce)}catch{}we||t.pause(),p(`${U}?2004l`),Y="",ee="",o.input="",o.inputActive=!1,o.inputSubmitted=L!==null,o.inputNotice=L===null?"You can provide this value later.":"Input received locally.",h=void 0,v&&!a?m():y(),g(),x(),Z(L)}function ue(){Te(null)}function te(){K=re=ae=ce=!1,B="",Te(null)}function w(L){ae=!0;for(let v of typeof L=="string"?L:L.toString("utf8")){let Pe=re?`${U}201~`:`${U}200~`;B=v===Pe[B.length]?B+v:v==="\x1B"?v:"",B===Pe&&(re=!re,B="")}}function A(){ae=!1,Ne()}function T(L){Y.length+L.length>Di?(be=!0,o.inputNotice="Too long. Ctrl+U clears input."):(Y+=L,be||(o.inputNotice=void 0))}function de(L,v){if(!(Ie||!v))try{if(!ae&&v.name==="escape"&&(B=""),!B&&v.sequence?.startsWith("\x1B")&&(ce=!1),le){v.name==="paste-start"?K=!0:v.name==="paste-end"&&(K=!1),Ne();return}if(v.name==="paste-start"){K=!0,ee="";return}if(v.name==="escape"||v.ctrl&&["c","d"].includes(v.name??"")){ue();return}if(v.name==="paste-end")K=!1,T(ee.replace(/\r\n?/g,`
|
|
134
|
+
`)),ee="";else if(K){let Pe=(L||v.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(v.sequence??"").includes("\x1B")||(ee.length+Pe.length<=Di?ee+=Pe:(be=!0,o.inputNotice="Too long. Ctrl+U clears input."));return}else if(v.ctrl&&v.name==="u")Y="",be=!1,o.inputNotice=void 0;else if(v.name==="backspace")Y=[...Fn.segment(Y)].slice(0,-1).map(ls=>ls.segment).join("");else if(v.name==="return"||v.name==="enter"){if(!Y.trim())o.inputNotice="Enter a value, or Esc to answer later.";else if(!be){Te(Y);return}}else!v.ctrl&&!v.meta&&L&&T(L.replace(/[\x00-\x1f\x7f-\x9f]/g,""));o.input=Y,y()}catch{ue()}}h={settle:Te};try{if(t.prependListener("data",w),ic(t),t.on("keypress",de),t.on("data",A),t.once("end",te),t.once("error",te),t.once("close",te),j?.addEventListener("abort",ue,{once:!0}),j?.aborted){ue();return}t.setRawMode(!0),t.resume(),p(`${U}?2004h${U}?25l`),y()}catch{ue()}}):(o.inputActive=!1,m(),null))}return e.on("resize",C),process.on("SIGINT",F),process.on("SIGTERM",D),process.once("exit",R),u=setInterval(y,80),u.unref(),p(`${U}?25l`),y(),{update($,j){a||(o.status=$,o.detail=j,h||(o.question=void 0,o.input=void 0,d=!1),p(`${U}?25l`),y())},warn($){if(!a)try{i.render([])}catch{R()}p(`
|
|
135
|
+
Warning: ${$.split(/\r?\n/).map(N).join(`
|
|
113
136
|
`)}
|
|
114
137
|
|
|
115
|
-
`),
|
|
116
|
-
${
|
|
138
|
+
`),y()},ask:ye,finish($){if(a)return;h?.settle(null),o.question=void 0,o.outcome=$,d=!1,y(),R();let j=[$.message,...$.updatedFiles?.length?[`Updated locally: ${$.updatedFiles.join(", ")}`]:[],...$.warning?[`Warning: ${$.warning}`]:[],...$.next?[`Next: ${$.next}`]:[]].filter(Z=>!!Z);j.length&&p(`
|
|
139
|
+
${j.flatMap(Z=>Z.split(/\r?\n/).map(N)).join(`
|
|
117
140
|
`)}
|
|
118
|
-
`)},stop:
|
|
119
|
-
`);function
|
|
120
|
-
Fix: ${
|
|
121
|
-
`).length,o=
|
|
122
|
-
`)||void 0,next:`Open Canary: ${
|
|
141
|
+
`)},stop:R}}var Je=3e3,Bt=2,yc=9e4,Vi=new Set(["pending","running","needs_input","green","red","error","interrupted"]);function G(n,e){for(let t of[...n.secrets].sort((r,i)=>i.length-r.length))t&&(e=e.split(t).join("[redacted]"));return e}var Un=n=>gc(n,".canary","verify-job.json");function gt(n){try{let e=JSON.parse(dc(Un(n),"utf8"));if(!e||typeof e.jobId!="string"||!e.jobId)throw new Error("invalid job ID");if(e.sourceUploadId!==void 0&&(typeof e.sourceUploadId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.sourceUploadId)))throw new Error("invalid source upload ID");if(e.scope&&(!e.source||!Ut(e.source)||typeof e.recipeHash!="string"||typeof e.scope.apiUrl!="string"||![e.scope.userId,e.scope.workspaceId,e.scope.repositoryId].every(r=>typeof r=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(r))))throw new Error("invalid scope");let t=e.workspace&&typeof e.workspace.id=="string"&&typeof e.workspace.name=="string"?{id:e.workspace.id,name:e.workspace.name}:void 0;return{jobId:e.jobId,...typeof e.recipeHash=="string"?{recipeHash:e.recipeHash}:{},...t?{workspace:t}:{},...e.scope?{scope:e.scope}:{},...e.source?{source:e.source}:{},...e.sourceUploadId?{sourceUploadId:e.sourceUploadId}:{}}}catch(e){if(e.code==="ENOENT")return null;throw new z("invalid_setup_receipt","The saved setup job in .canary/verify-job.json is unreadable, so no new job was started.","Fix or remove .canary/verify-job.json, then run canary setup again.")}}function wc(n){return gt(n)?.jobId??null}var Wi=(n,e)=>fc(Un(n),JSON.stringify(e)+`
|
|
142
|
+
`);function Vt(n){try{pc(Un(n))}catch{}}var qe=(n,e)=>mc(n,void 0,{signal:e});function bc(n){let e=n?.setup?.services;return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.name:void 0).filter(t=>typeof t=="string"):[]}function Sc(n,e){let t,r;try{t=_e(n),Qe(n),r=tt(n).name}catch(u){if(u instanceof z||u instanceof E){e?console.log(JSON.stringify({ok:!1,error:u.code,message:u.message,..."fix"in u&&u.fix?{fix:u.fix}:{}})):console.error(`\u2717 ${u.message}${"fix"in u&&u.fix?`
|
|
143
|
+
Fix: ${u.fix}`:""}`),process.exitCode=1;return}throw u}let i=r??null,s=t.setupSh.trim().split(`
|
|
144
|
+
`).length,o=bc(t.runJson),a=[...new Set([...t.envManifest.map(u=>u.name),...Object.keys(t.envValues)])],c=t.envManifest.filter(u=>u.neededAt==="boot").map(u=>u.name),{missing:l}=gn(t.envManifest,t.envValues),d=l.length===0;e?console.log(JSON.stringify({ok:d,repo:i,recipe:{setupShLines:s,services:o,envKeys:a,bootRequired:c,missing:l}})):(console.log(`Repo ${i??"(local repository)"}`),console.log(`Recipe .canary/ \xB7 setup.sh (${s} lines) \xB7 run.json (${o.length} service${o.length===1?"":"s"}${o.length?": "+o.join(", "):""})`),console.log(`Env ${a.length} key${a.length===1?"":"s"} \xB7 ${c.length} boot-required \xB7 ${l.length?`MISSING: ${l.join(", ")}`:"all present"}`),d?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${l.join(", ")} (boot-required) ${l.length===1?"has":"have"} no value.`)),d||(process.exitCode=1)}async function Ji(n,e,t,r,i={}){if(e.status==="green"){let s=gt(n),o=s?.workspace,a=i.recipeChanged??!1;if(s?.recipeHash)try{a||=Ee(_e(n))!==s.recipeHash}catch{a=!0}let c=!1;if(s?.source){let u=(f,p)=>f.sha256===p.sha256&&f.treeHash===p.treeHash&&f.baseTreeHash===p.baseTreeHash&&f.baseSha===p.baseSha&&f.provenance.baselineMode===p.provenance.baselineMode&&(f.provenance.baseRef??null)===(p.provenance.baseRef??null);if(e.approved?.source&&!u(e.approved.source,s.source))throw new Error("The approved source does not match the source this job was submitted with. Run canary setup again to verify the current files.");let h;try{h=await pt(n,{baseRef:s.source.provenance.baseRef??void 0}),c=h.manifest.treeHash!==s.source.treeHash||h.manifest.baseTreeHash!==s.source.baseTreeHash||h.manifest.provenance.baselineMode!==s.source.provenance.baselineMode||(h.manifest.provenance.baseRef??null)!==(s.source.provenance.baseRef??null)}catch{c=!0}finally{await h?.dispose()}}if(s?.recipeHash)try{a||=Ee(_e(n))!==s.recipeHash}catch{a=!0}let l=i.writeBack!==!1&&!a&&!c;if(a||c){let u="This result is for the files as they were when submitted. They changed since, so the approved recipe was not written over your files. Run canary setup again to verify the current files.";r.warnings.push(u),!t&&!r.display&&console.error(`! ${u}`)}Vt(n);let d=[];if(e.approved?.healed&&l)try{d=xr(n,e.approved)}catch(u){let h=G(r,`Could not update .canary/ with the approved changes: ${u instanceof Error?u.message:String(u)}`);r.warnings.push(h),r.display||console.error(`! ${h}`)}return t?console.log(JSON.stringify({ok:!0,status:"green",jobId:e.jobId,...o?{workspace:o}:{},...a?{recipeChanged:!0}:{},...c?{sourceChanged:!0}:{},...s?.source?{source:s.source,repositoryId:s.scope?.repositoryId}:{},...e.approved?{approved:{healed:e.approved.healed,...e.approved.recipeId?{recipeId:e.approved.recipeId}:{},...e.approved.recipeVersionId?{recipeVersionId:e.approved.recipeVersionId}:{},...e.approved.version!==void 0?{version:e.approved.version}:{},...d.length?{updatedFiles:d}:{}}}:{}})):r.display?r.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${o?` Workspace: ${o.name}.`:""}`,updatedFiles:d,warning:r.warnings.join(`
|
|
145
|
+
`)||void 0,next:`Open Canary: ${$e().replace(/\/+$/,"")}/repositories`}):(console.log("\u2713 Verified \u2014 the recipe boots from zero in a clean sandbox. This repo is set up on Canary."),o&&console.log(` Workspace: ${o.name}`),e.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),d.length?console.log(` Updated locally to match: ${d.join(", ")}`):l||console.log(" Its approved version was not written over your newer files."))),!0}if(e.status==="interrupted")return!1;if(e.status==="red"||e.status==="error"){Vt(n);let s={phase:e.failure?.phase?G(r,e.failure.phase):null,failingCommand:e.failure?.failingCommand?G(r,e.failure.failingCommand):null,log:e.failure?.log?G(r,e.failure.log):null};return t?console.log(JSON.stringify({ok:!1,status:e.status,jobId:e.jobId,failure:s})):r.display?r.display.finish({status:e.status,message:`Verification ${e.status==="error"?"errored":"failed"}${s.phase?` (${s.phase})`:""}${s.failingCommand?` at: ${s.failingCommand}`:""}${s.log?`
|
|
123
146
|
|
|
124
|
-
${s.log.slice(-2e3)}`:""}`,warning:
|
|
147
|
+
${s.log.slice(-2e3)}`:""}`,warning:r.warnings.join(`
|
|
125
148
|
`)||void 0,next:"Fix the recipe in .canary/ and run canary setup again."}):(console.error(`\u2717 Verify ${e.status==="error"?"errored":"failed"}${s.phase?` (${s.phase})`:""}${s.failingCommand?` at: ${s.failingCommand}`:""}`),s.log&&console.error(`
|
|
126
|
-
${s.log.slice(-2e3)}`),console.error("\nFix the recipe in .canary/ and run `canary setup` again.")),process.exitCode=1,!0}if(e.status==="needs_input"&&e.needsInput){let s={...e.needsInput,key:
|
|
127
|
-
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function
|
|
128
|
-
`+(
|
|
129
|
-
Fix: ${a}`:""}`)}else if(s instanceof
|
|
130
|
-
Fix: ${a}`:""}`)}else{let o=
|
|
131
|
-
|
|
149
|
+
${s.log.slice(-2e3)}`),console.error("\nFix the recipe in .canary/ and run `canary setup` again.")),process.exitCode=1,!0}if(e.status==="needs_input"&&e.needsInput){let s={...e.needsInput,key:G(r,e.needsInput.key),prompt:G(r,e.needsInput.prompt)};return t?console.log(JSON.stringify({ok:!1,status:"needs_input",jobId:e.jobId,needsInput:s})):(console.log(`? The cloud verifier needs input${s.secret?" (a secret \u2014 pass the real value, don't echo it anywhere else)":""}:`),console.log(` ${s.key}: ${s.prompt}`),console.log(`
|
|
150
|
+
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function qi(n,e){return n.status==="needs_input"&&n.needsInput?.questionId===e.questionId}async function kc(n,e,t){let r=new AbortController,i=new AbortController,s=n.display.ask({...e,key:G(n,e.key),prompt:G(n,e.prompt)},r.signal).then(a=>({kind:"answer",value:a})),o=(async()=>{for(;;){await qe(Je,i.signal);let a=await t(i.signal);if(!qi(a,e))return{kind:"state",view:a}}})();try{return await Promise.race([s,o])}finally{i.abort(),r.abort(),await Promise.allSettled([s,o])}}async function _c(n,e,t,r,i,s){let o="",a=null;async function c(d){for(;;)try{let u=await I(`/api/v1/cli/verify/${e}`,{token:t,baseUrl:i.context?.apiUrl,signal:d});if(!u||!Vi.has(u.status))throw new Error("Verification returned an unrecognized state. Run canary setup again to retry.");return a=null,u}catch(u){if(d?.aborted)throw u;if(u instanceof O&&u.status===0&&(a===null&&(a=Date.now(),i.display?i.display.update("retrying","Cloud service unreachable. Retrying the same job."):r||console.log(" \u2026 cloud service unreachable \u2014 retrying")),Date.now()-a<yc)){await qe(Je,d);continue}throw u}}let l;for(;;){let d=l??await c();if(l=void 0,d.status==="interrupted")return"interrupted";if(d.status==="needs_input"&&s&&d.needsInput?.questionId===s.questionId&&Date.now()<s.until){await qe(Je);continue}if(d.status==="needs_input"&&d.needsInput&&i.display){let u=d.needsInput,h=await kc({...i,display:i.display},u,c);if(h.kind==="state"){l=h.view;continue}let f=h.value;if(f===null)return i.display.finish({status:"paused",message:"The verifier is waiting for your answer.",next:"Run canary setup to resume, or canary setup --answer '<value>' to answer directly."}),process.exitCode=3,"terminal";let p=await c();if(!qi(p,u)){l=p;continue}i.display.update("answering","Sending your answer to the verifier.");try{await Ki(n,e,t,u,f,r,i)}catch(g){if(g instanceof O&&g.status===409)continue;throw g}s={questionId:u.questionId,until:Date.now()+3e4},i.display.update("answering","Answer received. Waiting for verification to continue."),await qe(Je);continue}if((d.status==="pending"||d.status==="running")&&(i.display?i.display.update(d.status):d.status!==o&&!r&&console.log(` \u2026 ${d.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),o=d.status,await Ji(n,d,r,i))return"terminal";await qe(Je)}}async function Wt(n,e,t,r,i,s){je();let o=e;for(let a=0;;){if(await _c(n,o,t,r,i,s)==="terminal")return;if(Vt(n),i.freshUpload=!0,a>=Bt){r?console.log(JSON.stringify({ok:!1,status:"interrupted",jobId:o})):i.display?i.display.finish({status:"error",message:"Verification kept getting interrupted by the cloud service.",next:"Run canary setup again in a minute to restart from your local .canary/ files."}):console.error("\u2717 Verification kept getting interrupted (the cloud service may be redeploying). Run `canary setup` again in a minute \u2014 it restarts from your local .canary/ files."),process.exitCode=1;return}a+=1,r?console.error(JSON.stringify({event:"resubmitted",attempt:a,of:Bt})):i.display?i.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${Bt}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${Bt})`);let l=await zi(n,t,r,i);if(l===null)return;o=l,s=void 0}}async function Yi(n,e,t,r){let i=r.context??=await it(n,e),s=t.scope;if(s.apiUrl.replace(/\/+$/,"")!==i.apiUrl.replace(/\/+$/,"")||s.userId!==i.userId||s.workspaceId!==i.workspaceId)throw new E("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json was started by a different account, workspace, or Canary server. Switch back to it to resume that job, or remove the file to start over.");if((await rt({...i,token:e})).repositoryId!==s.repositoryId)throw new E("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json belongs to a different repository. Remove the file to start over.");r.baseRef??=t.source?.provenance.baseRef??void 0,Pn(t.source,i,s.repositoryId,{requestKey:`setup:${t.recipeHash}`,uploadId:t.sourceUploadId})}async function zi(n,e,t,r){let i=_e(n);Qe(n);let{missing:s}=gn(i.envManifest,i.envValues);if(s.length)return t?console.log(JSON.stringify({ok:!1,error:"missing_boot_env",missing:s})):r.display?r.display.finish({status:"error",message:`Boot-required environment values are missing: ${s.join(", ")}`,next:"Fill .canary/env.json and run canary setup again."}):console.error(`\u2717 Boot-required env without values: ${s.join(", ")} \u2014 fill .canary/env.json first.`),process.exitCode=1,null;let o=r.context??=await it(n,e),a=await rt({...o,token:e}),c=await pt(n,{baseRef:r.baseRef});try{r.display?.update("submitting","Uploading your local source and the .canary/ recipe.");let l=Ee(i),d=await Ht(c,o,a.repositoryId,e,{requestKey:`setup:${l}`,fresh:r.freshUpload});r.freshUpload=!1;let u=await I("/api/v1/cli/verify",{method:"POST",token:e,baseUrl:o.apiUrl,body:{workspaceId:o.workspaceId,repositoryId:a.repositoryId,source:d,setupSh:i.setupSh,runJson:JSON.stringify(i.runJson??null),env:{manifest:i.envManifest,values:i.envValues}}});if(!u?.jobId||u.repositoryId!==a.repositoryId||u.workspace&&u.workspace.id!==o.workspaceId||u.source&&u.source.sha256!==c.manifest.sha256)throw new Error("Canary's answer does not match the repository and source that were uploaded. Run canary setup again.");return Wi(n,{jobId:u.jobId,recipeHash:l,workspace:u.workspace??a.workspace,source:c.manifest,sourceUploadId:d.uploadId,scope:{apiUrl:o.apiUrl,userId:o.userId,workspaceId:o.workspaceId,repositoryId:a.repositoryId}}),Pn(c.manifest,o,a.repositoryId,{requestKey:`setup:${l}`,uploadId:d.uploadId}),u.jobId}finally{await c.dispose()}}async function vc(n,e,t){let r=V();if(!r){e?console.log(JSON.stringify({ok:!1,error:"not_logged_in",fix:"canary login"})):t.display?t.display.finish({status:"error",message:"You're not signed in.",next:"Run canary login first."}):console.error("\u2717 Not logged in \u2014 run `canary login` first."),process.exitCode=1;return}xt();let i=gt(n);i?.scope&&await Yi(n,r,i,t);let s=i?.jobId??null;if(s){t.display?.update("submitting","Checking your saved verification job.");let a=null,c=!1,l=Date.now()+3e4;for(;;)try{if(a=await I(`/api/v1/cli/verify/${s}`,{token:r,baseUrl:t.context?.apiUrl}),!a||!Vi.has(a.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(d){if(d instanceof O&&d.status===0){if(Date.now()<l){t.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await qe(Je);continue}c=!0}else if(!(d instanceof O&&d.status===404))throw d;break}if(c){e?console.log(JSON.stringify({ok:!1,error:"unreachable",jobId:s})):t.display?t.display.finish({status:"error",message:"Could not reach the cloud service to check your saved job.",next:"Run canary setup again shortly. Your job is saved."}):console.error("\u2717 Could not reach the cloud service to check your saved verify job \u2014 try again shortly."),process.exitCode=1;return}if(a){if(a.status==="pending"||a.status==="running"||a.status==="needs_input"){t.display?t.display.update(a.status==="needs_input"?"answering":a.status,"Resuming your saved verification job."):e||console.log(`Resuming verify job ${s} \u2026`),await Wt(n,s,r,e,t);return}if(a.status==="green"||a.status==="red"||a.status==="error"){let d=!1;if(i?.recipeHash)try{d=Ee(_e(n))!==i.recipeHash}catch{d=!0}e?console.error(JSON.stringify({event:"previous_job_result",jobId:s,...d?{recipeChanged:!0}:{}})):t.display?t.warnings.push(d?"This is your earlier verification result, and .canary/ changed since it was submitted: its approved version was not written over your files. Run canary setup again to verify the current files.":"This is your earlier verification result. If you changed .canary/ since then, run canary setup again to verify the current files."):console.log(`Your earlier verify job ${s} finished after the previous run stopped \u2014 applying its result now.
|
|
151
|
+
`+(d?" .canary/ changed since it was submitted, so its approved version was NOT written over your files. Run `canary setup` again to verify the current files.":" If you changed .canary/ since then, run `canary setup` again to verify the current files.")),await Ji(n,a,e,t,{writeBack:!d,recipeChanged:d});return}}Vt(n),t.freshUpload=!0}let o=await zi(n,r,e,t);o!==null&&(t.display?t.display.update("pending","Recipe sent. Waiting for the cloud verifier."):e||console.log(`Shipped the recipe \u2014 verify job ${o}`),await Wt(n,o,r,e,t))}async function Ki(n,e,t,r,i,s,o){if(r.secret&&i&&o.secrets.add(i),await I(`/api/v1/cli/verify/${e}/answer`,{method:"POST",token:t,baseUrl:o.context?.apiUrl,body:{questionId:r.questionId,value:i}}),r.secret){let a=gt(n),c=!1;try{c=!!a?.recipeHash&&Ee(_e(n))===a.recipeHash}catch{}try{if(a?.recipeHash&&!c)throw new Error("Local recipe changed since submission; the answered value was not written over it.");mn(n,[{name:r.key,value:i,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),c&&a&&Wi(n,{...a,recipeHash:Ee(_e(n))}),!s&&!o.display&&console.log(`Saved ${G(o,r.key)} to .canary/env.json for future runs.`)}catch(l){let d=G(o,`Could not save ${r.key} to .canary/env.json: ${l instanceof Error?l.message:String(l)}`);o.display?o.display.warn(d):console.error(`! ${d}`)}}}async function xc(n,e,t,r){let i=V(),s=wc(n);if(!i||!s){t?console.log(JSON.stringify({ok:!1,error:s?"not_logged_in":"no_active_job",fix:s?"canary login":"canary setup"})):r.display?r.display.finish({status:"error",message:s?"You're not signed in.":"No active verification job.",next:s?"Run canary login first.":"Run canary setup first."}):console.error(s?"\u2717 Not logged in \u2014 run `canary login`.":"\u2717 No active verify job \u2014 run `canary setup` first."),process.exitCode=1;return}let o=gt(n);o?.scope&&await Yi(n,i,o,r);let a=await I(`/api/v1/cli/verify/${s}`,{token:i,baseUrl:r.context?.apiUrl});if(a.status!=="needs_input"||!a.needsInput){r.display?r.display.update("submitting","Nothing is waiting for input. Checking the saved job."):t||console.log("Nothing is waiting for input \u2014 following the job instead."),await Wt(n,s,i,t,r);return}let c=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await Ki(n,s,i,c,e,t,r),r.display?r.display.update("answering","Answer received. Waiting for verification to continue."):t||console.log(`Answered ${G(r,c.key)} \u2014 resuming \u2026`),await Wt(n,s,i,t,r,{questionId:c.questionId,until:Date.now()+3e4})}function Xi(n){n.command("setup").description("Set up this repo on Canary: ship the .canary/ recipe for a cloud verify (boot + heal)").option("--check","validate the .canary/ recipe locally (no cloud)").option("--answer <value>","answer the question the cloud verifier is waiting on").option("--json","output machine-readable JSON").option("--no-animation","use plain progress output and answer questions with --answer").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","locally resolvable baseline for the submitted source snapshot").action(async e=>{let t=e.dir??process.cwd();Ct({cwd:t});let r=e.json===!0;if(e.check){Sc(t,r);return}let i={secrets:new Set(e.answer?[e.answer]:[]),warnings:[],baseRef:e.base};try{let s=P().team;i.display=Bi({json:r,animation:e.animation!==!1,repository:hc(t),workspace:s?.name||(s?.id?"Saved workspace":"Select a workspace")}),e.answer!==void 0?await xc(t,e.answer,r,i):await vc(t,r,i)}catch(s){if(s instanceof z||s instanceof me||s instanceof E){let o=G(i,s.message),a="fix"in s&&s.fix?G(i,s.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:s.code,message:o,...a?{fix:a}:{}})):i.display?i.display.finish({status:"error",message:o,next:a}):console.error(`\u2717 ${o}${a?`
|
|
152
|
+
Fix: ${a}`:""}`)}else if(s instanceof O){let o=G(i,s.message),a="fix"in s&&s.fix?G(i,s.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:"api_error",status:s.status,message:o,...a?{fix:a}:{}})):i.display?i.display.finish({status:"error",message:o,next:a||"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}${a?`
|
|
153
|
+
Fix: ${a}`:""}`)}else{let o=G(i,s instanceof Error?s.message:String(s));r?console.log(JSON.stringify({ok:!1,error:"setup_error",message:o})):i.display?i.display.finish({status:"error",message:o,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}`)}process.exitCode=1}finally{i.display?.stop()}})}import{lstatSync as Cc,mkdirSync as Ic,readFileSync as Qi,writeFileSync as Zi}from"node:fs";import{join as Hn}from"node:path";var Rc=5e3,$c=/^[a-z0-9][a-z0-9-]{0,39}$/,Oc=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,Ac="npm i -g @runcanary/cli@latest";function ts(n){let e=Hn(Le(),"skills");return{dir:e,body:Hn(e,`${n}.md`),meta:Hn(e,`${n}.json`)}}function Ec(n){let e=ts(n);try{let t=JSON.parse(Qi(e.meta,"utf8"));return{body:Qi(e.body,"utf8"),meta:t}}catch{return null}}function mt(n){try{return Cc(n).isSymbolicLink()}catch{return!1}}function Tc(n,e){let t=ts(n);try{if(mt(Le())||mt(t.dir)||mt(t.body)||mt(t.meta)||(Ic(t.dir,{recursive:!0,mode:448}),mt(t.dir)))return;Zi(t.body,e.body,{flag:"w",mode:384}),Zi(t.meta,JSON.stringify(e.meta,null,2)+`
|
|
154
|
+
`,{flag:"w",mode:384})}catch{}}function es(n){return n instanceof Error?n.message:String(n)}async function Nc(n,e){let t;try{t=await fetch(n,{headers:{...ke(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${e}`},signal:AbortSignal.timeout(Rc)})}catch(r){return{kind:"failed",reason:es(r)}}if(t.status===404)return{kind:"missing"};if(!t.ok){let r=(await t.text().catch(()=>"")).trim().slice(0,200);return{kind:"failed",reason:`HTTP ${t.status}${r?`: ${r}`:""}`}}try{return{kind:"ok",body:await t.text(),contentVersion:t.headers.get("x-canary-skills-version")??void 0}}catch(r){return{kind:"failed",reason:`response body interrupted: ${es(r)}`}}}async function Dn(n){let e=await Nc(n.url,n.cliVersion);switch(e.kind){case"ok":{let t={url:n.url,fetchedAt:new Date().toISOString(),cliVersion:n.cliVersion,contentVersion:e.contentVersion};return Tc(n.key,{body:e.body,meta:t}),{ok:!0,body:e.body,url:n.url,contentVersion:e.contentVersion,offline:!1}}case"missing":return{ok:!1,error:n.notFound};case"failed":{let t=Ec(n.key);if(t&&t.meta.url===n.url)return{ok:!0,body:t.body,url:n.url,contentVersion:t.meta.contentVersion,offline:!0,reason:e.reason,fetchedAt:t.meta.fetchedAt,savedByCli:t.meta.cliVersion};let r=t?`the saved copy is from ${t.meta.url}, not this server`:"there is no saved copy";return{ok:!1,error:`live fetch of ${n.url} failed (${e.reason}) and ${r} \u2014 retry when the server is reachable`}}}}function Pc(n,e){let t=s=>s.replace(/^v/,"").split("-")[0].split(".").map(o=>Number.parseInt(o,10)||0),r=t(n),i=t(e);for(let s=0;s<3;s++){let o=(r[s]??0)-(i[s]??0);if(o!==0)return o<0?-1:1}return 0}function Lc(n){let e=/^---\r?\n([\s\S]*?)\r?\n---/.exec(n);if(e)return/^minCli:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m.exec(e[1])?.[1]}function ns(n){return n.offline?`OFFLINE COPY \u2014 live fetch of ${n.url} failed (${n.reason}). Showing the copy fetched ${n.fetchedAt} by CLI ${n.savedByCli}; it may be outdated.`:`Source: ${n.url}${n.contentVersion?` (content version ${n.contentVersion})`:""}`}function Ye(n,e,t={}){if(!n.ok)return e?{stream:"stdout",text:JSON.stringify({ok:!1,error:n.error,...t})+`
|
|
132
155
|
`,exit:1}:{stream:"stderr",text:`\u2717 ${n.error}
|
|
133
|
-
`,exit:1};if(e){let
|
|
134
|
-
`,exit:0}}return{stream:"stdout",text:`${
|
|
156
|
+
`,exit:1};if(e){let r={ok:!0,source:n.url,contentVersion:n.contentVersion??null,offline:n.offline,...n.offline?{reason:n.reason,fetchedAt:n.fetchedAt}:{},...t,body:n.body};return{stream:"stdout",text:JSON.stringify(r)+`
|
|
157
|
+
`,exit:0}}return{stream:"stdout",text:`${ns(n)}
|
|
135
158
|
|
|
136
159
|
${n.body}${n.body.endsWith(`
|
|
137
160
|
`)?"":`
|
|
138
|
-
`}`,exit:0}}function
|
|
139
|
-
`,exit:0}}function
|
|
161
|
+
`}`,exit:0}}function yt(n){(n.stream==="stdout"?process.stdout:process.stderr).write(n.text),process.exit(n.exit)}function Mc(n,e,t={}){if(!n.ok||e){let r=Ye(n,e,t);return r.stream==="stdout"?{stdout:r.text,stderr:"",exit:r.exit}:{stdout:"",stderr:r.text,exit:r.exit}}return{stdout:n.body,stderr:`${ns(n)}
|
|
162
|
+
`,exit:0}}function Jt(){return W().replace(/\/+$/,"")}function rs(n){n.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 Dn({key:"index",url:`${Jt()}/llms.txt`,cliVersion:n.version()??"0.0.0",notFound:`this Canary server (${Jt()}) does not publish skills yet`});yt(Ye(t,!!e.json))}),n.command("skill <name>").description("Print the hosted instructions for one Canary operation").option("--json","output machine-readable JSON").option("--asset <file>","print a file published beside the operation (a template, a schema) instead of its instructions").action(async(e,t)=>{let r=!!t.json;$c.test(e)||yt(Ye({ok:!1,error:`invalid operation name "${e.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},r));let i=n.version()??"0.0.0";if(t.asset!==void 0){Oc.test(t.asset)||yt(Ye({ok:!1,error:`invalid asset name "${t.asset.slice(0,80)}" \u2014 assets are lowercase file names ending in .html, .json, .md or .txt`},r));let o=await Dn({key:`${e}--${t.asset}`,url:`${Jt()}/skills/${e}/${t.asset}`,cliVersion:i,notFound:`no such asset "${t.asset}" for "${e}" \u2014 run \`canary skill ${e}\` to see which files it publishes`}),a=Mc(o,r,{name:e,asset:t.asset});a.stderr&&process.stderr.write(a.stderr);let c=()=>process.exit(a.exit);a.stdout?process.stdout.write(a.stdout,c):c()}let s=await Dn({key:e,url:`${Jt()}/skills/${e}.md`,cliVersion:i,notFound:`no such operation "${e}" \u2014 run \`canary skills\` to list the operations`});if(s.ok){let o=Lc(s.body);if(o&&i!=="0.0.0-dev"&&Pc(i,o)<0){let a=`"${e}" needs Canary CLI ${o} or newer (you have ${i}). Update: ${Ac}`,c=Ye({ok:!1,error:a},r,{needsCli:o,cliVersion:i});yt({...c,exit:2})}}yt(Ye(s,r,{name:e}))})}var jc=3e3;function Fc(n){let e=n.periodEnd?` \xB7 resets ${new Date(n.periodEnd).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`:"";return n.limit===null?`Runs this month: ${n.used} \xB7 no limit`:`Runs this month: ${n.used} of ${n.limit}${e}`}function is(n){n.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async e=>{let t=e.json===!0,r=V();if(!r){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=P().team,s=i?.id&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(i.id)?i:void 0,o=await I(`/api/v1/cli/auth/whoami${s?`?workspaceId=${encodeURIComponent(s.id)}`:""}`,{token:r}),a=s?{id:s.id,name:s.name??o.team.name}:void 0,c=vn(),l=c&&a?await At({token:r,apiUrl:W().replace(/\/+$/,""),userId:o.user.id},c,a.id,AbortSignal.timeout(jc)):void 0;t?console.log(JSON.stringify({ok:!0,user:o.user,team:o.team,workspace:a,...o.usage?{usage:o.usage}:{},...c?{repository:{name:c,...l?.state?{state:l.state}:{}}}:{}})):(console.log(`${o.user.email} (${a?.name??"No workspace selected"})`),o.usage&&console.log(Fc(o.usage)),c&&(console.log(Nt(c,l?.state)),console.log(De(l?.state))))}catch(i){let s=i instanceof O&&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 as(){let n=V();if(!n)throw new O(401,"not logged in");let{workspaces:e}=await I("/api/v1/cli/workspaces",{token:n});return e}function wt(n,e,t,r={}){n?console.log(JSON.stringify({ok:!1,error:e,message:t,...r})):console.error(t),process.exitCode=1}function ss(n,e){if(e instanceof O&&e.status===401){wt(n,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}wt(n,"workspace_error",e instanceof Error?e.message:String(e))}async function Uc(n){let e=await as(),t=P().team?.id;if(n){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 r=String(e.length).length;e.forEach((i,s)=>{let o=i.id===t?"*":" ",a=String(s+1).padStart(r," ");console.log(`${o} ${a} ${i.name}`)})}function os(n,e){fe({...P(),team:{id:n.id,name:n.name}}),console.log(e?JSON.stringify({ok:!0,workspace:{id:n.id,name:n.name}}):`Switched to ${n.name}.`)}async function Hc(n,e){let t=await as(),r=n.trim();if(/^\d+$/.test(r)){let s=Number(r);if(s<1||s>t.length){wt(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}os(t[s-1],e);return}let i=t.filter(s=>s.id===r||s.name.toLowerCase()===r.toLowerCase());if(i.length===0){wt(e,"workspace_not_found",`No workspace matching "${n}".`,{available:t.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}if(i.length>1){wt(e,"workspace_ambiguous",`"${n}" 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}os(i[0],e)}function Dc(n){let e=P().team;if(!e){n?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(n?JSON.stringify({workspace:e}):e.name)}function cs(n){let e=n.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 r=t.json===!0;try{await Uc(r)}catch(i){ss(r,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,r)=>{let i=r.json===!0;try{await Hc(t,i)}catch(s){ss(i,s)}}),e.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(t=>Dc(t.json===!0))}var ne=new nr;ne.name("canary").description("Canary \u2014 break the code your AI writes.").version(Se);hr();Xr(ne);is(ne);Zr(ne);rs(ne);cs(ne);Xi(ne);Ni(ne);Hi(ne);Qr(ne);ne.parseAsync(process.argv).catch(n=>{console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)});
|