@runcanary/cli 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canary.js +77 -77
- 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
|
|
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,
|
|
4
|
+
var Bi=Object.create;var an=Object.defineProperty;var Yi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var Ki=Object.getPrototypeOf,Xi=Object.prototype.hasOwnProperty;var Fe=(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 ge=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Qi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zi(e))!Xi.call(n,r)&&r!==t&&an(n,r,{get:()=>e[r],enumerable:!(i=Yi(e,r))||i.enumerable});return n};var Zi=(n,e,t)=>(t=n!=null?Bi(Ki(n)):{},Qi(e||!n||!n.__esModule?an(t,"default",{value:n,enumerable:!0}):t,n));var je=ge(_t=>{var tt=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},kt=class extends tt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};_t.CommanderError=tt;_t.InvalidArgumentError=kt});var nt=ge(Ct=>{var{InvalidArgumentError:er}=je(),vt=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,i)=>{if(!this.argChoices.includes(t))throw new er(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function tr(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Ct.Argument=vt;Ct.humanReadableArgName=tr});var St=ge(cn=>{var{humanReadableArgName:nr}=nt(),xt=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((r,s)=>r.name().localeCompare(s.name())),t}compareOptions(e,t){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!r&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!r&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let r=i.options.filter(s=>!s.hidden);t.push(...r)}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(i=>nr(i)).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((i,r)=>Math.max(i,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,r)=>Math.max(i,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,r)=>Math.max(i,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.name()+" "+i;return i+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(i=>JSON.stringify(i)).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(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),r=t.helpWidth||80,s=2,o=2;function a(d,m){if(m){let p=`${d.padEnd(i+o)}${m}`;return t.wrap(p,r-s,i+o)}return d}function c(d){return d.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(s))}let u=[`Usage: ${t.commandUsage(e)}`,""],l=t.commandDescription(e);l.length>0&&(u=u.concat([t.wrap(l,r,0),""]));let f=t.visibleArguments(e).map(d=>a(t.argumentTerm(d),t.argumentDescription(d)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let h=t.visibleOptions(e).map(d=>a(t.optionTerm(d),t.optionDescription(d)));if(h.length>0&&(u=u.concat(["Options:",c(h),""])),this.showGlobalOptions){let d=t.visibleGlobalOptions(e).map(m=>a(t.optionTerm(m),t.optionDescription(m)));d.length>0&&(u=u.concat(["Global Options:",c(d),""]))}let g=t.visibleCommands(e).map(d=>a(t.subcommandTerm(d),t.subcommandDescription(d)));return g.length>0&&(u=u.concat(["Commands:",c(g),""])),u.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,i,r=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-i;if(a<r)return e;let c=e.slice(0,i),u=e.slice(i).replace(`\r
|
|
7
7
|
`,`
|
|
8
|
-
`),
|
|
9
|
-
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),d=
|
|
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=r=>[r.name()].concat(r.aliases()),
|
|
8
|
+
`),l=" ".repeat(i),h="\\s\u200B",g=new RegExp(`
|
|
9
|
+
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),d=u.match(g)||[];return c+d.map((m,p)=>m===`
|
|
10
|
+
`?"":(p>0?l:"")+m.trimEnd()).join(`
|
|
11
|
+
`)}};cn.Help=xt});var Ot=ge(At=>{var{InvalidArgumentError:ir}=je(),$t=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 i=sr(e);this.short=i.shortFlag,this.long=i.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,i)=>{if(!this.argChoices.includes(t))throw new ir(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return rr(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Rt=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,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}};function rr(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function sr(n){let e,t,i=n.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}At.Option=$t;At.DualOptions=Rt});var un=ge(ln=>{function or(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let i=0;i<=n.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let r=1;r<=n.length;r++){let s=1;n[r-1]===e[i-1]?s=0:s=1,t[r][i]=Math.min(t[r-1][i]+1,t[r][i-1]+1,t[r-1][i-1]+s),r>1&&i>1&&n[r-1]===e[i-2]&&n[r-2]===e[i-1]&&(t[r][i]=Math.min(t[r][i],t[r-2][i-2]+1))}return t[n.length][e.length]}function ar(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 i=[],r=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=or(n,o),c=Math.max(n.length,o.length);(c-a)/c>s&&(a<r?(r=a,i=[o]):a===r&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
|
|
12
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
13
|
+
(Did you mean ${i[0]}?)`:""}ln.suggestSimilar=ar});var gn=ge(hn=>{var cr=Fe("node:events").EventEmitter,It=Fe("node:child_process"),Z=Fe("node:path"),Et=Fe("node:fs"),T=Fe("node:process"),{Argument:lr,humanReadableArgName:ur}=nt(),{CommanderError:Tt}=je(),{Help:dr}=St(),{Option:dn,DualOptions:fr}=Ot(),{suggestSimilar:fn}=un(),Nt=class n extends cr{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=>T.stdout.write(t),writeErr:t=>T.stderr.write(t),getOutHelpWidth:()=>T.stdout.isTTY?T.stdout.columns:void 0,getErrHelpWidth:()=>T.stderr.isTTY?T.stderr.columns:void 0,outputError:(t,i)=>i(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,i){let r=t,s=i;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return r&&(c.description(r),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),r?this:c}createCommand(e){return new n(e)}createHelp(){return Object.assign(new dr,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 lr(e,t)}argument(e,t,i,r){let s=this.createArgument(e,t);return typeof i=="function"?s.default(r).argParser(i):s.default(i),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[,i,r]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),r&&o.arguments(r),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 i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
15
|
+
Expecting one of '${i.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,i){this._exitCallback&&this._exitCallback(new Tt(e,t,i)),T.exit(e)}action(e){let t=i=>{let r=this.registeredArguments.length,s=i.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new dn(e,t)}_callParseArg(e,t,i,r){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${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 i=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 '${i}'
|
|
16
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),i=t(e).find(r=>this._findCommand(r));if(i){let r=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let r=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(i);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(i,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")}),this}_optionEx(e,t,i,r,s){if(typeof t=="object"&&t instanceof dn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(s).argParser(r);else if(r instanceof RegExp){let a=r;r=(c,u)=>{let l=a.exec(c);return l?l[0]:u},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,i,r){return this._optionEx({},e,t,i,r)}requiredOption(e,t,i,r){return this._optionEx({mandatory:!0},e,t,i,r)}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,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.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){T.versions?.electron&&(t.from="electron");let r=T.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=T.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":T.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=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",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(l,f){let h=Z.resolve(l,f);if(Et.existsSync(h))return h;if(r.includes(Z.extname(f)))return;let g=r.find(d=>Et.existsSync(`${h}${d}`));if(g)return`${h}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let l;try{l=Et.realpathSync(this._scriptPath)}catch{l=this._scriptPath}a=Z.resolve(Z.dirname(l),a)}if(a){let l=s(a,o);if(!l&&!e._executableFile&&this._scriptPath){let f=Z.basename(this._scriptPath,Z.extname(this._scriptPath));f!==this._name&&(l=s(a,`${f}-${e._name}`))}o=l||o}i=r.includes(Z.extname(o));let c;T.platform!=="win32"?i?(t.unshift(o),t=pn(T.execArgv).concat(t),c=It.spawn(T.argv[0],t,{stdio:"inherit"})):c=It.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=pn(T.execArgv).concat(t),c=It.spawn(T.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{T.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let u=this._exitCallback;c.on("close",l=>{l=l??1,u?u(new Tt(l,"commander.executeSubCommandAsync","(close)")):T.exit(l)}),c.on("error",l=>{if(l.code==="ENOENT"){let f=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
|
-
- ${f}`;throw new Error(h)}else if(
|
|
19
|
+
- ${f}`;throw new Error(h)}else if(l.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)T.exit(1);else{let f=new Tt(1,"commander.executeSubCommandAsync","(error)");f.nestedError=l,u(f)}}),this.runningCommand=c}_dispatchSubcommand(e,t,i){let r=this._findCommand(e);r||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(i));else return r._parseCommand(t,i)}),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=(i,r,s)=>{let o=r;if(r!==null&&i.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,r,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,r)=>{let s=i.defaultValue;i.variadic?r<this.args.length?(s=this.args.slice(r),i.parseArg&&(s=s.reduce((o,a)=>e(i,a,o),i.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],i.parseArg&&(s=e(i,s,i.defaultValue))),t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let r=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{r=this._chainOrCall(r,()=>s(this,t))}),r}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.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(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),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))r(),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():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),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(i=>{let r=i.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let r=e.find(s=>i.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],r=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==="--"){r===i&&r.push(c),r.push(...s);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let u=this._findOption(c);if(u){if(u.required){let l=s.shift();l===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,l)}else if(u.optional){let l=null;s.length>0&&!o(s[0])&&(l=s.shift()),this.emit(`option:${u.name()}`,l)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),l=this._findOption(c.slice(0,u));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,c.slice(u+1));continue}}if(o(c)&&(r=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(c)){t.push(c),s.length>0&&i.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){i.push(c),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){r.push(c),s.length>0&&r.push(...s);break}r.push(c)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let r=this.options[i].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}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(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
26
|
-
`,{mode:384}),
|
|
22
|
+
`),this.outputHelp({error:!0}));let i=t||{},r=i.exitCode||1,s=i.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in T.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()}`,T.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new fr(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"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 i=o=>{let a=o.attributeName(),c=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),l=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:l||o},r=o=>{let a=i(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=fn(e,r)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),t=fn(e,r)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let r=this.createOption(t,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.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 i=this.parent?._findCommand(e);if(i){let r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}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(i=>ur(i));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=Z.basename(e,Z.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},i;return t.error?i=r=>this._outputConfiguration.writeErr(r):i=r=>this._outputConfiguration.writeOut(r),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let r=this.helpInformation(i);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",i))}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=T.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
24
|
+
Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,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(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function pn(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",r="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])?r=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],r=s[4]),t&&r!=="0"?`${t}=${i}:${parseInt(r)+1}`:e})}hn.Command=Nt});var bn=ge(G=>{var{Argument:mn}=nt(),{Command:Pt}=gn(),{CommanderError:pr,InvalidArgumentError:yn}=je(),{Help:hr}=St(),{Option:wn}=Ot();G.program=new Pt;G.createCommand=n=>new Pt(n);G.createOption=(n,e)=>new wn(n,e);G.createArgument=(n,e)=>new mn(n,e);G.Command=Pt;G.Option=wn;G.Argument=mn;G.Help=hr;G.CommanderError=pr;G.InvalidArgumentError=yn;G.InvalidOptionArgumentError=yn});var kn=Zi(bn(),1),{program:ca,createCommand:la,createArgument:ua,createOption:da,CommanderError:fa,InvalidArgumentError:pa,InvalidOptionArgumentError:ha,Command:_n,Argument:ga,Option:ma,Help:ya}=kn.default;import{createHash as hs,randomBytes as Qn}from"node:crypto";import{spawn as gs}from"node:child_process";import{createServer as ms}from"node:http";import{existsSync as On,lstatSync as Rr,mkdirSync as Ar,readFileSync as Or,writeFileSync as Ir}from"node:fs";import{homedir as Ut}from"node:os";import{join as He}from"node:path";import{randomUUID as gr}from"node:crypto";import{chmodSync as mr,mkdirSync as yr,readFileSync as wr,renameSync as br,rmSync as kr,writeFileSync as _r}from"node:fs";import{homedir as vr}from"node:os";import{dirname as Cr,join as vn}from"node:path";var xr="https://api.runcanary.ai",Sr="https://www.runcanary.ai";function Lt(){return process.env.CANARY_HOME||vn(vr(),".canary")}function Cn(){return vn(Lt(),"config.json")}var xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Mt=null;function Ft(){let{config:n,unreadable:e}=it();if(n.installId&&xn.test(n.installId))return n.installId;if(Mt??=gr(),!e)try{X({...n,installId:Mt})}catch{}return Mt}function O(){return it().config}function Sn(n){return O().repoFingerprints?.[n]}function $n(n,e){let{config:t,unreadable:i}=it();if(!i)try{X({...t,repoFingerprints:{...t.repoFingerprints,[n]:e}})}catch{}}function it(){let n;try{n=wr(Cn(),"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 X(n){let e=Cn();yr(Cr(e),{recursive:!0,mode:448});let t=`${e}.${process.pid}.tmp`;try{_r(t,JSON.stringify(n,null,2)+`
|
|
26
|
+
`,{mode:384}),mr(t,384),br(t,e)}catch(i){throw kr(t,{force:!0}),i}}function jt(n){let e={...O()};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);(!e.installId||!xn.test(e.installId))&&(e.installId=Ft()),X(e)}function Rn(){let{config:n,unreadable:e}=it();if(e)return;let{apiUrl:t,webUrl:i,installId:r,agentSkills:s,repoFingerprints:o}=n;X({...t?{apiUrl:t}:{},...i?{webUrl:i}:{},...r?{installId:r}:{},...s!==void 0?{agentSkills:s}:{},...o?{repoFingerprints:o}:{}})}function U(){return process.env.CANARY_TOKEN||O().token}function ce(){return process.env.CANARY_API_URL||O().apiUrl||xr}function ee(){let n=process.env.CANARY_WEB_URL||O().webUrl;if(n)return n;let e=process.env.CANARY_API_URL||O().apiUrl;return e?e.replace("//api.","//www."):Sr}var te="Onboard this repository to Canary.",rt="Verify my changes with Canary.";var Ht=`---
|
|
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,78 @@ 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(r=>r.trim()).filter(r=>r.length>0);if(
|
|
70
|
-
`)&&(
|
|
71
|
-
`)}catch{}
|
|
72
|
-
`)}catch{}}function
|
|
73
|
-
`),Ve(
|
|
74
|
-
`}catch{}
|
|
65
|
+
`;var Er="canary";function An(n){try{return Rr(n).isSymbolicLink()}catch{return!1}}function Tr(){return[He(Ut(),".claude"),He(Ut(),".agents"),He(Ut(),".codex")].filter(n=>On(n))}function Ue(){let n={installed:[],refreshed:[],current:[],skipped:[]};if(O().agentSkills===!1)return n;for(let e of Tr()){let t=He(e,"skills",Er),i=He(t,"SKILL.md");try{if(An(t)||An(i)){n.skipped.push(i);continue}let r=On(i)?Or(i,"utf8"):null;if(r===Ht){n.current.push(i);continue}Ar(t,{recursive:!0}),Ir(i,Ht),(r===null?n.installed:n.refreshed).push(i)}catch{}}return n}var st=`Open your coding agent inside the repo you want to onboard and say: "${te}"`;import{createHash as Ur}from"node:crypto";import{execFileSync as Dr,spawn as Vr}from"node:child_process";import{mkdirSync as Nr,readFileSync as Pr,writeFileSync as Mr}from"node:fs";import{homedir as Lr}from"node:os";import{dirname as Fr,join as In}from"node:path";var le="0.1.8",En="@runcanary/cli",jr=1440*60*1e3,Dt=()=>In(process.env.CANARY_HOME||In(Lr(),".canary"),"update-check.json");function Tn(){try{return JSON.parse(Pr(Dt(),"utf8"))}catch{return{}}}function Hr(n,e){let t=n.split(".").map(Number),i=e.split(".").map(Number);for(let r=0;r<3;r+=1){let s=(t[r]||0)-(i[r]||0);if(s!==0)return s>0}return!1}function Nn(){if(le==="0.0.0-dev")return;let{latest:n}=Tn();n&&Hr(n,le)&&console.error(`A newer Canary CLI is available (${le} -> ${n}): npm install -g ${En}`)}function me(){if(le==="0.0.0-dev")return;let n=Tn();n.checkedAt&&Date.now()-n.checkedAt<jr||(async()=>{let e=t=>{try{Nr(Fr(Dt()),{recursive:!0}),Mr(Dt(),JSON.stringify({checkedAt:Date.now(),latest:t??n.latest})+`
|
|
66
|
+
`)}catch{}};try{let t=await fetch(`https://registry.npmjs.org/${En}/latest`,{signal:AbortSignal.timeout(1500)});if(!t.ok)return e();let{version:i}=await t.json();e(i||void 0)}catch{e()}})()}var D={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"},ye={},De=null;function ot(n){ye={...ye,...n},De=null}function Wr(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 Gr(n,e){return Ur("sha256").update(`${e}\0${n}`).digest("hex").slice(0,24)}function Pn(n,e){try{let{GIT_DIR:t,GIT_WORK_TREE:i,GIT_COMMON_DIR:r,...s}=process.env;return Dr("git",n,{cwd:e,env:s,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function Jr(n,e){let[t,i,r]=(Pn(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],n)??"").split(`
|
|
67
|
+
`);if(!t)return{};let s={worktreeId:Gr(t,e)};if(r!=="true"){let o=Sn(s.worktreeId);o&&Pn(["cat-file","-e",`${o}^{commit}`],t)!==null?s.repoFingerprint=o:qr(t,s.worktreeId)}return s.branch=i&&i!=="HEAD"?i:"HEAD",s}var Mn=new Map;function qr(n,e){Mn.has(e)||Mn.set(e,new Promise(t=>{try{let{GIT_DIR:i,GIT_WORK_TREE:r,GIT_COMMON_DIR:s,...o}=process.env,a=Vr("git",["rev-list","--max-parents=0","HEAD"],{cwd:n,env:o,stdio:["ignore","pipe","ignore"],timeout:6e4}),c="";a.stdout.on("data",u=>{c+=u.toString("utf8")}),a.on("error",()=>t()),a.on("close",u=>{let l=u===0?c.trim().split(`
|
|
68
|
+
`).filter(Boolean).sort()[0]:void 0;l&&$n(e,l),t()}),a.unref(),a.stdout.unref?.()}catch{t()}}))}function Br(){if(De)return De;let n=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",{harness:e,chatId:t}=Wr(),i="",r={};try{i=Ft(),r=Jr(ye.cwd??process.cwd(),i)}catch{}return De={cliVersion:le,command:n,installId:i,...r,harness:e,...t?{chatId:t}:{},...ye.agent!==void 0?{agent:ye.agent}:{},...ye.mode?{mode:ye.mode}:{}},De}function Ce(){let n=Br(),e=i=>i.replace(/[^\x20-\x7e]/g,"?").slice(0,200),t={[D.cli]:n.cliVersion,[D.harness]:n.harness};return n.installId&&(t[D.install]=n.installId),n.command&&(t[D.command]=e(n.command)),n.worktreeId&&(t[D.worktree]=n.worktreeId),n.repoFingerprint&&(t[D.repo]=n.repoFingerprint),n.branch&&(t[D.branch]=e(n.branch)),n.chatId&&(t[D.chat]=e(n.chatId)),n.agent!==void 0&&(t[D.agent]=n.agent?"1":"0"),n.mode&&(t[D.mode]=n.mode),t}var E=class extends Error{constructor(t,i,r,s){super(i);this.status=t;this.fix=r;this.runId=s;this.name="ApiError"}},ue=n=>n instanceof E&&(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||ce()).replace(/\/+$/,""),i=Ce();e.token&&(i.authorization=`Bearer ${e.token}`),e.body!==void 0&&(i["content-type"]="application/json");let r;try{r=await fetch(t+n,{method:e.method??"GET",headers:i,body:e.body!==void 0?JSON.stringify(e.body):void 0,signal:e.signal})}catch(s){throw new E(0,`could not reach ${t} (${s instanceof Error?s.message:String(s)})`)}if(!r.ok){let s=r.statusText,o,a;try{let c=await r.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 E(r.status,s,o,a)}return r.status===204?null:await r.json()}import{createHash as Yr}from"node:crypto";import{execFileSync as zr}from"node:child_process";import{existsSync as Kr,mkdirSync as Vt,readFileSync as xe,writeFileSync as at}from"node:fs";import{join as ne}from"node:path";var V=class extends Error{constructor(t,i,r){super(i);this.code=t;this.fix=r;this.name="RecipeError"}};function Se(n){return ne(n,".canary")}function Xr(n){let e=n.trim();if(!e)return null;if(!e.includes("://")){let t=e.match(/^[^@]+@([^:]+):(.+)$/);if(t){let i=t[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return i.length>=2?{host:t[1],owner:i[0],name:i.slice(1).join("/")}:null}}try{let t=new URL(e),i=t.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(i.length>=2)return{host:t.host,owner:i[0],name:i.slice(1).join("/")}}catch{}return null}function de(n=process.cwd()){let e;try{e=zr("git",["remote","get-url","origin"],{cwd:n,stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return null}return Xr(e)}var Qr=new Set(["github.com","ssh.github.com"]);function we(n){let e=n.host.toLowerCase().replace(/:\d+$/,"");if(!Qr.has(e))throw new V("unsupported_remote",`origin is on ${n.host}, but Canary connects GitHub repositories`,"run inside a checkout whose `origin` points at github.com")}function Ve(n){let e=Se(n),t=ne(e,".gitignore");try{let i=xe(t,"utf8").split(`
|
|
69
|
+
`).map(r=>r.trim()).filter(r=>r.length>0);if(i[i.length-1]==="*")return}catch{}try{Vt(e,{recursive:!0});let i="";try{i=xe(t,"utf8"),i&&!i.endsWith(`
|
|
70
|
+
`)&&(i+=`
|
|
71
|
+
`)}catch{}at(t,`${i}*
|
|
72
|
+
`)}catch{}}function ct(n){let e=Se(n),t;try{t=xe(ne(e,"setup.sh"),"utf8")}catch{throw new V("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 V("recipe_invalid",".canary/setup.sh is empty.");let i;try{i=JSON.parse(xe(ne(e,"run.json"),"utf8"))}catch(a){throw new V("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let r=[],s={},o=ne(e,"env.json");if(Kr(o)){let a;try{a=JSON.parse(xe(o,"utf8"))}catch(u){throw new V("recipe_invalid",`Cannot read .canary/env.json: ${u instanceof Error?u.message:String(u)}`)}if(a===null||typeof a!="object"||Array.isArray(a))throw new V("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let c=a;r=jn(c.manifest),s=Hn(c.values),es(r)}return{setupSh:t,runJson:i,envManifest:r,envValues:s}}function Wt(n){return Yr("sha256").update(JSON.stringify([n.setupSh,n.runJson,n.envManifest,n.envValues])).digest("hex")}function Gt(n,e){let t=n.filter(i=>i.neededAt==="boot").map(i=>i.name).filter(i=>!Object.prototype.hasOwnProperty.call(e,i)||e[i]==="");return{missing:[...new Set(t)]}}function jn(n){return Array.isArray(n)?n.filter(e=>!!e&&typeof e=="object"&&typeof e.name=="string"):[]}var Ln=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),Zr=new Set(["boot","runtime"]);function es(n){for(let e of n){if(!Ln.has(String(e.class)))throw new V("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has unknown class "${String(e.class)}"`,`use one of: ${[...Ln].join(", ")}`);if(!Zr.has(String(e.neededAt)))throw new V("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has invalid neededAt "${String(e.neededAt)}"`,'use "boot" or "runtime"')}}function Hn(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function ts(n){try{let e=JSON.parse(xe(ne(Se(n),"env.json"),"utf8"));return{manifest:jn(e.manifest),values:Hn(e.values)}}catch{return{manifest:[],values:{}}}}function ns(n,e){Vt(Se(n),{recursive:!0}),at(ne(Se(n),"env.json"),JSON.stringify(e,null,2)+`
|
|
73
|
+
`),Ve(n)}var Fn=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"]);function Jt(n,e){if(e.length===0)return;let t=ts(n),i=new Map(t.manifest.map(r=>[r.name,r]));for(let r of e){t.values[r.name]=r.value;let s=i.get(r.name);if(s)r.class&&Fn.has(r.class)&&!Fn.has(s.class??"")&&(s.class=r.class,s.neededAt="boot");else{let o={name:r.name,class:r.class??"config",neededAt:"boot",why:r.why??"added during cloud verification"};i.set(r.name,o),t.manifest.push(o)}}ns(n,t)}function Un(n,e){let t=[],i=Se(n);if(Vt(i,{recursive:!0}),typeof e.setupSh=="string"&&e.setupSh.trim()&&(at(ne(i,"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{}at(ne(i,"run.json"),s),t.push(".canary/run.json")}let r=Object.entries(e.envOverrides??{});return r.length>0&&(Jt(n,r.map(([s,o])=>({name:s,value:o,why:"authored by the cloud verifier while fixing the boot"}))),t.push(".canary/env.json")),Ve(n),t}var is=new Set(["onboarded","connected","not_connected","no_access","connected_elsewhere"]),rs=/^https?:\/\/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%-]+$/;async function ie(n,e,t,i=AbortSignal.timeout(3e3)){try{let r=await I(`/api/v1/cli/repos/status?fullName=${encodeURIComponent(e)}&workspaceId=${encodeURIComponent(t)}`,{token:n.token,baseUrl:n.apiUrl,signal:i});if(!r||!is.has(r.state))return;let s=typeof r.connectUrl=="string"&&rs.test(r.connectUrl)?r.connectUrl:void 0,o=Array.isArray(r.workspaces)?r.workspaces.filter(a=>!!a&&typeof a.id=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(a.id)&&typeof a.name=="string"&&a.name.length>0):[];return{state:r.state,...s?{connectUrl:s}:{},...o.length?{workspaces:o}:{}}}catch{return}}function Dn(n){try{return new URL(n).href.replace(/\/+$/,"")}catch{return}}function $e(){try{let n=de();return n?(we(n),`${n.owner}/${n.name}`):void 0}catch{return}}async function Vn(n,e,t,i){let r={id:n.team.id,name:n.team.name},s={workspace:r,workspaces:[r],source:"active on platform"},o=$e();o&&(s.repository=o);let a=AbortSignal.timeout(3e3),c={token:n.token,apiUrl:i},u=o?ie(c,o,r.id,a):Promise.resolve(void 0);try{let l=await I("/api/v1/cli/workspaces",{token:n.token,baseUrl:i,signal:a});if(!Array.isArray(l?.workspaces)||l.workspaces.some(d=>!d||typeof d.id!="string"||!d.id||typeof d.name!="string"))throw new Error("Invalid workspace list");let f=new Map(l.workspaces.map(({id:d,name:m})=>[d,{id:d,name:m}]));s.workspaces=[...f.values()],f.has(r.id)||s.workspaces.unshift(r);let h=Dn(t);if(e.user?.id===n.user.id&&h!==void 0&&h===Dn(i)&&e.team?.id){let d=f.get(e.team.id);d?(s.workspace=d,s.source="saved in CLI"):s.workspaceNotice="Saved workspace could not be confirmed. Using the workspace from sign-in."}}catch{s.workspaceNotice="Workspace list unavailable. Using the workspace from sign-in."}if(o){let l=s.workspace.id===r.id?await u:await ie(c,o,s.workspace.id,a),f=l?.state==="connected_elsewhere"&&l.workspaces?.length===1?l.workspaces[0]:void 0,h=f&&s.workspaces.find(g=>g.id===f.id);h&&(s.workspace=h,s.source="chosen for this repository",l=await ie(c,o,h.id,a)??{state:"connected"}),l&&(s.repositoryState=l.state,l.connectUrl&&(s.connectUrl=l.connectUrl),l.workspaces&&(s.repositoryWorkspaces=l.workspaces))}return s}import{stripVTControlCharacters as Wn}from"node:util";var L="\x1B[";function Ge(n,e,t){let i={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[e];return t?`${L}${i}m${n}${L}0m`:n}function S(n){return Wn(n).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var qt=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Gn(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 We(n){return[...qt.segment(Wn(n))].reduce((e,t)=>e+Gn(t.segment),0)}function lt(n,e){let t=0,i="";for(let r of n.split(/(\x1b\[[0-9;]*m)/)){if(r.startsWith(L)){i+=r;continue}for(let{segment:s}of qt.segment(r))t+=Gn(s),t<=e&&(i+=s)}return i}function re(n,e){let t=[],i="";for(let r of S(n).split(/\s+/)){i&&We(i+" "+r)>e&&(t.push(i),i="");for(let{segment:s}of qt.segment((i?" ":"")+r))We(i+s)>e&&i&&(t.push(i),i=""),i+=s}return i&&t.push(i),t}function Re(n){let e=[];return{render(t){if(t.join(`
|
|
75
75
|
`)===e.join(`
|
|
76
|
-
`))return;let
|
|
76
|
+
`))return;let i=Math.max(2,n.columns||80),r=Math.max(3,n.rows||24),s=Math.min(r-1,e.reduce((o,a)=>o+Math.max(1,Math.ceil(We(a)/i)),0));n.write((s?`\r${L}${s}A`:"")+`${L}0J`+(t.length?t.join(`\r
|
|
77
77
|
`)+`\r
|
|
78
|
-
`:"")),e=t}}}function
|
|
78
|
+
`:"")),e=t}}}function ss(n){return n.map(e=>`"${S(e.name)}" (canary workspace use ${S(e.id)})`).join(", ")}function Jn(n){return`Workspace switched to "${S(n.name)}" \u2014 this repository is connected there.`}function qn(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
79
|
`:" ")+t+`
|
|
80
|
-
`]}function qn(i,e){return i?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 lt(i,e,t,n=[]){let r=C(i);switch(e){case"connected_elsewhere":return n.length===1?`Repository ${r} \xB7 connected in your workspace "${C(n[0].name)}", not the selected one`:`Repository ${r} \xB7 connected in ${n.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 ${C(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(i,e,t,n=[]){switch(i){case"connected_elsewhere":return n.length===1?`Next: switch the CLI to that workspace: canary workspace use ${C(n[0].id)}, then in your coding agent say "${ee}"`:`Next: switch the CLI to the workspace it is connected in: ${ts(n)}; then in your coding agent say "${ee}"`;case"onboarded":return`Next: in your coding agent, say "${it}"`;case"not_connected":{let r=t?` (choose "${C(t)}" as the workspace there)`:"";return`Next: connect this repository at ${C(e)}${r}, then in your coding agent say "${ee}"`}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 "${ee}"`}}import{stripVTControlCharacters as ns}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 qe="\x1B[",is={gold:"33",text:"39",muted:"90",green:"32"};function rs(i,e,t){if(!t)return i;let n=e==="gold"?"38;2;255;212;0":is[e];return`${qe}${n}m${i}${qe}0m`}function Bn(i){return ns(i).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Yn=1.4;function ss(i){let{phase:e,seconds:t,columns:n,rows:r,color:s,open:o}=i,a=i.phaseSeconds??t,c=1.4,u=t%(c+.2),f=w=>Math.sin(w/c*Math.PI*2)*Math.sin(w/c*Math.PI),h=e==="waiting"&&u<c?f(u):e==="success"&&a<Yn?f(a):0,m=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",p=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.",g=(w,b="text")=>rs(w,b,s),_=e==="success"?"green":e==="failed"?"muted":"gold",k;if(r<5)k=[g(d)];else if(n>=72&&r>=18){let w={1:g("CANARY","gold"),3:g(d,e==="success"?"green":"text"),5:g(p,"muted")};k=["",...m.map((b,v)=>` ${g(b,_)} ${w[v]??""}`)]}else n>=42&&r>=23?k=["",...m.map(w=>` ${g(w,_)}`),` ${g("CANARY","gold")}`,"",` ${g(d)}`,` ${g(p,"muted")}`]:k=["",` ${g("CANARY","gold")}`,` ${g(d)}`];return r>=10&&(k.push("",` ${g("\u2500".repeat(Math.max(1,Math.min(54,n-5))),"gold")}`),(e==="waiting"||e==="saving")&&k.push(` ${g("Ctrl+C","muted")} ${g("cancel sign-in","muted")}`),k.push("")),k.slice(0,Math.max(1,r-2)).map(w=>{let b=0;return w.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,v=>v.startsWith("\x1B")||++b<n?v:"")})}function zn(i){if(i.json||!i.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,n=performance.now(),r="waiting",s=n,o=g=>{r=g,s=performance.now()},a=Re(e),c=!1;function l(){if(c)return;let g=Math.max(2,e.columns||80),_=Math.max(3,e.rows||24),k=performance.now(),w=ss({phase:r,seconds:(k-n)/1e3,phaseSeconds:(k-s)/1e3,columns:g,rows:_,color:t,open:i.open});a.render(w)}let u=()=>e.write(`${qe}0m${qe}?25h`);function f(){c||(c=!0,clearInterval(p),e.removeListener("resize",l),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",d),process.removeListener("exit",u),u())}function h(g){o("failed"),l(),f(),e.write(`Sign-in cancelled.
|
|
81
|
-
`),process.exit(
|
|
82
|
-
Workspace ${
|
|
80
|
+
`]}function Bn(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 qe="\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`${qe}${i}m${n}${qe}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,l=t%(c+.2),f=v=>Math.sin(v/c*Math.PI*2)*Math.sin(v/c*Math.PI),h=e==="waiting"&&l<c?f(l):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 u(){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 l=()=>e.write(`${qe}0m${qe}?25h`);function f(){c||(c=!0,clearInterval(m),e.removeListener("resize",u),process.removeListener("SIGINT",g),process.removeListener("SIGTERM",d),process.removeListener("exit",l),l())}function h(p){o("failed"),u(),f(),e.write(`Sign-in cancelled.
|
|
81
|
+
`),process.exit(p)}let g=()=>h(130),d=()=>h(143),m=setInterval(u,80);return m.unref(),e.on("resize",u),process.once("SIGINT",g),process.once("SIGTERM",d),process.once("exit",l),e.write(`${qe}?25l`),u(),{saving(){o("saving"),u()},celebrate(){return o("success"),u(),new Promise(p=>setTimeout(p,zn*1e3+100))},succeed(p,_){o("success"),u(),f(),process.stdout.write(` Account ${Yn(p)}
|
|
82
|
+
Workspace ${Yn(_)}
|
|
83
83
|
|
|
84
|
-
`)},fail(){o("failed"),
|
|
85
|
-
${Be(
|
|
86
|
-
`);return}let a=e.isRaw,c=e.readableFlowing===!0,
|
|
87
|
-
${Be(
|
|
84
|
+
`)},fail(){o("failed"),u(),f()},clear(){a.render([]),f()},stop:f}}import{spawn as us}from"node:child_process";import{emitKeypressEvents as ds}from"node:readline";function Bt(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 dt(n){return n.workspaces.length>1&&n.repositoryState!=="no_access"}function Be(n){return n.repositoryState==="onboarded"?rt:te}function fs(n,e,t,i){let{context:r}=n,s=Math.max(1,e-5),o=(h,g="text")=>Ge(S(h),g,i),a=(h="",g="text")=>` ${o(h,g)}`,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("",...Ae[8].map((g,d)=>` ${o(g,"green")} ${h[d]??""}`),"")}else c.push(a("CANARY","gold"),a("You're connected."),"");if(c.push(a(`Account ${S(n.email)}`)),c.push(a(`Workspace ${S(r.workspace.name)}`)),c.push(a(` ${r.source}${!n.done&&dt(r)?" \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)),g=Math.max(0,Math.min(n.highlighted-Math.floor(h/2),r.workspaces.length-h));for(let d=g;d<Math.min(g+h,r.workspaces.length);d++){let m=r.workspaces[d],_=r.workspaces.some(v=>v.id!==m.id&&v.name===m.name)?` \xB7 ${S(m.id)}`:"",k=m.id===r.workspace.id?" \xB7 current":"";c.push(a(`${d===n.highlighted?"\u203A":" "} ${S(m.name)}${_}${k}`,d===n.highlighted?"gold":"text"))}c.push(a(`${n.highlighted+1} of ${r.workspaces.length}`,"muted"),"",a("\u2191 \u2193 choose \xB7 Enter select \xB7 Esc back","muted"))}else{let h=r.repositoryState==="onboarded",g=r.repositoryState==="not_connected",d=r.repository?S(r.repository):void 0;if(!d)c.push(a("Repository Open a GitHub repository to continue"));else if(h)c.push(a(`Repository ${d} \xB7 connected`,"green"));else if(r.repositoryState==="connected")c.push(a(`Repository ${d} \xB7 not set up yet`));else if(g)c.push(a(`Repository ${d} \xB7 not connected to Canary`,"gold")),r.connectUrl&&c.push(...re(`Connect it at ${S(r.connectUrl)} with this workspace active there, before onboarding.`,Math.max(1,s-12)).map(p=>a(` ${p}`,"muted")));else if(r.repositoryState==="connected_elsewhere"){let p=r.repositoryWorkspaces??[];c.push(a(`Repository ${d} \xB7 connected in ${p.length===1?`your workspace "${S(p[0].name)}"`:"other workspaces of yours"}`,"gold")),c.push(a(` ${dt(r)?"Press [w] to switch to it, then set up.":"Switch to it with canary workspace use, then set up."}`,"muted"))}else r.repositoryState==="no_access"?(c.push(a(`Repository ${d} \xB7 connected in a workspace you're not a member of`,"gold")),c.push(a(" Ask that workspace's admin to add you.","muted"))):c.push(a(`Repository ${d} \xB7 detected locally`));c.push(a(`Agent skill ${Bt(n.skill)}`,n.skill&&Bt(n.skill).startsWith("Installed")?"green":"muted")),r.workspaceNotice&&c.push(...re(r.workspaceNotice,s).map(p=>a(p,"muted"))),c.push("",a("\u2500".repeat(Math.min(68,s)),"muted"),a(h?"NEXT \xB7 VERIFY A CHANGE":g?"NEXT \xB7 CONNECT THE REPOSITORY, THEN SET IT UP":r.repositoryState==="connected_elsewhere"?"NEXT \xB7 SWITCH TO THAT WORKSPACE, THEN SET IT UP":"NEXT \xB7 REPOSITORY SETUP","gold"));let m=!!n.skill&&Bt(n.skill).startsWith("Installed");c.push(a(m?"Open your coding agent in this repository and say:":"In your coding agent, run canary skills, then say:","muted")),c.push(...re(Be(r),s-2).map(p=>a(`\u2502 ${p}`))),n.done||c.push("",a(`${dt(r)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),n.message&&c.push(...re(n.message,s).map(p=>a(p,"muted"))),c.push("",a(h?"Signed in \xB7 Ready to verify":g?"Signed in \xB7 Repository not connected":r.repositoryState==="connected_elsewhere"?"Signed in \xB7 Repository in another workspace":"Signed in \xB7 Setup hasn't started",h?"green":"muted"))}let l=Math.max(1,t-2);return(l<=3?c.slice(0,l):c.length>l?[...c.slice(0,Math.max(0,l-3)),...c.slice(-3)]:c).map(h=>lt(h,Math.max(1,e-1)))}async function ps(n,e){let t=process.platform==="darwin"?[["pbcopy"]]:process.platform==="win32"?[["clip.exe"]]:[["wl-copy"],["xclip","-selection","clipboard"],["xsel","--clipboard","--input"]];for(let[i,...r]of t){if(e.aborted)return!1;if(await new Promise(o=>{let a=us(i,r,{stdio:["pipe","ignore","ignore"],signal:e}),c=setTimeout(()=>{a.kill(),o(!1)},1e3),u=l=>{clearTimeout(c),o(l)};a.on("error",()=>u(!1)),a.on("close",l=>u(l===0)),a.stdin.on("error",()=>{}),a.stdin.end(n)}))return!0}return!1}async function Xn(n){let e=process.stdin,t=process.stderr,i={...n,picker:!1,highlighted:0},r=!process.env.NO_COLOR,s=Re(t),o=()=>s.render(fs(i,t.columns||80,t.rows||24,r));if(!e.isTTY||!t.isTTY||(t.rows||24)<16||(t.columns||80)<30){i.done=!0,o(),t.write(`
|
|
85
|
+
${Be(i.context)}
|
|
86
|
+
`);return}let a=e.isRaw,c=e.readableFlowing===!0,u=new AbortController,l=!1,f,h=0;await new Promise(g=>{function d(){if(l)return;l=!0,u.abort(),e.off("keypress",k),e.off("end",d),t.off("resize",_),process.off("SIGINT",d),process.off("SIGTERM",p),process.off("exit",m),i.picker=!1,i.done=!0,i.message=void 0;let v=n.sessionCurrent();v?o():s.render(["CLI session changed in another process. Run canary whoami to check the active account."]),m(),v&&t.write(`
|
|
87
|
+
${Be(i.context)}
|
|
88
88
|
|
|
89
|
-
`),m()}function p(){e.setRawMode(a),c||e.pause(),t.write(`${M}0m${M}?25h`)}function g(){process.exitCode=143,d()}function _(){(t.rows||24)<16||(t.columns||80)<30?d():o()}function k(w,b){if(!(!b||u)){if(!i.sessionCurrent()){d();return}if(b.ctrl&&["c","d"].includes(b.name??"")){d();return}if(!(b.ctrl||b.meta)){if(n.picker){let v=n.context.workspaces.length;if(b.name==="escape")n.picker=!1;else if(b.name==="up")n.highlighted=(n.highlighted+v-1)%v;else if(b.name==="down")n.highlighted=(n.highlighted+1)%v;else if(b.name==="return"){let R=n.context.workspaces[n.highlighted];try{i.selectWorkspace(R);let I=R.id!==n.context.workspace.id;if(n.context={...n.context,workspace:R,source:"selected in CLI",...I?{repositoryState:void 0}:{}},n.picker=!1,n.message="Workspace saved for future CLI commands.",I&&(f?.abort(),i.repositoryState&&n.context.repository)){let F=++h;i.repositoryState(R.id).then(j=>{if(!u){if(!i.sessionCurrent()){d();return}F!==h||n.context.workspace.id!==R.id||(n.context={...n.context,repositoryState:j?.state,connectUrl:j?.connectUrl??n.context.connectUrlDefault,repositoryWorkspaces:j?.workspaces},o())}})}}catch{if(!i.sessionCurrent()){d();return}n.picker=!1,n.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"&&ut(n.context))n.picker=!0,n.highlighted=Math.max(0,n.context.workspaces.findIndex(v=>v.id===n.context.workspace.id));else if(b.name==="c"&&!f){let v=Be(n.context),R=new AbortController;f=R,l.signal.addEventListener("abort",()=>R.abort(),{once:!0}),ls(v,R.signal).then(I=>{f===R&&(f=void 0),!u&&(n.message=R.signal.aborted||v!==Be(n.context)?"The next step changed while copying. Press [c] to copy the current one.":I?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",o())})}o()}}}as(e),e.setRawMode(!0),e.resume(),e.on("keypress",k),e.once("end",d),t.on("resize",_),process.once("SIGINT",d),process.once("SIGTERM",g),process.once("exit",p),t.write(`${M}?25l`),o()})}var ps=900*1e3,hs=6e4,gs=3e3,Qn=i=>i.toString("base64url");function ms(i){let e=process.platform,[t,n]=e==="darwin"?["open",[i]]:e==="win32"?["explorer.exe",[i]]:["xdg-open",[i]];try{let r=ds(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}function ys(i,e){return`<!doctype html><meta charset="utf-8"><title>${i}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${i}</h2><p style="color:#555">${e}</p></body>`}function ws(i){return new Promise((e,t)=>{let n,r,s=new Promise((l,u)=>{n=l,r=u}),o=fs((l,u)=>{let f=new URL(l.url??"/","http://127.0.0.1"),h=(p,g,_)=>{u.writeHead(_,{"content-type":"text/html",connection:"close"}),u.end(ys(p,g))};if(f.pathname!=="/callback"){u.writeHead(404,{connection:"close"}),u.end("not found");return}if(f.searchParams.get("state")!==i){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let m=f.searchParams.get("error");if(m){h("Authorization failed","You can close this tab and return to your terminal.",400),r(new Error(`authorization failed: ${m}`));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),n(d)}),a=setTimeout(()=>r(new Error("timed out waiting for browser authorization")),ps);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 bs(i,e){let t=A(),n=t.apiUrl||"",r=(e.apiUrl||ce()).replace(/\/+$/,""),s=Qn(Xn(32)),o=us("sha256").update(s).digest("base64url"),a=Qn(Xn(16)),{port:c,code:l,close:u}=await ws(a),f=`http://127.0.0.1:${c}/callback`,h=(e.webUrl||Z()).replace(/\/+$/,""),m=`${h}/cli/authorize?challenge=${encodeURIComponent(o)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(f)}`;for(let _ of Jn(i,e.open,m))console.error(_);let d=zn({json:i,animation:e.animation,open:e.open}),p=Date.now(),g=d?void 0:setInterval(()=>console.error(qn(i,Math.round((Date.now()-p)/1e3))),hs);g?.unref?.();try{e.open&&ms(m);let _=await l;g&&clearInterval(g),d?.saving();let k=await O("/api/v1/cli/auth/token",{method:"POST",body:{code:_,codeVerifier:s},baseUrl:r});Lt({token:k.token,user:k.user,team:k.team,apiUrl:r,webUrl:h,agentSkills:e.agentSkills});let w=e.agentSkills?Ue():void 0;if(d){let[b]=await Promise.all([Dn(k,t,n,r),d.celebrate()]),v=()=>{let F=A();return F.token===k.token&&F.apiUrl===r};if(!v()){d.clear(),console.error("CLI session changed in another process. Run canary whoami to check the active account.");return}let R=F=>{let j=A();if(j.token!==k.token||j.apiUrl!==r)throw new Error("CLI session changed");K({...j,team:F})};try{R(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 I=b.repository?F=>ne({token:k.token,apiUrl:r},b.repository,F):void 0;await Kn({email:k.user.email,context:b,skill:w,selectWorkspace:R,sessionCurrent:v,repositoryState:I})}else{let b=$e(),v={token:k.token,apiUrl:r},R=AbortSignal.timeout(gs),I=b&&!i?await ne(v,b,k.team.id,R):void 0,F,j=I?.state==="connected_elsewhere"&&I.workspaces?.length===1?I.workspaces[0]:void 0;if(j&&b){let Y=A();if(Y.token===k.token&&Y.apiUrl===r)try{K({...Y,team:j}),F=j,I=await ne(v,b,j.id,R)??{state:"connected"}}catch{}}let x=I?.connectUrl??`${h}/integrations`,N=F?.name??k.team.name;ei(i,k.user.email,k.team,b?{name:b,state:I?.state,connectUrl:x,workspaces:I?.workspaces}:void 0,F);let S=b?Je(I?.state,x,N,I?.workspaces):void 0;w?ti(i,w,S):i||console.log(S??rt)}}catch(_){throw d?.fail(),_}finally{g&&clearInterval(g),d?.stop(),u()}}async function Zn(i,e,t){let n=await O("/api/v1/cli/auth/whoami",{token:i,baseUrl:t});Lt({token:i,user:n.user,team:n.team,apiUrl:t});let r=$e(),s=`${Z().replace(/\/+$/,"")}/integrations`;return ei(e,n.user.email,n.team,r?{name:r,connectUrl:s}:void 0),r?Je(void 0,s):void 0}function ei(i,e,t,n,r){if(i){console.log(JSON.stringify({ok:!0,user:{email:e},team:t,...n?{repository:n}:{},...r?{workspace:r}:{}}));return}console.log(`Logged in as ${C(e)} (${C(t.name)}).`),r&&console.log(Gn(r)),n&&console.log(lt(n.name,n.state,n.connectUrl,n.workspaces))}function ks(i,e){let t=Ue();ti(i,t,e)}function ti(i,e,t=rt){if(i)return;let n=[...e.installed,...e.refreshed];n.length&&console.log(`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${n.join(", ")}).`),console.log(t)}function ni(i){i.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 n;if(e.token!==void 0){let r=e.token.trim();if(!r)throw new Error("--token was provided but is empty");n=await Zn(r,t,e.apiUrl)}else{let r=(process.env.CANARY_TOKEN??"").trim();if(r)n=await Zn(r,t,e.apiUrl);else{await bs(t,{webUrl:e.webUrl,apiUrl:e.apiUrl,open:e.open!==!1,animation:e.animation!==!1,agentSkills:e.agentSkills!==!1}),me();return}}K({...A(),agentSkills:e.agentSkills!==!1}),e.agentSkills!==!1?ks(t,n):t||console.log(n??rt),e.token===void 0&&!(process.env.CANARY_TOKEN??"").trim()&&me()}catch(n){let r=n instanceof E?`${n.message}`:n instanceof Error?n.message:String(n);t?console.log(JSON.stringify({ok:!1,error:r})):console.error(`Login failed: ${r}`),process.exitCode=1}})}var _s={[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 ii(i){i.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=xe();if(e.json===!0)return void console.log(JSON.stringify(t));for(let[n,r]of Object.entries(t)){let s=n===D.harness&&r==="unknown"?"(no running coding-agent session detected)":_s[n]??"";console.log(`${n.padEnd(18)} ${r}${s?` ${s}`:""}`)}})}function ri(i){i.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async e=>{let t=e.json===!0,n=U();if(n)try{await O("/api/v1/cli/auth/logout",{method:"POST",token:n})}catch{}$n();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 di}from"node:fs";import{execFileSync as vs}from"node:child_process";import{copyFileSync as xs,existsSync as si,mkdirSync as Cs,mkdtempSync as Ss,rmSync as oi,statSync as $s,utimesSync as Rs,writeFileSync as As}from"node:fs";import{tmpdir as ai}from"node:os";import{join as Oe,resolve as ci}from"node:path";var P=class extends Error{constructor(t,n,r){super(n);this.code=t;this.fix=r;this.name="SnapshotError"}},be=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:i=>`canary verify: tree ${i}`});function Os(i,e){return{args:["-c","i18n.commitEncoding=utf-8","-c","commit.gpgsign=false","commit-tree",i,"-p",e,"--no-gpg-sign","-m",be.message(i)],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 Is=["apply","--binary","--whitespace=nowarn"],dt=i=>`tree:${i.slice(0,12)}`;function Es(i){let e=0,t=0,n=0;for(let r of i.split(`
|
|
90
|
-
`)){if(!r)continue;let[s,o]=r.split(" ");
|
|
91
|
-
`).filter(o=>o&&o!=="refs/remotes/origin/HEAD"&&!e.includes(o)),s=
|
|
92
|
-
`)+1)))}function
|
|
93
|
-
`);let
|
|
94
|
-
`).filter(Boolean);throw new
|
|
95
|
-
`);let t=[
|
|
96
|
-
(${
|
|
97
|
-
${
|
|
98
|
-
`)}function W(
|
|
99
|
-
fix: ${y(
|
|
100
|
-
run: ${y(o)}`:""}`)}process.exitCode=r}async function
|
|
101
|
-
`))}async function
|
|
102
|
-
`))}async function
|
|
103
|
-
Input needed: ${C
|
|
104
|
-
${
|
|
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||l)){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(!l){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=Be(i.context),x=new AbortController;f=x,u.signal.addEventListener("abort",()=>x.abort(),{once:!0}),ps(w,x.signal).then(A=>{f===x&&(f=void 0),!l&&(i.message=x.signal.aborted||w!==Be(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((u,l)=>{i=u,r=l}),o=ms((u,l)=>{let f=new URL(u.url??"/","http://127.0.0.1"),h=(m,p,_)=>{l.writeHead(_,{"content-type":"text/html",connection:"close"}),l.end(_s(m,p))};if(f.pathname!=="/callback"){l.writeHead(404,{connection:"close"}),l.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",u=>{clearTimeout(a),t(u)}),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:u,close:l}=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 qn(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(Bn(n,Math.round((Date.now()-m)/1e3))),ws);p?.unref?.();try{e.open&&ks(g);let _=await u;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(),l()}}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
|
+
`)){if(!r)continue;let[s,o]=r.split(" ");i+=1,e+=s==="-"?0:Number(s)||0,t+=o==="-"?0:Number(o)||0}return{additions:e,deletions:t,changedFiles:i}}function Ls(n){let e=0;for(;n[e]==="-c";)e+=2;return n[e]??n[0]}function se(n,e){try{return $s("git",[...js,...n],{cwd:e.cwd,env:e.env,input:e.input,stdio:[e.input===void 0?"ignore":"pipe","pipe","pipe"],maxBuffer:1024*1024*1024})}catch(t){let i=t;if(i.code==="ENOENT")throw new M("git_not_found","git is not installed or not on PATH","install git");if(i.code==="ENOBUFS")throw new M("snapshot_too_large","the change set is larger than 1 GiB and cannot be snapshotted in one piece","verify a smaller change set (commit or stash part of it first)");let r=i.stderr?.toString("utf8").trim()??"";throw new M("git_failed",`git ${Ls(n)} failed${r?`: ${r}`:""}`,"this is git's own error, not Canary's \u2014 resolve it in the repo, then run `canary verify` again")}}var B=(n,e)=>se(n,e).toString("utf8").trim();function oe(n,e){try{return B(n,e)}catch(t){if(t instanceof M&&t.code==="git_failed")return null;throw t}}var Fs=[["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"]],js=Fs.flatMap(([n,e])=>["-c",`${n}=${e}`]),Hs=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT","GIT_EXTERNAL_DIFF","GIT_DIFF_OPTS","GIT_LITERAL_PATHSPECS","GIT_GLOB_PATHSPECS","GIT_NOGLOB_PATHSPECS","GIT_ICASE_PATHSPECS","GIT_NAMESPACE"]),Us=["GIT_CONFIG_KEY_","GIT_CONFIG_VALUE_","GIT_AUTHOR_","GIT_COMMITTER_"];function Ds(){let n={};for(let[e,t]of Object.entries(process.env))Hs.has(e)||Us.some(i=>e.startsWith(i))||(n[e]=t);return n.GIT_OPTIONAL_LOCKS="0",n.GIT_TERMINAL_PROMPT="0",n}function ui(n,e){let t=null;for(let i of n){let r=oe(["merge-base","HEAD",i],e);if(!r)continue;let s=Number(B(["rev-list","--count",`${r}..HEAD`],e));(!t||s<t.distance)&&(t={baseRef:i,baseSha:r,distance:s})}return t&&{baseRef:t.baseRef,baseSha:t.baseSha}}function Vs(n){if(oe(["remote","get-url","origin"],n)===null)throw new M("no_git_remote","no `origin` remote \u2014 Canary verifies changes against the GitHub repo they belong to","add the GitHub remote as `origin` and fetch it (`git fetch origin`)");let e=[],t=oe(["symbolic-ref","-q","refs/remotes/origin/HEAD"],n);t&&e.push(t);for(let o of["refs/remotes/origin/main","refs/remotes/origin/master"])!e.includes(o)&&oe(["rev-parse","--verify","-q",`${o}^{commit}`],n)!==null&&e.push(o);let i=ui(e,n);if(i)return i;let r=B(["for-each-ref","--format=%(refname)","refs/remotes/origin/"],n).split(`
|
|
91
|
+
`).filter(o=>o&&o!=="refs/remotes/origin/HEAD"&&!e.includes(o)),s=ui(r,n);if(s)return s;throw e.length===0&&r.length===0?new M("base_not_found","no `origin/*` branches are known locally, so there is no pushed commit to diff against","run `git fetch origin`, then run `canary verify` again"):new M("base_not_found","HEAD shares no history with any `origin/*` branch, so there is no pushed commit to diff against","the repo's default branch must exist on origin (`origin/main`) and share history with this checkout \u2014 ask a human; do not push this branch to work around it")}function Ws(n){let e=n.toString("utf8").split("\0"),t=[],i=0;for(;i<e.length&&e[i]!=="";){let[,r,,,s]=e[i].split(" "),o=s[0];o==="R"||o==="C"?(t.push({status:o,from:e[i+1],path:e[i+2],dstMode:r}),i+=3):(t.push({status:o,path:e[i+1],dstMode:r}),i+=2)}return t}function Gs(n,e){if(oe(["cat-file","-e",`${n}:.gitmodules`],e)===null)return new Set;let t=oe(["config","-z","--blob",`${n}:.gitmodules`,"--get-regexp","^submodule\\..*\\.path$"],e);return t===null?new Set:new Set(t.split("\0").filter(Boolean).map(i=>i.slice(i.indexOf(`
|
|
92
|
+
`)+1)))}function Js(){try{return Os(Oe(ci(),"canary-snapshot-"))}catch(n){throw new M("tmp_unwritable",`cannot create a scratch directory under ${ci()} (${n instanceof Error?n.message:String(n)})`,"set TMPDIR to a writable directory")}}function di(n){if(!oi(n))throw new M("not_a_git_repo",`${n} does not exist`,"run inside the git checkout you want verified");let e=Ds(),t=oe(["rev-parse","--show-toplevel"],{cwd:n,env:e});if(!t)throw new M("not_a_git_repo",`${n} is not inside a git checkout`,"run inside the git checkout you want verified");let i={cwd:t,env:e};if(oe(["rev-parse","--verify","-q","HEAD^{commit}"],i)===null)throw new M("no_commits","this repo has no commits yet","commit and push a base first");if(se(["ls-files","-u","-z"],i).length>0)throw new M("merge_in_progress","the index has unresolved conflicts (a merge, rebase or cherry-pick is in progress)","resolve the conflicts \u2014 or abort with `git merge --abort` / `git rebase --abort` \u2014 then run `canary verify` again");let r=oe(["symbolic-ref","-q","--short","HEAD"],i)??"HEAD",{baseRef:s,baseSha:o}=Vs(i),a=B(["rev-parse",`${o}^{tree}`],i),c=li(t,B(["rev-parse","--git-path","objects"],i)),u=li(t,B(["rev-parse","--git-path","index"],i)),l=Js(),f=h=>{ai(l,{recursive:!0,force:!0}),process.exit(h==="SIGINT"?130:143)};process.once("SIGINT",f),process.once("SIGTERM",f);try{let h=Oe(l,"objects");As(Oe(h,"info"),{recursive:!0}),Ts(Oe(h,"info","alternates"),c+`
|
|
93
|
+
`);let g=Oe(l,"index"),d={cwd:t,env:{...e,GIT_OBJECT_DIRECTORY:h,GIT_INDEX_FILE:g}};if(oi(u)){Rs(u,g);let{atime:$,mtime:z}=Is(u);Es(g,$,z)}else se(["read-tree","HEAD"],d);se(["add","-A"],d);let m=B(["write-tree"],d);if(m===a)throw new M("nothing_to_verify",`nothing to verify \u2014 the working tree is identical to ${s.replace("refs/remotes/","")} (${ft(m)})`,"make the change you want pressure-tested, then run `canary verify` again");let p=Ws(se(["diff","--raw","-z","-M","--no-color","--no-ext-diff",a,m],d)),_=p.map(({status:$,path:z,from:Qe})=>Qe===void 0?{status:$,path:z}:{status:$,path:z,from:Qe}),k=Gs(m,d),v=p.filter($=>$.dstMode==="160000"&&!k.has($.path)).map($=>$.path);if(v.length)throw new M("embedded_repo",`${v.join(", ")} ${v.length===1?"is a nested git repository":"are nested git repositories"} \u2014 its files would not be part of the snapshot`,`remove the nested \`.git\` directory (${v.map($=>`${$}/.git`).join(", ")}) so the files are plain files, or add it as a submodule`);let b=se(["diff","--binary","-M","--full-index","--no-color","--no-ext-diff","--no-textconv","--src-prefix=a/","--dst-prefix=b/",a,m],d),w={...d,env:{...d.env,GIT_INDEX_FILE:Oe(l,"index.reproduce")}};se(["read-tree",a],w);let x="",A=null;try{se([...Ps,"--cached"],{...w,input:b}),x=B(["write-tree"],w)}catch($){if(!($ instanceof M))throw $;A=$.message}if(x!==m){let $=A?[]:B(["diff","--name-only",m,x],w).split(`
|
|
94
|
+
`).filter(Boolean);throw new M("snapshot_not_reproducible",`the patch does not rebuild the snapshot tree (${A??`differs at: ${$.slice(0,10).join(", ")}${$.length>10?", \u2026":""}`})`,"this is a Canary bug, nothing was uploaded \u2014 report this message to Canary")}let N=Ns(m,o),j=B(N.args,{...d,env:{...d.env,...N.env}}),C=se(["log","--format=%B%x00",`${o}..HEAD`],i).toString("utf8").split("\0").map($=>$.trim()).filter(Boolean),P=Ms(B(["diff","--numstat","-M","--no-color","--no-ext-diff","--no-textconv",a,m],d));return{root:t,branch:r,baseRef:s,baseSha:o,treeHash:m,headSha:j,patch:b,files:_,commitMessages:C,diffStats:P}}finally{process.off("SIGINT",f),process.off("SIGTERM",f),ai(l,{recursive:!0,force:!0})}}var Yt=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,qs=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,pi=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,zt=new Set(["completed","failed","cancelled"]),Ie=class extends Error{constructor(t,i,r){super(i);this.code=t;this.fix=r;this.name="VerifyError"}},y=n=>(n??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g," ").trim(),Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pt=n=>new Promise(e=>setTimeout(e,n)),hi=3,Bs=1e3;function Ys(n){if(n===void 0)return;let e=n;try{n==="-"?e=fi(0,"utf8"):n.startsWith("@")&&(e=fi(n.slice(1),"utf8"))}catch(t){throw new Ie("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 Q(n){return n==="P3"?null:n==="P0"||n==="P1"?n:"P2"}var gi=n=>n?n.startLine?`${n.file}:${n.startLine}`:n.file:null;function zs(n,e){if(Q(n.materiality)===null)return null;let i=e??null;return n.result==="fail"?{checkRunId:n.checkRunId,kind:"fail",proof:i?.isStatic===!1?"runtime":"source",headline:y(i?.finding?.headline)||y(n.title),summary:y(i?.verdict?.reasonOneLiner??i?.finding?.whatWasTested),location:gi(i?.finding?.nextActionCodeRef??i?.codeRefs?.[0]),fix:y(i?.finding?.reproduce)||null}:n.result==="blocked"?{checkRunId:n.checkRunId,kind:"blocked",proof:"none",headline:y(n.title),summary:y(i?.verdict?.reasonOneLiner)||(ze[n.blockedReason??""]??""),location:gi(i?.checkReadback?.codeRefs?.[0]??i?.codeRefs?.[0]),fix:null}:null}var mi={P0:0,P1:1,P2:2},ze={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 yi(n,e,t){let i=U();I("/api/v1/cli/events",{method:"POST",...i?{token:i}:{},...t?{baseUrl:t}:{},body:{outcome:n,...e?{runId:e}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function wi(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 Ks(n,e,t={}){let i=f=>I(f,{token:e,...t.baseUrl?{baseUrl:t.baseUrl}:{}}),r=new Map,s="",o=new Set,a=!1,c=!1,u=null,l=Date.now();for(;;){let f;try{f=(await i(`/api/v1/red-team/runs/${n}`)).run,u=null}catch(d){if(ue(d)&&(u??=Date.now(),Date.now()-u<qs)){t.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await pt(Yt);continue}throw d}for(let d of f.stageC.checks)if(!(!(d.status==="completed"&&(d.result==="fail"||d.result==="blocked"))||r.has(d.checkRunId))){if(!Ye.test(d.checkRunId)){r.set(d.checkRunId,null);continue}try{r.set(d.checkRunId,await i(`/api/v1/red-team/runs/${n}/checks/${d.checkRunId}/finding`))}catch(p){ue(p)||r.set(d.checkRunId,null)}}for(let d of f.stageC.checks){if(o.has(d.checkRunId)||!(d.status==="completed"||d.status==="failed"||d.status==="cancelled")||Q(d.materiality)===null)continue;o.add(d.checkRunId);let p=r.get(d.checkRunId),_=d.status!=="completed"?"!":d.result==="pass"?"\u2713":d.result==="fail"?"\u2717":"\u23F8",k=d.status!=="completed"?"errored":d.result==="pass"?"passed":d.result==="fail"?p?.isStatic===!1?"verified failure":"finding from the code":"could not verify";t.onProgress?.(`${_} ${k}: ${y(d.title)}`)}f.stageB.status!=="completed"&&(c=!0);let h=f.stageC.checks.length>0||f.stageB.finalChecksCount===0||zt.has(f.status);!a&&f.stageB.status==="completed"&&h&&(a=!0,t.onProgress?.(Qs(f,c?Date.now()-l:null,r)));let g=Xs(f);if(g!==s&&(t.onProgress?.(g),s=g),zt.has(f.status)){for(let m=0;m<3;m++){let p=f.stageC.checks.filter(_=>_.status==="completed"&&(_.result==="fail"||_.result==="blocked")&&!r.has(_.checkRunId));if(p.length===0)break;await pt(Math.min(Yt,1e3));for(let _ of p)try{r.set(_.checkRunId,await i(`/api/v1/red-team/runs/${n}/checks/${_.checkRunId}/finding`))}catch(k){(!ue(k)||m===2)&&r.set(_.checkRunId,null)}}let d=f.stageC.checks.filter(m=>m.status==="completed"&&(m.result==="fail"||m.result==="blocked")).sort((m,p)=>mi[Q(m.materiality)??"P2"]-mi[Q(p.materiality)??"P2"]).map(m=>zs(m,r.get(m.checkRunId)??null)).filter(m=>m!==null);return{run:f,findings:d}}if(Date.now()-l>pi)throw new Ie("still_running",`run ${n} is still ${f.status} after ${Math.round(pi/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await pt(Yt)}}function Xs(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 Qs(n,e,t=new Map){let i=n.stageC.checks.filter(f=>Q(f.materiality)!==null),r=f=>f.result==="fail"&&t.get(f.checkRunId)?.isStatic!==!1,s=i.filter(r).length,o=n.stageC.checks.filter(f=>f.status==="failed"||f.status==="cancelled").length,a=i.filter(f=>!r(f)&&f.status!=="failed"&&f.status!=="cancelled").length,c=n.stageC.results.pass+n.stageC.results.blocked+i.filter(f=>f.result==="fail"&&t.get(f.checkRunId)?.isStatic===!1).length,u=zt.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 ${J(s,"finding")} from the code \xB7 ${a} runtime check${a===1?"":"s"}${o?` \xB7 ${o} errored`:""} \xB7 ${u}`}function Zs(n,e,t){let i=n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns;if(wi(n)===2)return`Verification did not complete (${n.status})${i?`: ${J(i,"check")} errored`:""}; nothing was verified.`;let r=e.filter(l=>l.kind==="fail"&&l.proof==="runtime").length,s=e.filter(l=>l.kind==="fail"&&l.proof==="source").length,o=e.filter(l=>l.kind==="blocked").length,a=n.stageC.results.pass,c=[`${J(r,"verified failure")}`,`${J(a,"check")} passed`,`${J(s,"finding")} from the code (source-reasoned, not run)`,...o?[`${o} could not be verified`]:[],`${J(i,"check")} errored`],u=a===0&&r===0&&o===0&&i===0;return`${c.join("; ")}.${u?" Nothing in this change was executed.":""}${eo(t)}`}function eo(n){let e=n?n.reverifiable-n.carried:0;return!n||e<=0?"":` ${e} of run ${n.sourceRunId.slice(0,8)}'s ${J(n.reverifiable,"failed check")} ${e===1?"was":"were"} not re-run (reported disputed or skipped).`}function to(n,e){let t=n.slice(0,8);if(!e)return`re-checking the failed set of run ${t} \u2014`;let i=`of run ${t}'s ${J(e.reverifiable,"failed check")}`;return e.excludedReported>0?`re-checking ${e.carried} ${i} (${e.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${e.reverifiable} failed checks of run ${t} \u2014`}function no(n,e,t,i){return{ok:!0,runId:n.runId,treeHash:e,status:n.status,findings:t,summary:Zs(n,t,i),failed:t.filter(r=>r.kind==="fail").length,passed:n.stageC.results.pass,blocked:t.filter(r=>r.kind==="blocked").length,errored:n.stageC.failedCheckRuns+n.stageC.cancelledCheckRuns,exitCode:wi(n),failureMessage:n.failure?.publicMessage??null,...i?{reverify:i}:{}}}var io={fail:"\u2717",blocked:"\u23F8"},ro={fail:"",blocked:" (could not be verified)"},J=(n,e)=>`${n} ${e}${n===1?"":"s"}`;function so(n){let e=[];if(e.push(`Receipt ${ft(n.treeHash)} \xB7 run ${y(n.runId)}`),n.exitCode===2)return e.push(`\u2717 Verification did not complete (${y(n.status)})${n.failureMessage?`: ${y(n.failureMessage)}`:""}`),n.errored>0&&e.push(` ${J(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 ${y(n.runId)}.`),e.join(`
|
|
95
|
+
`);let t=[n.failed?`\u2717 ${J(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 i of n.findings)e.push(""),e.push(`${io[i.kind]} ${y(i.headline)}${ro[i.kind]}`),i.summary&&e.push(` ${y(i.summary)}`),i.location&&e.push(` \u2192 ${y(i.location)}`),i.fix&&e.push(` reproduce: ${y(i.fix)}`);return n.errored>0&&e.push(`
|
|
96
|
+
(${J(n.errored,"check")} errored and could not be verified.)`),e.push(`
|
|
97
|
+
${n.summary}`),e.join(`
|
|
98
|
+
`)}function W(n,e,t,i,r,s={}){if(n)console.log(JSON.stringify({ok:!1,error:e,message:t,...i?{fix:i}:{},exitCode:r,...s}));else{let o=typeof s.runId=="string"?s.runId:null;console.error(`\u2717 ${y(t)}${i?`
|
|
99
|
+
fix: ${y(i)}`:""}${o?`
|
|
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,u;try{c=Ys(e),u=di(n)}catch(p){if(p instanceof M||p instanceof Ie)return o(p.code,p.message,p.fix);throw p}let l=de(u.root);if(!l)return o("no_git_remote","no GitHub origin found","run inside the checkout you want verified");try{we(l)}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=u.branch.replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256),v=()=>I("/api/v1/cli/runs",{method:"POST",token:a,...s,body:{repoFullName:`${l.owner}/${l.name}`,..._?{workspaceId:_}:{},baseSha:u.baseSha,treeHash:u.treeHash,headSha:u.headSha,patchBase64:u.patch.toString("base64"),...c!==void 0?{brief:c}:{},commitMessages:u.commitMessages,diffStats:u.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(Bs*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(u.treeHash)} \xB7 run ${h} \xB7 ${J(u.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,u.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 u=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)})),l={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:u,passed:u.filter(g=>g.status==="passed").length,failed:u.filter(g=>g.status==="failed").length,couldNotRun:u.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,...l,...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 u of c.checks){let l=Ci(u),f=l==="could_not_run"?"could not verify":l,h=u.result==="blocked"?ze[u.blockedReason??""]:void 0;a.push(` ${Q(u.materiality)??"P3"} ${f.padEnd(16)} ${y(u.title)} ${y(u.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
|
|
101
|
+
`))}async function go(n,e,t,i){let r=await Kt(t,[n,e],`/api/v1/red-team/runs/${n}/checks/${e}/finding`,i);if(!r)return;if(t)return void console.log(JSON.stringify({ok:!0,runId:n,checkRunId:e,...r}));let s=[];s.push(y(r.finding?.headline)||"(no finding written for this check yet)"),r.verdict&&s.push(`verdict: ${y(r.verdict.result)}${r.verdict.reasonOneLiner?` \u2014 ${y(r.verdict.reasonOneLiner)}`:""}${r.isStatic?" (reasoned from the code, not run)":""}`),r.assertion&&s.push(`assertion: ${y(r.assertion)}`),r.observable&&s.push(`observable: ${y(r.observable)}`),r.checkReadback?.whyThisCheck&&s.push(`why this check: ${y(r.checkReadback.whyThisCheck)}`),r.finding?.whatWasTested&&s.push(`tested: ${y(r.finding.whatWasTested)}`),r.finding?.reproduce&&s.push(`reproduce: ${y(r.finding.reproduce)}`),r.finding?.nextActionCodeRef&&s.push(`\u2192 ${xi(r.finding.nextActionCodeRef)}`);for(let o of r.codeRefs??[])s.push(` ref ${xi(o)}${o.reason?` \u2014 ${y(o.reason)}`:""}`);for(let o of r.evidence??[])s.push(` evidence ${y(o.modality)}: ${y(o.caption)}${o.media?` ${y(o.media.url)}`:o.failureReason?` (${y(o.failureReason)})`:""}`);for(let o of r.verdict?.limitations??[])s.push(` limitation: ${y(o)}`);r.network?.failures?.length&&s.push(` network failures: ${r.network.failures.length}`),console.log(s.join(`
|
|
102
|
+
`))}async function mo(n,e,t,i,r,s){if(await Kt(r,[n,e],`/api/v1/red-team/runs/${n}/checks/${e}/report`,s,{method:"POST",body:{reported:t,...i?{note:i}:{}}})){if(r)return void console.log(JSON.stringify({ok:!0,runId:n,checkRunId:e,reported:t}));console.log(`reported ${t}${i?`: ${y(i)}`:""}`)}}function $i(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 ho(e,t.json===!0)}catch(i){W(t.json===!0,"internal_error",i instanceof Error?i.message:String(i),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,i)=>{try{let r=[i.fixed?"fixed":null,i.disputed!==void 0?"disputed":null,i.skipped!==void 0?"skipped":null].filter(Boolean);if(r.length>1)return W(i.json===!0,"bad_report","report exactly one of --fixed, --disputed, --skipped",void 0,3);if(r.length===1){let s=(r[0]==="disputed"?i.disputed:r[0]==="skipped"?i.skipped:void 0)?.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").trim();return s!==void 0&&!s?W(i.json===!0,"bad_report",`--${r[0]} needs a reason`,void 0,3):await mo(e,t,r[0],s,i.json===!0)}await go(e,t,i.json===!0)}catch(r){W(i.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}})}import{readFileSync as xo,unlinkSync as So,writeFileSync as $o}from"node:fs";import{basename as Ro,join as Ao}from"node:path";import{setTimeout as Oo}from"node:timers/promises";import{emitKeypressEvents as yo}from"node:readline";var wo=36,bo=12,Ri=64*1024,Xt=new Intl.Segmenter(void 0,{granularity:"grapheme"}),ko={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},_o={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function ht(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 vo(n,e){let t="";for(let{segment:i}of[...Xt.segment(S(n))].reverse()){if(We(i+t)>e)break;t=i+t}return t}function Ai(n,e,t){let i=n.question,r=Math.max(1,e-5),s=(c,u="text")=>` ${Ge(S(c),u,t)}`,o=0;if(i.secret){for(let c of Xt.segment(n.input??""))if(++o===24)break}let a=i.secret?"\u2022".repeat(o):vo(n.input??"",Math.max(1,r-2));return[s("CANARY \xB7 SETUP","gold"),s(`${n.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${ht(n.seconds)}`),s(`CLI workspace ${n.workspace}`,"muted"),"",s(i.key,"gold"),...re(i.prompt,r).map(c=>s(c)),s(n.inputActive?`\u203A ${a||(i.secret?"(hidden)":"")}`:n.inputSubmitted?"Value captured locally.":"Input deferred","muted"),s(n.inputNotice??(i.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 Co(n,e,t,i){let r=Math.max(1,e-5),s=Math.max(1,t-2),o=n.outcome?_o[n.outcome.status]:n.question?"Your input is needed":ko[n.status],a=n.outcome?.status==="green"?"green":"gold",c=(f,h="text")=>Ge(S(f),h,i),u;if(s<=3)u=[c(o,a),c(`Elapsed ${ht(n.seconds)}`,"muted")].slice(0,s);else if(n.question&&!n.outcome)u=Ai(n,e,i);else{let f=n.seconds%1.6,h=!n.outcome&&["pending","running"].includes(n.status)&&f<1.4?Math.sin(f/1.4*Math.PI*2)*Math.sin(f/1.4*Math.PI):0,g=Ae[Math.max(0,Math.min(16,Math.round(h*10)+8))];if(e>=76&&t>=23){let d={1:c("CANARY \xB7 SETUP","gold"),3:c(o,a),5:c(`Elapsed ${ht(n.seconds)}`,"muted")};u=["",...g.map((m,p)=>` ${c(m,a)} ${d[p]??""}`)]}else u=[` ${c("CANARY \xB7 SETUP","gold")}`,` ${c(o,a)}`,` ${c(`Elapsed ${ht(n.seconds)}`,"muted")}`];u.push("",` ${c(`Repository ${n.repository}`)}`,` ${c(`CLI workspace ${n.workspace}`)}`),n.detail&&!n.outcome&&u.push(...re(n.detail,r).map(d=>` ${c(d,"muted")}`)),n.outcome||u.push("",` ${c("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(u.length>s?[...u.slice(0,Math.max(0,s-2)),...u.slice(-2)]:u).map(f=>lt(f,Math.max(1,e-1)))}function Oi(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,i=!process.env.NO_COLOR,r=Re(e),s=performance.now(),o={...n,status:"submitting",seconds:0},a=!1,c=!1,u,l=!1,f,h,g=()=>({columns:e.columns||80,rows:e.rows||24}),d=C=>{try{e.write(C)}catch{}},m=()=>d(`${L}0m${L}?25h`);function p(){if(a||l)return;o.seconds=(performance.now()-s)/1e3;let{columns:C,rows:P}=g();try{r.render(Co(o,C,P,i))}catch{w()}}function _(){let{columns:C,rows:P}=g();return t.isTTY&&C>=wo&&P>=bo&&Ai(o,C,!1).length<=P-2}function k(){let C=o.question;if(!C)return;l=!0;try{r.render([])}catch{}let P=Math.max(1,g().columns-3);d(`
|
|
103
|
+
Input needed: ${S(C.key)}
|
|
104
|
+
${re(C.prompt,P).join(`
|
|
105
105
|
`)}
|
|
106
106
|
|
|
107
107
|
Answer with: canary setup --answer '<value>'
|
|
108
|
-
`)}function
|
|
108
|
+
`)}function v(){h&&!_()?h.settle(null,!0):p()}function b(){!a||h||c||(c=!0,process.off("SIGINT",A),process.off("SIGTERM",N),process.off("exit",w),m(),u!==void 0&&(d(`
|
|
109
109
|
Stopped watching. Run canary setup to resume verification.
|
|
110
|
-
`),process.exit(
|
|
111
|
-
`)),fe="";else if(ae){let ve=(
|
|
112
|
-
Warning: ${
|
|
110
|
+
`),process.exit(u)))}function w(){a||(a=!0,clearInterval(f),e.off("resize",v),h?.settle(null),b())}function x(C){u=C,w(),b()}function A(){h?h.settle(null):x(130)}function N(){x(143)}async function j(C,P){return a||h||P?.aborted?null:(o.question={...C},o.input="",o.inputActive=!0,o.inputSubmitted=!1,o.inputNotice=void 0,l=!1,_()?new Promise($=>{let z=t.isRaw,Qe=t.readableFlowing===!0,K="",fe="",ae=!1,pe=!1,q="",Pe=!1,Me=!1,Le=!1,Ze=!1,he;function et(F,R=!1){Ze||(he={answer:he&&F!==null?he.answer:F,showStatic:R||he?.showStatic||!1},Me||=!!q&&!pe,K=fe="",o.input="",(ae||pe||q||Me)&&(o.inputNotice="Finishing clipboard input.",p()),bt())}function bt(){if(Ze||!he||Pe||ae||pe||q||Me)return;let{answer:F,showStatic:R}=he;Ze=!0,t.off("keypress",on),t.off("data",nn),t.off("data",rn),t.off("end",_e),t.off("error",_e),t.off("close",_e),P?.removeEventListener("abort",ke);try{t.setRawMode(z)}catch{}Qe||t.pause(),d(`${L}?2004l`),K="",fe="",o.input="",o.inputActive=!1,o.inputSubmitted=F!==null,o.inputNotice=F===null?"You can provide this value later.":"Input received locally.",h=void 0,R&&!a?k():p(),m(),b(),$(F)}function ke(){et(null)}function _e(){ae=pe=Pe=Me=!1,q="",et(null)}function nn(F){Pe=!0;for(let R of typeof F=="string"?F:F.toString("utf8")){let ve=pe?`${L}201~`:`${L}200~`;q=R===ve[q.length]?q+R:R==="\x1B"?R:"",q===ve&&(pe=!pe,q="")}}function rn(){Pe=!1,bt()}function sn(F){K.length+F.length>Ri?(Le=!0,o.inputNotice="Too long. Ctrl+U clears input."):(K+=F,Le||(o.inputNotice=void 0))}function on(F,R){if(!(Ze||!R))try{if(!Pe&&R.name==="escape"&&(q=""),!q&&R.sequence?.startsWith("\x1B")&&(Me=!1),he){R.name==="paste-start"?ae=!0:R.name==="paste-end"&&(ae=!1),bt();return}if(R.name==="paste-start"){ae=!0,fe="";return}if(R.name==="escape"||R.ctrl&&["c","d"].includes(R.name??"")){ke();return}if(R.name==="paste-end")ae=!1,sn(fe.replace(/\r\n?/g,`
|
|
111
|
+
`)),fe="";else if(ae){let ve=(F||R.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(R.sequence??"").includes("\x1B")||(fe.length+ve.length<=Ri?fe+=ve:(Le=!0,o.inputNotice="Too long. Ctrl+U clears input."));return}else if(R.ctrl&&R.name==="u")K="",Le=!1,o.inputNotice=void 0;else if(R.name==="backspace")K=[...Xt.segment(K)].slice(0,-1).map(qi=>qi.segment).join("");else if(R.name==="return"||R.name==="enter"){if(!K.trim())o.inputNotice="Enter a value, or Esc to answer later.";else if(!Le){et(K);return}}else!R.ctrl&&!R.meta&&F&&sn(F.replace(/[\x00-\x1f\x7f-\x9f]/g,""));o.input=K,p()}catch{ke()}}h={settle:et};try{if(t.prependListener("data",nn),yo(t),t.on("keypress",on),t.on("data",rn),t.once("end",_e),t.once("error",_e),t.once("close",_e),P?.addEventListener("abort",ke,{once:!0}),P?.aborted){ke();return}t.setRawMode(!0),t.resume(),d(`${L}?2004h${L}?25l`),p()}catch{ke()}}):(o.inputActive=!1,k(),null))}return e.on("resize",v),process.on("SIGINT",A),process.on("SIGTERM",N),process.once("exit",w),f=setInterval(p,80),f.unref(),d(`${L}?25l`),p(),{update(C,P){a||(o.status=C,o.detail=P,h||(o.question=void 0,o.input=void 0,l=!1),d(`${L}?25l`),p())},warn(C){if(!a)try{r.render([])}catch{w()}d(`
|
|
112
|
+
Warning: ${C.split(/\r?\n/).map(S).join(`
|
|
113
113
|
`)}
|
|
114
114
|
|
|
115
|
-
`),
|
|
116
|
-
${
|
|
115
|
+
`),p()},ask:j,finish(C){if(a)return;h?.settle(null),o.question=void 0,o.outcome=C,l=!1,p(),w();let P=[C.message,...C.updatedFiles?.length?[`Updated locally: ${C.updatedFiles.join(", ")}`]:[],...C.warning?[`Warning: ${C.warning}`]:[],...C.next?[`Next: ${C.next}`]:[]].filter($=>!!$);P.length&&d(`
|
|
116
|
+
${P.flatMap($=>$.split(/\r?\n/).map(S)).join(`
|
|
117
117
|
`)}
|
|
118
|
-
`)},stop:
|
|
119
|
-
`);function
|
|
120
|
-
Fix: ${f.fix}`:""}`),process.exitCode=1;return}throw f}let r=
|
|
121
|
-
`).length,o=
|
|
122
|
-
`)||void 0,next:`Open Canary: ${
|
|
118
|
+
`)},stop:w}}var Ee=3e3,gt=2,Io=9e4;function H(n,e){for(let t of[...n.secrets].sort((i,r)=>r.length-i.length))t&&(e=e.split(t).join("[redacted]"));return e}var Qt=n=>Ao(n,".canary","verify-job.json");function Zt(n){try{let e=JSON.parse(xo(Qt(n),"utf8"));if(typeof e.jobId!="string")return null;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}:{}}}catch{return null}}function Eo(n){return Zt(n)?.jobId??null}var To=(n,e)=>$o(Qt(n),JSON.stringify(e)+`
|
|
119
|
+
`);function mt(n){try{So(Qt(n))}catch{}}var Te=(n,e)=>Oo(n,void 0,{signal:e});function No(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 Po(n,e){let t,i=null;try{t=ct(n),Ve(n),i=de(n),i&&we(i)}catch(f){if(f instanceof V){e?console.log(JSON.stringify({ok:!1,error:f.code,message:f.message,...f.fix?{fix:f.fix}:{}})):console.error(`\u2717 ${f.message}${f.fix?`
|
|
120
|
+
Fix: ${f.fix}`:""}`),process.exitCode=1;return}throw f}let r=i?`${i.owner}/${i.name}`:null,s=t.setupSh.trim().split(`
|
|
121
|
+
`).length,o=No(t.runJson),a=[...new Set([...t.envManifest.map(f=>f.name),...Object.keys(t.envValues)])],c=t.envManifest.filter(f=>f.neededAt==="boot").map(f=>f.name),{missing:u}=Gt(t.envManifest,t.envValues),l=u.length===0;e?console.log(JSON.stringify({ok:l,repo:r,recipe:{setupShLines:s,services:o,envKeys:a,bootRequired:c,missing:u}})):(console.log(`Repo ${r??"(no git remote)"}`),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 ${u.length?`MISSING: ${u.join(", ")}`:"all present"}`),l?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${u.join(", ")} (boot-required) ${u.length===1?"has":"have"} no value.`)),l||(process.exitCode=1)}function Ii(n,e,t,i,r={}){if(e.status==="green"){let s=Zt(n)?.workspace;mt(n);let o=[];if(e.approved?.healed&&r.writeBack!==!1)try{o=Un(n,e.approved)}catch(a){let c=H(i,`Could not update .canary/ with the approved changes: ${a instanceof Error?a.message:String(a)}`);i.warnings.push(c),i.display||console.error(`! ${c}`)}return t?console.log(JSON.stringify({ok:!0,status:"green",jobId:e.jobId,...s?{workspace:s}:{},...r.recipeChanged?{recipeChanged:!0}:{},...e.approved?{approved:{healed:e.approved.healed,...e.approved.version!==void 0?{version:e.approved.version}:{},...o.length?{updatedFiles:o}:{}}}:{}})):i.display?i.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${s?` Workspace: ${s.name}.`:""}`,updatedFiles:o,warning:i.warnings.join(`
|
|
122
|
+
`)||void 0,next:`Open Canary: ${ee().replace(/\/+$/,"")}/repositories`}):(console.log("\u2713 Verified \u2014 the recipe boots from zero in a clean sandbox. This repo is set up on Canary."),s&&console.log(` Workspace: ${s.name}`),e.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),o.length?console.log(` Updated locally to match: ${o.join(", ")}`):r.writeBack===!1&&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"){mt(n);let s={phase:e.failure?.phase?H(i,e.failure.phase):null,failingCommand:e.failure?.failingCommand?H(i,e.failure.failingCommand):null,log:e.failure?.log?H(i,e.failure.log):null};return t?console.log(JSON.stringify({ok:!1,status:e.status,jobId:e.jobId,failure:s})):i.display?i.display.finish({status:e.status,message:`Verification ${e.status==="error"?"errored":"failed"}${s.phase?` (${s.phase})`:""}${s.failingCommand?` at: ${s.failingCommand}`:""}${s.log?`
|
|
123
123
|
|
|
124
|
-
${s.log.slice(-2e3)}`:""}`,warning:
|
|
124
|
+
${s.log.slice(-2e3)}`:""}`,warning:i.warnings.join(`
|
|
125
125
|
`)||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:H(
|
|
127
|
-
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function
|
|
128
|
-
`+(
|
|
129
|
-
Fix: ${a}`:""}`)}else if(s instanceof E){let o=H(r,s.message),a=s.fix?H(r,s.fix):void 0;
|
|
130
|
-
Fix: ${a}`:""}`)}else{let o=H(r,s instanceof Error?s.message:String(s));
|
|
131
|
-
`)}catch{}}function
|
|
132
|
-
`,exit:1}:{stream:"stderr",text:`\u2717 ${
|
|
133
|
-
`,exit:1};if(e){let
|
|
134
|
-
`,exit:0}}return{stream:"stdout",text:`${
|
|
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:H(i,e.needsInput.key),prompt:H(i,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(`
|
|
127
|
+
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function Ei(n,e){return n.status==="needs_input"&&n.needsInput?.questionId===e.questionId}async function Mo(n,e,t){let i=new AbortController,r=new AbortController,s=n.display.ask({...e,key:H(n,e.key),prompt:H(n,e.prompt)},i.signal).then(a=>({kind:"answer",value:a})),o=(async()=>{for(;;){await Te(Ee,r.signal);let a=await t(r.signal);if(!Ei(a,e))return{kind:"state",view:a}}})();try{return await Promise.race([s,o])}finally{r.abort(),i.abort(),await Promise.allSettled([s,o])}}async function Lo(n,e,t,i,r,s){let o="",a=null;async function c(l){for(;;)try{let f=await I(`/api/v1/cli/verify/${e}`,{token:t,signal:l});return a=null,f}catch(f){if(l?.aborted)throw f;if(f instanceof E&&f.status===0&&(a===null&&(a=Date.now(),r.display?r.display.update("retrying","Cloud service unreachable. Retrying the same job."):i||console.log(" \u2026 cloud service unreachable \u2014 retrying")),Date.now()-a<Io)){await Te(Ee,l);continue}throw f}}let u;for(;;){let l=u??await c();if(u=void 0,l.status==="interrupted")return"interrupted";if(l.status==="needs_input"&&s&&l.needsInput?.questionId===s.questionId&&Date.now()<s.until){await Te(Ee);continue}if(l.status==="needs_input"&&l.needsInput&&r.display){let f=l.needsInput,h=await Mo({...r,display:r.display},f,c);if(h.kind==="state"){u=h.view;continue}let g=h.value;if(g===null)return r.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 d=await c();if(!Ei(d,f)){u=d;continue}r.display.update("answering","Sending your answer to the verifier.");try{await Ni(n,e,t,f,g,i,r)}catch(m){if(m instanceof E&&m.status===409)continue;throw m}s={questionId:f.questionId,until:Date.now()+3e4},r.display.update("answering","Answer received. Waiting for verification to continue."),await Te(Ee);continue}if((l.status==="pending"||l.status==="running")&&(r.display?r.display.update(l.status):l.status!==o&&!i&&console.log(` \u2026 ${l.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),o=l.status,Ii(n,l,i,r))return"terminal";await Te(Ee)}}async function yt(n,e,t,i,r,s){me();let o=e;for(let a=0;;){if(await Lo(n,o,t,i,r,s)==="terminal")return;if(mt(n),a>=gt){i?console.log(JSON.stringify({ok:!1,status:"interrupted",jobId:o})):r.display?r.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,i?console.error(JSON.stringify({event:"resubmitted",attempt:a,of:gt})):r.display?r.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${gt}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${gt})`);let u=await Ti(n,t,i,r);if(u===null)return;o=u,s=void 0}}async function Ti(n,e,t,i){let r=ct(n);Ve(n);let s=de(n);if(!s)return t?console.log(JSON.stringify({ok:!1,error:"no_git_remote",fix:"run inside a git repo with a GitHub origin"})):i.display?i.display.finish({status:"error",message:"No GitHub origin found.",next:"Run canary setup inside the repository you want to set up."}):console.error("\u2717 No GitHub origin found \u2014 run inside the repo you're setting up."),process.exitCode=1,null;we(s);let{missing:o}=Gt(r.envManifest,r.envValues);if(o.length)return t?console.log(JSON.stringify({ok:!1,error:"missing_boot_env",missing:o})):i.display?i.display.finish({status:"error",message:`Boot-required environment values are missing: ${o.join(", ")}`,next:"Fill .canary/env.json and run canary setup again."}):console.error(`\u2717 Boot-required env without values: ${o.join(", ")} \u2014 fill .canary/env.json first.`),process.exitCode=1,null;let a=await I("/api/v1/cli/verify",{method:"POST",token:e,body:{repoFullName:`${s.owner}/${s.name}`,...O().team?.id?{workspaceId:O().team?.id}:{},setupSh:r.setupSh,runJson:JSON.stringify(r.runJson??null),env:{manifest:r.envManifest,values:r.envValues}}}),c=a.workspace&&typeof a.workspace.id=="string"&&typeof a.workspace.name=="string"?a.workspace:void 0;return To(n,{jobId:a.jobId,recipeHash:Wt(r),...c?{workspace:c}:{}}),a.jobId}async function Fo(n,e,t){let i=U();if(!i){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}Ue();let r=Zt(n),s=r?.jobId??null;if(s){t.display?.update("submitting","Checking your saved verification job.");let a=null,c=!1,u=Date.now()+3e4;for(;;)try{if(a=await I(`/api/v1/cli/verify/${s}`,{token:i}),!a||!["pending","running","needs_input","green","red","error","interrupted"].includes(a.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(l){if(l instanceof E&&l.status===0){if(Date.now()<u){t.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await Te(Ee);continue}c=!0}else if(!(l instanceof E&&l.status===404))throw l;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 yt(n,s,i,e,t);return}if(a.status==="green"||a.status==="red"||a.status==="error"){let l=!1;if(r?.recipeHash)try{l=Wt(ct(n))!==r.recipeHash}catch{l=!0}e?console.error(JSON.stringify({event:"previous_job_result",jobId:s,...l?{recipeChanged:!0}:{}})):t.display?t.warnings.push(l?"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.
|
|
128
|
+
`+(l?" .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.")),Ii(n,a,e,t,{writeBack:!l,recipeChanged:l});return}}mt(n)}let o=await Ti(n,i,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 yt(n,o,i,e,t))}async function Ni(n,e,t,i,r,s,o){if(i.secret&&r&&o.secrets.add(r),await I(`/api/v1/cli/verify/${e}/answer`,{method:"POST",token:t,body:{questionId:i.questionId,value:r}}),i.secret)try{Jt(n,[{name:i.key,value:r,class:"external_boot",why:i.prompt.slice(0,200)||"asked during cloud verification"}]),!s&&!o.display&&console.log(`Saved ${H(o,i.key)} to .canary/env.json for future runs.`)}catch(a){let c=H(o,`Could not save ${i.key} to .canary/env.json: ${a instanceof Error?a.message:String(a)}`);o.display?o.display.warn(c):console.error(`! ${c}`)}}async function jo(n,e,t,i){let r=U(),s=Eo(n);if(!r||!s){t?console.log(JSON.stringify({ok:!1,error:s?"not_logged_in":"no_active_job",fix:s?"canary login":"canary setup"})):i.display?i.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=await I(`/api/v1/cli/verify/${s}`,{token:r});if(o.status!=="needs_input"||!o.needsInput){i.display?i.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 yt(n,s,r,t,i);return}let a=o.needsInput;i.display?.update("answering","Sending your answer to the verifier."),await Ni(n,s,r,a,e,t,i),i.display?i.display.update("answering","Answer received. Waiting for verification to continue."):t||console.log(`Answered ${H(i,a.key)} \u2014 resuming \u2026`),await yt(n,s,r,t,i,{questionId:a.questionId,until:Date.now()+3e4})}function Pi(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)").action(async e=>{let t=e.dir??process.cwd();ot({cwd:t});let i=e.json===!0;if(e.check){Po(t,i);return}let r={secrets:new Set(e.answer?[e.answer]:[]),warnings:[]};try{let s=de(t),o=O().team;r.display=Oi({json:i,animation:e.animation!==!1,repository:s?`${s.owner}/${s.name}`:Ro(t),workspace:o?.name||(o?.id?"Saved workspace":"Platform default")}),e.answer!==void 0?await jo(t,e.answer,i,r):await Fo(t,i,r)}catch(s){if(s instanceof V){let o=H(r,s.message),a=s.fix?H(r,s.fix):void 0;i?console.log(JSON.stringify({ok:!1,error:s.code,message:o,...a?{fix:a}:{}})):r.display?r.display.finish({status:"error",message:o,next:a}):console.error(`\u2717 ${o}${a?`
|
|
129
|
+
Fix: ${a}`:""}`)}else if(s instanceof E){let o=H(r,s.message),a=s.fix?H(r,s.fix):void 0;i?console.log(JSON.stringify({ok:!1,error:"api_error",status:s.status,message:o,...a?{fix:a}:{}})):r.display?r.display.finish({status:"error",message:o,next:a||"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}${a?`
|
|
130
|
+
Fix: ${a}`:""}`)}else{let o=H(r,s instanceof Error?s.message:String(s));i?console.log(JSON.stringify({ok:!1,error:"setup_error",message:o})):r.display?r.display.finish({status:"error",message:o,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}`)}process.exitCode=1}finally{r.display?.stop()}})}import{mkdirSync as Ho,readFileSync as Mi,writeFileSync as Li}from"node:fs";import{join as en}from"node:path";var Uo=5e3,Do=/^[a-z0-9][a-z0-9-]{0,39}$/,Vo=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,Wo="npm i -g @runcanary/cli@latest";function ji(n){let e=en(Lt(),"skills");return{dir:e,body:en(e,`${n}.md`),meta:en(e,`${n}.json`)}}function Go(n){let e=ji(n);try{let t=JSON.parse(Mi(e.meta,"utf8"));return{body:Mi(e.body,"utf8"),meta:t}}catch{return null}}function Jo(n,e){let t=ji(n);try{Ho(t.dir,{recursive:!0,mode:448}),Li(t.body,e.body),Li(t.meta,JSON.stringify(e.meta,null,2)+`
|
|
131
|
+
`)}catch{}}function Fi(n){return n instanceof Error?n.message:String(n)}async function qo(n,e){let t;try{t=await fetch(n,{headers:{...Ce(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${e}`},signal:AbortSignal.timeout(Uo)})}catch(i){return{kind:"failed",reason:Fi(i)}}if(t.status===404)return{kind:"missing"};if(!t.ok){let i=(await t.text().catch(()=>"")).trim().slice(0,200);return{kind:"failed",reason:`HTTP ${t.status}${i?`: ${i}`:""}`}}try{return{kind:"ok",body:await t.text(),contentVersion:t.headers.get("x-canary-skills-version")??void 0}}catch(i){return{kind:"failed",reason:`response body interrupted: ${Fi(i)}`}}}async function tn(n){let e=await qo(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 Jo(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=Go(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 i=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 ${i} \u2014 retry when the server is reachable`}}}}function Bo(n,e){let t=s=>s.replace(/^v/,"").split("-")[0].split(".").map(o=>Number.parseInt(o,10)||0),i=t(n),r=t(e);for(let s=0;s<3;s++){let o=(i[s]??0)-(r[s]??0);if(o!==0)return o<0?-1:1}return 0}function Yo(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 Hi(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 Ne(n,e,t={}){if(!n.ok)return e?{stream:"stdout",text:JSON.stringify({ok:!1,error:n.error,...t})+`
|
|
132
|
+
`,exit:1}:{stream:"stderr",text:`\u2717 ${n.error}
|
|
133
|
+
`,exit:1};if(e){let i={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(i)+`
|
|
134
|
+
`,exit:0}}return{stream:"stdout",text:`${Hi(n)}
|
|
135
135
|
|
|
136
|
-
${
|
|
136
|
+
${n.body}${n.body.endsWith(`
|
|
137
137
|
`)?"":`
|
|
138
|
-
`}`,exit:0}}function
|
|
139
|
-
`,exit:0}}function
|
|
138
|
+
`}`,exit:0}}function Ke(n){(n.stream==="stdout"?process.stdout:process.stderr).write(n.text),process.exit(n.exit)}function zo(n,e,t={}){if(!n.ok||e){let i=Ne(n,e,t);return i.stream==="stdout"?{stdout:i.text,stderr:"",exit:i.exit}:{stdout:"",stderr:i.text,exit:i.exit}}return{stdout:n.body,stderr:`${Hi(n)}
|
|
139
|
+
`,exit:0}}function wt(){return ce().replace(/\/+$/,"")}function Ui(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 tn({key:"index",url:`${wt()}/llms.txt`,cliVersion:n.version()??"0.0.0",notFound:`this Canary server (${wt()}) does not publish skills yet`});Ke(Ne(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 i=!!t.json;Do.test(e)||Ke(Ne({ok:!1,error:`invalid operation name "${e.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},i));let r=n.version()??"0.0.0";if(t.asset!==void 0){Vo.test(t.asset)||Ke(Ne({ok:!1,error:`invalid asset name "${t.asset.slice(0,80)}" \u2014 assets are lowercase file names ending in .html, .json, .md or .txt`},i));let o=await tn({key:`${e}--${t.asset}`,url:`${wt()}/skills/${e}/${t.asset}`,cliVersion:r,notFound:`no such asset "${t.asset}" for "${e}" \u2014 run \`canary skill ${e}\` to see which files it publishes`}),a=zo(o,i,{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 tn({key:e,url:`${wt()}/skills/${e}.md`,cliVersion:r,notFound:`no such operation "${e}" \u2014 run \`canary skills\` to list the operations`});if(s.ok){let o=Yo(s.body);if(o&&r!=="0.0.0-dev"&&Bo(r,o)<0){let a=`"${e}" needs Canary CLI ${o} or newer (you have ${r}). Update: ${Wo}`,c=Ne({ok:!1,error:a},i,{needsCli:o,cliVersion:r});Ke({...c,exit:2})}}Ke(Ne(s,i,{name:e}))})}var Ko=3e3;function Di(n){n.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async e=>{let t=e.json===!0,i=U();if(!i){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 r=await I("/api/v1/cli/auth/whoami",{token:i}),s=O().team,o=s?.id?{id:s.id,name:s.name??r.team.name}:r.team,a=$e(),c=a?await ie({token:i,apiUrl:ce().replace(/\/+$/,"")},a,o.id,AbortSignal.timeout(Ko)):void 0,u=c?.connectUrl??`${ee().replace(/\/+$/,"")}/integrations`;t?console.log(JSON.stringify({ok:!0,user:r.user,team:r.team,workspace:o,...a?{repository:{name:a,...c?.state?{state:c.state}:{},connectUrl:u,...c?.workspaces?{workspaces:c.workspaces}:{}}}:{}})):(console.log(`${r.user.email} (${o.name})`),a&&(console.log(ut(a,c?.state,u,c?.workspaces)),console.log(Je(c?.state,u,o.name,c?.workspaces))))}catch(r){let s=r instanceof E&&r.status===401,o=s?"invalid_token":r instanceof Error?r.message:String(r);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 Gi(){let n=U();if(!n)throw new E(401,"not logged in");let{workspaces:e}=await I("/api/v1/cli/workspaces",{token:n});return e}function Xe(n,e,t,i={}){n?console.log(JSON.stringify({ok:!1,error:e,message:t,...i})):console.error(t),process.exitCode=1}function Vi(n,e){if(e instanceof E&&e.status===401){Xe(n,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}Xe(n,"workspace_error",e instanceof Error?e.message:String(e))}async function Xo(n){let e=await Gi(),t=O().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 i=String(e.length).length;e.forEach((r,s)=>{let o=r.id===t?"*":" ",a=String(s+1).padStart(i," ");console.log(`${o} ${a} ${r.name}`)})}function Wi(n,e){X({...O(),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 Qo(n,e){let t=await Gi(),i=n.trim();if(/^\d+$/.test(i)){let s=Number(i);if(s<1||s>t.length){Xe(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}Wi(t[s-1],e);return}let r=t.filter(s=>s.id===i||s.name.toLowerCase()===i.toLowerCase());if(r.length===0){Xe(e,"workspace_not_found",`No workspace matching "${n}".`,{available:t.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}if(r.length>1){Xe(e,"workspace_ambiguous",`"${n}" matches multiple workspaces \u2014 use the id.`,{matches:r.map(s=>({id:s.id,name:s.name})),fix:`canary workspace use ${r[0].id}`});return}Wi(r[0],e)}function Zo(n){let e=O().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 Ji(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 i=t.json===!0;try{await Xo(i)}catch(r){Vi(i,r)}}),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,i)=>{let r=i.json===!0;try{await Qo(t,r)}catch(s){Vi(r,s)}}),e.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(t=>Zo(t.json===!0))}var Y=new _n;Y.name("canary").description("Canary \u2014 break the code your AI writes.").version(le);Nn();ii(Y);Di(Y);si(Y);Ui(Y);Ji(Y);Pi(Y);bi(Y);$i(Y);ri(Y);Y.parseAsync(process.argv).catch(n=>{console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)});
|