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