@runcanary/cli 0.1.11 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canary.js +54 -54
- package/package.json +1 -1
package/dist/canary.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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 Va=Object.create;var Dn=Object.defineProperty;var qa=Object.getOwnPropertyDescriptor;var Ya=Object.getOwnPropertyNames;var Ka=Object.getPrototypeOf,za=Object.prototype.hasOwnProperty;var
|
|
5
|
-
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${n.commandUsage(e)}`,""],u=n.commandDescription(e);u.length>0&&(c=c.concat([n.wrap(u,o,0),""]));let d=n.visibleArguments(e).map(f=>a(n.argumentTerm(f),n.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let h=n.visibleOptions(e).map(f=>a(n.optionTerm(f),n.optionDescription(f)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let f=n.visibleGlobalOptions(e).map(
|
|
4
|
+
var Va=Object.create;var Dn=Object.defineProperty;var qa=Object.getOwnPropertyDescriptor;var Ya=Object.getOwnPropertyNames;var Ka=Object.getPrototypeOf,za=Object.prototype.hasOwnProperty;var dt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Xa=(t,e)=>{for(var n in e)Dn(t,n,{get:e[n],enumerable:!0})},Qa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ya(e))!za.call(t,o)&&o!==n&&Dn(t,o,{get:()=>e[o],enumerable:!(r=qa(e,o))||r.enumerable});return t};var Za=(t,e,n)=>(n=t!=null?Va(Ka(t)):{},Qa(e||!t||!t.__esModule?Dn(n,"default",{value:t,enumerable:!0}):n,t));var ft=Ne(Jn=>{var qt=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Gn=class extends qt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Jn.CommanderError=qt;Jn.InvalidArgumentError=Gn});var Yt=Ne(Bn=>{var{InvalidArgumentError:ec}=ft(),Wn=class{constructor(e,n){switch(this.description=n||"",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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new ec(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function tc(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Bn.Argument=Wn;Bn.humanReadableArgName=tc});var qn=Ne(yo=>{var{humanReadableArgName:nc}=Yt(),Vn=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(o=>!o._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((o,i)=>o.name().localeCompare(i.name())),n}compareOptions(e,n){let r=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(o=>!o.hidden),r=e._getHelpOption();if(r&&!r.hidden){let o=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!o&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!o&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let o=r.options.filter(i=>!i.hidden);n.push(...o)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>nc(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,o)=>Math.max(r,n.subcommandTerm(o).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,o)=>Math.max(r,n.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,o)=>Math.max(r,n.optionTerm(o).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,o)=>Math.max(r,n.argumentTerm(o).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let o=e.parent;o;o=o.parent)r=o.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),o=n.helpWidth||80,i=2,s=2;function a(f,m){if(m){let g=`${f.padEnd(r+s)}${m}`;return n.wrap(g,o-i,r+s)}return f}function l(f){return f.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${n.commandUsage(e)}`,""],u=n.commandDescription(e);u.length>0&&(c=c.concat([n.wrap(u,o,0),""]));let d=n.visibleArguments(e).map(f=>a(n.argumentTerm(f),n.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let h=n.visibleOptions(e).map(f=>a(n.optionTerm(f),n.optionDescription(f)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let f=n.visibleGlobalOptions(e).map(m=>a(n.optionTerm(m),n.optionDescription(m)));f.length>0&&(c=c.concat(["Global Options:",l(f),""]))}let p=n.visibleCommands(e).map(f=>a(n.subcommandTerm(f),n.subcommandDescription(f)));return p.length>0&&(c=c.concat(["Commands:",l(p),""])),c.join(`
|
|
6
6
|
`)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,o=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",s=new RegExp(`[\\n][${i}]+`);if(e.match(s))return e;let a=n-r;if(a<o)return e;let l=e.slice(0,r),c=e.slice(r).replace(`\r
|
|
7
7
|
`,`
|
|
8
8
|
`),u=" ".repeat(r),h="\\s\u200B",p=new RegExp(`
|
|
9
|
-
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=c.match(p)||[];return l+f.map((
|
|
10
|
-
`?"":(g>0?u:"")+
|
|
11
|
-
`)}};yo.Help=Vn});var Xn=Ne(zn=>{var{InvalidArgumentError:rc}=
|
|
9
|
+
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=c.match(p)||[];return l+f.map((m,g)=>m===`
|
|
10
|
+
`?"":(g>0?u:"")+m.trimEnd()).join(`
|
|
11
|
+
`)}};yo.Help=Vn});var Xn=Ne(zn=>{var{InvalidArgumentError:rc}=ft(),Yn=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=ic(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new rc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return oc(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Kn=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let o=this.negativeOptions.get(r).presetArg,i=o!==void 0?o:!1;return n.negate===(i===e)}};function oc(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function ic(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}zn.Option=Yn;zn.DualOptions=Kn});var bo=Ne(wo=>{function sc(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let i=1;t[o-1]===e[r-1]?i=0:i=1,n[o][r]=Math.min(n[o-1][r]+1,n[o][r-1]+1,n[o-1][r-1]+i),o>1&&r>1&&t[o-1]===e[r-2]&&t[o-2]===e[r-1]&&(n[o][r]=Math.min(n[o][r],n[o-2][r-2]+1))}return n[t.length][e.length]}function ac(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let r=[],o=3,i=.4;return e.forEach(s=>{if(s.length<=1)return;let a=sc(t,s),l=Math.max(t.length,s.length);(l-a)/l>i&&(a<o?(o=a,r=[s]):a===o&&r.push(s))}),r.sort((s,a)=>s.localeCompare(a)),n&&(r=r.map(s=>`--${s}`)),r.length>1?`
|
|
12
12
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
13
|
-
(Did you mean ${r[0]}?)`:""}wo.suggestSimilar=ac});var vo=Ne(xo=>{var cc=
|
|
13
|
+
(Did you mean ${r[0]}?)`:""}wo.suggestSimilar=ac});var vo=Ne(xo=>{var cc=dt("node:events").EventEmitter,Qn=dt("node:child_process"),we=dt("node:path"),Zn=dt("node:fs"),L=dt("node:process"),{Argument:lc,humanReadableArgName:uc}=Yt(),{CommanderError:er}=ft(),{Help:dc}=qn(),{Option:ko,DualOptions:fc}=Xn(),{suggestSimilar:So}=bo(),tr=class t extends cc{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:n=>L.stdout.write(n),writeErr:n=>L.stderr.write(n),getOutHelpWidth:()=>L.stdout.isTTY?L.stdout.columns:void 0,getErrHelpWidth:()=>L.stderr.isTTY?L.stderr.columns:void 0,outputError:(n,r)=>r(n)},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 n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let o=n,i=r;typeof o=="object"&&o!==null&&(i=o,o=null),i=i||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return o&&(l.description(o),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),o?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new dc,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,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
14
|
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new lc(e,n)}argument(e,n,r,o){let i=this.createArgument(e,n);return typeof r=="function"?i.default(o).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.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,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,o]=e.match(/([^ ]+) *(.*)/),i=n??"display help for command",s=this.createCommand(r);return s.helpOption(!1),o&&s.arguments(o),i&&s.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),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,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
15
15
|
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new er(e,n,r)),L.exit(e)}action(e){let n=r=>{let o=this.registeredArguments.length,i=r.slice(0,o);return this._storeOptionsAsProperties?i[o]=this:i[o]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new ko(e,n)}_callParseArg(e,n,r,o){try{return e.parseArg(n,r)}catch(i){if(i.code==="commander.invalidArgument"){let s=`${o} ${i.message}`;this.error(s,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
16
16
|
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=o=>[o.name()].concat(o.aliases()),r=n(e).find(o=>this._findCommand(o));if(r){let o=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let o=(i,s,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,s):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,a)};return this.on("option:"+n,i=>{let s=`error: option '${e.flags}' argument '${i}' is invalid.`;o(i,s,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let s=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;o(i,s,"env")}),this}_optionEx(e,n,r,o,i){if(typeof n=="object"&&n instanceof ko)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(n,r);if(s.makeOptionMandatory(!!e.mandatory),typeof o=="function")s.default(i).argParser(o);else if(o instanceof RegExp){let a=o;o=(l,c)=>{let u=a.exec(l);return u?u[0]:c},s.default(i).argParser(o)}else s.default(o);return this.addOption(s)}option(e,n,r,o){return this._optionEx({},e,n,r,o)}requiredOption(e,n,r,o){return this._optionEx({mandatory:!0},e,n,r,o)}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,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){L.versions?.electron&&(n.from="electron");let o=L.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(n.from="eval")}e===void 0&&(e=L.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":L.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let h=we.resolve(u,d);if(Zn.existsSync(h))return h;if(o.includes(we.extname(d)))return;let p=o.find(f=>Zn.existsSync(`${h}${f}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Zn.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=we.resolve(we.dirname(u),a)}if(a){let u=i(a,s);if(!u&&!e._executableFile&&this._scriptPath){let d=we.basename(this._scriptPath,we.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}s=u||s}r=o.includes(we.extname(s));let l;L.platform!=="win32"?r?(n.unshift(s),n=_o(L.execArgv).concat(n),l=Qn.spawn(L.argv[0],n,{stdio:"inherit"})):l=Qn.spawn(s,n,{stdio:"inherit"}):(n.unshift(s),n=_o(L.execArgv).concat(n),l=Qn.spawn(L.execPath,n,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{L.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new er(u,"commander.executeSubCommandAsync","(close)")):L.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${s}' does not exist
|
|
@@ -22,63 +22,63 @@ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
22
22
|
`),this.outputHelp({error:!0}));let r=n||{},o=r.exitCode||1,i=r.code||"commander.error";this._exit(o,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in L.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,L.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new fc(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(o=>!n(o)).forEach(o=>{this.setOptionValueWithSource(o,r.implied[o],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=s=>{let a=s.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||s},o=s=>{let a=r(s),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${o(e)} cannot be used with ${o(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],i=this;do{let s=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);o=o.concat(s),i=i.parent}while(i&&!i._enablePositionalOptions);n=So(e,o)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(i=>{o.push(i.name()),i.alias()&&o.push(i.alias())}),n=So(e,o)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let o=this.createOption(n,r);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
23
23
|
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let o=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>uc(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=we.basename(e,we.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=o=>this._outputConfiguration.writeErr(o):r=o=>this._outputConfiguration.writeOut(o),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation(r);if(n&&(o=n(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),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 n=L.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
24
24
|
Expecting one of '${r.join("', '")}'`);let o=`${e}Help`;return this.on(o,i=>{let s;typeof n=="function"?s=n({error:i.error,command:i.command}):s=n,s&&i.write(`${s}
|
|
25
|
-
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(o=>n.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function _o(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",o="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?o=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],o=i[4]),n&&o!=="0"?`${n}=${r}:${parseInt(o)+1}`:e})}xo.Command=tr});var Ro=Ne(te=>{var{Argument:Co}=Yt(),{Command:nr}=vo(),{CommanderError:pc,InvalidArgumentError:$o}=
|
|
25
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(o=>n.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function _o(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",o="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?o=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],o=i[4]),n&&o!=="0"?`${n}=${r}:${parseInt(o)+1}`:e})}xo.Command=tr});var Ro=Ne(te=>{var{Argument:Co}=Yt(),{Command:nr}=vo(),{CommanderError:pc,InvalidArgumentError:$o}=ft(),{Help:hc}=qn(),{Option:Io}=Xn();te.program=new nr;te.createCommand=t=>new nr(t);te.createOption=(t,e)=>new Io(t,e);te.createArgument=(t,e)=>new Co(t,e);te.Command=nr;te.Option=Io;te.Argument=Co;te.Help=hc;te.CommanderError=pc;te.InvalidArgumentError=$o;te.InvalidOptionArgumentError=$o});import{execFileSync as gc}from"node:child_process";import{randomUUID as mc}from"node:crypto";import{chmodSync as yc,mkdirSync as ir,readFileSync as sr,renameSync as wc,rmSync as No,statSync as bc,writeFileSync as Po}from"node:fs";import{homedir as kc}from"node:os";import{dirname as Lo,join as ar}from"node:path";function ne(){return process.env.CANARY_HOME||ar(kc(),".canary")}function cr(){return ar(ne(),"config.json")}function Mo(){let{config:t}=ur();if(t.installId&&Ao.test(t.installId))return t.installId;To??=mc();let e=To;try{z(n=>n.installId&&Ao.test(n.installId)?n:{...n,installId:e})}catch{}return e}function T(){return ur().config}function jo(t){return T().repoFingerprints?.[t]}function Ho(t,e){try{z(n=>({...n,repoFingerprints:{...n.repoFingerprints,[t]:e}}))}catch{}}function Uo(t){Fo=t}function Do(){return`${cr()}.lock`}function Ic(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Ec(t){try{let e=gc("ps",["-o","lstart=","-p",String(t)],{env:{...process.env,LC_ALL:"C"},encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=Date.parse(e);return Number.isFinite(n)?n:null}catch{return null}}function Ac(t){let e;try{e=sr(lr(t),"utf8").trim()}catch{return"unknown"}let[n,r]=e.split(" ").map(Number);if(!Number.isInteger(n)||n<=0||!Number.isFinite(r))return"unknown";try{process.kill(n,0)}catch(i){if(i.code==="ESRCH")return!1}let o=Ec(n);return o===null?!0:Math.abs(o-r)<=Oc}function Jo(t){try{return sr(lr(t),"utf8").trim()===Go}catch{return!1}}function rr(t){try{No(t,{recursive:!0,force:!0})}catch{}}function Wo(t=Do(),e="the config lock"){let n=Date.now()+$c();for(;;)try{return ir(Lo(t),{recursive:!0,mode:448}),ir(t),Po(lr(t),`${Go}
|
|
26
26
|
`,{flag:"wx"}),()=>{Jo(t)&&rr(t)}}catch(r){if(r.code!=="EEXIST")throw r;let o=Ac(t);if(o===!1){rr(t);continue}if(o==="unknown")try{if(Date.now()-bc(t).mtimeMs>vc){rr(t);continue}}catch{}if(Date.now()>=n)throw new Pe(`another canary process is holding ${e}`);Ic(Cc)}}function Bo(t,e,n){let r=Wo(t,e);try{return n()}finally{r()}}function z(t,e={}){let n=()=>{let{config:o,unreadable:i}=ur();if(i&&!e.overwriteUnreadable)return!1;let s=t(i?{}:o);if(!Jo(Do()))throw new Pe("the config lock changed hands during the write");return Tc(s),!0};if(or>0)return n();let r=Wo();or+=1;try{return n()}finally{or-=1,r()}}function ur(){let t;try{t=sr(cr(),"utf8")}catch(e){return{config:{},unreadable:e.code!=="ENOENT"}}try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?{config:{},unreadable:!0}:{config:e,unreadable:!1}}catch{return{config:{},unreadable:!0}}}function Tc(t){let e=cr();ir(Lo(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;try{Po(n,JSON.stringify(t,null,2)+`
|
|
27
27
|
`,{mode:384}),yc(n,384),wc(n,e)}catch(r){throw No(n,{force:!0}),r}}function Vo(){z(({apiUrl:t,webUrl:e,installId:n,agentSkills:r,repoFingerprints:o,gate:i,hooks:s})=>({...t?{apiUrl:t}:{},...e?{webUrl:e}:{},...n?{installId:n}:{},...r!==void 0?{agentSkills:r}:{},...o?{repoFingerprints:o}:{},...i?{gate:i}:{},...s?{hooks:s}:{}}))}function H(){return process.env.CANARY_TOKEN||T().token}function W(){return process.env.CANARY_API_URL||T().apiUrl||Sc}function be(){let t=process.env.CANARY_WEB_URL||T().webUrl;if(t)return t;let e=process.env.CANARY_API_URL||T().apiUrl;return e?e.replace("//api.","//www."):_c}var Sc,_c,Ao,To,Pe,xc,vc,Cc,Fo,$c,lr,Rc,Go,Oc,or,j=J(()=>{"use strict";Sc="https://api.runcanary.ai",_c="https://www.runcanary.ai";Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,To=null;Pe=class extends Error{constructor(e="another canary process is holding the config lock"){super(`${e}; run the command again`),this.name="ConfigLockError"}},xc=15e3,vc=1e4,Cc=20;$c=()=>Fo??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||xc);lr=t=>ar(t,"owner");Rc=Math.round(Date.now()-process.uptime()*1e3),Go=`${process.pid} ${Rc}`,Oc=3e3;or=0});import{mkdirSync as Jc,readFileSync as Wc,writeFileSync as Bc}from"node:fs";import{homedir as Vc}from"node:os";import{dirname as qc,join as Ko}from"node:path";function Xo(){try{return JSON.parse(Wc(hr(),"utf8"))}catch{return{}}}function Kc(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o+=1){let i=(n[o]||0)-(r[o]||0);if(i!==0)return i>0}return!1}function Qo(){if(ve==="0.0.0-dev")return;let{latest:t}=Xo();t&&Kc(t,ve)&&console.error(`A newer Canary CLI is available (${ve} -> ${t}): npm install -g ${zo}`)}function qe(){if(ve==="0.0.0-dev")return;let t=Xo();t.checkedAt&&Date.now()-t.checkedAt<Yc||(async()=>{let e=n=>{try{Jc(qc(hr()),{recursive:!0}),Bc(hr(),JSON.stringify({checkedAt:Date.now(),latest:n??t.latest})+`
|
|
28
|
-
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${zo}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return e();let{version:r}=await n.json();e(r||void 0)}catch{e()}})()}var ve,zo,Yc,hr,Ye=J(()=>{"use strict";ve="0.1.
|
|
28
|
+
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${zo}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return e();let{version:r}=await n.json();e(r||void 0)}catch{e()}})()}var ve,zo,Yc,hr,Ye=J(()=>{"use strict";ve="0.1.12",zo="@runcanary/cli",Yc=1440*60*1e3,hr=()=>Ko(process.env.CANARY_HOME||Ko(Vc(),".canary"),"update-check.json")});import{createHash as zc}from"node:crypto";import{execFileSync as Xc,spawn as Qc}from"node:child_process";function Ke(t){Me={...Me,...t},pt=null}function gr(t=process.env){if(t.CLAUDECODE==="1"||t.CLAUDE_CODE_SESSION_ID){let e=t.CLAUDE_CODE_SESSION_ID??t.CLAUDE_CODE_HOST_SESSION_ID;return{harness:"claude-code",...e?{chatId:e}:{}}}return t.CODEX_SANDBOX||t.CODEX_SANDBOX_NETWORK_DISABLED==="1"?{harness:"codex"}:t.CURSOR_AGENT==="1"?{harness:"cursor"}:{harness:"unknown"}}function Zc(t,e){return zc("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function ti(){return{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(t))),GIT_OPTIONAL_LOCKS:"0",GIT_NO_LAZY_FETCH:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_TERMINAL_PROMPT:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"}}function Zo(t,e){try{let n=ti();return Xc("git",t,{cwd:e,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function el(t,e){let[n,r,o]=(Zo(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],t)??"").split(`
|
|
29
29
|
`);if(!n)return{};let i={worktreeId:Zc(n,e)};if(o!=="true"){let s=jo(i.worktreeId);s&&Zo(["cat-file","-e",`${s}^{commit}`],n)!==null?i.repoFingerprint=s:tl(n,i.worktreeId)}return i.branch=r&&r!=="HEAD"?r:"HEAD",i}function tl(t,e){ei.has(e)||ei.set(e,new Promise(n=>{try{let r=ti(),o=Qc("git",["rev-list","--max-parents=0","HEAD"],{cwd:t,env:r,stdio:["ignore","pipe","ignore"],timeout:6e4}),i="";o.stdout.on("data",s=>{i+=s.toString("utf8")}),o.on("error",()=>n()),o.on("close",s=>{let a=s===0?i.trim().split(`
|
|
30
|
-
`).filter(Boolean).sort()[0]:void 0;a&&Ho(e,a),n()}),o.unref(),o.stdout.unref?.()}catch{n()}}))}function nl(){if(
|
|
31
|
-
`,{flag:"wx",mode:r===null?384:br(s).mode&511});let l;try{l=Xe(t,"utf8")}catch{l=null}if(l!==r){ri(a,{force:!0});continue}return il(a,s),{result:"written"}}catch(l){return ri(a,{force:!0}),{result:"refused",detail:`the file cannot be written (${l.code??"error"})`}}}return{result:"refused",detail:"the file kept changing while it was being edited"}}function ul(t,e,n){for(let r of t){if(!fe(r))throw new ke(`its \`hooks.${e}\` list holds an entry that is not an object`);if(n&&r[n]!==void 0&&!(Array.isArray(r[n])&&r[n].every(fe)))throw new ke(`its \`hooks.${e}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Ie(t,e,n,r="hooks"){if(t.hooks===void 0){if(!n)return null;t.hooks={}}if(!fe(t.hooks))throw new ke("its `hooks` entry is not an object");if(t.hooks[e]===void 0){if(!n)return null;t.hooks[e]=[]}if(!Array.isArray(t.hooks[e]))throw new ke(`its \`hooks.${e}\` entry is not a list`);return ul(t.hooks[e],e,r),t.hooks[e]}function ai(t,e){fe(t.hooks)&&(Array.isArray(t.hooks[e])&&!t.hooks[e].length&&delete t.hooks[e],Object.keys(t.hooks).length||delete t.hooks)}function ci(t){let e;try{e=JSON.parse(Xe(t,"utf8"))}catch(n){return n.code==="ENOENT"?{state:"missing"}:{state:"unreadable",detail:"the file cannot be read as JSON"}}return fe(e)?{doc:e}:{state:"unreadable",detail:"the file does not hold a JSON object"}}function li(t){let e=ll(t.harness),n=Sr(t.harness),r=()=>({matcher:t.matcher,hooks:[{type:"command",command:e,timeout:en}]}),o=l=>fe(l)&&Array.isArray(l.hooks)&&l.hooks.some(n),i=l=>{let c=l.filter(o);return c.length===1&&JSON.stringify(c[0])===JSON.stringify(r())},s=l=>{let c=Ie(l,"PreToolUse",!1);if(!c)return!1;let u=!1;for(let d=c.length-1;d>=0;d--){let h=c[d];if(!fe(h)||!Array.isArray(h.hooks))continue;let p=h.hooks.filter(f=>!n(f));p.length!==h.hooks.length&&(u=!0,p.length?h.hooks=p:c.splice(d,1))}return u&&ai(l,"PreToolUse"),u},a={harness:t.harness,file:t.file,summary:`a PreToolUse hook that runs \`${e}\` before shell and MCP tool calls (${en} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[r()]}},null,2)};return{detected:()=>ze(t.dir),plan:()=>[a],install:()=>[{...a,...Zt(t.file,l=>i(Ie(l,"PreToolUse",!0))?!1:(s(l),Ie(l,"PreToolUse",!0).push(r()),!0))}],uninstall:()=>{if(!ze(t.file))return[{...a,result:"unchanged"}];let l=Zt(t.file,s);return[{...a,...l.result==="written"?{result:"removed"}:l}]},status:()=>{let l=ci(t.file);if(!("doc"in l))return[{harness:t.harness,file:t.file,...l}];let c;try{c=Ie(l.doc,"PreToolUse",!1)}catch(u){return[{harness:t.harness,file:t.file,state:"unreadable",detail:u.message}]}return c?.some(o)?t.disabledKey&&l.doc[t.disabledKey]===!0?[{harness:t.harness,file:t.file,state:"disabled",detail:`\`${t.disabledKey}\` is set, so no hooks run`}]:i(c)?[{harness:t.harness,file:t.file,state:"registered"}]:[{harness:t.harness,file:t.file,state:"modified",detail:"the entry differs from what `canary hooks install` writes; install again to restore it"}]:[{harness:t.harness,file:t.file,state:"missing"}]}}}function dl(t){let e=se(t,"hooks.json"),n=Sr("cursor"),r=()=>({command:"canary hook cursor",timeout:en}),o=a=>
|
|
32
|
-
`):[];if(e==="uninstall"){let s=r.filter(a=>a.trim()!==
|
|
33
|
-
`)),"switched Codex's hooks feature back off")}let o=r.find(s=>/^\s*codex_hooks\s*=/.test(s));if(o)return/=\s*true\b/.test(o)?null:"Codex's hooks feature is switched off in its config.toml (`codex_hooks = false`); the check runs once it is on";let i=r.findIndex(s=>s.trim()==="[features]");return i>=0?r.splice(i+1,0,
|
|
30
|
+
`).filter(Boolean).sort()[0]:void 0;a&&Ho(e,a),n()}),o.unref(),o.stdout.unref?.()}catch{n()}}))}function nl(){if(pt)return pt;let t=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",{harness:e,chatId:n}=gr(),r="",o={};try{r=Mo(),o=el(Me.cwd??process.cwd(),r)}catch{}return pt={cliVersion:ve,command:t,installId:r,...o,harness:e,...n?{chatId:n}:{},...Me.agent!==void 0?{agent:Me.agent}:{},...Me.mode?{mode:Me.mode}:{}},pt}function Ce(){let t=nl(),e=r=>r.replace(/[^\x20-\x7e]/g,"?").slice(0,200),n={[q.cli]:t.cliVersion,[q.harness]:t.harness};return t.installId&&(n[q.install]=t.installId),t.command&&(n[q.command]=e(t.command)),t.worktreeId&&(n[q.worktree]=t.worktreeId),t.repoFingerprint&&(n[q.repo]=t.repoFingerprint),t.branch&&(n[q.branch]=e(t.branch)),t.chatId&&(n[q.chat]=e(t.chatId)),t.agent!==void 0&&(n[q.agent]=t.agent?"1":"0"),t.mode&&(n[q.mode]=t.mode),n}var q,Me,pt,ei,$e=J(()=>{"use strict";j();Ye();q={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={},pt=null;ei=new Map});async function v(t,e={}){let n=(e.baseUrl||W()).replace(/\/+$/,""),r=Ce();e.token&&(r.authorization=`Bearer ${e.token}`),e.body!==void 0&&(r["content-type"]="application/json");let o;try{o=await fetch(n+t,{method:e.method??"GET",headers:r,body:e.body!==void 0?JSON.stringify(e.body):void 0,signal:e.signal})}catch(i){throw new R(0,`could not reach ${n} (${i instanceof Error?i.message:String(i)})`)}if(!o.ok){let i=o.statusText,s,a;try{let l=await o.json();i=l.error||l.message||i,typeof l.fix=="string"&&l.fix&&(s=l.fix),typeof l.runId=="string"&&l.runId&&(a=l.runId)}catch{}throw new R(o.status,i,s,a)}return o.status===204?null:await o.json()}var R,re,B=J(()=>{"use strict";j();$e();R=class extends Error{constructor(n,r,o,i){super(r);this.status=n;this.fix=o;this.runId=i;this.name="ApiError"}},re=t=>t instanceof R&&(t.status===0||t.status===408||t.status===429||t.status===502||t.status===503||t.status===504)});function ni(t){return z(e=>({...e,gate:{...e.gate,mode:t}}))}var je,Qt=J(()=>{"use strict";j();je=()=>T().gate?.mode==="off"?"off":"on"});import{accessSync as oi,constants as ii,existsSync as ze,lstatSync as rl,readFileSync as Xe,readlinkSync as ol,renameSync as il,rmSync as ri,statSync as br,writeFileSync as yr}from"node:fs";import{randomUUID as sl}from"node:crypto";import{homedir as kr}from"node:os";import{delimiter as si,dirname as wr,join as se,resolve as al}from"node:path";function tn(t,e=process.env,n=process.platform){let r=n==="win32"?[t,...(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(o=>t+o.toLowerCase())]:[t];for(let o of(e.PATH??"").split(si).filter(Boolean))for(let i of r)try{if(oi(se(o,i),ii.X_OK),br(se(o,i)).isFile())return!0}catch{}return!1}function cl(t){let e=t;for(let n=0;n<16;n++){let r;try{if(!rl(e).isSymbolicLink())return e;r=ol(e)}catch{return e}e=al(wr(e),r)}throw new ke("its symlinks do not end anywhere")}function Zt(t,e){for(let n=0;n<3;n++){let r;try{r=Xe(t,"utf8")}catch(l){if(l.code!=="ENOENT")return{result:"refused",detail:"the file cannot be read"};r=null}let o={};if(r!==null&&r.trim())try{o=JSON.parse(r)}catch{return{result:"refused",detail:"the file is not valid JSON"}}if(!fe(o))return{result:"refused",detail:"the file does not hold a JSON object"};try{if(!e(o))return{result:"unchanged"}}catch(l){if(l instanceof ke)return{result:"refused",detail:l.message};throw l}let i=r?/^([ \t]+)"/m.exec(r)?.[1]??" ":" ",s;try{s=cl(t)}catch(l){return{result:"refused",detail:l.message}}if(s!==t&&!ze(wr(s)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let a=se(wr(s),`.${sl()}.canary.tmp`);try{yr(a,JSON.stringify(o,null,i)+`
|
|
31
|
+
`,{flag:"wx",mode:r===null?384:br(s).mode&511});let l;try{l=Xe(t,"utf8")}catch{l=null}if(l!==r){ri(a,{force:!0});continue}return il(a,s),{result:"written"}}catch(l){return ri(a,{force:!0}),{result:"refused",detail:`the file cannot be written (${l.code??"error"})`}}}return{result:"refused",detail:"the file kept changing while it was being edited"}}function ul(t,e,n){for(let r of t){if(!fe(r))throw new ke(`its \`hooks.${e}\` list holds an entry that is not an object`);if(n&&r[n]!==void 0&&!(Array.isArray(r[n])&&r[n].every(fe)))throw new ke(`its \`hooks.${e}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Ie(t,e,n,r="hooks"){if(t.hooks===void 0){if(!n)return null;t.hooks={}}if(!fe(t.hooks))throw new ke("its `hooks` entry is not an object");if(t.hooks[e]===void 0){if(!n)return null;t.hooks[e]=[]}if(!Array.isArray(t.hooks[e]))throw new ke(`its \`hooks.${e}\` entry is not a list`);return ul(t.hooks[e],e,r),t.hooks[e]}function ai(t,e){fe(t.hooks)&&(Array.isArray(t.hooks[e])&&!t.hooks[e].length&&delete t.hooks[e],Object.keys(t.hooks).length||delete t.hooks)}function ci(t){let e;try{e=JSON.parse(Xe(t,"utf8"))}catch(n){return n.code==="ENOENT"?{state:"missing"}:{state:"unreadable",detail:"the file cannot be read as JSON"}}return fe(e)?{doc:e}:{state:"unreadable",detail:"the file does not hold a JSON object"}}function li(t){let e=ll(t.harness),n=Sr(t.harness),r=()=>({matcher:t.matcher,hooks:[{type:"command",command:e,timeout:en}]}),o=l=>fe(l)&&Array.isArray(l.hooks)&&l.hooks.some(n),i=l=>{let c=l.filter(o);return c.length===1&&JSON.stringify(c[0])===JSON.stringify(r())},s=l=>{let c=Ie(l,"PreToolUse",!1);if(!c)return!1;let u=!1;for(let d=c.length-1;d>=0;d--){let h=c[d];if(!fe(h)||!Array.isArray(h.hooks))continue;let p=h.hooks.filter(f=>!n(f));p.length!==h.hooks.length&&(u=!0,p.length?h.hooks=p:c.splice(d,1))}return u&&ai(l,"PreToolUse"),u},a={harness:t.harness,file:t.file,summary:`a PreToolUse hook that runs \`${e}\` before shell and MCP tool calls (${en} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[r()]}},null,2)};return{detected:()=>ze(t.dir),plan:()=>[a],install:()=>[{...a,...Zt(t.file,l=>i(Ie(l,"PreToolUse",!0))?!1:(s(l),Ie(l,"PreToolUse",!0).push(r()),!0))}],uninstall:()=>{if(!ze(t.file))return[{...a,result:"unchanged"}];let l=Zt(t.file,s);return[{...a,...l.result==="written"?{result:"removed"}:l}]},status:()=>{let l=ci(t.file);if(!("doc"in l))return[{harness:t.harness,file:t.file,...l}];let c;try{c=Ie(l.doc,"PreToolUse",!1)}catch(u){return[{harness:t.harness,file:t.file,state:"unreadable",detail:u.message}]}return c?.some(o)?t.disabledKey&&l.doc[t.disabledKey]===!0?[{harness:t.harness,file:t.file,state:"disabled",detail:`\`${t.disabledKey}\` is set, so no hooks run`}]:i(c)?[{harness:t.harness,file:t.file,state:"registered"}]:[{harness:t.harness,file:t.file,state:"modified",detail:"the entry differs from what `canary hooks install` writes; install again to restore it"}]:[{harness:t.harness,file:t.file,state:"missing"}]}}}function dl(t){let e=se(t,"hooks.json"),n=Sr("cursor"),r=()=>({command:"canary hook cursor",timeout:en}),o=a=>ht.every(l=>{let c=(Ie(a,l,!1,null)??[]).filter(n);return c.length===1&&JSON.stringify(c[0])===JSON.stringify(r())}),i=a=>{let l=!1;for(let c of ht){let u=Ie(a,c,!1,null);if(!u)continue;let d=u.filter(h=>!n(h));d.length!==u.length&&(l=!0,a.hooks[c]=d,ai(a,c))}return l},s={harness:"cursor",file:e,summary:`a command that runs \`canary hook cursor\` before shell commands and MCP tool calls (${en} s limit)`,snippet:JSON.stringify({version:1,hooks:Object.fromEntries(ht.map(a=>[a,[r()]]))},null,2)};return{detected:()=>ze(t),plan:()=>[s],install:()=>[{...s,...Zt(e,a=>{if(a.version!==void 0&&a.version!==1)throw new ke(`it is version ${JSON.stringify(a.version)} of Cursor's hooks file, which this CLI does not know`);if(o(a))return!1;i(a),a.version===void 0&&(a.version=1);for(let l of ht)Ie(a,l,!0,null).push(r());return!0})}],uninstall:()=>{if(!ze(e))return[{...s,result:"unchanged"}];let a=Zt(e,i);return[{...s,...a.result==="written"?{result:"removed"}:a}]},status:()=>{let a=ci(e);if(!("doc"in a))return[{harness:"cursor",file:e,...a}];try{return ht.some(l=>(Ie(a.doc,l,!1,null)??[]).some(n))?[o(a.doc)?{harness:"cursor",file:e,state:"registered"}:{harness:"cursor",file:e,state:"modified",detail:"the entries differ from what `canary hooks install` writes; install again to restore them"}]:[{harness:"cursor",file:e,state:"missing"}]}catch(l){return[{harness:"cursor",file:e,state:"unreadable",detail:l.message}]}}}}function pl(t=process.env){let e=t.CLAUDE_CONFIG_DIR||se(kr(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...li({harness:"claude",dir:e,file:se(e,"settings.json"),matcher:fl,disabledKey:"disableAllHooks"})}}function hl(t,e){let n;try{n=Xe(t,"utf8")}catch(s){if(s.code!=="ENOENT"||e==="uninstall")return null;n=""}let r=n?n.split(`
|
|
32
|
+
`):[];if(e==="uninstall"){let s=r.filter(a=>a.trim()!==gt);return s.length===r.length?null:(yr(t,s.join(`
|
|
33
|
+
`)),"switched Codex's hooks feature back off")}let o=r.find(s=>/^\s*codex_hooks\s*=/.test(s));if(o)return/=\s*true\b/.test(o)?null:"Codex's hooks feature is switched off in its config.toml (`codex_hooks = false`); the check runs once it is on";let i=r.findIndex(s=>s.trim()==="[features]");return i>=0?r.splice(i+1,0,gt):r.push(...n.trim()?[""]:[],"[features]",gt,""),yr(t,r.join(`
|
|
34
34
|
`)),"switched on Codex's hooks feature (`codex_hooks = true` in its config.toml)"}function gl(t=process.env,e=process.platform){let n=i=>/[\s"']/.test(i)?`"${i}"`:i,r=e==="win32"?["codex.cmd","codex.exe","codex"]:["codex"];for(let i of(t.PATH??"").split(si).filter(Boolean))for(let s of r){let a=se(i,s);try{if(oi(a,ii.X_OK),br(a).isFile())return n(a)}catch{}}let o="/Applications/ChatGPT.app/Contents/Resources/codex";return e==="darwin"&&ze(o)?n(o):null}function yl(t,e,n){let r;try{r=Xe(t,"utf8")}catch(a){return a.code==="ENOENT"?!1:null}let o=`[hooks.state."${e}:pre_tool_use:${n}:0"]`,i=r.split(`
|
|
35
|
-
`),s=i.findIndex(a=>a.trim()===o);if(s<0)return!1;for(let a of i.slice(s+1)){if(/^\s*\[/.test(a))break;if(/^\s*trusted_hash\s*=/.test(a))return!0}return!1}function wl(t=process.env){let e=t.CODEX_HOME||se(kr(),".codex"),n=se(e,"hooks.json"),r=li({harness:"codex",dir:e,file:n,matcher:".*"}),o=se(e,"config.toml"),i=ml(gl(t)),s=Sr("codex"),a=()=>{try{return JSON.parse(Xe(n,"utf8")).hooks.PreToolUse.findIndex(u=>fe(u)&&Array.isArray(u.hooks)&&u.hooks.some(s))}catch{return-1}},l=(c,u)=>{let d=c[0];if(!d||d.result==="refused")return c;let h=null;try{h=hl(o,u)}catch(p){let f=u==="install"?`the hook was added, but Codex's hooks feature could not be switched on: add \`${
|
|
35
|
+
`),s=i.findIndex(a=>a.trim()===o);if(s<0)return!1;for(let a of i.slice(s+1)){if(/^\s*\[/.test(a))break;if(/^\s*trusted_hash\s*=/.test(a))return!0}return!1}function wl(t=process.env){let e=t.CODEX_HOME||se(kr(),".codex"),n=se(e,"hooks.json"),r=li({harness:"codex",dir:e,file:n,matcher:".*"}),o=se(e,"config.toml"),i=ml(gl(t)),s=Sr("codex"),a=()=>{try{return JSON.parse(Xe(n,"utf8")).hooks.PreToolUse.findIndex(u=>fe(u)&&Array.isArray(u.hooks)&&u.hooks.some(s))}catch{return-1}},l=(c,u)=>{let d=c[0];if(!d||d.result==="refused")return c;let h=null;try{h=hl(o,u)}catch(p){let f=u==="install"?`the hook was added, but Codex's hooks feature could not be switched on: add \`${gt}\` under \`[features]\` in ${o} yourself`:`the hook was removed, but the line \`${gt}\` could not be taken out of ${o}: remove it yourself`;return[{...d,result:"refused",detail:`${f} (${p.code??"error"})`},...c.slice(1)]}return h?[{...d,detail:d.detail?`${d.detail}; ${h}`:h},...c.slice(1)]:c};return{id:"codex",label:"Codex",byDefault:!0,afterInstall:mr(i),...r,plan:()=>r.plan().map(c=>({...c,summary:`${c.summary}; switches on Codex's hooks feature in its config.toml`})),install:()=>l(r.install(),"install"),uninstall:()=>l(r.uninstall(),"uninstall"),status:()=>r.status().map(c=>{if(c.state!=="registered")return c;let u=a();if(u<0)return c;let d=yl(o,n,u);if(d===!0)return c;let h=d===null?`Codex's config.toml could not be read, so whether the hook is trusted is unknown. ${mr(i)}`:mr(i);return{...c,state:"untrusted",detail:h,pending:i}})}}function bl(t=process.env){let e=t.CURSOR_CONFIG_DIR||se(kr(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...dl(e)}}var fe,ke,en,ll,Sr,ht,fl,gt,ml,mr,mt,ui=J(()=>{"use strict";fe=t=>!!t&&typeof t=="object"&&!Array.isArray(t),ke=class extends Error{};en=10,ll=(t,e=process.platform)=>e==="win32"?`canary hook ${t}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${t}`,Sr=t=>e=>fe(e)&&typeof e.command=="string"&&new RegExp(`^\\s*(?:command -v canary >/dev/null 2>&1 \\|\\| exit 0;\\s*)?(?:node\\s+)?["']?(?:[^"'\\s]*[\\\\/])?canary(?:\\.js)?["']?\\s+hook\\s+${t}\\s*$`).test(e.command);ht=["beforeShellExecution","beforeMCPExecution"];fl="^(Bash|PowerShell|Monitor|mcp__.*)$";gt="codex_hooks = true # added by canary";ml=t=>({why:"Canary's push check runs before your agent pushes code or opens a pull request: the push is held until the exact code has a Canary run with nothing open, or the agent records a reason to skip. Codex runs a hook only after you have trusted it once, and Codex Desktop has no screen for that yet, so the check does nothing until then.",command:t??"npm i -g @openai/codex && codex",after:'In Codex, choose "Review hooks", accept the Canary entry, then quit.'}),mr=t=>`${t.why} Run \`${t.command}\` in a terminal. ${t.after}`;mt=(t=process.env)=>[pl(t),wl(t),bl(t)]});var Xp,nn,kl,Qp,di=J(()=>{"use strict";Xp=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:t=>`canary verify: tree ${t}`}),nn=t=>`tree:${t.slice(0,12)}`,kl=[["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"]],Qp=kl.flatMap(([t,e])=>["-c",`${t}=${e}`])});import{createHash as Sl}from"node:crypto";import{existsSync as _l,mkdirSync as _r,readFileSync as Qe,writeFileSync as rn}from"node:fs";import{join as Se}from"node:path";function Ze(t){return Se(t,".canary")}function hi(t){let e=t.trim();if(!e)return null;if(!e.includes("://")){let n=e.match(/^[^@]+@([^:]+):(.+)$/);if(n){let r=n[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return r.length>=2?{host:n[1],owner:r[0],name:r.slice(1).join("/")}:null}}try{let n=new URL(e),r=n.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(r.length>=2)return{host:n.host,owner:r[0],name:r.slice(1).join("/")}}catch{}return null}function yt(t){let e=Ze(t),n=Se(e,".gitignore");try{let r=Qe(n,"utf8").split(`
|
|
36
36
|
`).map(o=>o.trim()).filter(o=>o.length>0);if(r[r.length-1]==="*")return}catch{}try{_r(e,{recursive:!0});let r="";try{r=Qe(n,"utf8"),r&&!r.endsWith(`
|
|
37
37
|
`)&&(r+=`
|
|
38
38
|
`)}catch{}rn(n,`${r}*
|
|
39
39
|
`)}catch{}}function Re(t){let e=Ze(t),n;try{n=Qe(Se(e,"setup.sh"),"utf8")}catch{throw new Z("recipe_missing","No .canary/setup.sh found. Produce the recipe first (run the Canary setup skill in your coding agent).","canary setup skill")}if(!n.trim())throw new Z("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(Qe(Se(e,"run.json"),"utf8"))}catch(a){throw new Z("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let o=[],i={},s=Se(e,"env.json");if(_l(s)){let a;try{a=JSON.parse(Qe(s,"utf8"))}catch(c){throw new Z("recipe_invalid",`Cannot read .canary/env.json: ${c instanceof Error?c.message:String(c)}`)}if(a===null||typeof a!="object"||Array.isArray(a))throw new Z("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let l=a;o=mi(l.manifest),i=yi(l.values),vl(o)}return{setupSh:n,runJson:r,envManifest:o,envValues:i}}function He(t){return Sl("sha256").update(JSON.stringify([t.setupSh,t.runJson,t.envManifest,t.envValues])).digest("hex")}function xr(t,e){let n=t.filter(r=>r.neededAt==="boot").map(r=>r.name).filter(r=>!Object.prototype.hasOwnProperty.call(e,r)||e[r]==="");return{missing:[...new Set(n)]}}function mi(t){return Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.name=="string"):[]}function vl(t){for(let e of t){if(!fi.has(String(e.class)))throw new Z("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has unknown class "${String(e.class)}"`,`use one of: ${[...fi].join(", ")}`);if(!xl.has(String(e.neededAt)))throw new Z("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has invalid neededAt "${String(e.neededAt)}"`,'use "boot" or "runtime"')}}function yi(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Cl(t){try{let e=JSON.parse(Qe(Se(Ze(t),"env.json"),"utf8"));return{manifest:mi(e.manifest),values:yi(e.values)}}catch{return{manifest:[],values:{}}}}function $l(t,e){_r(Ze(t),{recursive:!0}),rn(Se(Ze(t),"env.json"),JSON.stringify(e,null,2)+`
|
|
40
|
-
`),
|
|
41
|
-
`}catch{}rn(Se(r,"run.json"),i),n.push(".canary/run.json")}let o=Object.entries(e.envOverrides??{});return o.length>0&&(vr(t,o.map(([i,s])=>({name:i,value:s,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),
|
|
40
|
+
`),yt(t)}function vr(t,e){if(e.length===0)return;let n=Cl(t),r=new Map(n.manifest.map(o=>[o.name,o]));for(let o of e){n.values[o.name]=o.value;let i=r.get(o.name);if(i)o.class&&pi.has(o.class)&&!pi.has(i.class??"")&&(i.class=o.class,i.neededAt="boot");else{let s={name:o.name,class:o.class??"config",neededAt:"boot",why:o.why??"added during cloud verification"};r.set(o.name,s),n.manifest.push(s)}}$l(t,n)}function wi(t,e){let n=[],r=Ze(t);if(_r(r,{recursive:!0}),typeof e.setupSh=="string"&&e.setupSh.trim()&&(rn(Se(r,"setup.sh"),e.setupSh),n.push(".canary/setup.sh")),typeof e.runJson=="string"&&e.runJson.trim()){let i=e.runJson;try{i=JSON.stringify(JSON.parse(e.runJson),null,2)+`
|
|
41
|
+
`}catch{}rn(Se(r,"run.json"),i),n.push(".canary/run.json")}let o=Object.entries(e.envOverrides??{});return o.length>0&&(vr(t,o.map(([i,s])=>({name:i,value:s,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),yt(t),n}var Z,gi,fi,xl,pi,Cr=J(()=>{"use strict";Z=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="RecipeError"}};gi=new Set(["github.com","ssh.github.com"]);fi=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),xl=new Set(["boot","runtime"]);pi=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as Il}from"node:child_process";import{createHash as Rl,randomUUID as Ir}from"node:crypto";import{linkSync as Ol,lstatSync as El,mkdirSync as Rr,readFileSync as Al,realpathSync as on,renameSync as Tl,rmSync as Nl,writeFileSync as Si}from"node:fs";import{basename as Or,dirname as _i,isAbsolute as Pl,join as _e,relative as Ll,resolve as xi,sep as Ml}from"node:path";function jl(t){let e=hi(t);if(!(!e||!gi.has(e.host.toLowerCase().replace(/:\d+$/,"")))&&!(!bi.test(e.owner)||!bi.test(e.name)))return`${e.owner}/${e.name}`}function kt(t=process.cwd()){let e={...Object.fromEntries(Object.entries(process.env).filter(([a])=>!a.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(a))),GIT_OPTIONAL_LOCKS:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"},n=a=>Il("git",a,{cwd:t,env:e,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").replace(/\r?\n$/,""),r,o;try{r=on(n(["rev-parse","--show-toplevel"])),o=on(xi(on(t),n(["rev-parse","--git-common-dir"])))}catch{throw new N("not_a_git_repository","Run this command inside the Git repository you want Canary to use.")}let i;try{i=jl(n(["remote","get-url","origin"]))}catch{}if(i)return{root:r,commonDirectory:o,name:i,githubFullName:i};let s=Or(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:o,name:s}}function Hl(t){let e;try{e=new URL(t)}catch{throw new N("invalid_api_url","The Canary API URL is invalid.")}if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new N("invalid_api_url","The Canary API URL must be HTTP(S) without credentials, a query, or a fragment.");return e.href.replace(/\/+$/,"")}function Er(t){try{return on(t)}catch(e){if(e.code!=="ENOENT")throw e;if(El(t,{throwIfNoEntry:!1})?.isSymbolicLink())throw new N("cache_path_unresolvable","A symlink under CANARY_HOME/local-repositories points at a missing target. Remove or fix that link, then run the command again.");let n=_i(t);if(n===t)throw e;return _e(Er(n),Or(t))}}function $r(t,e){let n=Ll(t,e);return n===""||!Pl(n)&&n!==".."&&!n.startsWith(`..${Ml}`)}function Ar(t,e){let n=Er(e);if(!$r(t,n))throw new N("cache_outside_home","Something under CANARY_HOME/local-repositories links outside CANARY_HOME. Remove that link, then run the command again.");return n}function St(t){if(!wt.test(t.userId)||!wt.test(t.workspaceId))throw new N("invalid_account_context","Sign in with canary login and select a workspace with canary workspace use <id>, then run the command again.");let e=kt(t.directory),n=Hl(t.apiUrl),r=Er(xi(ne())),o=Or(e.commonDirectory)===".git"?_i(e.commonDirectory):e.commonDirectory,i=Rl("sha256").update(JSON.stringify([sn,n,t.userId,t.workspaceId,e.githubFullName?`github:${e.githubFullName.toLowerCase()}`:e.commonDirectory])).digest("hex"),s=_e(r,"local-repositories"),a=Ar(s,_e(s,i));if([e.root,e.commonDirectory,o].some(l=>$r(l,r)||$r(l,a)))throw new N("cache_inside_checkout","CANARY_HOME is inside this repository. Point it at a directory outside the checkout, then run the command again.");return{...e,apiUrl:n,scope:i,cacheRoot:s,cacheDirectory:a}}function ki(t,e){let n=Ar(t.cacheRoot,_e(t.cacheDirectory,e)),r;try{r=Al(n,"utf8")}catch(s){if(s.code==="ENOENT")return null;throw new N("binding_unreadable","Could not read Canary's saved record for this repository under CANARY_HOME/local-repositories. Check its permissions, then run the command again.")}let o;try{o=JSON.parse(r)}catch{}let i=e==="identity.json"?["version","scope","localKey"]:["version","scope","localKey","repositoryId"];if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(s=>!i.includes(s))||o.version!==sn||o.scope!==t.scope||typeof o.localKey!="string"||!wt.test(o.localKey)||e==="repository.json"&&(typeof o.repositoryId!="string"||!wt.test(o.repositoryId)))throw new N("invalid_binding","Canary's saved record for this repository under CANARY_HOME/local-repositories is damaged. Canary left it in place: restore it, or remove it to register this repository as new.");return o}function bt(t){let e=ki(t,"identity.json"),n=ki(t,"repository.json");if(!e&&!n)return null;if(!e||n&&n.localKey!==e.localKey)throw new N("invalid_binding","Canary's saved records for this repository under CANARY_HOME/local-repositories disagree with each other. Canary left them in place: restore them, or remove them to register this repository as new.");return{localKey:e.localKey,...n?{repositoryId:n.repositoryId}:{}}}function vi(t,e,n){Rr(t.cacheDirectory,{recursive:!0,mode:448});let r=_e(t.cacheDirectory,`${e}.${Ir()}.tmp`);try{Si(r,JSON.stringify({version:sn,scope:t.scope,...n})+`
|
|
42
42
|
`,{flag:"wx",mode:384});try{Ol(r,_e(t.cacheDirectory,e))}catch(o){if(o.code!=="EEXIST")throw o}}finally{Nl(r,{force:!0})}}function Ci(t,e){Rr(t.cacheDirectory,{recursive:!0,mode:448});let n=_e(t.cacheDirectory,`repository.json.${Ir()}.tmp`);Si(n,JSON.stringify({version:sn,scope:t.scope,...e})+`
|
|
43
|
-
`,{flag:"wx",mode:384}),Tl(n,_e(t.cacheDirectory,"repository.json"))}function an(t){return
|
|
43
|
+
`,{flag:"wx",mode:384}),Tl(n,_e(t.cacheDirectory,"repository.json"))}function an(t){return bt(St(t))}function cn(t,e){let n=St(t),r=bt(n);!r?.repositoryId||r.repositoryId===e||Ci(n,{localKey:r.localKey,repositoryId:e})}function ae(t,e){if(!/^[a-z0-9-]+\.json(?:\.gz)?$/.test(e))throw new N("invalid_receipt_name","Invalid cache file name.");let n=St(t);return Rr(n.cacheDirectory,{recursive:!0,mode:448}),Ar(n.cacheRoot,_e(n.cacheDirectory,e))}function Fl(t){let e=St(t),n=bt(e);return n||(vi(e,"identity.json",{localKey:Ir()}),bt(e))}function Ul(t,e,n,r){let o=t,i=n.githubFullName?"github":"local";if(!o||typeof o.repositoryId!="string"||!wt.test(o.repositoryId)||o.provider!==i||e.repositoryId&&o.repositoryId!==e.repositoryId&&i!=="github"||(i==="local"?o.localKey!==e.localKey:o.localKey!==void 0)||typeof o.name!="string"||!o.name.trim()||o.name.length>512||/[\u0000-\u001f\u007f]/.test(o.name)||!o.workspace||o.workspace.id!==r||typeof o.workspace.name!="string")throw new N("invalid_repository_response","Canary returned an unexpected answer while looking up this repository. Run the command again; if it repeats, update the CLI.");return o}async function _t(t,e=v){if(!t.token)throw new N("not_logged_in","Run canary login first.");let n=St(t),r=Fl(t),o={token:t.token,baseUrl:n.apiUrl},i=r.repositoryId?await e(`/api/v1/cli/local-repositories/${r.repositoryId}?workspaceId=${encodeURIComponent(t.workspaceId)}`,o):await e("/api/v1/cli/local-repositories",{...o,method:"POST",body:{workspaceId:t.workspaceId,localKey:r.localKey,name:n.name,...n.githubFullName?{githubFullName:n.githubFullName}:{}}}),s=Ul(i,r,n,t.workspaceId);r.repositoryId&&r.repositoryId!==s.repositoryId?Ci(n,{localKey:r.localKey,repositoryId:s.repositoryId}):vi(n,"repository.json",{localKey:r.localKey,repositoryId:s.repositoryId});let a=bt(n);if(a?.repositoryId!==s.repositoryId||a.localKey!==r.localKey)throw new N("binding_conflict","Another canary process registered this repository at the same time. Run the command again.");return s}var wt,sn,bi,N,pe=J(()=>{"use strict";B();j();Cr();wt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sn=2,bi=/^[A-Za-z0-9_.-]+$/,N=class extends Error{constructor(n,r){super(r);this.code=n;this.name="LocalRepositoryError"}}});async function xt(t,e,n=W()){let r=T().team?.id;if(!r)throw new N("workspace_selection_required","Select a workspace with canary workspace list and canary workspace use <id>, then run the command again.");let o=await v("/api/v1/cli/auth/whoami",{token:e,baseUrl:n});if(!o?.user?.id)throw new N("invalid_identity_response","Canary could not tell which account this token belongs to. Run canary login again.");return{apiUrl:n,userId:o.user.id,workspaceId:r,directory:t}}async function ln(t,e,n){let r=an(t);if(!r?.repositoryId)return;let o=await v(`/api/v1/cli/local-repositories/${r.repositoryId}/status?workspaceId=${encodeURIComponent(t.workspaceId)}`,{token:e,baseUrl:t.apiUrl,signal:n});if(typeof o?.repositoryId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o.repositoryId)||!["setup_required","ready"].includes(o.state))throw new N("invalid_readiness_response","Canary returned an unexpected answer about this repository's setup. Run the command again.");return o.repositoryId!==r.repositoryId&&cn(t,o.repositoryId),o}function $i(t=process.cwd()){try{return kt(t).name}catch{return}}var un=J(()=>{"use strict";B();j();pe()});import{spawn as Dl}from"node:child_process";import{createHash as Mr}from"node:crypto";import{constants as Ii}from"node:fs";import{lstat as Gl,mkdir as Oi,mkdtemp as Ei,open as Ai,readFile as Jl,readdir as Wl,readlink as Bl,realpath as vt,rm as Ti,writeFile as Vl}from"node:fs/promises";import{tmpdir as Ni}from"node:os";import{basename as ql,isAbsolute as Yl,join as ce,relative as Kl,resolve as Pi,sep as zl}from"node:path";import{promisify as Xl}from"node:util";import{deflate as Ql}from"node:zlib";function jr(t,e){let n=t.split("/");(!t||Buffer.byteLength(t)>e.maxPathBytes||n.length>e.maxDepth||n.some(r=>!r||Buffer.byteLength(r)>255||r==="."||r===".."||Mi(r)||r.includes("\0")||r.includes("\\")))&&S("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(t)}.`)}function tu(t){return{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")||!t&&["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(n))),GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_NO_LAZY_FETCH:"1",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0",...t?{GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"}:{}}}function ji(t,e){return $t(t).map(n=>{let r=n.indexOf(" "),[o,i,s]=n.slice(0,r).split(" ");return r<0||!(e?Tr.test(i):Tr.test(s))?S("git_source_error","Git returned an invalid source entry."):(e&&s!=="0"&&S("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(r+1),mode:o,oid:e?i:s})})}function tt(t){return(t??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function Ri(t,e){let n=await t.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await Nr(t),o={headSha:n,branch:r,baseRef:null,baseSha:null,baselineMode:"whole-project"};if(e!==void 0){(!e||e.startsWith("-")||e.length>1024||/[\x00-\x1f\x7f]/.test(e))&&S("invalid_base","--base must name a local Git commit or ref.");let a=await t.text(["rev-parse","--verify","--quiet",`${e}^{commit}`],!0);return Tr.test(a)||S("invalid_base",`--base ${JSON.stringify(e)} is not a local commit or ref. Canary does not fetch; pass one that exists locally.`),{...o,baseRef:e,baseSha:a,baselineMode:"explicit"}}if(!n)return o;let i=await t.text(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"],!0),s;for(let a of[[i],["refs/remotes/origin/main","refs/remotes/origin/master"],["main","master"].filter(l=>l!==r).map(l=>`refs/heads/${l}`)]){for(let l of[...new Set(a.filter(Boolean))]){let c=await t.text(["rev-parse","--verify","--quiet",`${l}^{commit}`],!0);if(!c)continue;let u=await t.text(["merge-base",n,c],!0);if(!u)continue;let d=Number(await t.text(["rev-list","--count",`${u}..${n}`]));(!s||d<s.distance)&&(s={ref:l,base:u,distance:d})}if(s)break}return s?{...o,baseRef:s.ref,baseSha:s.base,baselineMode:"merge-base"}:o}async function Pr(t){return new Set($t(await t.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function Fe(t,e,n){if(!e.length)return;let r=$t(await t.run(["check-attr",...n?["--cached"]:[],"-z","--stdin","filter"],{input:`${e.join("\0")}\0`}));for(let o=0;o<r.length;o+=3)r[o+2]==="lfs"&&S("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[o])}. Remove the LFS attribute for it, or ignore the file.`)}function ru(t,e){(t.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
|
|
44
44
|
`)||t.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
|
|
45
45
|
`))&&S("unsupported_lfs",`${JSON.stringify(e)} is a Git LFS pointer. Canary needs the real file contents.`)}function Lr(t,e){(t.length>e.maxTreeFiles||t.reduce((i,s)=>i+s.size,0)>e.maxTreeBytes)&&S("snapshot_limit","This repository has too many files, or too many bytes, to upload.");let n=new Map,r=new Map,o=new Map;for(let i of t){jr(i.path,e),i.link!==void 0&&o.set(i.path,i.link);let s=i.path.split("/");for(let a=1;a<=s.length;a++){let l=s.slice(0,a).join("/"),c=l.normalize("NFC").toLowerCase();n.has(c)&&n.get(c)!==l&&S("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(l)}.`),n.set(c,l);let u=a<s.length;r.has(l)&&r.get(l)!==u&&S("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(l)}.`),r.set(l,u)}}[...r.values()].filter(Boolean).length+1>e.maxObjects&&S("snapshot_limit","This repository has too many directories to upload.");for(let[i,s]of o){(!s||Buffer.byteLength(s)>e.maxSymlinkBytes||s.startsWith("/")||s.includes("\0")||s.includes("\\")||/^[a-z]:/i.test(s))&&S("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(i)}.`);let a=s.split("/"),l=i.split("/").slice(0,-1),c=0;for(;a.length;){let u=a.shift();if(!u||u===".")continue;if(u===".."){l.length||S("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(i)}.`),l.pop();continue}Mi(u)&&S("unsafe_symlink",`Symlink enters Git metadata: ${JSON.stringify(i)}.`),l.push(u);let d=n.get(l.join("/").normalize("NFC").toLowerCase());if(d!==void 0&&o.has(d)){++c>e.maxDepth&&S("unsafe_symlink",`Symlink cycle or excessive chain depth at ${JSON.stringify(i)}.`);let h=o.get(d);(h.startsWith("/")||h.includes("\\")||/^[a-z]:/i.test(h))&&S("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(i)}.`),l.pop(),a.unshift(...h.split("/"))}a.length+l.length>e.maxPathBytes&&S("unsafe_symlink","Symlink expansion exceeds the source limit.")}}}async function hn(t,e){let n=new Map;for(let o of t){let i=o.path.split("/"),s=n;for(let a of i.slice(0,-1))s.has(a)||s.set(a,new Map),s=s.get(a);s.set(i.at(-1),o)}let r=async o=>{let i=[];for(let[s,a]of o)i.push(a instanceof Map?{name:s,mode:"40000",oid:await r(a)}:{name:s,mode:a.mode,oid:a.oid});return i.sort((s,a)=>Buffer.compare(Buffer.from(s.name+(s.mode==="40000"?"/":"")),Buffer.from(a.name+(a.mode==="40000"?"/":"")))),e.put("tree",Buffer.concat(i.map(s=>Buffer.concat([Buffer.from(`${s.mode} ${s.name}\0`),Buffer.from(s.oid,"hex")]))))};return r(n)}async function Hi(t,e){let n=e.split("/");for(let r=1;r<=n.length;r++)try{let o=await Gl(ce(t,...n.slice(0,r)));if(r===n.length)return o;if(!o.isDirectory())return null}catch(o){if(["ENOENT","ENOTDIR"].includes(o.code??""))return null;throw o}return null}async function ou(t,e,n,r){let o=await Hi(t,e);if(n.set(e,o?et(o):null),!o||o.isDirectory())return null;if(!o.isFile()&&!o.isSymbolicLink()&&S("unsupported_file",`This is not a regular file or symlink and cannot be uploaded: ${JSON.stringify(e)}.`),o.size>(o.isSymbolicLink()?r.maxSymlinkBytes:r.maxObjectBytes)&&S("snapshot_limit",`This file is too large to upload: ${JSON.stringify(e)}.`),o.isSymbolicLink())return{data:await Bl(ce(t,e),{encoding:"buffer"}),mode:"120000"};let i=await Ai(ce(t,e),Ii.O_RDONLY|Ii.O_NOFOLLOW);try{et(await i.stat())!==et(o)&&S("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.");let s=Buffer.alloc(o.size+1),a=0;for(;a<s.length;){let c=await i.read(s,a,s.length-a);if(!c.bytesRead)break;a+=c.bytesRead}return(a!==o.size||et(await i.stat())!==et(o))&&S("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped."),{data:s.subarray(0,a),mode:o.mode&73?"100755":"100644"}}finally{await i.close()}}async function iu(t,e,n,r,o){let i=Buffer.from(`# v2 git bundle
|
|
46
46
|
${n} refs/canary/base
|
|
47
47
|
${r} refs/canary/head
|
|
48
48
|
|
|
49
49
|
`),s=await Ai(e,"wx",384);try{let a=t.child(["pack-objects","--stdout","--revs","--no-reuse-delta","--no-reuse-object","--window=0","--threads=1","--compression=6"]),l=Mr("sha256"),c=0,u="";a.stderr.on("data",p=>{u.length<8192&&(u+=p.toString())}),a.stdin.on("error",()=>{});let d=new Promise((p,f)=>{a.on("close",p),a.on("error",f)});d.catch(()=>{});let h=async p=>{c+=p.length,c>o.maxBundleBytes&&S("snapshot_limit","This repository is too large to upload, even compressed."),l.update(p),await s.writeFile(p)};try{await h(i),a.stdin.end(`${r}
|
|
50
|
-
`);for await(let p of a.stdout)await h(p);return await d!==0&&S("git_source_error",`Cannot package source: ${u.trim()}`),{bytes:c,sha256:l.digest("hex")}}finally{a.kill(),await d.catch(()=>{})}}finally{await s.close()}}function Fi(t){let e={
|
|
50
|
+
`);for await(let p of a.stdout)await h(p);return await d!==0&&S("git_source_error",`Cannot package source: ${u.trim()}`),{bytes:c,sha256:l.digest("hex")}}finally{a.kill(),await d.catch(()=>{})}}finally{await s.close()}}function Fi(t){let e={...Ct,...t};for(let[n,r]of Object.entries(e))(!Object.hasOwn(Ct,n)||!Number.isSafeInteger(r)||r<=0||r>Ct[n])&&S("invalid_limit",`Invalid source snapshot limit ${n}.`);return e}async function Ui(t,e){let n=await vt(t),r=new Ue(n,e),o;try{o=await vt(await r.text(["rev-parse","--show-toplevel"]))}catch(l){if(e?.aborted)throw l;return S("not_a_git_repository","Run this command inside a Git repository.")}let i=new Ue(o,e),s=await vt(Pi(o,await i.text(["rev-parse","--git-common-dir"]))),a=await i.text(["config","--get-regexp","^(extensions\\.partialclone|remote\\..*\\.promisor|extensions\\.objectformat)$"],!0);return a.split(`
|
|
51
51
|
`).some(l=>/^extensions\.objectformat\s+(?!sha1$)/i.test(l))&&S("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(a.split(`
|
|
52
|
-
`).some(l=>/^extensions\.partialclone\s/i.test(l)||/^remote\..*\.promisor(?:\s|$)/i.test(l)&&!/\s(false|no|off|0)$/i.test(l))||(await Wl(ce(s,"objects","pack")).catch(()=>[])).some(l=>l.endsWith(".promisor")))&&S("partial_clone","This is a partial clone. Canary needs every Git object on disk and will not fetch them; use a full clone."),{root:o,common:s,git:i}}async function gn(t){let e=ji(await t.run(["ls-files","--stage","-z"]),!0),n=await Pr(t),r=e.filter(s=>Gi(s,n)),o
|
|
52
|
+
`).some(l=>/^extensions\.partialclone\s/i.test(l)||/^remote\..*\.promisor(?:\s|$)/i.test(l)&&!/\s(false|no|off|0)$/i.test(l))||(await Wl(ce(s,"objects","pack")).catch(()=>[])).some(l=>l.endsWith(".promisor")))&&S("partial_clone","This is a partial clone. Canary needs every Git object on disk and will not fetch them; use a full clone."),{root:o,common:s,git:i}}async function gn(t){let e=ji(await t.run(["ls-files","--stage","-z"]),!0),n=await Pr(t),r=e.filter(s=>Gi(s,n)),o=$t(await t.run(["ls-files","--others","--exclude-standard","-z"])).filter(s=>!Di(s)),i=new Set($t(await t.run(["ls-files","-t","-z"])).filter(s=>s.startsWith("S ")).map(s=>s.slice(2)));return{tracked:r,paths:[...new Set([...r.map(s=>s.path),...o])].sort(),skip:i}}async function Ji(t,e){let n=Pi(e,await t.text(["rev-parse","--git-path","index"]));return async()=>{try{return Mr("sha256").update(await Jl(n)).digest("hex")}catch(r){if(r.code==="ENOENT")return"missing";throw r}}}function Wi(t,e){for(let n of t)jr(n.path,e),n.mode==="160000"&&S("unsupported_submodule",`Submodules cannot be uploaded: ${JSON.stringify(n.path)}.`),["100644","100755","120000"].includes(n.mode)||S("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function Bi(t,e){for(let n of t)n.endsWith("/")&&S("unsupported_submodule",`Nested Git repositories cannot be uploaded: ${JSON.stringify(n)}.`),jr(n,e)}function Vi(t,e){let n=new Map;return async(r,o,i)=>{ru(o,r.path);let s=await t.put("blob",o);r.oid&&r.oid!==s&&S("invalid_source_object",`Git blob contents do not match their hash: ${JSON.stringify(r.path)}.`);let a=(n.get(i)??0)+o.length;n.set(i,a),a>e.maxTreeBytes&&S("snapshot_limit","This repository has too many bytes to upload."),i.push({...r,oid:s,size:o.length,...r.mode==="120000"?{link:Li(o)}:{}})}}async function qi(t){let{root:e,current:n,trustFileMode:r,limits:o,stamps:i,capture:s,out:a}=t,l=new Map(n.tracked.map(c=>[c.path,c]));for(let c of n.paths){t.signal?.throwIfAborted();let u=await ou(e,c,i,o);if(u){let d=l.get(c),h=!r&&u.mode!=="120000"&&d&&["100644","100755"].includes(d.mode)?d.mode:u.mode;await s({path:c,mode:h,oid:""},u.data,a)}else if(i.get(c)===null&&n.skip.has(c)){let d=l.get(c);await s(d,await t.blob(d.oid),a)}}}async function Yi(t,e){for(let[n,r]of e){let o=await Hi(t,n);(o?et(o):null)!==r&&S("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function Rt(t,e={}){let n=Fi(e.limits),{root:r,common:o,git:i}=await Ui(t,e.signal),s=await vt(Ni());(fn(r,s)||fn(o,s))&&S("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Ei(ce(s,"canary-source-")),l,c=()=>Ti(a,{recursive:!0,force:!0});try{let u=await Ri(i,e.baseRef),d=await Ji(i,r),h=await d(),p=new Ue(r,e.signal,!1,{GIT_INDEX_FILE:ce(a,"baseline-index")});await p.run(["read-tree",u.baseSha??"--empty"]);let f=u.baseSha?ji(await i.run(["ls-tree","-r","-z","--full-tree",u.baseSha]),!1):[],m=await Pr(p),g=f.filter(I=>Gi(I,m)),w=await gn(i),_=await i.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(g.length>n.maxTreeFiles||w.paths.length>n.maxTreeFiles)&&S("snapshot_limit","This repository has too many files to upload."),Wi([...g,...w.tracked],n),Bi(w.paths,n),await Fe(p,g.map(I=>I.path),!0),await Fe(i,w.paths,!1);let y=ce(a,"repository.git");await Oi(y);let k=new Ue(y,e.signal,!0);await k.run(["init","--bare","--quiet","--template="]);let x=new It(y,n,e.signal);l=new pn(i,n);let E=[],C=[],D=Vi(x,n),xe=l;for(let I of g)await D(I,await l.get(I.oid),E);let O=new Map;await qi({root:r,current:w,trustFileMode:_,limits:n,signal:e.signal,stamps:O,capture:D,blob:I=>xe.get(I),out:C}),Lr(E,n),Lr(C,n);let M=await hn(E,x),me=await hn(C,x);for(let[I,ie]of[[M,E],[me,C]])await k.run(["read-tree",I]),await Fe(k,ie.map(K=>K.path),!0);let ut=await x.put("commit",Buffer.from(`tree ${M}
|
|
53
53
|
author ${dn}
|
|
54
54
|
committer ${dn}
|
|
55
55
|
|
|
56
56
|
Canary snapshot baseline
|
|
57
57
|
`)),Bt=await x.put("commit",Buffer.from(`tree ${me}
|
|
58
|
-
parent ${
|
|
58
|
+
parent ${ut}
|
|
59
59
|
author ${dn}
|
|
60
60
|
committer ${dn}
|
|
61
61
|
|
|
62
62
|
Canary snapshot current
|
|
63
|
-
`)),Q=ce(a,"source.bundle"),ye=await iu(k,Q,
|
|
63
|
+
`)),Q=ce(a,"source.bundle"),ye=await iu(k,Q,ut,Bt,n),le=await gn(i);(h!==await d()||JSON.stringify(w.paths)!==JSON.stringify(le.paths)||JSON.stringify([...m].sort())!==JSON.stringify([...await Pr(p)].sort())||JSON.stringify(u)!==JSON.stringify(await Ri(i,e.baseRef)))&&S("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await Yi(r,O),await Fe(p,g.map(I=>I.path),!0),await Fe(i,w.paths,!1);let ue=new Map(E.map(I=>[I.path,I])),Y=new Map(C.map(I=>[I.path,I])),de=[];for(let I of[...new Set([...ue.keys(),...Y.keys()])].sort()){let ie=ue.get(I),K=Y.get(I);ie?K?(ie.oid!==K.oid||ie.mode!==K.mode)&&de.push({path:I,status:ie.mode==="120000"!=(K.mode==="120000")?"T":"M"}):de.push({path:I,status:"D"}):de.push({path:I,status:"A"})}await l.close(),l=void 0;let Te=C.map(I=>({path:I.path,mode:I.mode,oid:I.oid}));return{bundlePath:Q,manifest:{kind:"local_snapshot",version:2,...ye,baseTreeHash:M,treeHash:me,baseSha:ut,headSha:Bt,provenance:u},files:de,entries:Te,dispose:c}}catch(u){throw await l?.close(),await c(),u}}async function su(t,e,n,r,o,i){let s=await vt(Ni());(fn(t,s)||fn(e,s))&&S("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Ei(ce(s,"canary-identity-"));try{let l=new Ue(a,i,!0);await l.run(["init","--bare","--quiet","--template="]);let c=new It(a,o,i);for(let u of r.values())await c.put("blob",u);await l.run(["read-tree",await hn(n,c)]),await Fe(l,n.map(u=>u.path),!0)}finally{await Ti(a,{recursive:!0,force:!0})}}async function mn(t,e={}){let n=Fi(e.limits),{root:r,common:o,git:i}=await Ui(t,e.signal),s;try{let a=await Nr(i),l=await Ji(i,r),c=await l(),u=await gn(i),d=await i.text(["config","--bool","--get","core.fileMode"],!0)!=="false";u.paths.length>n.maxTreeFiles&&S("snapshot_limit","This repository has too many files to upload."),Wi(u.tracked,n),Bi(u.paths,n),await Fe(i,u.paths,!1);let h=new It(null,n,e.signal),p=[],f=new Map,m=new Map,g=Vi(h,n),w=(k,x,E)=>(ql(k.path)===".gitattributes"&&m.set(k.path,x),g(k,x,E));await qi({root:r,current:u,trustFileMode:d,limits:n,signal:e.signal,stamps:f,capture:w,blob:k=>(s??=new pn(i,n)).get(k),out:p}),Lr(p,n);let _=await hn(p,h);[...m.values()].some(k=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(k.toString("utf8")))&&await su(r,o,p,m,n,e.signal);let y=await gn(i);return(c!==await l()||JSON.stringify(u.paths)!==JSON.stringify(y.paths)||a!==await Nr(i))&&S("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await Yi(r,f),{root:r,treeHash:_,branch:a,files:p.map(k=>({path:k.path,mode:k.mode,oid:k.oid}))}}finally{await s?.close()}}var Ct,ee,S,Zl,eu,Tr,dn,fn,Li,$t,Mi,nu,Ue,Nr,pn,It,et,Di,Gi,nt=J(()=>{"use strict";Ct={maxBundleBytes:4*1024*1024*1024,maxObjectBytes:1024*1024*1024,maxExpandedBytes:16*1024*1024*1024,maxObjects:1e6,maxTreeFiles:5e5,maxTreeBytes:16*1024*1024*1024,maxDepth:64,maxPathBytes:4096,maxSymlinkBytes:4096},ee=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="SourceSnapshotError"}},S=(t,e)=>{throw new ee(t,e)},Zl=Xl(Ql),eu=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),Tr=/^[a-f0-9]{40}$/,dn="Canary Snapshot <snapshot@runcanary.ai> 0 +0000",fn=(t,e)=>{let n=Kl(t,e);return n===""||!n.startsWith(`..${zl}`)&&n!==".."&&!Yl(n)},Li=t=>{try{return eu.decode(t)}catch{return S("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},$t=t=>t.length?Li(t).split("\0").filter(Boolean):[],Mi=t=>{let e=t.normalize("NFC").replace(/[\u200c-\u200f\u202a-\u202e\u206a-\u206f\ufeff]/g,"").toLowerCase().replace(/[ .]+$/g,"");return e===".git"||e.startsWith(".git:")||/^git~[0-9]+(?:\.|$)/.test(e)};nu=["-c","core.fsmonitor=false","-c","core.untrackedCache=false","-c","core.hooksPath=/dev/null","-c","gc.auto=0","-c","maintenance.auto=false","-c","protocol.allow=never"],Ue=class{constructor(e,n,r=!1,o={}){this.cwd=e;this.signal=n;this.isolated=r;this.extra=o}child(e){return this.signal?.throwIfAborted(),Dl("git",[...nu,...e],{cwd:this.cwd,env:{...tu(this.isolated),...this.extra},signal:this.signal,stdio:"pipe"})}async run(e,n={}){let r=this.child(e),o=[],i=0,s="",a;r.on("error",c=>{a=c}),r.stdout.on("data",c=>{i+=c.length,i>(n.maxBytes??256*1024*1024)?(a=new ee("snapshot_limit","This repository's Git metadata is too large to upload."),r.kill()):o.push(c)}),r.stderr.on("data",c=>{s.length<8192&&(s+=c.toString("utf8"))}),r.stdin.on("error",()=>{}),r.stdin.end(n.input);let l=await new Promise(c=>r.on("close",c));if(a)throw a;return l!==0&&!(n.optional&&l===1)&&S("git_source_error",`Cannot read local Git source: ${s.trim()||`git ${e[0]} failed`}`),l===1?Buffer.alloc(0):Buffer.concat(o)}async text(e,n=!1){return(await this.run(e,{optional:n})).toString("utf8").trim()}};Nr=async t=>await t.text(["symbolic-ref","--quiet","--short","HEAD"],!0)||null;pn=class{constructor(e,n){this.limits=n;this.child=e.child(["cat-file","--batch"]),this.child.on("error",r=>{this.error=r}),this.child.stdin.on("error",()=>{}),this.child.stderr.resume(),this.iterator=this.child.stdout[Symbol.asyncIterator]()}child;iterator;pending=Buffer.alloc(0);error;async read(e){let n=[],r=e;for(;r;){if(!this.pending.length){let i=await this.iterator.next();if(i.done)throw this.error??new ee("missing_source_object","A Git object this repository needs is missing on disk. Canary does not fetch; restore it, then run the command again.");this.pending=i.value}let o=Math.min(r,this.pending.length);n.push(this.pending.subarray(0,o)),this.pending=this.pending.subarray(o),r-=o}return Buffer.concat(n,e)}async get(e){this.child.stdin.write(`${e}
|
|
64
64
|
`);let n="";for(;!n.endsWith(`
|
|
65
|
-
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[r,o,i]=n.trim().split(" "),s=Number(i);(r!==e||o!=="blob"||!Number.isSafeInteger(s)||s<0)&&S("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),s>this.limits.maxObjectBytes&&S("snapshot_limit","A file in this repository is too large to upload.");let a=await this.read(s);return(await this.read(1))[0]!==10&&S("git_source_error","Invalid Git object framing."),a}async close(){this.child.exitCode!==null||this.child.signalCode!==null||(this.child.stdin.end(),this.child.kill(),await new Promise(e=>this.child.on("close",()=>e())))}},
|
|
66
|
-
`,{flag:"wx",mode:384}),lu(r,n)}catch(o){throw Ki(r,{force:!0}),o}}catch{}}function yn(t,e=Date.now()){try{let n=ae(t,Xi),r=Date.parse(JSON.parse(cu(n,"utf8")).at??"");return Ki(n,{force:!0}),Number.isFinite(r)&&e-r>=0&&e-r<fu}catch{return!1}}var du,Xi,fu,wn=J(()=>{"use strict";B();pe();du=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);Xi="last-denial.json",fu=1440*60*1e3});import{randomUUID as pu}from"node:crypto";import{readdirSync as hu,readFileSync as gu,renameSync as mu,rmSync as Zi,statSync as ts,writeFileSync as yu}from"node:fs";import{dirname as es,join as wu}from"node:path";import{gunzipSync as bu,gzipSync as ku}from"node:zlib";function os(t,e,n){try{let r=ae(t,rs(e)),o=`${r}.${pu()}.tmp`,i=ku(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:e,entries:n.map(s=>[s.path,s.mode,s.oid])})));try{yu(o,i,{flag:"wx",mode:384}),mu(o,r)}catch(s){throw Zi(o,{force:!0}),s}for(let s of hu(es(r))){if(!s.startsWith("tree-")||!s.endsWith(".json.gz"))continue;let a=wu(es(r),s);try{Date.now()-ts(a).mtimeMs>ns&&Zi(a,{force:!0})}catch{}}}catch{}}function _u(t,e){try{let n=ae(t,rs(e));if(Date.now()-ts(n).mtimeMs>ns)return null;let r=JSON.parse(bu(gu(n)).toString("utf8"));if(r.version!==1||r.treeHash!==e||!Array.isArray(r.entries))return null;let o=new Map;for(let i of r.entries)Array.isArray(i)&&i.length===3&&i.every(s=>typeof s=="string")&&o.set(i[0],`${i[1]}:${i[2]}`);return o}catch{return null}}function is(t,e,n){let r=_u(t,e);if(!r)return null;let o=new Map;for(let a of n){let l=r.get(a.path);l!==`${a.mode}:${a.oid}`&&o.set(a.path,l===void 0?`${a.path} (new)`:a.path)}let i=new Set(n.map(a=>a.path));for(let a of r.keys())i.has(a)||o.set(a,`${a} (removed)`);let s=[...o.keys()].sort().map(a=>o.get(a));return{files:s.slice(0,Su),total:s.length}}var Su,ns,rs,Hr=J(()=>{"use strict";pe();Su=8,ns=720*60*60*1e3,rs=t=>`tree-${t}.json.gz`});import{createHash as xu}from"node:crypto";import{constants as ss}from"node:fs";import{open as vu}from"node:fs/promises";import{Readable as Cu}from"node:stream";function Sn(t){if(!Fr(t,fs))return!1;let e=t.provenance;return t.kind==="local_snapshot"&&t.version===2&&typeof t.sha256=="string"&&/^[a-f0-9]{64}$/.test(t.sha256)&&typeof t.bytes=="number"&&Number.isSafeInteger(t.bytes)&&t.bytes>0&&t.bytes
|
|
67
|
-
`,{flag:"wx",mode:384}),Au(d,i)}finally{ys(d,{force:!0})}}});return{...l.source,uploadId:l.uploadId}}var Gr=J(()=>{"use strict";pe();Ur()});import{readFileSync as ks}from"node:fs";function Mu(t){if(t===void 0)return;let e=t;try{t==="-"?e=ks(0,"utf8"):t.startsWith("@")&&(e=ks(t.slice(1),"utf8"))}catch(n){throw new he("brief_unreadable",`could not read the brief from ${t==="-"?"stdin":t.slice(1)}: ${n instanceof Error?n.message:String(n)}`,"pass the brief as text, @<file>, or - (stdin)")}return e.trim()===""?void 0:e}function ge(t){return t==="P3"?null:t==="P0"||t==="P1"?t:"P2"}function ju(t,e){if(ge(t.materiality)===null)return null;let r=e??null;return t.result==="fail"?{checkRunId:t.checkRunId,kind:"fail",proof:r?.isStatic===!1?"runtime":"source",headline:b(r?.finding?.headline)||b(t.title),summary:b(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:vs(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:b(r?.finding?.reproduce)||null}:t.result==="blocked"?{checkRunId:t.checkRunId,kind:"blocked",proof:"none",headline:b(t.title),summary:b(r?.verdict?.reasonOneLiner)||(
|
|
65
|
+
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[r,o,i]=n.trim().split(" "),s=Number(i);(r!==e||o!=="blob"||!Number.isSafeInteger(s)||s<0)&&S("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),s>this.limits.maxObjectBytes&&S("snapshot_limit","A file in this repository is too large to upload.");let a=await this.read(s);return(await this.read(1))[0]!==10&&S("git_source_error","Invalid Git object framing."),a}async close(){this.child.exitCode!==null||this.child.signalCode!==null||(this.child.stdin.end(),this.child.kill(),await new Promise(e=>this.child.on("close",()=>e())))}},It=class{constructor(e,n,r){this.directory=e;this.limits=n;this.signal=r}sizes=new Map;expanded=0;async put(e,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&S("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.from(`${e} ${n.length}\0`),o=Mr("sha1").update(r).update(n).digest("hex");if(!this.sizes.has(o)&&((this.sizes.size+1>this.limits.maxObjects||this.expanded+n.length>this.limits.maxExpandedBytes)&&S("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(o,n.length),this.expanded+=n.length,this.directory!==null)){let i=ce(this.directory,"objects",o.slice(0,2));await Oi(i,{recursive:!0}),await Vl(ce(i,o.slice(2)),await Zl(Buffer.concat([r,n]),{level:6}),{mode:384,flag:"wx"})}return o}};et=t=>`${t.dev}:${t.ino}:${t.mode}:${t.size}:${t.mtimeMs}:${t.ctimeMs}`;Di=t=>t.split("/").some(e=>e.toLowerCase()===".git"),Gi=(t,e)=>!e.has(t.path)&&!Di(t.path)});import{randomUUID as au}from"node:crypto";import{readFileSync as cu,renameSync as lu,rmSync as Ki,writeFileSync as uu}from"node:fs";async function Ot(t,e,n={}){try{await v("/api/v1/cli/events",{method:"POST",token:e.token,baseUrl:e.apiUrl,body:{outcome:t,...n.runId?{runId:n.runId}:{}},signal:AbortSignal.timeout(n.timeoutMs??1500)})}catch{}}function zi(t,e){return!e||t.decision!=="allow"||!du.has(t.cause)?Promise.resolve():Ot(`gate_allow:${t.cause}`,e,{timeoutMs:500})}function Qi(t,e){try{let n=ae(t,Xi),r=`${n}.${au()}.tmp`;try{uu(r,JSON.stringify({version:1,at:new Date().toISOString(),treeHash:e})+`
|
|
66
|
+
`,{flag:"wx",mode:384}),lu(r,n)}catch(o){throw Ki(r,{force:!0}),o}}catch{}}function yn(t,e=Date.now()){try{let n=ae(t,Xi),r=Date.parse(JSON.parse(cu(n,"utf8")).at??"");return Ki(n,{force:!0}),Number.isFinite(r)&&e-r>=0&&e-r<fu}catch{return!1}}var du,Xi,fu,wn=J(()=>{"use strict";B();pe();du=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);Xi="last-denial.json",fu=1440*60*1e3});import{randomUUID as pu}from"node:crypto";import{readdirSync as hu,readFileSync as gu,renameSync as mu,rmSync as Zi,statSync as ts,writeFileSync as yu}from"node:fs";import{dirname as es,join as wu}from"node:path";import{gunzipSync as bu,gzipSync as ku}from"node:zlib";function os(t,e,n){try{let r=ae(t,rs(e)),o=`${r}.${pu()}.tmp`,i=ku(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:e,entries:n.map(s=>[s.path,s.mode,s.oid])})));try{yu(o,i,{flag:"wx",mode:384}),mu(o,r)}catch(s){throw Zi(o,{force:!0}),s}for(let s of hu(es(r))){if(!s.startsWith("tree-")||!s.endsWith(".json.gz"))continue;let a=wu(es(r),s);try{Date.now()-ts(a).mtimeMs>ns&&Zi(a,{force:!0})}catch{}}}catch{}}function _u(t,e){try{let n=ae(t,rs(e));if(Date.now()-ts(n).mtimeMs>ns)return null;let r=JSON.parse(bu(gu(n)).toString("utf8"));if(r.version!==1||r.treeHash!==e||!Array.isArray(r.entries))return null;let o=new Map;for(let i of r.entries)Array.isArray(i)&&i.length===3&&i.every(s=>typeof s=="string")&&o.set(i[0],`${i[1]}:${i[2]}`);return o}catch{return null}}function is(t,e,n){let r=_u(t,e);if(!r)return null;let o=new Map;for(let a of n){let l=r.get(a.path);l!==`${a.mode}:${a.oid}`&&o.set(a.path,l===void 0?`${a.path} (new)`:a.path)}let i=new Set(n.map(a=>a.path));for(let a of r.keys())i.has(a)||o.set(a,`${a} (removed)`);let s=[...o.keys()].sort().map(a=>o.get(a));return{files:s.slice(0,Su),total:s.length}}var Su,ns,rs,Hr=J(()=>{"use strict";pe();Su=8,ns=720*60*60*1e3,rs=t=>`tree-${t}.json.gz`});import{createHash as xu}from"node:crypto";import{constants as ss}from"node:fs";import{open as vu}from"node:fs/promises";import{Readable as Cu}from"node:stream";function Sn(t){if(!Fr(t,fs))return!1;let e=t.provenance;return t.kind==="local_snapshot"&&t.version===2&&typeof t.sha256=="string"&&/^[a-f0-9]{64}$/.test(t.sha256)&&typeof t.bytes=="number"&&Number.isSafeInteger(t.bytes)&&t.bytes>0&&t.bytes<=Ct.maxBundleBytes&&[t.baseTreeHash,t.treeHash,t.baseSha,t.headSha].every(n=>typeof n=="string"&&as.test(n))&&Fr(e,ps)&&[e.headSha,e.baseSha].every(n=>n===null||typeof n=="string"&&as.test(n))&&[e.branch,e.baseRef].every(n=>n===null||typeof n=="string"&&n.length>0&&n.length<=1024&&!/[\x00-\x1f\x7f]/.test(n))&&["explicit","merge-base","whole-project"].includes(e.baselineMode)}function $u(t,e){return fs.filter(n=>n!=="provenance").every(n=>t[n]===e[n])&&ps.every(n=>t.provenance[n]===e.provenance[n])}function Et(t,e){if(!Fr(t,["uploadId","expiresAt","status","source"])||typeof t.uploadId!="string"||!kn.test(t.uploadId)||typeof t.expiresAt!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t.expiresAt)||!Number.isFinite(Date.parse(t.expiresAt))||!["pending","uploading","completed","cancelled"].includes(t.status)||!Sn(t.source)||e?.uploadId!==void 0&&e.uploadId!==t.uploadId||e?.manifest!==void 0&&!$u(e.manifest,t.source))throw new F(502,"invalid_upload_response","Canary's answer does not match the upload in progress.","Run the command again to continue the upload.",e?.uploadId);return t}function hs(t){if(!kn.test(t))throw new F(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${ds}/${t}`}function Iu(t,e){return t instanceof F?new F(t.status,t.code,t.message,t.fix,e):t instanceof R?new F(t.status,"source_upload_failed",t.message,t.fix,e):new F(0,"source_upload_failed",t instanceof Error?t.message:"The source upload failed.","Run the command again to continue the upload.",e)}function bn(t){if(t.status==="completed")return t;throw t.status==="cancelled"?new F(410,"source_upload_cancelled","This upload was cancelled.",void 0,t.uploadId):new F(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",t.uploadId)}async function cs(t,e,n={}){let r=await(n.request??v)(hs(t),{...e});return Et(r,{uploadId:t})}async function*gs(t,e,n){let r=0;for(;r<e;){n?.throwIfAborted();let o=Buffer.allocUnsafe(Math.min(64*1024,e-r)),i=await t.read(o,0,o.length,r);if(!i.bytesRead)throw new F(0,"source_changed","The source changed while it was being uploaded. Run the command again.");r+=i.bytesRead,yield o.subarray(0,i.bytesRead)}}async function ls(t,e,n){let r=await t.stat();if(!r.isFile()||r.size!==e.bytes)throw new F(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let o=xu("sha256");for await(let s of gs(t,e.bytes,n))o.update(s);let i=await t.stat();if(o.digest("hex")!==e.sha256||i.size!==r.size||i.mtimeMs!==r.mtimeMs||i.ctimeMs!==r.ctimeMs)throw new F(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function us(t,e,n,r){let o=Cu.from(gs(t,e.manifest.bytes,e.signal));try{let i=await(r.fetch??fetch)(`${e.baseUrl.replace(/\/+$/,"")}${hs(n)}/content`,{method:"PUT",headers:{...(r.headers??Ce)(),authorization:`Bearer ${e.token}`,"content-type":"application/octet-stream","content-length":String(e.manifest.bytes)},body:o,duplex:"half",signal:e.signal,redirect:"error"});if(!i.ok){let s={};try{s=await i.json()}catch{}throw new F(i.status,typeof s.code=="string"?s.code:"source_upload_failed",typeof s.error=="string"?s.error:i.statusText,typeof s.fix=="string"?s.fix:void 0,n)}return bn(Et(await i.json(),{uploadId:n,manifest:e.manifest}))}catch(i){throw i instanceof F?i:new F(0,"source_upload_uncertain","The connection dropped before Canary confirmed the upload.","An earlier upload is still in progress. Run the command again to continue it.",n)}finally{o.destroy()}}async function ms(t,e={}){if(!Sn(t.manifest)||!kn.test(t.workspaceId)||!kn.test(t.repositoryId))throw new F(0,"invalid_source_receipt","A captured source, a workspace, and a repository are required before uploading.");let n={token:t.token,baseUrl:t.baseUrl,signal:t.signal},r;if(t.uploadId&&(r=Et(await cs(t.uploadId,n,e),{uploadId:t.uploadId,manifest:t.manifest}),r.status!=="pending"))return bn(r);let o=await vu(t.bundlePath,ss.O_RDONLY|ss.O_NOFOLLOW);try{if(await ls(o,t.manifest,t.signal),r||(r=Et(await(e.request??v)(ds,{...n,method:"POST",body:{workspaceId:t.workspaceId,repositoryId:t.repositoryId,source:t.manifest}}),{manifest:t.manifest})),t.onReceipt?.(r),r.status!=="pending")return bn(r);try{return await us(o,t,r.uploadId,e)}catch(i){if(t.signal?.aborted||!(re(i)||i instanceof R&&i.status===409))throw i;let s=Et(await cs(r.uploadId,n,e),{uploadId:r.uploadId,manifest:t.manifest});return s.status!=="pending"?bn(s):(await ls(o,t.manifest,t.signal),await us(o,t,r.uploadId,e))}}catch(i){throw r?Iu(i,r.uploadId):i}finally{await o.close()}}var F,ds,kn,as,fs,ps,Fr,Ur=J(()=>{"use strict";B();$e();nt();F=class extends R{constructor(n,r,o,i,s){super(n,o,i);this.code=r;this.uploadId=s;this.name="SourceUploadError"}},ds="/api/v1/cli/source-uploads",kn=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,as=/^[a-f0-9]{40}$/,fs=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],ps=["headSha","branch","baseRef","baseSha","baselineMode"],Fr=(t,e)=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===e.length&&e.every(n=>Object.hasOwn(t,n))});import{createHash as Ru,randomUUID as Ou}from"node:crypto";import{readFileSync as Eu,renameSync as Au,rmSync as ys,writeFileSync as Tu}from"node:fs";function ws(t,e,n,r="verify"){let o=Ru("sha256").update(JSON.stringify([n,t,r])).digest("hex");return ae(e,`source-upload-${o}.json`)}function bs(t){try{let e=JSON.parse(Eu(t,"utf8"));if(typeof e.uploadId!="string"||!/^[a-f0-9-]{36}$/i.test(e.uploadId)||typeof e.expiresAt!="string"||!Number.isFinite(Date.parse(e.expiresAt)))throw new Error("invalid upload record");return{uploadId:e.uploadId,expiresAt:e.expiresAt}}catch(e){if(e.code!=="ENOENT")throw new F(0,"invalid_upload_receipt","Canary's record of an earlier upload under CANARY_HOME/local-repositories is unreadable.","Fix or remove that file, then run the command again.")}}function Dr(t,e,n,r){let o=ws(t,e,n,r.requestKey),i=bs(o);i&&(!r.uploadId||i.uploadId===r.uploadId)&&ys(o,{force:!0})}async function _n(t,e,n,r,o={}){let i=ws(t.manifest,e,n,o.requestKey),s=o.fresh?void 0:bs(i),a=s&&Date.parse(s.expiresAt)>Date.now()?s.uploadId:void 0,l=await ms({bundlePath:t.bundlePath,manifest:t.manifest,workspaceId:e.workspaceId,repositoryId:n,token:r,baseUrl:e.apiUrl,...a?{uploadId:a}:{},onReceipt:({uploadId:c,expiresAt:u})=>{let d=`${i}.${Ou()}.tmp`;try{Tu(d,JSON.stringify({uploadId:c,expiresAt:u})+`
|
|
67
|
+
`,{flag:"wx",mode:384}),Au(d,i)}finally{ys(d,{force:!0})}}});return{...l.source,uploadId:l.uploadId}}var Gr=J(()=>{"use strict";pe();Ur()});import{readFileSync as ks}from"node:fs";function Mu(t){if(t===void 0)return;let e=t;try{t==="-"?e=ks(0,"utf8"):t.startsWith("@")&&(e=ks(t.slice(1),"utf8"))}catch(n){throw new he("brief_unreadable",`could not read the brief from ${t==="-"?"stdin":t.slice(1)}: ${n instanceof Error?n.message:String(n)}`,"pass the brief as text, @<file>, or - (stdin)")}return e.trim()===""?void 0:e}function ge(t){return t==="P3"?null:t==="P0"||t==="P1"?t:"P2"}function ju(t,e){if(ge(t.materiality)===null)return null;let r=e??null;return t.result==="fail"?{checkRunId:t.checkRunId,kind:"fail",proof:r?.isStatic===!1?"runtime":"source",headline:b(r?.finding?.headline)||b(t.title),summary:b(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:vs(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:b(r?.finding?.reproduce)||null}:t.result==="blocked"?{checkRunId:t.checkRunId,kind:"blocked",proof:"none",headline:b(t.title),summary:b(r?.verdict?.reasonOneLiner)||(Tt[t.blockedReason??""]??""),location:vs(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}function Br(t,e,n){let r=H();v("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...n?{baseUrl:n}:{},body:{outcome:t,...e?{runId:e}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function $s(t){if(t.status!=="completed"||t.stageB.status==="failed")return 2;let e=t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns;return e>0&&t.stageC.checks.length===e?2:0}async function Vr(t,e,n={}){let r=d=>v(d,{token:e,...n.baseUrl?{baseUrl:n.baseUrl}:{}}),o=new Map,i="",s=new Set,a=!1,l=!1,c=null,u=Date.now();for(;;){let d;try{d=(await r(`/api/v1/red-team/runs/${t}`)).run,c=null}catch(f){if(re(f)&&(c??=Date.now(),Date.now()-c<Nu)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await At(Jr);continue}throw f}for(let f of d.stageC.checks)if(!(!(f.status==="completed"&&(f.result==="fail"||f.result==="blocked"))||o.has(f.checkRunId))){if(!De.test(f.checkRunId)){o.set(f.checkRunId,null);continue}try{o.set(f.checkRunId,await r(`/api/v1/red-team/runs/${t}/checks/${f.checkRunId}/finding`))}catch(g){re(g)||o.set(f.checkRunId,null)}}for(let f of d.stageC.checks){if(s.has(f.checkRunId)||!(f.status==="completed"||f.status==="failed"||f.status==="cancelled")||ge(f.materiality)===null)continue;s.add(f.checkRunId);let g=o.get(f.checkRunId),w=f.status!=="completed"?"!":f.result==="pass"?"\u2713":f.result==="fail"?"\u2717":"\u23F8",_=f.status!=="completed"?"errored":f.result==="pass"?"passed":f.result==="fail"?g?.isStatic===!1?"verified failure":"finding from the code":"could not verify";n.onProgress?.(`${w} ${_}: ${b(f.title)}`)}d.stageB.status!=="completed"&&(l=!0);let h=d.stageC.checks.length>0||d.stageB.finalChecksCount===0||Wr.has(d.status);!a&&d.stageB.status==="completed"&&h&&(a=!0,n.onProgress?.(Fu(d,l?Date.now()-u:null,o)));let p=Hu(d);if(p!==i&&(n.onProgress?.(p),i=p),Wr.has(d.status)){for(let m=0;m<3;m++){let g=d.stageC.checks.filter(w=>w.status==="completed"&&(w.result==="fail"||w.result==="blocked")&&!o.has(w.checkRunId));if(g.length===0)break;await At(Math.min(Jr,1e3));for(let w of g)try{o.set(w.checkRunId,await r(`/api/v1/red-team/runs/${t}/checks/${w.checkRunId}/finding`))}catch(_){(!re(_)||m===2)&&o.set(w.checkRunId,null)}}let f=d.stageC.checks.filter(m=>m.status==="completed"&&(m.result==="fail"||m.result==="blocked")).sort((m,g)=>Cs[ge(m.materiality)??"P2"]-Cs[ge(g.materiality)??"P2"]).map(m=>ju(m,o.get(m.checkRunId)??null)).filter(m=>m!==null);return{run:d,findings:f}}if(Date.now()-u>Ss)throw new he("still_running",`run ${t} is still ${d.status} after ${Math.round(Ss/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await At(Jr)}}function Hu(t){if(t.status==="queued")return"\u2026 queued";if(t.phase==="stage_b"||t.stageC.checks.length===0){let n=t.stageB.risksFound??0;return`\u2026 analyzing the change${n?` \xB7 ${n} risk${n===1?"":"s"} found`:""}`}return`\u2026 ${t.stageC.completedCheckRuns+t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns}/${t.stageC.checks.length} checks done \xB7 ${t.stageC.results.fail} failed`}function Fu(t,e,n=new Map){let r=t.stageC.checks.filter(d=>ge(d.materiality)!==null),o=d=>d.result==="fail"&&n.get(d.checkRunId)?.isStatic!==!1,i=r.filter(o).length,s=t.stageC.checks.filter(d=>d.status==="failed"||d.status==="cancelled").length,a=r.filter(d=>!o(d)&&d.status!=="failed"&&d.status!=="cancelled").length,l=t.stageC.results.pass+t.stageC.results.blocked+r.filter(d=>d.result==="fail"&&n.get(d.checkRunId)?.isStatic===!1).length,c=Wr.has(t.status)?l>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 ${oe(i,"finding")} from the code \xB7 ${a} runtime check${a===1?"":"s"}${s?` \xB7 ${s} errored`:""} \xB7 ${c}`}function Uu(t,e,n){let r=t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns;if($s(t)===2)return`Verification did not complete (${t.status})${r?`: ${oe(r,"check")} errored`:""}; nothing was verified.`;let o=e.filter(u=>u.kind==="fail"&&u.proof==="runtime").length,i=e.filter(u=>u.kind==="fail"&&u.proof==="source").length,s=e.filter(u=>u.kind==="blocked").length,a=t.stageC.results.pass,l=[`${oe(o,"verified failure")}`,`${oe(a,"check")} passed`,`${oe(i,"finding")} from the code (source-reasoned, not run)`,...s?[`${s} could not be verified`]:[],`${oe(r,"check")} errored`],c=a===0&&o===0&&s===0&&r===0;return`${l.join("; ")}.${c?" Nothing in this change was executed.":""}${Du(n)}`}function Du(t){let e=t?t.reverifiable-t.carried:0;return!t||e<=0?"":` ${e} of run ${t.sourceRunId.slice(0,8)}'s ${oe(t.reverifiable,"failed check")} ${e===1?"was":"were"} not re-run (reported disputed or skipped).`}function Gu(t,e){let n=t.slice(0,8);if(!e)return`re-checking the failed set of run ${n} \u2014`;let r=`of run ${n}'s ${oe(e.reverifiable,"failed check")}`;return e.excludedReported>0?`re-checking ${e.carried} ${r} (${e.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${e.reverifiable} failed checks of run ${n} \u2014`}function qr(t,e,n,r){return{ok:!0,runId:t.runId,treeHash:e,status:t.status,findings:n,summary:Uu(t,n,r),failed:n.filter(o=>o.kind==="fail").length,passed:t.stageC.results.pass,blocked:n.filter(o=>o.kind==="blocked").length,errored:t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns,exitCode:$s(t),failureMessage:t.failure?.publicMessage??null,...r?{reverify:r}:{}}}function Yr(t){let e=[];if(e.push(`Receipt ${nn(t.treeHash)} \xB7 run ${b(t.runId)}`),t.exitCode===2)return e.push(`\u2717 Verification did not complete (${b(t.status)})${t.failureMessage?`: ${b(t.failureMessage)}`:""}`),t.errored>0&&e.push(` ${oe(t.errored,"check")} errored \u2014 nothing was verified; this is not a clean result.`),e.push(` Run \`canary verify\` again; if it repeats, report run ${b(t.runId)}.`),e.join(`
|
|
68
68
|
`);let n=[t.failed?`\u2717 ${oe(t.failed,"finding")}`:"",t.passed?`\u2713 ${t.passed} passed`:"",t.blocked?`\u23F8 ${t.blocked} could not be verified`:""].filter(Boolean);t.findings.length===0&&t.errored===0?e.push(`\u2713 Clean \u2014 no findings in this change${t.passed?` \xB7 ${t.passed} passed`:""}.`):e.push(`${t.failed?"":"\u2713 No verified findings"}${t.failed||n.length===0?"":" \xB7 "}${n.join(" \xB7 ")}`);for(let r of t.findings)e.push(""),e.push(`${Ju[r.kind]} ${b(r.headline)}${Wu[r.kind]}`),r.summary&&e.push(` ${b(r.summary)}`),r.location&&e.push(` \u2192 ${b(r.location)}`),r.fix&&e.push(` reproduce: ${b(r.fix)}`);return t.errored>0&&e.push(`
|
|
69
69
|
(${oe(t.errored,"check")} errored and could not be verified.)`),e.push(`
|
|
70
70
|
${t.summary}`),e.join(`
|
|
71
71
|
`)}function Bu(t){let e=t;return!e||!["EPERM","EACCES","EROFS"].includes(e.code??"")||typeof e.path!="string"||!e.path.startsWith(ne())?null:{message:`Canary keeps its records under ${ne()} and cannot write there from here (${e.code})`,fix:"run the command outside the sandbox, or let it write under that folder"}}function $(t,e,n,r,o,i={}){if(t)console.log(JSON.stringify({ok:!1,error:e,message:n,...r?{fix:r}:{},exitCode:o,...i}));else{let s=typeof i.runId=="string"?i.runId:null;console.error(`\u2717 ${b(n)}${r?`
|
|
72
72
|
fix: ${b(r)}`:""}${s?`
|
|
73
|
-
run: ${b(s)}`:""}`)}process.exitCode=o}async function Vu(t,e,n,r,o={}){let i={baseUrl:o.baseUrl??W()};Ke({cwd:t,agent:n,mode:r!==void 0?"reverify_failed":"full"});let s=(
|
|
74
|
-
${k.next}`);return}let w;try{w=await Vr(f,a,{...i,onProgress:p})}catch(
|
|
73
|
+
run: ${b(s)}`:""}`)}process.exitCode=o}async function Vu(t,e,n,r,o={}){let i={baseUrl:o.baseUrl??W()};Ke({cwd:t,agent:n,mode:r!==void 0?"reverify_failed":"full"});let s=(y,k,x,E=3,C={})=>{$(n,y,k,x,E,C),Br(`exit${E}:${y}`,C.runId,i.baseUrl)},a=H();if(!a)return s("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!De.test(r))return s("bad_run_id",`"${r}" is not a run id`,"pass the run id from your last `canary verify` (see the receipt line), e.g. `canary verify --failed <run-id>`");let l,c;try{l=Mu(e),c=await Rt(t,{baseRef:o.baseRef})}catch(y){if(y instanceof ee||y instanceof he)return s(y.code,y.message,y.fix);throw y}if(c.manifest.treeHash===c.manifest.baseTreeHash&&r===void 0)return await c.dispose(),s("nothing_to_verify","The current source matches the selected baseline","make a change, or choose a different baseline with --base <ref>");let u,d,h;try{u=await xt(t,a,i.baseUrl),d=await _t({...u,token:a});let y=AbortSignal.timeout(3e3);if((await ln(u,a,y).catch(x=>{throw y.aborted?new R(0,"Checking this repository's setup timed out","run `canary verify` again"):x}))?.state!=="ready")throw new he("setup_required",`This repository isn't set up for you in ${b(d.workspace.name)} yet`,"run `canary setup`");h=await _n(c,u,d.repositoryId,a,{fresh:!0}),os(u,c.manifest.treeHash,c.entries)}catch(y){if(y instanceof N||y instanceof he)return s(y.code,y.message,"fix"in y?y.fix:void 0);if(y instanceof R)return s("api_error",y.message,y.fix,y.status>=400&&y.status<500?3:2);throw y}finally{await c.dispose()}l===void 0&&r===void 0&&console.error("! No --brief given \u2014 Canary will attack the change using the submitted source and baseline. A brief with acceptance criteria and must-not-break finds more."),qe();let p=y=>{n?console.error(` ${y}`):console.log(` ${y}`)};c.manifest.provenance.baselineMode==="whole-project"?p("No comparison branch found: reviewing the whole eligible project against an empty baseline."):p(`Baseline: ${b(c.manifest.provenance.baseRef)} \xB7 source ${nn(c.manifest.treeHash)}`);let f,m,g;{let y,k=tt(c.manifest.provenance.branch),x=()=>v("/api/v1/cli/runs",{method:"POST",token:a,...i,body:{repositoryId:d.repositoryId,workspaceId:u.workspaceId,source:h,...l!==void 0?{brief:l}:{},...k?{branch:k}:{},...r!==void 0?{reverifySourceRunId:r}:{}}});try{for(let C=1;;C+=1)try{y=await x();break}catch(D){if(C>=_s||!re(D)||D instanceof R&&D.runId&&De.test(D.runId))throw D;p(`${D.message} \u2014 retrying (${C}/${_s-1})`),await At(xs*C)}}catch(C){if(C instanceof R){let D=!re(C)&&C.status>=400&&C.status<500,xe=C.fix??(C.status===401||C.status===403?"run `canary login`":D?void 0:"run `canary verify` again in a minute"),O={httpStatus:C.status,...C.runId?{runId:C.runId}:{}};return D?$(n,"api_error",C.message,xe,3,O):s("api_error",C.message,xe,2,O)}throw C}if(y.treeHash!==c.manifest.treeHash||y.headSha!==c.manifest.headSha)return $(n,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!De.test(y.runId))return $(n,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);f=y.runId;let E=r?Gu(r,y.reverify):y.created?"submitted":"same verification inputs as an existing run \u2014 following it:";p(`${E} ${nn(c.manifest.treeHash)} \xB7 run ${f} \xB7 ${oe(c.files.length,"file")}`),m=y.reverify,g=y.created,g&&Ot(`started_by:${yn(u)?"hook":n||gr().harness!=="unknown"?"skill":"manual"}`,{token:a,apiUrl:i.baseUrl},{runId:f})}if(o.noWait){let y=!1;if(r!==void 0&&!m&&!g)for(let x=0;x<3&&!m;x++)try{m=(await v(`/api/v1/red-team/runs/${f}`,{token:a,...i})).run.reverify;break}catch(E){if(!re(E)||x===2){y=!0;break}await At(xs*(x+1))}let k={ok:!0,runId:f,runUrl:Pu(f),treeHash:c.manifest.treeHash,created:g,...m?{reverify:m}:{},next:`${Lu(f)}${y?" What this re-check carried could not be read just now; the document from `canary run wait` will say.":""}`};console.log(n?JSON.stringify(k):`Run ${f} is under way: ${k.runUrl}
|
|
74
|
+
${k.next}`);return}let w;try{w=await Vr(f,a,{...i,onProgress:p})}catch(y){if(y instanceof he)return s(y.code,y.message,y.fix,2,{runId:f});if(y instanceof R){let k=y.status===401||y.status===403;return s("api_error",`${y.message} \u2014 run ${f} may still be running`,y.fix??(k?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:f,httpStatus:y.status})}throw y}let _={...qr(w.run,c.manifest.treeHash,w.findings,m),source:c.manifest,repositoryId:d.repositoryId};console.log(n?JSON.stringify(_):Yr(_)),process.exitCode=_.exitCode}function Is(t){t.command("verify").description("Pressure-test your local change set with Canary (no commit or PR needed)").option("--brief <text>","what the change intends and must not break (text, @file, or - for stdin)").option("--failed <runId>","re-check only the failed checks of an earlier run, against your current (fixed) code").option("--json","output one JSON document").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","compare directly with a local commit (use HEAD for worktree changes only)").option("--no-wait","start the run and return its id at once; collect it later with `canary run wait <runId>`").action(async e=>{try{H()&&await(await Promise.resolve().then(()=>(Ge(),Rs))).installByDefault({json:e.json===!0}),await Vu(e.dir??process.cwd(),e.brief,e.json===!0,e.failed,{baseRef:e.base,noWait:e.wait===!1})}catch(n){let r=Bu(n);if(r){$(e.json===!0,"home_not_writable",r.message,r.fix,2),Br("exit2:home_not_writable");return}$(e.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),Br("exit2:internal_error")}})}var Jr,Nu,Ss,Wr,he,b,De,Pu,Lu,At,_s,xs,vs,Cs,Tt,Ju,Wu,oe,rt=J(()=>{"use strict";B();$e();j();di();un();pe();nt();wn();Hr();Gr();Ye();Jr=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,Nu=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Ss=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,Wr=new Set(["completed","failed","cancelled"]),he=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="VerifyError"}},b=t=>(t??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g," ").trim(),De=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Pu=t=>`${be().replace(/\/+$/,"")}/runs/${t}`,Lu=t=>`Collect the result with \`canary run wait ${t}\` (it returns when the run has finished; run it in the background where your shell allows).`,At=t=>new Promise(e=>setTimeout(e,t)),_s=3,xs=1e3;vs=t=>t?t.startLine?`${t.file}:${t.startLine}`:t.file:null;Cs={P0:0,P1:1,P2:2},Tt={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"};Ju={fail:"\u2717",blocked:"\u23F8"},Wu={fail:"",blocked:" (could not be verified)"},oe=(t,e)=>`${t} ${e}${t===1?"":"s"}`});var Rs={};Xa(Rs,{hooksStatus:()=>Nt,installByDefault:()=>Pt,pendingPushCheck:()=>Xr,registerHooks:()=>Qr,runHooksInstall:()=>As,runHooksUninstall:()=>Ts,statusLines:()=>xn});function zr(t,e=[]){try{z(n=>({...n,hooks:{state:t,at:new Date().toISOString(),...e.length?{refused:e}:{}}}))}catch{}}function qu(t){return[Kr,"It is a hook in the agent's own settings, which the agent runs. `canary hooks install` adds:","",...t.flatMap(e=>[` ${e.file}`,` ${e.summary}`,...e.snippet.split(`
|
|
75
75
|
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${Os}`].join(`
|
|
76
76
|
`)}function Es(t){for(let e of t)e.result==="refused"?console.log(`\u2717 ${e.file} was left alone: ${e.detail}. To do it by hand:
|
|
77
|
-
${e.snippet}`):console.log(`${e.result==="unchanged"?"\xB7":"\u2713"} ${e.file}: ${e.result==="written"?"added":e.result==="removed"?"removed":"nothing to change"}`)}function Yu(t,e){for(let n of e)n.afterInstall&&t.some(r=>r.harness===n.id&&r.result==="written")&&console.log(`${n.label}: ${n.afterInstall}`);tn("canary")||console.log("Note: `canary` is not on PATH in this shell. The agent's harness must be able to find it, or the hook does nothing."),t.some(n=>n.result==="written")&&je()==="off"&&console.log("The check itself is switched off (`canary gate on` turns it on).")}function Ku(t,e){return e?.length?{targets:t.filter(n=>e.includes(n.id)&&n.detected()),unknown:e.filter(n=>!t.some(r=>r.id===n&&r.detected()))}:{targets:t.filter(n=>n.byDefault&&n.detected()),unknown:[]}}async function As(t){let e=t.targets??
|
|
78
|
-
`));return}if(t.plan){console.log(t.json?JSON.stringify({ok:!0,plan:o}):qu(o));return}let i=n.flatMap(s=>s.install());i.some(s=>s.result!=="refused")&&zr("installed"),t.json?console.log(JSON.stringify({ok:!i.some(s=>s.result==="refused"),outcomes:i,canaryOnPath:tn("canary"),mode:je(),notes:n.filter(s=>s.afterInstall&&i.some(a=>a.harness===s.id&&a.result==="written")).map(s=>`${s.label}: ${s.afterInstall}`)})):(Es(i),Yu(i,n)),i.some(s=>s.result==="refused")&&(process.exitCode=2)}function Ts(t){let e=(t.targets??
|
|
77
|
+
${e.snippet}`):console.log(`${e.result==="unchanged"?"\xB7":"\u2713"} ${e.file}: ${e.result==="written"?"added":e.result==="removed"?"removed":"nothing to change"}`)}function Yu(t,e){for(let n of e)n.afterInstall&&t.some(r=>r.harness===n.id&&r.result==="written")&&console.log(`${n.label}: ${n.afterInstall}`);tn("canary")||console.log("Note: `canary` is not on PATH in this shell. The agent's harness must be able to find it, or the hook does nothing."),t.some(n=>n.result==="written")&&je()==="off"&&console.log("The check itself is switched off (`canary gate on` turns it on).")}function Ku(t,e){return e?.length?{targets:t.filter(n=>e.includes(n.id)&&n.detected()),unknown:e.filter(n=>!t.some(r=>r.id===n&&r.detected()))}:{targets:t.filter(n=>n.byDefault&&n.detected()),unknown:[]}}async function As(t){let e=t.targets??mt(),{targets:n,unknown:r}=Ku(e,t.harnesses),o=n.flatMap(s=>s.plan());if(r.length)return $(t.json,"harness_not_found",`not found on this machine: ${r.join(", ")}`,`known: ${e.map(s=>s.id).join(", ")}; one counts as found once its settings folder exists`,3);if(!n.length){let s=e.filter(a=>!a.byDefault&&a.detected()).map(a=>`\`canary hooks install --harness ${a.id}\` registers ${a.label}, which is not covered by default yet.`);t.json?console.log(JSON.stringify({ok:!0,installed:[],note:"no coding agent to register by default"})):console.log([`No coding agent to register was found on this machine (looked for ${e.filter(a=>a.byDefault).map(a=>a.label).join(", ")}).`,...s].join(`
|
|
78
|
+
`));return}if(t.plan){console.log(t.json?JSON.stringify({ok:!0,plan:o}):qu(o));return}let i=n.flatMap(s=>s.install());i.some(s=>s.result!=="refused")&&zr("installed"),t.json?console.log(JSON.stringify({ok:!i.some(s=>s.result==="refused"),outcomes:i,canaryOnPath:tn("canary"),mode:je(),notes:n.filter(s=>s.afterInstall&&i.some(a=>a.harness===s.id&&a.result==="written")).map(s=>`${s.label}: ${s.afterInstall}`)})):(Es(i),Yu(i,n)),i.some(s=>s.result==="refused")&&(process.exitCode=2)}function Ts(t){let e=(t.targets??mt()).flatMap(n=>n.uninstall());zr("removed"),t.json?console.log(JSON.stringify({ok:!e.some(n=>n.result==="refused"),outcomes:e})):Es(e),e.some(n=>n.result==="refused")&&(process.exitCode=2)}function Nt(t=mt()){return{mode:je(),registration:T().hooks?.state??null,canaryOnPath:tn("canary"),harnesses:t.map(e=>({harness:e.id,label:e.label,detected:e.detected(),items:e.status()}))}}function Xr(t){try{return je()==="off"?[]:Nt(t).harnesses.flatMap(e=>e.items.filter(n=>n.state==="untrusted"&&n.pending).map(n=>({harness:e.harness,label:e.label,...n.pending})))}catch{return[]}}function xn(t){let e=[];for(let n of t.harnesses){if(!n.detected&&n.items.every(r=>r.state==="missing")){e.push(`${n.label}: not found on this machine`);continue}for(let r of n.items)e.push(`${n.label}: ${r.state==="registered"?"registered":r.state==="untrusted"?"registered, not yet trusted":r.state==="missing"?"not registered":r.state} (${r.file})${r.detail?`: ${r.detail}`:""}`)}return t.harnesses.some(n=>n.items.some(r=>r.state!=="missing"))&&!t.canaryOnPath&&e.push("`canary` is not on PATH in this shell; a harness that cannot find it runs no check."),t.harnesses.some(n=>n.items.some(r=>r.state!=="missing"))&&e.push("Switch the check off: `canary gate off`. Take it out: `canary hooks uninstall` (before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)."),e}async function Pt(t){try{if(process.env.CI||!t.targets&&process.env.NODE_TEST_CONTEXT)return;let e=T();if(e.agentSkills===!1||e.hooks?.state==="removed")return;let n=new Set(e.hooks?.refused??[]);if(e.hooks?.state==="installed"&&!n.size)return;let r=(t.targets??mt()).filter(c=>c.byDefault&&c.detected());if(!r.length)return;let o=r.flatMap(c=>c.install()),i=o.filter(c=>c.result==="written"),s=o.filter(c=>c.result==="refused"&&!n.has(c.file)),a=o.filter(c=>c.result==="refused").map(c=>c.file);if(o.some(c=>c.result!=="refused")||e.hooks?.state==="installed")zr("installed",a);else if(a.length)try{z(c=>({...c,hooks:{...c.hooks,refused:a}}))}catch{}let l=r.filter(c=>c.afterInstall&&i.some(u=>u.harness===c.id)).map(c=>`${c.label}: ${c.afterInstall}`);if(t.json){(i.length||s.length)&&console.error(JSON.stringify({notice:"push_check",added:i.map(c=>c.file),leftAlone:s.map(c=>({file:c.file,why:c.detail})),message:Kr,off:"canary gate off",remove:"canary hooks uninstall",notes:l}));return}if(i.length){let c=r.filter(u=>i.some(d=>d.harness===u.id)).map(u=>u.label).join(" and ");console.error(`
|
|
79
79
|
Canary added its push check to ${c} (${i.map(u=>u.file).join(", ")}).
|
|
80
80
|
${Kr}
|
|
81
|
-
${Os}`);for(let u of l)console.error(u)}for(let c of s)console.error(`Canary left ${c.file} alone (${c.detail}): not added there: ${c.summary}. \`canary hooks install --plan\` shows what to add by hand.`)}catch{}}function Qr(t){let e=t.command("hooks").description("The push check in your coding agents' settings: install, uninstall, status. Login adds it; `canary hooks uninstall` takes it out, also as `npx -y @runcanary/cli hooks uninstall` once the CLI is gone");e.command("install").description("Add the push check to your coding agents' settings (login does this by default)").option("--plan","show exactly what would be added, and add nothing").option("--harness <id...>","register only these (claude, codex, cursor); default: every one found that is covered by default").option("--json","print one JSON document").action(async n=>{try{await As({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(r){$(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),e.command("uninstall").description("Remove exactly what `canary hooks install` added (do this before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)").option("--json","print one JSON document").action(n=>{try{Ts({json:n.json===!0})}catch(r){$(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),e.command("status").description("Show where the check is registered, and anything that stops it from running").option("--json","print one JSON document").action(n=>{let r=
|
|
81
|
+
${Os}`);for(let u of l)console.error(u)}for(let c of s)console.error(`Canary left ${c.file} alone (${c.detail}): not added there: ${c.summary}. \`canary hooks install --plan\` shows what to add by hand.`)}catch{}}function Qr(t){let e=t.command("hooks").description("The push check in your coding agents' settings: install, uninstall, status. Login adds it; `canary hooks uninstall` takes it out, also as `npx -y @runcanary/cli hooks uninstall` once the CLI is gone");e.command("install").description("Add the push check to your coding agents' settings (login does this by default)").option("--plan","show exactly what would be added, and add nothing").option("--harness <id...>","register only these (claude, codex, cursor); default: every one found that is covered by default").option("--json","print one JSON document").action(async n=>{try{await As({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(r){$(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),e.command("uninstall").description("Remove exactly what `canary hooks install` added (do this before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)").option("--json","print one JSON document").action(n=>{try{Ts({json:n.json===!0})}catch(r){$(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),e.command("status").description("Show where the check is registered, and anything that stops it from running").option("--json","print one JSON document").action(n=>{let r=Nt();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(`The push check is ${r.mode}.`);for(let o of xn(r))console.log(o)}})}var Kr,Os,Ge=J(()=>{"use strict";j();Qt();ui();rt();Kr="Before an agent pushes or opens a pull request, Canary checks that this exact code has a verified run, and holds that one call if it has not. No other command is affected.",Os="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`."});var Oo=Za(Ro(),1),{program:ip,createCommand:sp,createArgument:ap,createOption:cp,CommanderError:lp,InvalidArgumentError:up,InvalidOptionArgumentError:dp,Command:Eo,Argument:fp,Option:pp,Help:hp}=Oo.default;import{createHash as id,randomBytes as Ws}from"node:crypto";import{spawn as sd}from"node:child_process";import{createServer as ad}from"node:http";j();import{existsSync as pr,lstatSync as Pc,mkdirSync as Lc,readFileSync as qo,rmSync as Mc,rmdirSync as jc,writeFileSync as Hc}from"node:fs";import{homedir as fr}from"node:os";import{join as Le}from"node:path";var Ve="Onboard this repository to Canary.",Kt="Verify my changes with Canary.";var dr=`---
|
|
82
82
|
name: canary
|
|
83
83
|
description: >-
|
|
84
84
|
Use whenever you finish a code change and are about to report it done, or whenever a change
|
|
@@ -117,75 +117,75 @@ If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then start at step
|
|
|
117
117
|
"Getting started" section covers logging in.
|
|
118
118
|
Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
|
|
119
119
|
you act on it.
|
|
120
|
-
`;var Fc="canary",Uc="canary-setup";function Dc(t){let e=Le(t,"skills",Uc),n=Le(e,"SKILL.md");if(zt(e)||zt(n)||!pr(n))return;let r;try{r=qo(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{Mc(n,{force:!1})}catch{return}try{jc(e)}catch{}}}function zt(t){try{return Pc(t).isSymbolicLink()}catch{return!1}}function Gc(){return[Le(fr(),".claude"),Le(fr(),".agents"),Le(fr(),".codex")].filter(t=>pr(t))}function Xt(){let t={installed:[],refreshed:[],current:[],skipped:[]};if(T().agentSkills===!1)return t;for(let e of Gc()){Dc(e);let n=Le(e,"skills",Fc),r=Le(n,"SKILL.md");try{if(zt(n)||zt(r)){t.skipped.push(r);continue}let o=pr(r)?qo(r,"utf8"):null;if(o===dr){t.current.push(r);continue}Lc(n,{recursive:!0}),Hc(r,dr),(o===null?t.installed:t.refreshed).push(r)}catch{}}return t}var Yo=`Open your coding agent inside the repo you want to onboard and say: "${Ve}"`;B();Ye();j();Ge();B();un();function Ns(t){try{return new URL(t).href.replace(/\/+$/,"")}catch{return}}var Zr=$i;async function Ps(t,e,n,r){let o=await v("/api/v1/cli/workspaces",{token:t.token,baseUrl:r,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(o?.workspaces)||o.workspaces.some(d=>!d||typeof d.id!="string"||!d.id||typeof d.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let i=[...new Map(o.workspaces.map(({id:d,name:h})=>[d,{id:d,name:h}])).values()],a=e.user?.id===t.user.id&&Ns(n)===Ns(r)?i.find(d=>d.id===e.team?.id):void 0,l=i.length===1?i[0]:void 0,c=a??l??i.find(d=>d.id===t.team.id)??i[0]??{id:"",name:"No workspace selected"},u=Zr();return{workspace:c,workspaces:i,source:a?"saved in CLI":l?"only workspace":"active on platform",selectionRequired:!a&&!l,...u?{repository:u}:{},...i.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function vn(t,e,n,r=AbortSignal.timeout(3e3)){try{let o=await ln({apiUrl:t.apiUrl,userId:t.userId,workspaceId:n},t.token,r);return o?{state:o.state}:void 0}catch{return}}function Cn(t,e){let n=/^\d+$/.test(e)?Number(e)-1:-1,r=n>=0?t.workspaces.filter((o,i)=>i===n):t.workspaces.filter(o=>o.id===e||o.name.toLowerCase()===e.toLowerCase());if(r.length!==1)throw new Error(r.length?"Workspace name is ambiguous. Use its ID.":"Workspace not found. Run canary workspace list.");return r[0]}import{stripVTControlCharacters as Ls}from"node:util";var U="\x1B[";function
|
|
120
|
+
`;var Fc="canary",Uc="canary-setup";function Dc(t){let e=Le(t,"skills",Uc),n=Le(e,"SKILL.md");if(zt(e)||zt(n)||!pr(n))return;let r;try{r=qo(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{Mc(n,{force:!1})}catch{return}try{jc(e)}catch{}}}function zt(t){try{return Pc(t).isSymbolicLink()}catch{return!1}}function Gc(){return[Le(fr(),".claude"),Le(fr(),".agents"),Le(fr(),".codex")].filter(t=>pr(t))}function Xt(){let t={installed:[],refreshed:[],current:[],skipped:[]};if(T().agentSkills===!1)return t;for(let e of Gc()){Dc(e);let n=Le(e,"skills",Fc),r=Le(n,"SKILL.md");try{if(zt(n)||zt(r)){t.skipped.push(r);continue}let o=pr(r)?qo(r,"utf8"):null;if(o===dr){t.current.push(r);continue}Lc(n,{recursive:!0}),Hc(r,dr),(o===null?t.installed:t.refreshed).push(r)}catch{}}return t}var Yo=`Open your coding agent inside the repo you want to onboard and say: "${Ve}"`;B();Ye();j();Ge();B();un();function Ns(t){try{return new URL(t).href.replace(/\/+$/,"")}catch{return}}var Zr=$i;async function Ps(t,e,n,r){let o=await v("/api/v1/cli/workspaces",{token:t.token,baseUrl:r,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(o?.workspaces)||o.workspaces.some(d=>!d||typeof d.id!="string"||!d.id||typeof d.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let i=[...new Map(o.workspaces.map(({id:d,name:h})=>[d,{id:d,name:h}])).values()],a=e.user?.id===t.user.id&&Ns(n)===Ns(r)?i.find(d=>d.id===e.team?.id):void 0,l=i.length===1?i[0]:void 0,c=a??l??i.find(d=>d.id===t.team.id)??i[0]??{id:"",name:"No workspace selected"},u=Zr();return{workspace:c,workspaces:i,source:a?"saved in CLI":l?"only workspace":"active on platform",selectionRequired:!a&&!l,...u?{repository:u}:{},...i.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function vn(t,e,n,r=AbortSignal.timeout(3e3)){try{let o=await ln({apiUrl:t.apiUrl,userId:t.userId,workspaceId:n},t.token,r);return o?{state:o.state}:void 0}catch{return}}function Cn(t,e){let n=/^\d+$/.test(e)?Number(e)-1:-1,r=n>=0?t.workspaces.filter((o,i)=>i===n):t.workspaces.filter(o=>o.id===e||o.name.toLowerCase()===e.toLowerCase());if(r.length!==1)throw new Error(r.length?"Workspace name is ambiguous. Use its ID.":"Workspace not found. Run canary workspace list.");return r[0]}import{stripVTControlCharacters as Ls}from"node:util";var U="\x1B[";function Mt(t,e,n){let r={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[e];return n?`${U}${r}m${t}${U}0m`:t}function P(t){return Ls(t).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var eo=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Ms(t){if(/^[\p{Mark}\u200d\ufe0f]+$/u.test(t))return 0;if(new RegExp("\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\u20e3","u").test(t))return 2;let e=t.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 Lt(t){return[...eo.segment(Ls(t))].reduce((e,n)=>e+Ms(n.segment),0)}function $n(t,e){let n=0,r="";for(let o of t.split(/(\x1b\[[0-9;]*m)/)){if(o.startsWith(U)){r+=o;continue}for(let{segment:i}of eo.segment(o))n+=Ms(i),n<=e&&(r+=i)}return r}function Oe(t,e){let n=[],r="";for(let o of P(t).split(/\s+/)){r&&Lt(r+" "+o)>e&&(n.push(r),r="");for(let{segment:i}of eo.segment((r?" ":"")+o))Lt(r+i)>e&&r&&(n.push(r),r=""),r+=i}return r&&n.push(r),n}function ot(t){let e=[];return{render(n){if(n.join(`
|
|
121
121
|
`)===e.join(`
|
|
122
|
-
`))return;let r=Math.max(2,t.columns||80),o=Math.max(3,t.rows||24),i=Math.min(o-1,e.reduce((s,a)=>s+Math.max(1,Math.ceil(
|
|
122
|
+
`))return;let r=Math.max(2,t.columns||80),o=Math.max(3,t.rows||24),i=Math.min(o-1,e.reduce((s,a)=>s+Math.max(1,Math.ceil(Lt(a)/r)),0));t.write((i?`\r${U}${i}A`:"")+`${U}0J`+(n.length?n.join(`\r
|
|
123
123
|
`)+`\r
|
|
124
124
|
`:"")),e=n}}}function js(t,e,n){return t?[JSON.stringify({authorizeUrl:n})]:[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:
|
|
125
125
|
`:" ")+n+`
|
|
126
|
-
`]}function Hs(t,e){return t?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 In(t,e){let n=e==="ready"?"your setup is ready":e==="setup_required"?"not set up yet":"detected locally";return`Repository ${P(t)} \xB7 ${n}`}function it(t){return`Next: in your coding agent, say "${t==="ready"?Kt:Ve}"`}import{stripVTControlCharacters as zu}from"node:util";var st=[[" "," \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 Ht="\x1B[",Xu={gold:"33",text:"39",muted:"90",green:"32"};function Qu(t,e,n){if(!n)return t;let r=e==="gold"?"38;2;255;212;0":Xu[e];return`${Ht}${r}m${t}${Ht}0m`}function Fs(t){return zu(t).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Us=1.4;function Zu(t){let{phase:e,seconds:n,columns:r,rows:o,color:i,open:s}=t,a=t.phaseSeconds??n,l=1.4,u=n%(l+.2),d=m=>Math.sin(m/l*Math.PI*2)*Math.sin(m/l*Math.PI),h=e==="waiting"&&u<l?d(u):e==="success"&&a<Us?d(a):0,p=st[Math.max(0,Math.min(16,Math.round(h*10)+8))],f=e==="success"?"You're signed in.":e==="failed"?"Sign-in didn't finish.":e==="saving"?"Securing your CLI session":n<1.5?"Let's get you connected.":"Waiting for browser approval",y=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.":s&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",g=(m,k="text")=>Qu(m,k,i),w=e==="success"?"green":e==="failed"?"muted":"gold",_;if(o<5)_=[g(f)];else if(r>=72&&o>=18){let m={1:g("CANARY","gold"),3:g(f,e==="success"?"green":"text"),5:g(y,"muted")};_=["",...p.map((k,x)=>` ${g(k,w)} ${m[x]??""}`)]}else r>=42&&o>=23?_=["",...p.map(m=>` ${g(m,w)}`),` ${g("CANARY","gold")}`,"",` ${g(f)}`,` ${g(y,"muted")}`]:_=["",` ${g("CANARY","gold")}`,` ${g(f)}`];return o>=10&&(_.push("",` ${g("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(e==="waiting"||e==="saving")&&_.push(` ${g("Ctrl+C","muted")} ${g("cancel sign-in","muted")}`),_.push("")),_.slice(0,Math.max(1,o-2)).map(m=>{let k=0;return m.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,x=>x.startsWith("\x1B")||++k<r?x:"")})}function Ds(t){if(t.json||!t.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let e=process.stderr,n=!process.env.NO_COLOR,r=performance.now(),o="waiting",i=r,s=g=>{o=g,i=performance.now()},a=ot(e),l=!1;function c(){if(l)return;let g=Math.max(2,e.columns||80),w=Math.max(3,e.rows||24),_=performance.now(),m=Zu({phase:o,seconds:(_-r)/1e3,phaseSeconds:(_-i)/1e3,columns:g,rows:w,color:n,open:t.open});a.render(m)}let u=()=>e.write(`${Ht}0m${Ht}?25h`);function d(){l||(l=!0,clearInterval(y),e.removeListener("resize",c),process.removeListener("SIGINT",p),process.removeListener("SIGTERM",f),process.removeListener("exit",u),u())}function h(g){s("failed"),c(),d(),e.write(`Sign-in cancelled.
|
|
127
|
-
`),process.exit(g)}let p=()=>h(130),f=()=>h(143),
|
|
126
|
+
`]}function Hs(t,e){return t?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 In(t,e){let n=e==="ready"?"your setup is ready":e==="setup_required"?"not set up yet":"detected locally";return`Repository ${P(t)} \xB7 ${n}`}function jt(t){return`Next: in your coding agent, say "${t==="ready"?Kt:Ve}"`}import{stripVTControlCharacters as zu}from"node:util";var it=[[" "," \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 Ht="\x1B[",Xu={gold:"33",text:"39",muted:"90",green:"32"};function Qu(t,e,n){if(!n)return t;let r=e==="gold"?"38;2;255;212;0":Xu[e];return`${Ht}${r}m${t}${Ht}0m`}function Fs(t){return zu(t).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Us=1.4;function Zu(t){let{phase:e,seconds:n,columns:r,rows:o,color:i,open:s}=t,a=t.phaseSeconds??n,l=1.4,u=n%(l+.2),d=y=>Math.sin(y/l*Math.PI*2)*Math.sin(y/l*Math.PI),h=e==="waiting"&&u<l?d(u):e==="success"&&a<Us?d(a):0,p=it[Math.max(0,Math.min(16,Math.round(h*10)+8))],f=e==="success"?"You're signed in.":e==="failed"?"Sign-in didn't finish.":e==="saving"?"Securing your CLI session":n<1.5?"Let's get you connected.":"Waiting for browser approval",m=e==="success"?"Your terminal is ready for the next step.":e==="failed"?"Run canary login to try again.":e==="saving"?"Exchanging authorization and saving credentials.":s&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",g=(y,k="text")=>Qu(y,k,i),w=e==="success"?"green":e==="failed"?"muted":"gold",_;if(o<5)_=[g(f)];else if(r>=72&&o>=18){let y={1:g("CANARY","gold"),3:g(f,e==="success"?"green":"text"),5:g(m,"muted")};_=["",...p.map((k,x)=>` ${g(k,w)} ${y[x]??""}`)]}else r>=42&&o>=23?_=["",...p.map(y=>` ${g(y,w)}`),` ${g("CANARY","gold")}`,"",` ${g(f)}`,` ${g(m,"muted")}`]:_=["",` ${g("CANARY","gold")}`,` ${g(f)}`];return o>=10&&(_.push("",` ${g("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(e==="waiting"||e==="saving")&&_.push(` ${g("Ctrl+C","muted")} ${g("cancel sign-in","muted")}`),_.push("")),_.slice(0,Math.max(1,o-2)).map(y=>{let k=0;return y.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,x=>x.startsWith("\x1B")||++k<r?x:"")})}function Ds(t){if(t.json||!t.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let e=process.stderr,n=!process.env.NO_COLOR,r=performance.now(),o="waiting",i=r,s=g=>{o=g,i=performance.now()},a=ot(e),l=!1;function c(){if(l)return;let g=Math.max(2,e.columns||80),w=Math.max(3,e.rows||24),_=performance.now(),y=Zu({phase:o,seconds:(_-r)/1e3,phaseSeconds:(_-i)/1e3,columns:g,rows:w,color:n,open:t.open});a.render(y)}let u=()=>e.write(`${Ht}0m${Ht}?25h`);function d(){l||(l=!0,clearInterval(m),e.removeListener("resize",c),process.removeListener("SIGINT",p),process.removeListener("SIGTERM",f),process.removeListener("exit",u),u())}function h(g){s("failed"),c(),d(),e.write(`Sign-in cancelled.
|
|
127
|
+
`),process.exit(g)}let p=()=>h(130),f=()=>h(143),m=setInterval(c,80);return m.unref(),e.on("resize",c),process.once("SIGINT",p),process.once("SIGTERM",f),process.once("exit",u),e.write(`${Ht}?25l`),c(),{saving(){s("saving"),c()},celebrate(){return s("success"),c(),new Promise(g=>setTimeout(g,Us*1e3+100))},succeed(g,w){s("success"),c(),d(),process.stdout.write(` Account ${Fs(g)}
|
|
128
128
|
Workspace ${Fs(w)}
|
|
129
129
|
|
|
130
130
|
`)},fail(){s("failed"),c(),d()},clear(){a.render([]),d()},stop:d}}import{spawn as ed}from"node:child_process";import{createInterface as td,emitKeypressEvents as nd}from"node:readline";function to(t){return t?t.installed.length+t.refreshed.length+t.current.length?`Installed \xB7 available to your coding agent${t.skipped.length?" (some locations skipped)":""}`:"Not installed \xB7 no writable agent location found":"Skipped \xB7 --no-agent-skills"}function no(t){return t.workspaces.length>1}function Ft(t){return t.repositoryState==="ready"?Kt:Ve}async function Gs(t){let e=process.stdin,n=process.stderr,r=e.readableFlowing===!0;n.write(`Choose a workspace:
|
|
131
131
|
`),t.workspaces.forEach((s,a)=>{let l=t.workspaces.some(c=>c.id!==s.id&&c.name===s.name);n.write(` ${a+1}. ${P(s.name)}${l?` (${P(s.id)})`:""}
|
|
132
132
|
`)});let o=td({input:e,output:n,terminal:!1}),i=()=>o.close();process.once("SIGINT",i);try{n.write("Workspace (number or name): ");for await(let s of o)try{return Cn(t,s.trim())}catch(a){n.write(`${a instanceof Error?a.message:"Choose a listed workspace."}
|
|
133
|
-
Workspace (number or name): `)}}finally{process.off("SIGINT",i),o.close(),r||e.pause()}}function rd(t,e,n,r){let{context:o}=t,i=Math.max(1,e-5),s=(h,p="text")=>
|
|
133
|
+
Workspace (number or name): `)}}finally{process.off("SIGINT",i),o.close(),r||e.pause()}}function rd(t,e,n,r){let{context:o}=t,i=Math.max(1,e-5),s=(h,p="text")=>Mt(P(h),p,r),a=(h="",p="text")=>` ${s(h,p)}`,l=[];if(e>=90&&n>=36&&!t.picker){let h={1:s("CANARY","gold"),3:s("You're connected."),5:s("Let's give your agent the next step.","muted")};l.push("",...it[8].map((p,f)=>` ${s(p,"green")} ${h[f]??""}`),"")}else l.push(a("CANARY","gold"),a("You're connected."),"");if(l.push(a(`Account ${P(t.email)}`)),l.push(a(`Workspace ${o.selectionRequired?"Choose below":P(o.workspace.name)}`)),l.push(a(` ${o.source}${!t.done&&no(o)?" \xB7 [w] Change":""}`,"muted")),t.picker){l.push("",a("Choose a workspace","gold"));let h=Math.max(1,Math.min(8,n-l.length-5)),p=Math.max(0,Math.min(t.highlighted-Math.floor(h/2),o.workspaces.length-h));for(let f=p;f<Math.min(p+h,o.workspaces.length);f++){let m=o.workspaces[f],w=o.workspaces.some(y=>y.id!==m.id&&y.name===m.name)?` \xB7 ${P(m.id)}`:"",_=!o.selectionRequired&&m.id===o.workspace.id?" \xB7 current":"";l.push(a(`${f===t.highlighted?"\u203A":" "} ${f+1}. ${P(m.name)}${w}${_}`,f===t.highlighted?"gold":"text"))}l.push(a(`${t.highlighted+1} of ${o.workspaces.length}`,"muted"),"",a("\u2191 \u2193 choose \xB7 number highlight \xB7 Enter select \xB7 Esc back","muted"))}else{let h=o.repositoryState==="ready",p=o.repository?P(o.repository):void 0;p?h?l.push(a(`Repository ${p} \xB7 your setup is ready`,"green")):o.repositoryState==="setup_required"?l.push(a(`Repository ${p} \xB7 not set up yet`)):l.push(a(`Repository ${p} \xB7 detected locally`)):l.push(a("Repository Open a local Git repository to continue")),l.push(a(`Agent skill ${to(t.skill)}`,t.skill&&to(t.skill).startsWith("Installed")?"green":"muted")),o.workspaceNotice&&l.push(...Oe(o.workspaceNotice,i).map(m=>a(m,"muted"))),l.push("",a("\u2500".repeat(Math.min(68,i)),"muted"),a(h?"NEXT \xB7 VERIFY A CHANGE":"NEXT \xB7 SET UP THIS REPOSITORY","gold"));let f=!!t.skill&&to(t.skill).startsWith("Installed");l.push(a(f?"Open your coding agent in this repository and say:":"In your coding agent, run canary skills, then say:","muted")),l.push(...Oe(Ft(o),i-2).map(m=>a(`\u2502 ${m}`))),t.done||l.push("",a(`${no(o)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),t.message&&l.push(...Oe(t.message,i).map(m=>a(m,"muted"))),l.push("",a(h?"Signed in \xB7 Ready to verify":o.repositoryState==="setup_required"?"Signed in \xB7 This repo isn't set up yet":"Signed in \xB7 Couldn't check this repo's setup",h?"green":"muted"))}let u=Math.max(1,n-2);return(u<=3?l.slice(0,u):l.length>u?[...l.slice(0,Math.max(0,u-3)),...l.slice(-3)]:l).map(h=>$n(h,Math.max(1,e-1)))}async function od(t,e){let n=process.platform==="darwin"?[["pbcopy"]]:process.platform==="win32"?[["clip.exe"]]:[["wl-copy"],["xclip","-selection","clipboard"],["xsel","--clipboard","--input"]];for(let[r,...o]of n){if(e.aborted)return!1;if(await new Promise(s=>{let a=ed(r,o,{stdio:["pipe","ignore","ignore"],signal:e}),l=setTimeout(()=>{a.kill(),s(!1)},1e3),c=u=>{clearTimeout(l),s(u)};a.on("error",()=>c(!1)),a.on("close",u=>c(u===0)),a.stdin.on("error",()=>{}),a.stdin.end(t)}))return!0}return!1}async function Js(t){let e=process.stdin,n=process.stderr,r={...t,picker:t.context.workspaces.length>1,highlighted:Math.max(0,t.context.workspaces.findIndex(p=>p.id===t.context.workspace.id))},o=!process.env.NO_COLOR,i=ot(n),s=()=>i.render(rd(r,n.columns||80,n.rows||24,o));if(!e.isTTY||!n.isTTY||(n.rows||24)<16||(n.columns||80)<30){r.done=!0,s(),n.write(`
|
|
134
134
|
${Ft(r.context)}
|
|
135
|
-
`);return}let a=e.isRaw,l=e.readableFlowing===!0,c=new AbortController,u=!1,d,h=0;await new Promise(p=>{function f(){if(u)return;u=!0,c.abort(),e.off("keypress",_),e.off("end",f),n.off("resize",w),process.off("SIGINT",f),process.off("SIGTERM",g),process.off("exit",
|
|
135
|
+
`);return}let a=e.isRaw,l=e.readableFlowing===!0,c=new AbortController,u=!1,d,h=0;await new Promise(p=>{function f(){if(u)return;u=!0,c.abort(),e.off("keypress",_),e.off("end",f),n.off("resize",w),process.off("SIGINT",f),process.off("SIGTERM",g),process.off("exit",m),r.picker=!1,r.done=!0,r.message=void 0;let y=t.sessionCurrent();y?s():i.render(["CLI session changed in another process. Run canary whoami to check the active account."]),m(),y&&!r.context.selectionRequired&&n.write(`
|
|
136
136
|
${Ft(r.context)}
|
|
137
137
|
|
|
138
|
-
`),p()}function y(){e.setRawMode(a),l||e.pause(),n.write(`${U}0m${U}?25h`)}function g(){process.exitCode=143,f()}function w(){(n.rows||24)<16||(n.columns||80)<30?f():s()}function _(m,k){if(!(!k||u)){if(!t.sessionCurrent()){f();return}if(k.ctrl&&["c","d"].includes(k.name??"")){f();return}if(!(k.ctrl||k.meta)){if(r.picker){let x=r.context.workspaces.length;if(k.name==="escape"){if(r.context.selectionRequired){f();return}r.picker=!1}else if(/^[1-9]$/.test(k.sequence??"")&&Number(k.sequence)<=x)r.highlighted=Number(k.sequence)-1;else if(k.name==="up")r.highlighted=(r.highlighted+x-1)%x;else if(k.name==="down")r.highlighted=(r.highlighted+1)%x;else if(k.name==="return"){let E=r.context.workspaces[r.highlighted];try{t.selectWorkspace(E);let C=E.id!==r.context.workspace.id;if(r.context={...r.context,workspace:E,source:"selected in CLI",selectionRequired:!1,...C?{repositoryState:void 0}:{}},r.picker=!1,r.message="Workspace saved for future CLI commands.",(C||!r.context.repositoryState)&&(d?.abort(),t.repositoryState&&r.context.repository)){let D=++h;t.repositoryState(E.id).then(xe=>{if(!u){if(!t.sessionCurrent()){f();return}D!==h||r.context.workspace.id!==E.id||(r.context={...r.context,repositoryState:xe?.state},s())}})}}catch{if(!t.sessionCurrent()){f();return}r.picker=!1,r.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(k.name??"")){f();return}else if(k.name==="w"&&no(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(x=>x.id===r.context.workspace.id));else if(k.name==="c"&&!d){let x=Ft(r.context),E=new AbortController;d=E,c.signal.addEventListener("abort",()=>E.abort(),{once:!0}),od(x,E.signal).then(C=>{d===E&&(d=void 0),!u&&(r.message=E.signal.aborted||x!==Ft(r.context)?"The next step changed while copying. Press [c] to copy the current one.":C?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",s())})}s()}}}nd(e),e.setRawMode(!0),e.resume(),e.on("keypress",_),e.once("end",f),n.on("resize",w),process.once("SIGINT",f),process.once("SIGTERM",g),process.once("exit",y),n.write(`${U}?25l`),s()})}var cd=900*1e3,ld=6e4;var Bs=t=>t.toString("base64url");function ud(t){let e=process.platform,[n,r]=e==="darwin"?["open",[t]]:e==="win32"?["explorer.exe",[t]]:["xdg-open",[t]];try{let o=sd(n,r,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function dd(t,e){return`<!doctype html><meta charset="utf-8"><title>${t}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${t}</h2><p style="color:#555">${e}</p></body>`}function fd(t){return new Promise((e,n)=>{let r,o,i=new Promise((c,u)=>{r=c,o=u}),s=ad((c,u)=>{let d=new URL(c.url??"/","http://127.0.0.1"),h=(y,g,w)=>{u.writeHead(w,{"content-type":"text/html",connection:"close"}),u.end(dd(y,g))};if(d.pathname!=="/callback"){u.writeHead(404,{connection:"close"}),u.end("not found");return}if(d.searchParams.get("state")!==t){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let p=d.searchParams.get("error");if(p){h("Authorization failed","You can close this tab and return to your terminal.",400),o(new Error(`authorization failed: ${p}`));return}let f=d.searchParams.get("code");if(!f){h("Authorization failed","No authorization code was returned. Please run canary login again.",400),o(new Error("callback returned no code"));return}h("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),r(f)}),a=setTimeout(()=>o(new Error("timed out waiting for browser authorization")),cd);a.unref?.();let l=()=>{clearTimeout(a),s.closeAllConnections?.(),s.close()};i.then(l,l),s.on("error",c=>{clearTimeout(a),n(c)}),s.listen(0,"127.0.0.1",()=>{e({port:s.address().port,code:i,close:l})})})}async function pd(t,e){let n=T(),r=n.apiUrl||W(),o=(e.apiUrl||W()).replace(/\/+$/,""),i=Bs(Ws(32)),s=id("sha256").update(i).digest("base64url"),a=Bs(Ws(16)),{port:l,code:c,close:u}=await fd(a),d=`http://127.0.0.1:${l}/callback`,h=(e.webUrl||be()).replace(/\/+$/,""),p=`${h}/cli/authorize?challenge=${encodeURIComponent(s)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(d)}`;for(let w of js(t,e.open,p))console.error(w);let f=Ds({json:t,animation:e.animation,open:e.open}),y=Date.now(),g=f?void 0:setInterval(()=>console.error(Hs(t,Math.round((Date.now()-y)/1e3))),ld);g?.unref?.();try{e.open&&ud(p);let w=await c;g&&clearInterval(g),f?.saving();let _=await v("/api/v1/cli/auth/token",{method:"POST",body:{code:w,codeVerifier:i},baseUrl:o});f&&await f.celebrate(),f?.clear(),await qs(_,n,r,o,t,{webUrl:h,agentSkills:e.agentSkills,workspace:e.workspace,interactive:!!f&&!!process.stdin.isTTY&&(process.stderr.rows||24)>=16&&(process.stderr.columns||80)>=30,promptWorkspace:!t&&!process.env.CI&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&!!process.stderr.isTTY})}catch(w){throw f?.fail(),w}finally{g&&clearInterval(g),f?.stop(),u()}}async function qs(t,e,n,r,o,i){z(({team:p,...f})=>({...f,token:t.token,user:t.user,apiUrl:r,...i.webUrl?{webUrl:i.webUrl}:{},agentSkills:i.agentSkills}),{overwriteUnreadable:!0});let s=await Ps(t,e,n,r);i.workspace!==void 0&&(s.workspace=Cn(s,i.workspace),s.source="selected in CLI",s.selectionRequired=!1),s.selectionRequired||z(p=>({...p,team:s.workspace}));let a=i.agentSkills?Xt():void 0,l=()=>{let p=T();return p.token===t.token&&p.apiUrl===r},c=p=>{z(f=>{if(f.token!==t.token||f.apiUrl!==r)throw new Error("CLI session changed");return{...f,team:p}}),s.selectionRequired=!1},u=s.repository?p=>vn({token:t.token,apiUrl:r,userId:t.user.id},s.repository,p):void 0;if(!s.selectionRequired&&u&&(s.repositoryState=(await u(s.workspace.id))?.state),i.interactive&&s.workspaces.length)await Js({email:t.user.email,context:s,skill:a,selectWorkspace:c,sessionCurrent:l,repositoryState:u});else if(i.promptWorkspace&&s.selectionRequired&&s.workspaces.length){console.error(`Signed in as ${P(t.user.email)}.`);let p=await Gs(s);p&&(c(p),s.workspace=p,s.source="selected in CLI",u&&(s.repositoryState=(await u(p.id))?.state))}if(!l())throw new Error("CLI session changed in another process. Run canary whoami.");let d=T().team;if(!d){let p=s.workspaces.length?"workspace_selection_required":"workspace_required",f=s.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${be()}, then run canary login.`;o?console.log(JSON.stringify({ok:!1,authenticated:!0,error:p,user:t.user,workspaces:s.workspaces,fix:f})):(console.log(`Signed in as ${P(t.user.email)}. Select a workspace to continue.`),s.workspaces.forEach((y,g)=>console.log(` ${g+1}. ${P(y.name)} (${P(y.id)})`)),console.log(f)),process.exitCode=1;return}let h=s.repository?{name:s.repository,state:s.repositoryState}:void 0;return o?console.log(JSON.stringify({ok:!0,user:t.user,team:d,workspace:d,...h?{repository:h}:{}})):i.interactive||(console.log(`Logged in as ${P(t.user.email)} (${P(d.name??d.id)}).`),h&&console.log(In(h.name,h.state)),a?hd(!1,a,it(h?.state)):console.log(it(h?.state))),it(h?.state)}async function Vs(t,e,n){let r=T(),o=r.apiUrl||W(),i=(n.apiUrl||W()).replace(/\/+$/,""),s=await v("/api/v1/cli/auth/whoami",{token:t,baseUrl:i});await qs({...s,token:t,tokenType:"Bearer",expiresAt:null},r,o,i,e,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function hd(t,e,n=Yo){if(t)return;let r=[...e.installed,...e.refreshed];r.length&&console.log(`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${r.join(", ")}).`),console.log(n)}function Ys(t){t.command("login").description("Authenticate the Canary CLI with your account").option("--json","output machine-readable JSON").option("--token <token>","log in with a token directly (CI / headless; else $CANARY_TOKEN)").option("--web-url <url>","override the authorization web URL").option("--api-url <url>","override the API base URL (moves with --web-url)").option("--workspace <id-or-name>","select a workspace from your memberships (required for an unselected headless login)").option("--no-open","print the authorization URL instead of opening a browser").option("--no-animation","use plain login output without the animated Canary").option("--no-agent-skills","skip installing the Canary skill for your coding agents (written to ~/.claude, ~/.agents, ~/.codex when present)").option("--no-hooks","skip adding the push check to your coding agents' settings").action(async e=>{let n=e.json===!0;try{if(e.token!==void 0){let r=e.token.trim();if(!r)throw new Error("--token was provided but is empty");await Vs(r,n,{...e,agentSkills:e.agentSkills!==!1})}else{let r=(process.env.CANARY_TOKEN??"").trim();r?await Vs(r,n,{...e,agentSkills:e.agentSkills!==!1}):(await pd(n,{webUrl:e.webUrl,apiUrl:e.apiUrl,workspace:e.workspace,open:e.open!==!1,animation:e.animation!==!1,agentSkills:e.agentSkills!==!1}),qe())}!process.exitCode&&e.agentSkills!==!1&&e.hooks!==!1&&await Lt({json:n})}catch(r){let o=r instanceof R?`${r.message}`:r instanceof Error?r.message:String(r);n?console.log(JSON.stringify({ok:!1,error:o})):console.error(`Login failed: ${o}`),process.exitCode=1}})}j();Qt();Ge();B();j();pe();async function Ut(t,e){let n=H();if(!n)return{ok:!1,cause:"not_logged_in"};let r=T(),o=r.team?.id;if(!o)return{ok:!1,cause:"no_workspace"};let i=W();try{let s=n===r.token?r.user?.id:void 0;if(s||(s=(await v("/api/v1/cli/auth/whoami",{token:n,baseUrl:i,signal:e}))?.user?.id),!s)return{ok:!1,cause:"not_logged_in"};let a={apiUrl:i,userId:s,workspaceId:o,directory:t},l=an(a);return l?.repositoryId?{ok:!0,context:{token:n,apiUrl:i,repository:a,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(s){return{ok:!1,cause:s.code==="not_a_git_repository"?"no_binding":"context_error"}}}wn();B();pe();var Dt=5e3,gd=new Set(["verified","open","running","failed","none"]);async function Rn(t,e,n={}){let r=new URLSearchParams({repositoryId:t.repositoryId,workspaceId:t.repository.workspaceId,treeHash:e.treeHash});e.branch&&r.set("branch",e.branch);let o=AbortSignal.timeout(n.timeoutMs??Dt);try{let i=await v(`/api/v1/cli/runs/status?${r.toString()}`,{token:t.token,baseUrl:t.apiUrl,signal:n.signal?AbortSignal.any([o,n.signal]):o});if(!i||typeof i!="object"||!gd.has(String(i.state)))return{ok:!1,cause:"unknown_state",detail:"Canary answered in a way this CLI version does not understand (update the CLI)"};if(typeof i.repositoryId=="string"&&i.repositoryId!==t.repositoryId)try{cn(t.repository,i.repositoryId)}catch{}return{ok:!0,state:i.state,...i.runId?{runId:i.runId}:{},...i.runUrl?{runUrl:i.runUrl}:{},...i.counts?{open:i.counts.open}:{},lineageHasRuns:i.lineageHasRuns===!0,...i.newestRun&&typeof i.newestRun.runId=="string"&&["verified","open","running","failed"].includes(String(i.newestRun.state))?{newestRun:{runId:i.newestRun.runId,state:i.newestRun.state,...typeof i.newestRun.treeHash=="string"?{treeHash:i.newestRun.treeHash}:{},...typeof i.newestRun.headSha=="string"?{headSha:i.newestRun.headSha}:{}}}:{}}}catch(i){return o.aborted?{ok:!1,cause:"lookup_timeout",detail:`Canary did not answer within ${Math.round((n.timeoutMs??Dt)/1e3)} s`}:i instanceof R&&i.status>=400&&i.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${i.status}: ${i.message}${i.fix?` (${i.fix})`:""}`}:i instanceof R&&i.status>=500?{ok:!1,cause:"lookup_error",detail:`Canary answered ${i.status}`}:{ok:!1,cause:"lookup_unreachable",detail:i instanceof Error?i.message:String(i)}}}j();pe();import{randomUUID as md}from"node:crypto";import{readFileSync as yd,renameSync as wd,rmSync as bd,writeFileSync as kd}from"node:fs";var Ks="skips.json",Sd=720*60*60*1e3,_d=1440*60*1e3,xd=(t,e)=>{let n=Date.parse(t.at);return Number.isFinite(n)&&e-n<Sd&&n-e<_d};function On(t,e=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(yd(ae(t,Ks),"utf8"))}catch{return n}let o=r?.skips;if(!r||typeof r!="object"||r.version!==1||!o||typeof o!="object"||Array.isArray(o))return n;for(let[i,s]of Object.entries(o))/^[a-f0-9]{40}$/.test(i)&&s&&typeof s=="object"&&typeof s.reason=="string"&&typeof s.at=="string"&&xd(s,e)&&(n.skips[i]={reason:s.reason,at:s.at,...typeof s.branch=="string"?{branch:s.branch}:{}});return n}function zs(t,e,n=Date.now()){return On(t,n).skips[e]??null}function Xs(t,e,n,r=Date.now()){let o=ae(t,Ks);return Bo(`${o}.lock`,"this repository's skip records",()=>{let i=On(t,r),s={reason:n.reason,at:new Date(r).toISOString(),...n.branch?{branch:n.branch}:{}};i.skips[e]=s;let a=`${o}.${md()}.tmp`;try{kd(a,JSON.stringify(i,null,2)+`
|
|
139
|
-
`,{flag:"wx",mode:384}),wd(a,o)}catch(l){throw bd(a,{force:!0}),l}return s})}nt();rt();var vd=500,En={not_logged_in:["Not logged in","run `canary login` first"],no_workspace:["No workspace is selected","run `canary workspace list`, then `canary workspace use <id>`"],no_binding:["This checkout is not set up with Canary, so its pushes are not checked and there is nothing to skip","run `canary setup` to set it up"],context_error:["Canary's saved record for this checkout could not be read","run `canary setup` again"]};function Qs(t){return t==="on"?"The push check is on: an agent's push or pull request is held until its exact code has a Canary run with nothing open, or a recorded skip.":"The push check is off: agents push and open pull requests without Canary being asked."}function Cd(t,e){try{if(!ni(t))return $(e,"config_unreadable","~/.canary/config.json exists but cannot be read, so the setting was not saved","repair or remove the file, then run the command again",2)}catch(n){if(n instanceof Pe)return $(e,"config_busy",n.message,void 0,2);throw n}console.log(e?JSON.stringify({ok:!0,mode:t}):Qs(t))}async function $d(t,e,n){let r=(e??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,vd);if(!r)return $(n,"reason_required","a skip needs a reason",'canary skip --reason "<why this change needs no run>"',3);let o=await Ut(t);if(!o.ok){let[c,u]=En[o.cause]??En.context_error;return $(n,o.cause,c,u,3)}let i;try{i=await mn(t)}catch(c){if(c instanceof ee)return $(n,c.code,c.message,c.fix,3);throw c}let s=tt(i.branch),a;try{a=Xs(o.context.repository,i.treeHash,{reason:r,...s?{branch:s}:{}})}catch(c){if(c instanceof Pe)return $(n,"config_busy",c.message,void 0,2);throw c}yn(o.context.repository);let l=await Rn(o.context,{treeHash:i.treeHash,branch:s},{timeoutMs:3e3});await
|
|
140
|
-
This covers exactly the code on disk now; any further edit is a new tree.`)}async function Id(t,e){let n=await Ut(t);if(!n.ok){let[o,i]=En[n.cause]??En.context_error;return $(e,n.cause,o,i,3)}let r=Object.entries(On(n.context.repository).skips).map(([o,i])=>({treeHash:o,...i})).sort((o,i)=>i.at.localeCompare(o.at));if(e)return console.log(JSON.stringify({ok:!0,skips:r}));if(!r.length)return console.log("No skips recorded for this repository.");for(let o of r)console.log(`${o.treeHash.slice(0,12)} ${o.at.slice(0,16).replace("T"," ")} ${o.branch?b(o.branch):"(detached)"} ${b(o.reason)}`)}function Zs(t){let e=t.command("gate").description("The check on an agent's push or pull request: on, off, status");for(let n of["on","off"])e.command(n).description(n==="on"?"Hold an agent's unverified push or pull request (the default)":"Never hold a push or pull request").option("--json","print one JSON document").action(r=>Cd(n,r.json===!0));e.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=
|
|
138
|
+
`),p()}function m(){e.setRawMode(a),l||e.pause(),n.write(`${U}0m${U}?25h`)}function g(){process.exitCode=143,f()}function w(){(n.rows||24)<16||(n.columns||80)<30?f():s()}function _(y,k){if(!(!k||u)){if(!t.sessionCurrent()){f();return}if(k.ctrl&&["c","d"].includes(k.name??"")){f();return}if(!(k.ctrl||k.meta)){if(r.picker){let x=r.context.workspaces.length;if(k.name==="escape"){if(r.context.selectionRequired){f();return}r.picker=!1}else if(/^[1-9]$/.test(k.sequence??"")&&Number(k.sequence)<=x)r.highlighted=Number(k.sequence)-1;else if(k.name==="up")r.highlighted=(r.highlighted+x-1)%x;else if(k.name==="down")r.highlighted=(r.highlighted+1)%x;else if(k.name==="return"){let E=r.context.workspaces[r.highlighted];try{t.selectWorkspace(E);let C=E.id!==r.context.workspace.id;if(r.context={...r.context,workspace:E,source:"selected in CLI",selectionRequired:!1,...C?{repositoryState:void 0}:{}},r.picker=!1,r.message="Workspace saved for future CLI commands.",(C||!r.context.repositoryState)&&(d?.abort(),t.repositoryState&&r.context.repository)){let D=++h;t.repositoryState(E.id).then(xe=>{if(!u){if(!t.sessionCurrent()){f();return}D!==h||r.context.workspace.id!==E.id||(r.context={...r.context,repositoryState:xe?.state},s())}})}}catch{if(!t.sessionCurrent()){f();return}r.picker=!1,r.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(k.name??"")){f();return}else if(k.name==="w"&&no(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(x=>x.id===r.context.workspace.id));else if(k.name==="c"&&!d){let x=Ft(r.context),E=new AbortController;d=E,c.signal.addEventListener("abort",()=>E.abort(),{once:!0}),od(x,E.signal).then(C=>{d===E&&(d=void 0),!u&&(r.message=E.signal.aborted||x!==Ft(r.context)?"The next step changed while copying. Press [c] to copy the current one.":C?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",s())})}s()}}}nd(e),e.setRawMode(!0),e.resume(),e.on("keypress",_),e.once("end",f),n.on("resize",w),process.once("SIGINT",f),process.once("SIGTERM",g),process.once("exit",m),n.write(`${U}?25l`),s()})}var cd=900*1e3,ld=6e4;var Bs=t=>t.toString("base64url");function ud(t){let e=process.platform,[n,r]=e==="darwin"?["open",[t]]:e==="win32"?["explorer.exe",[t]]:["xdg-open",[t]];try{let o=sd(n,r,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function dd(t,e){return`<!doctype html><meta charset="utf-8"><title>${t}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${t}</h2><p style="color:#555">${e}</p></body>`}function fd(t){return new Promise((e,n)=>{let r,o,i=new Promise((c,u)=>{r=c,o=u}),s=ad((c,u)=>{let d=new URL(c.url??"/","http://127.0.0.1"),h=(m,g,w)=>{u.writeHead(w,{"content-type":"text/html",connection:"close"}),u.end(dd(m,g))};if(d.pathname!=="/callback"){u.writeHead(404,{connection:"close"}),u.end("not found");return}if(d.searchParams.get("state")!==t){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let p=d.searchParams.get("error");if(p){h("Authorization failed","You can close this tab and return to your terminal.",400),o(new Error(`authorization failed: ${p}`));return}let f=d.searchParams.get("code");if(!f){h("Authorization failed","No authorization code was returned. Please run canary login again.",400),o(new Error("callback returned no code"));return}h("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),r(f)}),a=setTimeout(()=>o(new Error("timed out waiting for browser authorization")),cd);a.unref?.();let l=()=>{clearTimeout(a),s.closeAllConnections?.(),s.close()};i.then(l,l),s.on("error",c=>{clearTimeout(a),n(c)}),s.listen(0,"127.0.0.1",()=>{e({port:s.address().port,code:i,close:l})})})}async function pd(t,e){let n=T(),r=n.apiUrl||W(),o=(e.apiUrl||W()).replace(/\/+$/,""),i=Bs(Ws(32)),s=id("sha256").update(i).digest("base64url"),a=Bs(Ws(16)),{port:l,code:c,close:u}=await fd(a),d=`http://127.0.0.1:${l}/callback`,h=(e.webUrl||be()).replace(/\/+$/,""),p=`${h}/cli/authorize?challenge=${encodeURIComponent(s)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(d)}`;for(let w of js(t,e.open,p))console.error(w);let f=Ds({json:t,animation:e.animation,open:e.open}),m=Date.now(),g=f?void 0:setInterval(()=>console.error(Hs(t,Math.round((Date.now()-m)/1e3))),ld);g?.unref?.();try{e.open&&ud(p);let w=await c;g&&clearInterval(g),f?.saving();let _=await v("/api/v1/cli/auth/token",{method:"POST",body:{code:w,codeVerifier:i},baseUrl:o});return f&&await f.celebrate(),f?.clear(),await qs(_,n,r,o,t,{webUrl:h,agentSkills:e.agentSkills,workspace:e.workspace,interactive:!!f&&!!process.stdin.isTTY&&(process.stderr.rows||24)>=16&&(process.stderr.columns||80)>=30,promptWorkspace:!t&&!process.env.CI&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&!!process.stderr.isTTY})}catch(w){throw f?.fail(),w}finally{g&&clearInterval(g),f?.stop(),u()}}async function qs(t,e,n,r,o,i){z(({team:f,...m})=>({...m,token:t.token,user:t.user,apiUrl:r,...i.webUrl?{webUrl:i.webUrl}:{},agentSkills:i.agentSkills}),{overwriteUnreadable:!0});let s=await Ps(t,e,n,r);i.workspace!==void 0&&(s.workspace=Cn(s,i.workspace),s.source="selected in CLI",s.selectionRequired=!1),s.selectionRequired||z(f=>({...f,team:s.workspace}));let a=i.agentSkills?Xt():void 0,l=()=>{let f=T();return f.token===t.token&&f.apiUrl===r},c=f=>{z(m=>{if(m.token!==t.token||m.apiUrl!==r)throw new Error("CLI session changed");return{...m,team:f}}),s.selectionRequired=!1},u=s.repository?f=>vn({token:t.token,apiUrl:r,userId:t.user.id},s.repository,f):void 0;if(!s.selectionRequired&&u&&(s.repositoryState=(await u(s.workspace.id))?.state),i.interactive&&s.workspaces.length)await Js({email:t.user.email,context:s,skill:a,selectWorkspace:c,sessionCurrent:l,repositoryState:u});else if(i.promptWorkspace&&s.selectionRequired&&s.workspaces.length){console.error(`Signed in as ${P(t.user.email)}.`);let f=await Gs(s);f&&(c(f),s.workspace=f,s.source="selected in CLI",u&&(s.repositoryState=(await u(f.id))?.state))}if(!l())throw new Error("CLI session changed in another process. Run canary whoami.");let d=!process.exitCode,h=T().team;if(!h){let f=s.workspaces.length?"workspace_selection_required":"workspace_required",m=s.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${be()}, then run canary login.`;return o?console.log(JSON.stringify({ok:!1,authenticated:!0,error:f,user:t.user,workspaces:s.workspaces,fix:m})):(console.log(`Signed in as ${P(t.user.email)}. Select a workspace to continue.`),s.workspaces.forEach((g,w)=>console.log(` ${w+1}. ${P(g.name)} (${P(g.id)})`)),console.log(m)),process.exitCode=1,d}let p=s.repository?{name:s.repository,state:s.repositoryState}:void 0;return o?console.log(JSON.stringify({ok:!0,user:t.user,team:h,workspace:h,...p?{repository:p}:{}})):i.interactive||(console.log(`Logged in as ${P(t.user.email)} (${P(h.name??h.id)}).`),p&&console.log(In(p.name,p.state)),a?hd(!1,a,jt(p?.state)):console.log(jt(p?.state))),d}async function Vs(t,e,n){let r=T(),o=r.apiUrl||W(),i=(n.apiUrl||W()).replace(/\/+$/,""),s=await v("/api/v1/cli/auth/whoami",{token:t,baseUrl:i});return qs({...s,token:t,tokenType:"Bearer",expiresAt:null},r,o,i,e,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function hd(t,e,n=Yo){if(t)return;let r=[...e.installed,...e.refreshed];r.length&&console.log(`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${r.join(", ")}).`),console.log(n)}function Ys(t){t.command("login").description("Authenticate the Canary CLI with your account").option("--json","output machine-readable JSON").option("--token <token>","log in with a token directly (CI / headless; else $CANARY_TOKEN)").option("--web-url <url>","override the authorization web URL").option("--api-url <url>","override the API base URL (moves with --web-url)").option("--workspace <id-or-name>","select a workspace from your memberships (required for an unselected headless login)").option("--no-open","print the authorization URL instead of opening a browser").option("--no-animation","use plain login output without the animated Canary").option("--no-agent-skills","skip installing the Canary skill for your coding agents (written to ~/.claude, ~/.agents, ~/.codex when present)").option("--no-hooks","skip adding the push check to your coding agents' settings").action(async e=>{let n=e.json===!0;try{let r;if(e.token!==void 0){let o=e.token.trim();if(!o)throw new Error("--token was provided but is empty");r=await Vs(o,n,{...e,agentSkills:e.agentSkills!==!1})}else{let o=(process.env.CANARY_TOKEN??"").trim();o?r=await Vs(o,n,{...e,agentSkills:e.agentSkills!==!1}):(r=await pd(n,{webUrl:e.webUrl,apiUrl:e.apiUrl,workspace:e.workspace,open:e.open!==!1,animation:e.animation!==!1,agentSkills:e.agentSkills!==!1}),qe())}r&&e.agentSkills!==!1&&e.hooks!==!1&&await Pt({json:n})}catch(r){let o=r instanceof R?`${r.message}`:r instanceof Error?r.message:String(r);n?console.log(JSON.stringify({ok:!1,error:o})):console.error(`Login failed: ${o}`),process.exitCode=1}})}j();Qt();Ge();B();j();pe();async function Ut(t,e){let n=H();if(!n)return{ok:!1,cause:"not_logged_in"};let r=T(),o=r.team?.id;if(!o)return{ok:!1,cause:"no_workspace"};let i=W();try{let s=n===r.token?r.user?.id:void 0;if(s||(s=(await v("/api/v1/cli/auth/whoami",{token:n,baseUrl:i,signal:e}))?.user?.id),!s)return{ok:!1,cause:"not_logged_in"};let a={apiUrl:i,userId:s,workspaceId:o,directory:t},l=an(a);return l?.repositoryId?{ok:!0,context:{token:n,apiUrl:i,repository:a,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(s){return{ok:!1,cause:s.code==="not_a_git_repository"?"no_binding":"context_error"}}}wn();B();pe();var Dt=5e3,gd=new Set(["verified","open","running","failed","none"]);async function Rn(t,e,n={}){let r=new URLSearchParams({repositoryId:t.repositoryId,workspaceId:t.repository.workspaceId,treeHash:e.treeHash});e.branch&&r.set("branch",e.branch);let o=AbortSignal.timeout(n.timeoutMs??Dt);try{let i=await v(`/api/v1/cli/runs/status?${r.toString()}`,{token:t.token,baseUrl:t.apiUrl,signal:n.signal?AbortSignal.any([o,n.signal]):o});if(!i||typeof i!="object"||!gd.has(String(i.state)))return{ok:!1,cause:"unknown_state",detail:"Canary answered in a way this CLI version does not understand (update the CLI)"};if(typeof i.repositoryId=="string"&&i.repositoryId!==t.repositoryId)try{cn(t.repository,i.repositoryId)}catch{}return{ok:!0,state:i.state,...i.runId?{runId:i.runId}:{},...i.runUrl?{runUrl:i.runUrl}:{},...i.counts?{open:i.counts.open}:{},lineageHasRuns:i.lineageHasRuns===!0,...i.newestRun&&typeof i.newestRun.runId=="string"&&["verified","open","running","failed"].includes(String(i.newestRun.state))?{newestRun:{runId:i.newestRun.runId,state:i.newestRun.state,...typeof i.newestRun.treeHash=="string"?{treeHash:i.newestRun.treeHash}:{},...typeof i.newestRun.headSha=="string"?{headSha:i.newestRun.headSha}:{}}}:{}}}catch(i){return o.aborted?{ok:!1,cause:"lookup_timeout",detail:`Canary did not answer within ${Math.round((n.timeoutMs??Dt)/1e3)} s`}:i instanceof R&&i.status>=400&&i.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${i.status}: ${i.message}${i.fix?` (${i.fix})`:""}`}:i instanceof R&&i.status>=500?{ok:!1,cause:"lookup_error",detail:`Canary answered ${i.status}`}:{ok:!1,cause:"lookup_unreachable",detail:i instanceof Error?i.message:String(i)}}}j();pe();import{randomUUID as md}from"node:crypto";import{readFileSync as yd,renameSync as wd,rmSync as bd,writeFileSync as kd}from"node:fs";var Ks="skips.json",Sd=720*60*60*1e3,_d=1440*60*1e3,xd=(t,e)=>{let n=Date.parse(t.at);return Number.isFinite(n)&&e-n<Sd&&n-e<_d};function On(t,e=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(yd(ae(t,Ks),"utf8"))}catch{return n}let o=r?.skips;if(!r||typeof r!="object"||r.version!==1||!o||typeof o!="object"||Array.isArray(o))return n;for(let[i,s]of Object.entries(o))/^[a-f0-9]{40}$/.test(i)&&s&&typeof s=="object"&&typeof s.reason=="string"&&typeof s.at=="string"&&xd(s,e)&&(n.skips[i]={reason:s.reason,at:s.at,...typeof s.branch=="string"?{branch:s.branch}:{}});return n}function zs(t,e,n=Date.now()){return On(t,n).skips[e]??null}function Xs(t,e,n,r=Date.now()){let o=ae(t,Ks);return Bo(`${o}.lock`,"this repository's skip records",()=>{let i=On(t,r),s={reason:n.reason,at:new Date(r).toISOString(),...n.branch?{branch:n.branch}:{}};i.skips[e]=s;let a=`${o}.${md()}.tmp`;try{kd(a,JSON.stringify(i,null,2)+`
|
|
139
|
+
`,{flag:"wx",mode:384}),wd(a,o)}catch(l){throw bd(a,{force:!0}),l}return s})}nt();rt();var vd=500,En={not_logged_in:["Not logged in","run `canary login` first"],no_workspace:["No workspace is selected","run `canary workspace list`, then `canary workspace use <id>`"],no_binding:["This checkout is not set up with Canary, so its pushes are not checked and there is nothing to skip","run `canary setup` to set it up"],context_error:["Canary's saved record for this checkout could not be read","run `canary setup` again"]};function Qs(t){return t==="on"?"The push check is on: an agent's push or pull request is held until its exact code has a Canary run with nothing open, or a recorded skip.":"The push check is off: agents push and open pull requests without Canary being asked."}function Cd(t,e){try{if(!ni(t))return $(e,"config_unreadable","~/.canary/config.json exists but cannot be read, so the setting was not saved","repair or remove the file, then run the command again",2)}catch(n){if(n instanceof Pe)return $(e,"config_busy",n.message,void 0,2);throw n}console.log(e?JSON.stringify({ok:!0,mode:t}):Qs(t))}async function $d(t,e,n){let r=(e??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,vd);if(!r)return $(n,"reason_required","a skip needs a reason",'canary skip --reason "<why this change needs no run>"',3);let o=await Ut(t);if(!o.ok){let[c,u]=En[o.cause]??En.context_error;return $(n,o.cause,c,u,3)}let i;try{i=await mn(t)}catch(c){if(c instanceof ee)return $(n,c.code,c.message,c.fix,3);throw c}let s=tt(i.branch),a;try{a=Xs(o.context.repository,i.treeHash,{reason:r,...s?{branch:s}:{}})}catch(c){if(c instanceof Pe)return $(n,"config_busy",c.message,void 0,2);throw c}yn(o.context.repository);let l=await Rn(o.context,{treeHash:i.treeHash,branch:s},{timeoutMs:3e3});await Ot(l.ok?`gate_skip:${l.state}:${l.lineageHasRuns?"prior":"first"}`:"gate_skip:unknown:unknown",o.context),console.log(n?JSON.stringify({ok:!0,treeHash:i.treeHash,...s?{branch:s}:{},reason:a.reason,at:a.at}):`Skipped tree ${i.treeHash.slice(0,12)}${s?` on ${b(s)}`:""}: ${b(a.reason)}
|
|
140
|
+
This covers exactly the code on disk now; any further edit is a new tree.`)}async function Id(t,e){let n=await Ut(t);if(!n.ok){let[o,i]=En[n.cause]??En.context_error;return $(e,n.cause,o,i,3)}let r=Object.entries(On(n.context.repository).skips).map(([o,i])=>({treeHash:o,...i})).sort((o,i)=>i.at.localeCompare(o.at));if(e)return console.log(JSON.stringify({ok:!0,skips:r}));if(!r.length)return console.log("No skips recorded for this repository.");for(let o of r)console.log(`${o.treeHash.slice(0,12)} ${o.at.slice(0,16).replace("T"," ")} ${o.branch?b(o.branch):"(detached)"} ${b(o.reason)}`)}function Zs(t){let e=t.command("gate").description("The check on an agent's push or pull request: on, off, status");for(let n of["on","off"])e.command(n).description(n==="on"?"Hold an agent's unverified push or pull request (the default)":"Never hold a push or pull request").option("--json","print one JSON document").action(r=>Cd(n,r.json===!0));e.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=Nt();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(Qs(r.mode));for(let o of xn(r))console.log(o)}}),t.command("skip").description("Let this exact code be pushed without a Canary run, with a reason").option("--reason <text>","why this change needs no run").option("--list","show the skips recorded for this repository").option("--dir <path>","repo directory (default: current directory)").option("--json","print one JSON document").action(async n=>{let r=n.json===!0;try{n.list?await Id(n.dir??process.cwd(),r):await $d(n.dir??process.cwd(),n.reason,r)}catch(o){$(r,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}})}Ge();$e();var Rd={[q.install]:"(random, minted once into ~/.canary/config.json)",[q.worktree]:"(hash of this checkout's path, salted by the install id; the path never leaves)",[q.repo]:"(root commit of the history; absent on a shallow clone)"};function ea(t){t.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 n=Ce();if(e.json===!0)return void console.log(JSON.stringify(n));for(let[r,o]of Object.entries(n)){let i=r===q.harness&&o==="unknown"?"(no running coding-agent session detected)":Rd[r]??"";console.log(`${r.padEnd(18)} ${o}${i?` ${i}`:""}`)}})}j();Qt();$e();nt();import{appendFileSync as Kd,existsSync as zd}from"node:fs";import{join as pa}from"node:path";var Ee=(t,e)=>({decision:"allow",cause:t,...e?{message:e}:{}}),ro=t=>t.replace(/[\x00-\x1f\x7f]+/g,"?");function An(t){if(t.mode==="off")return Ee("mode_off");if(!t.trigger)return Ee("not_a_trigger");if(t.trigger.dir===null)return Ee("unknown_directory");if(!t.context)return null;if(!t.context.ok)return Ee(t.context.cause);if(t.trigger.editsFirst)return{decision:"deny",cause:"edits_first",message:Ad(t.trigger)};if(!t.tree)return null;if(!t.tree.ok)return Ee("hash_failed",ta(`this checkout could not be read (${t.tree.detail})`));if(t.skip===void 0)return null;if(t.skip)return Ee("skipped",`Canary: this exact code goes out on a recorded skip, not a run (${ro(t.skip.reason)}). Tell the user it was published without a Canary run, and why.`);if(!t.lookup)return null;if(!t.lookup.ok)return Ee(t.lookup.cause,ta(t.lookup.detail));let{state:e}=t.lookup;return e==="verified"?t.leftOut?Ee("verified",t.leftOut.length?Od(t.leftOut):void 0):null:e==="none"&&t.lookup.newestRun?.treeHash&&t.since===void 0?null:{decision:"deny",cause:e,message:Td(t.trigger,t.tree,t.lookup,t.since)}}var ta=t=>`Canary did not check this: ${t}. Nothing was blocked.`;function Od(t){let e=t.slice(0,8).map(ro).join(", "),n=t.length;return`Canary: ${n} ${n===1?"file was":"files were"} present when this tree was verified but ${n===1?"is":"are"} not committed, so ${n===1?"it is":"they are"} not in what is being published: ${e}${n>8?`, and ${n-8} more`:""}.`}function Ed(t,e){let n=`Newest run on this branch: ${t.runId.slice(0,8)} (${t.state})`;if(e&&e.total>0){let r=e.total>e.files.length?` and ${e.total-e.files.length} more`:"";return`${n}. Changed since it: ${e.total} file${e.total===1?"":"s"}: ${e.files.map(ro).join(", ")}${r}.`}return t.headSha?`${n}, taken from commit ${t.headSha.slice(0,7)}; \`git diff ${t.headSha.slice(0,7)}..HEAD --stat\` shows what was committed since.`:`${n}.`}function Ad(t){let e=t.action==="push"?"push":"pull request",n=t.action==="push"?"`git push` as its own command (`git add \u2026 && git commit \u2026 && git push` is fine: a commit changes no file)":"`gh pr create` as its own command";return[`Canary held this ${e}: this command changes files before it publishes, so the code it would publish is not the code on disk now, which is what the check reads.`,`Make the edits first, then run ${n}. The check then reads the code being published.`].join(`
|
|
141
141
|
|
|
142
142
|
`)}function Td(t,e,n,r){let o=t.action==="push"?"push":"pull request",i="Two ways forward. This is your decision, not a question for the user: choose by whether what changed since the last verified code can alter behaviour, and by what the user asked for.",s=`tree ${e.treeHash.slice(0,12)}${e.branch?` on ${e.branch}`:""}`,a=n.runId?`run ${n.runId}${n.runUrl?` (${n.runUrl})`:""}`:"",l=`Skip it: \`canary skip --reason "<why this change needs no run>"\`, then repeat the ${o}.`,c=[];if(n.state==="running")c.push(`Canary held this ${o}: ${a} is still checking this exact code (${s}).`,"",i,`1. Wait for it: \`canary run wait ${n.runId}\` (it returns when the run has finished; run it as a background shell command where you can), then repeat the ${o}.`,`2. ${l}`);else if(n.state==="open"){let u=n.open??0;c.push(`Canary held this ${o}: ${a} found ${u} finding${u===1?"":"s"} still open on this exact code (${s}).`,"",i,`1. Close them: fix the code and re-check with \`canary verify --failed ${n.runId}\`, or report a finding you will not fix with \`canary check ${n.runId} <checkRunId> --disputed "<why>"\` (or \`--skipped\`). Repeat the ${o} once none is open.`,`2. ${l}`)}else c.push(n.state==="failed"?`Canary held this ${o}: ${a} did not finish or could not check anything, so this exact code (${s}) is unverified.`:`Canary held this ${o}: this exact code (${s}) has no verification run of yours; ${n.lineageHasRuns?`an earlier tree ${e.branch?"on this branch":"here"} has one`:`nothing ${e.branch?"on this branch":"here"} has been verified yet`}.`,...n.newestRun?[Ed(n.newestRun,r)]:[],"",i,`1. Verify it: \`canary verify\`, wait for the run, close what it finds, then repeat the ${o}.`,`2. ${l}`);return c.push("","`canary skill gate` says when each one fits."),c.join(`
|
|
143
143
|
`)}var na=["claude","codex","cursor"];function ra(t,e=0,n=[]){if(typeof t=="string")t&&n.push(t);else if(e<3&&t&&typeof t=="object")for(let r of Object.values(t))ra(r,e+1,n);return n}var Tn=t=>typeof t=="string"&&t?t:void 0,Nd=new Set(["Bash","PowerShell","Monitor"]);function oa(t,e,n=process.env,r=process.platform){if(!e||typeof e!="object"||Array.isArray(e))return null;let o=e;if(t==="cursor"){let l=Array.isArray(o.workspace_roots)?o.workspace_roots:[],c=Tn(o.cwd)??Tn(l[0])??Tn(n.CURSOR_PROJECT_DIR)??process.cwd();return o.hook_event_name==="beforeShellExecution"&&typeof o.command=="string"?{kind:"shell",command:o.command,cwd:c,shell:r==="win32"?"powershell":"posix"}:o.hook_event_name==="beforeMCPExecution"&&typeof o.tool_name=="string"?{kind:"tool",toolName:o.tool_name,cwd:c}:null}if(o.hook_event_name!=="PreToolUse"||typeof o.tool_name!="string")return null;let i=Tn(o.cwd)??process.cwd(),s=o.tool_input&&typeof o.tool_input=="object"?o.tool_input:{};if(Nd.has(o.tool_name)&&typeof s.command=="string")return{kind:"shell",command:s.command,cwd:i,shell:o.tool_name==="PowerShell"?"powershell":"posix"};let a=t==="codex"&&o.tool_name==="exec"?ra(typeof o.tool_input=="string"?o.tool_input:s):[];return a.length?{kind:"script",toolName:o.tool_name,texts:a,cwd:i}:{kind:"tool",toolName:o.tool_name,cwd:i}}function ia(t,e){if(t==="cursor"){if(e.decision!=="deny")return"";let n=e.message??"Canary held this call.";return JSON.stringify({permission:"deny",user_message:n,agent_message:n})}return e.decision==="deny"?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message??"Canary held this call."}}):e.message?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e.message}}):""}wn();import{execFile as Pd}from"node:child_process";function sa(t,e){let n={...Object.fromEntries(Object.entries(process.env).filter(([r])=>!r.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(r))),GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"};return new Promise(r=>{Pd("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","status","--porcelain=v1","-z"],{cwd:t,env:n,signal:e,timeout:3e3,maxBuffer:16*1024*1024,encoding:"buffer"},(o,i)=>{if(o)return r([]);let s=i.toString("utf8").split("\0"),a=[];for(let l=0;l<s.length;l++){let c=s[l];c.length<4||(a.push(c.slice(3)),(c[0]==="R"||c[0]==="C")&&l++)}r(a)})})}Hr();import{homedir as Ld}from"node:os";import{basename as Md,isAbsolute as jd,resolve as Hd}from"node:path";var Fd=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),Ud=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,aa=t=>t.replace(/\\(.)/g,(e,n)=>n==="n"?`
|
|
144
|
-
`:n==="t"?" ":n);function da(t,e){for(let n of t)for(let r of n.matchAll(Ud)){let o=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(s=>aa(s[1]??s[2]??"")).join(" "):aa(r[1]??r[2]??r[3]??""),i=so(o,e);if(i)return i}return null}function fa(t,e){let n=!t.includes("__");if(!n&&!t.startsWith("mcp__"))return null;let r=Fd.get(n?t:t.slice(t.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:e}:null}function Dd(t){let e=[];for(let n=0;n<t.length;n++){if(t[n]==="\\"){n++;continue}let r=t[n]==="$"&&t[n+1]==="("?2:t[n]==="`"?1:0;if(!r)continue;let o=Pn(t,n+r,r===2?")":"`");e.push(o.tokens),n=o.end-1}return e}var Nn=!1;function Pn(t,e,n){let r=[],o=[],i="",s=!1,a=!1,l=!0,c=e,u=0,d=()=>{s&&r.push({word:i,quoted:a,bare:l}),i="",s=!1,a=!1,l=!0},h=f=>{d(),r.push({op:f})},p=(f,
|
|
145
|
-
`||(i+=
|
|
146
|
-
`;)c++;continue}if(f==="<"&&
|
|
144
|
+
`:n==="t"?" ":n);function da(t,e){for(let n of t)for(let r of n.matchAll(Ud)){let o=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(s=>aa(s[1]??s[2]??"")).join(" "):aa(r[1]??r[2]??r[3]??""),i=so(o,e);if(i)return i}return null}function fa(t,e){let n=!t.includes("__");if(!n&&!t.startsWith("mcp__"))return null;let r=Fd.get(n?t:t.slice(t.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:e}:null}function Dd(t){let e=[];for(let n=0;n<t.length;n++){if(t[n]==="\\"){n++;continue}let r=t[n]==="$"&&t[n+1]==="("?2:t[n]==="`"?1:0;if(!r)continue;let o=Pn(t,n+r,r===2?")":"`");e.push(o.tokens),n=o.end-1}return e}var Nn=!1;function Pn(t,e,n){let r=[],o=[],i="",s=!1,a=!1,l=!0,c=e,u=0,d=()=>{s&&r.push({word:i,quoted:a,bare:l}),i="",s=!1,a=!1,l=!0},h=f=>{d(),r.push({op:f})},p=(f,m)=>{let g=Pn(t,f,m);return r.push({sub:g.tokens}),i+="$()",s=!0,g.end};for(;c<t.length;){let f=t[c],m=t[c+1];if(n==="`"&&f==="`")return d(),{tokens:r,end:c+1};if(n===")"&&f===")"&&u===0)return d(),{tokens:r,end:c+1};if(f==="\\"&&!Nn){m===`
|
|
145
|
+
`||(i+=m??"",s=!0),c+=2;continue}if(f==="'"){s||(l=!1);let g=t.indexOf("'",c+1);i+=t.slice(c+1,g<0?void 0:g),s=!0,a=!0,c=g<0?t.length:g+1;continue}if(f==='"'){for(s||(l=!1),s=!0,a=!0,c++;c<t.length&&t[c]!=='"';)t[c]==="\\"&&!Nn&&c+1<t.length&&/[$`"\\\n]/.test(t[c+1])?(i+=t[c+1],c+=2):t[c]==="$"&&t[c+1]==="("?c=p(c+2,")"):t[c]==="`"?c=p(c+1,"`"):(i+=t[c],c++);c++;continue}if(f==="#"&&!s){for(;c<t.length&&t[c]!==`
|
|
146
|
+
`;)c++;continue}if(f==="<"&&m==="<"&&t[c+2]!=="<"){let g=/^<<(-?)[ \t]*(?:'([^']*)'|"([^"]*)"|\\?([^\s;&|<>()]+))/.exec(t.slice(c));if(g){d(),o.push({end:g[2]??g[3]??g[4]??"",stripTabs:g[1]==="-",literal:g[4]===void 0||g[0].includes("\\")}),c+=g[0].length;continue}}if(f===`
|
|
147
147
|
`){h(`
|
|
148
148
|
`),c++;for(let g of o.splice(0))for(;;){let w=t.indexOf(`
|
|
149
|
-
`,c),_=t.slice(c,w<0?void 0:w);if(c=w<0?t.length:w+1,(g.stripTabs?_.replace(/^\t+/,""):_)===g.end||w<0)break;if(!g.literal)for(let
|
|
149
|
+
`,c),_=t.slice(c,w<0?void 0:w);if(c=w<0?t.length:w+1,(g.stripTabs?_.replace(/^\t+/,""):_)===g.end||w<0)break;if(!g.literal)for(let y of Dd(_))r.push({sub:y})}continue}if(f===" "||f===" "||f==="\r"){d(),c++;continue}if(f===">"||f==="<"){let g=f===">";d(),c++;let w=!1;for(;c<t.length&&(t[c]===">"||t[c]==="&"||t[c]==="|");)t[c]==="&"&&(w=!0),c++;for(;c<t.length&&(t[c]===" "||t[c]===" ");)c++;let _=c;for(;c<t.length&&!/[\s;&|()<>`]/.test(t[c]);)c++;if(g&&!w){let y=t.slice(_,c);y&&r.push({write:y})}continue}if(f==="&"&&m===">"){d(),c++;continue}if((f==="&"||f==="|")&&m===f){h(f+f),c+=2;continue}if(f==="$"&&m==="("){c=p(c+2,")");continue}if(f==="`"){c=p(c+1,"`");continue}if(f==="("){u++,h(f),c++;continue}if(f===")"){u=Math.max(0,u-1),h(f),c++;continue}if(f===";"||f==="&"||f==="|"){h(f),c++;continue}if(/[0-9]/.test(f)&&!s&&/^[0-9]+[<>]/.test(t.slice(c))){c++;continue}i+=f,s=!0,c++}return d(),{tokens:r,end:t.length}}var Gd=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),Jd=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),ca=t=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(t),Ae=!1,Wd=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),la=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),Bd=new Set(["sh","bash","zsh","dash","ksh"]),ua=6,Vd=new Set(["-c","--exec-path","--namespace","--super-prefix","--config-env","--attr-source"]);function oo(t,e){if(e===null||/[$`*?[]/.test(t.word))return null;let n=t.bare&&(t.word==="~"||t.word.startsWith("~/"))?Ld()+t.word.slice(1):t.word;return t.bare&&n.startsWith("~")?null:jd(n)?n:Hd(e,n)}function qd(t,e){let n=e,r=0;for(;r<t.length;r++){let i=t[r].word;if(i==="-C"){n=t[r+1]?oo(t[r+1],n):null,r++;continue}if(i.startsWith("-C")&&i.length>2){n=oo({...t[r],word:i.slice(2)},n);continue}if(/^--(git-dir|work-tree)(=|$)/.test(i)){n=null,i.includes("=")||r++;continue}if(Vd.has(i)){r++;continue}if(!i.startsWith("-"))break}if(t[r]?.word!=="push")return null;let o=[];for(let{word:i}of t.slice(r+1)){if(i==="--")break;if(i==="--dry-run"||i==="--help"||i==="-h"||/^-[a-zA-Z]*n[a-zA-Z]*$/.test(i)||i==="--delete"||/^-[a-zA-Z]*d[a-zA-Z]*$/.test(i))return null;i.startsWith("-")||o.push(i)}return o.length>1&&o.slice(1).every(i=>i.startsWith(":"))?null:{dir:n}}function Yd(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n].word;if(r==="--help"||r==="-h"||r==="--dry-run")return!1;if(r==="-R"||r==="--repo"){n++;continue}r.startsWith("-")||e.push(r)}return e[0]==="pr"&&(e[1]==="create"||e[1]==="new")}function io(t,e,n){let r=e,o=[],i=!1,s=()=>{let a=o;o=[];let l=i;i=!1;let c=g=>(!g&&l&&(Ae=!0),g),u=0,d=(g,w)=>g.bare&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(g.word)||!g.quoted&&(Wd.has(g.word)||la.has(g.word)||!!w&&la.has(w.word)&&g.word.startsWith("-"));for(;u<a.length&&d(a[u],a[u-1]);)u++;let h=a[u];if(!h)return c(null);let p=Md(h.word.replace(/\\/g,"/")).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase(),f=a.slice(u+1);if(p==="cd"||p==="pushd")return r=f[0]&&!f[0].word.startsWith("-")?oo(f[0],r):null,c(null);let m=(g,w)=>({action:g,via:"shell",dir:w,...Ae?{editsFirst:!0}:{}});if(p==="git"){let g=qd(f,r);if(g)return m("push",g.dir);let w=f.find(y=>!y.word.startsWith("-"))?.word,_=(w==="checkout"||w==="switch")&&f.some(y=>/^-(b|B|c|C|-orphan)$/.test(y.word));return w&&Jd.has(w)&&!_&&(Ae=!0),c(null)}if(p==="gh")return Yd(f)?m("pr_create",r):c(null);if(p==="tee"?f.some(g=>!g.word.startsWith("-")&&!ca(g.word))&&(Ae=!0):(Gd.has(p)||(p==="sed"||p==="perl")&&f.some(g=>/^-[a-zA-Z]*i/.test(g.word)))&&(Ae=!0),(p==="npm"||p==="pnpm"||p==="yarn")&&f[0]?.word==="version"&&(Ae=!0),n<ua&&(Bd.has(p)||p==="eval")){let g=p==="eval"?0:f.findIndex(_=>/^-[a-zA-Z]*c[a-zA-Z]*$/.test(_.word))+1,w=p==="eval"?f.map(_=>_.word).join(" "):g>0?f[g]?.word:void 0;if(w)return c(io(Pn(w,0,null).tokens,r,n+1))}return c(null)};for(let a of t){if("word"in a){o.push(a);continue}if("write"in a){i=i||!ca(a.write);continue}if("sub"in a){let c=n<ua?io(a.sub,r,n+1):null;if(c)return c;continue}let l=s();if(l)return l}return s()}function so(t,e,n={}){if(!/\bpush\b/.test(t)&&!/\bpr\b/.test(t))return null;Nn=n.shell==="powershell",Ae=!1;try{return io(Pn(t,0,null).tokens,e,0)}finally{Nn=!1,Ae=!1}}var Xd=8e3,Qd=64*1024*1024;async function Zd(t,e={}){let n=t.kind==="shell"?so(t.command,t.cwd,{shell:t.shell}):t.kind==="script"?da(t.texts,t.cwd):fa(t.toolName,t.cwd);if(!n)return An({mode:"on",trigger:null});let r={mode:je(),trigger:n},o,i="",s,a=[],l=[async()=>{Ke({cwd:n.dir,agent:!0});let u=await Ut(n.dir,e.signal);u.ok?(o=u.context,e.seen&&(e.seen.context=o),r.context={ok:!0}):r.context=u},async()=>{try{let u=await mn(n.dir,{signal:e.signal});i=u.root,a=u.files,s={treeHash:u.treeHash,branch:tt(u.branch)},r.tree={ok:!0,...s}}catch(u){if(e.signal?.aborted)throw u;r.tree={ok:!1,detail:u instanceof ee?u.message:"the working tree could not be read"}}},async()=>{r.skip=zs(o.repository,s.treeHash)},async()=>{let u=e.deadline?e.deadline-Date.now()-500:Dt;r.lookup=await Rn(o,s,{timeoutMs:Math.max(250,Math.min(Dt,u)),signal:e.signal})},async()=>{let u=r.lookup?.ok?r.lookup.newestRun:void 0;r.since=u?.treeHash&&o?is(o.repository,u.treeHash,a):null},async()=>{r.leftOut=await sa(i,e.signal)}],c=null;for(let u of l){if(c=An(r),c)break;await u()}return c??=An(r)??{decision:"allow",cause:"crash"},c.decision==="deny"&&o&&s&&Qi(o.repository,s.treeHash),c}async function ef(t){let e=[],n=0;for await(let r of t){let o=typeof r=="string"?Buffer.from(r):r;if(n+=o.length,n>Qd)throw new Error("event too large");e.push(o)}return JSON.parse(Buffer.concat(e).toString("utf8").replace(/^\uFEFF/,""))}async function tf(t,e){let n=e.ceilingMs??Xd;Uo(250);let r=new AbortController,o,i=new Promise(u=>{o=setTimeout(()=>{r.abort(),u({decision:"allow",cause:"ceiling"})},n)}),s={},a=(async()=>{let u=await ef(e.stdin);try{zd(pa(ne(),"hook-debug"))&&Kd(pa(ne(),"hook-events.log"),`${new Date().toISOString()} ${t} ${JSON.stringify(u)}
|
|
150
150
|
`)}catch{}let d=oa(t,u);return d?Zd(d,{signal:r.signal,deadline:Date.now()+n,seen:s}):{decision:"allow",cause:"not_a_trigger"}})().catch(()=>({decision:"allow",cause:r.signal.aborted?"ceiling":"crash"})),l=await Promise.race([a,i]);clearTimeout(o);let c=ia(t,l);return c&&await e.write(c),l.cause!=="not_a_trigger"&&e.note(`canary hook: ${l.decision} (${l.cause})`),await zi(l,s.context),l}function ha(t){t.command("hook <harness>",{hidden:!0}).description("check an agent's push or pull request before it happens (called by the agent harness, not by people)").action(async e=>{if(na.includes(e)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await tf(e,{stdin:process.stdin,ceilingMs:n,note:r=>process.stderr.write(r+`
|
|
151
151
|
`),write:r=>new Promise(o=>process.stdout.write(r+`
|
|
152
|
-
`,()=>o()))})}process.exit(0)})}B();j();function ga(t){t.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async e=>{let n=e.json===!0,r=H();if(r)try{await v("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}Vo();let o=!!process.env.CANARY_TOKEN;n?console.log(JSON.stringify({ok:!0,...o?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),o&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}B();j();rt();B();rt();var nf={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"},rf=15e3;function of(t){return t&&nf[t]||"Other"}var sf=t=>{let e=t?.finding?.nextActionCodeRef??t?.codeRefs?.[0]??t?.checkReadback?.codeRefs?.[0]??null;return e?{file:e.file,line:e.startLine??null}:null},af=t=>(Array.isArray(t?.evidence)?t.evidence:[]).filter(e=>e&&e.media&&typeof e.media.url=="string").map(e=>({kind:b(e.modality)||"evidence",caption:b(e.caption),url:e.media.url,expiresAt:e.media.expiresAt??null}));function cf(t,e,n){if(t.status!=="completed"||ge(t.materiality)===null)return null;let r=e??null,o=r?.isStatic===!0?"source":"runtime",i=t.result==="pass"?"passed":t.result==="fail"?"failed":"could_not_run",s=b(r?.assertion)||null;return{checkRunId:t.checkRunId,checkUrl:`${n}/checks/${t.checkRunId}`,scenarioId:t.stageBCheckId??t.checkRunId,category:of(r?.lane),title:b(t.title),proof:o,status:i,whatWasTried:o==="source"?b(r?.finding?.whatWasTested)||null:b(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:s||b(r?.finding?.whatWasTested)||null,observed:b(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:s,location:sf(r),evidence:af(r),fix:o==="source"&&b(r?.finding?.reproduce)||null,reason:i==="could_not_run"&&(b(r?.verdict?.reasonOneLiner)||
|
|
152
|
+
`,()=>o()))})}process.exit(0)})}B();j();function ga(t){t.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async e=>{let n=e.json===!0,r=H();if(r)try{await v("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}Vo();let o=!!process.env.CANARY_TOKEN;n?console.log(JSON.stringify({ok:!0,...o?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),o&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}B();j();rt();B();rt();var nf={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"},rf=15e3;function of(t){return t&&nf[t]||"Other"}var sf=t=>{let e=t?.finding?.nextActionCodeRef??t?.codeRefs?.[0]??t?.checkReadback?.codeRefs?.[0]??null;return e?{file:e.file,line:e.startLine??null}:null},af=t=>(Array.isArray(t?.evidence)?t.evidence:[]).filter(e=>e&&e.media&&typeof e.media.url=="string").map(e=>({kind:b(e.modality)||"evidence",caption:b(e.caption),url:e.media.url,expiresAt:e.media.expiresAt??null}));function cf(t,e,n){if(t.status!=="completed"||ge(t.materiality)===null)return null;let r=e??null,o=r?.isStatic===!0?"source":"runtime",i=t.result==="pass"?"passed":t.result==="fail"?"failed":"could_not_run",s=b(r?.assertion)||null;return{checkRunId:t.checkRunId,checkUrl:`${n}/checks/${t.checkRunId}`,scenarioId:t.stageBCheckId??t.checkRunId,category:of(r?.lane),title:b(t.title),proof:o,status:i,whatWasTried:o==="source"?b(r?.finding?.whatWasTested)||null:b(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:s||b(r?.finding?.whatWasTested)||null,observed:b(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:s,location:sf(r),evidence:af(r),fix:o==="source"&&b(r?.finding?.reproduce)||null,reason:i==="could_not_run"&&(b(r?.verdict?.reasonOneLiner)||Tt[t.blockedReason??""])||null}}async function ma(t,e,n){let r=new Map,o=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;for(let i of e)if(!(i.status!=="completed"||r.has(i.checkRunId)||!o.test(i.checkRunId)))try{r.set(i.checkRunId,await v(`/api/v1/red-team/runs/${t}/checks/${i.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(rf),...n.baseUrl?{baseUrl:n.baseUrl}:{}}))}catch{r.set(i.checkRunId,null)}return r}function ya(t,e,n){let r=t.stageC.checks.map(o=>cf(o,e.get(o.checkRunId)??null,n.runUrl)).filter(o=>o!==null);return{runId:t.runId,runUrl:n.runUrl,repo:n.repo,treeHash:t.target.treeHash??"",files:n.files,reverifySourceRunId:t.reverifySourceRunId??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null,checks:r,passed:r.filter(o=>o.status==="passed").length,failed:r.filter(o=>o.status==="failed").length,couldNotRun:r.filter(o=>o.status==="could_not_run").length,errored:t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns}}var Sa=new Set(["completed","failed","cancelled"]);function wa(t){return Sa.has(t.status)?null:t.status==="queued"?"queued":t.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function ba(t){return t.status==="failed"||t.status==="cancelled"?"errored":t.status!=="completed"?t.status==="running"?"running":"pending":t.result==="pass"?"passed":t.result==="fail"?"failed":"could_not_run"}async function ao(t,e,n,r,o={}){let i=H();if(!i)return $(t,"not_logged_in","Not logged in","run `canary login` first",3),null;if(e.some(s=>!De.test(s)))return $(t,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await v(n,{token:i,...r?{baseUrl:r}:{},...o})}catch(s){if(s instanceof R){if(s.status===404)return $(t,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let a=!re(s)&&s.status>=400&&s.status<500,l=s.fix??(s.status===401?"run `canary login`":a?void 0:"run the command again in a minute");return $(t,"api_error",s.message,l,a?3:2,{httpStatus:s.status}),null}throw s}}var ka=t=>{if(!t?.file)return"";let e=t.startLine?`:${t.startLine}`:"",n=t.startLine&&t.endLine&&t.endLine>t.startLine?`-${t.endLine}`:"";return`${b(t.file)}${e}${n}`};async function lf(t,e,n){let r=await ao(e,[t],`/api/v1/red-team/runs/${t}`,n);if(!r)return;let o=r.run,i=r.repository?.fullName??"";if(e){let c=o.stageC.checks.filter(p=>ge(p.materiality)!==null).map(p=>({checkRunId:p.checkRunId,scenarioId:p.stageBCheckId??p.checkRunId,title:b(p.title),status:ba(p)})),u={runId:o.runId,status:o.status,progress:wa(o),treeHash:o.target.treeHash??"",repo:i,reverifySourceRunId:o.reverifySourceRunId??null,startedAt:o.startedAt??null,completedAt:o.completedAt??null,failureMessage:o.failure?.publicMessage??null,checks:c,passed:c.filter(p=>p.status==="passed").length,failed:c.filter(p=>p.status==="failed").length,couldNotRun:c.filter(p=>p.status==="could_not_run").length,errored:o.stageC.failedCheckRuns+o.stageC.cancelledCheckRuns},d={},h=H();if(Sa.has(o.status)&&h){let p=await ma(t,o.stageC.checks,{token:h,...n?{baseUrl:n}:{}});d=ya(o,p,{runUrl:`${be().replace(/\/+$/,"")}/runs/${t}`,repo:i,files:null})}return void console.log(JSON.stringify({ok:!0,...u,...d}))}let s=wa(o),a=[`run ${b(o.runId)} \xB7 ${b(o.status)}${s?` \xB7 ${s}`:""}${o.target.treeHash?` \xB7 tree ${b(o.target.treeHash).slice(0,12)}`:""}`];o.failure?.publicMessage&&a.push(` ${b(o.failure.publicMessage)}`);let l=o.stageC;a.push(`checks ${l.checks.length} \xB7 ${l.results.pass} passed \xB7 ${l.results.fail} failed \xB7 ${l.results.blocked} could not verify \xB7 ${l.failedCheckRuns+l.cancelledCheckRuns} errored`);for(let c of l.checks){let u=ba(c),d=u==="could_not_run"?"could not verify":u,h=c.result==="blocked"?Tt[c.blockedReason??""]:void 0;a.push(` ${ge(c.materiality)??"P3"} ${d.padEnd(16)} ${b(c.title)} ${b(c.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
|
|
153
153
|
`))}async function uf(t,e,n,r){let o=await ao(n,[t,e],`/api/v1/red-team/runs/${t}/checks/${e}/finding`,r);if(!o)return;if(n)return void console.log(JSON.stringify({ok:!0,runId:t,checkRunId:e,...o}));let i=[];i.push(b(o.finding?.headline)||"(no finding written for this check yet)"),o.verdict&&i.push(`verdict: ${b(o.verdict.result)}${o.verdict.reasonOneLiner?` \u2014 ${b(o.verdict.reasonOneLiner)}`:""}${o.isStatic?" (reasoned from the code, not run)":""}`),o.assertion&&i.push(`assertion: ${b(o.assertion)}`),o.observable&&i.push(`observable: ${b(o.observable)}`),o.checkReadback?.whyThisCheck&&i.push(`why this check: ${b(o.checkReadback.whyThisCheck)}`),o.finding?.whatWasTested&&i.push(`tested: ${b(o.finding.whatWasTested)}`),o.finding?.reproduce&&i.push(`reproduce: ${b(o.finding.reproduce)}`),o.finding?.nextActionCodeRef&&i.push(`\u2192 ${ka(o.finding.nextActionCodeRef)}`);for(let s of o.codeRefs??[])i.push(` ref ${ka(s)}${s.reason?` \u2014 ${b(s.reason)}`:""}`);for(let s of o.evidence??[])i.push(` evidence ${b(s.modality)}: ${b(s.caption)}${s.media?` ${b(s.media.url)}`:s.failureReason?` (${b(s.failureReason)})`:""}`);for(let s of o.verdict?.limitations??[])i.push(` limitation: ${b(s)}`);o.network?.failures?.length&&i.push(` network failures: ${o.network.failures.length}`),console.log(i.join(`
|
|
154
|
-
`))}async function df(t,e,n,r,o,i){if(await ao(o,[t,e],`/api/v1/red-team/runs/${t}/checks/${e}/report`,i,{method:"POST",body:{reported:n,...r?{note:r}:{}}})){if(o)return void console.log(JSON.stringify({ok:!0,runId:t,checkRunId:e,reported:n}));console.log(`reported ${n}${r?`: ${b(r)}`:""}`)}}async function ff(t,e,n){let r=H();if(!r)return $(e,"not_logged_in","Not logged in","run `canary login` first",3);if(!De.test(t))return $(e,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let o;try{o=await Vr(t,r,{...n?{baseUrl:n}:{},onProgress:s=>console.error(` ${s}`)})}catch(s){if(s instanceof he)return $(e,s.code,s.message,`run \`canary run wait ${t}\` again to keep waiting`,2,{runId:t});if(s instanceof R){if(s.status===404)return $(e,"not_found","no such run in your workspace",void 0,3,{httpStatus:404});let a=!re(s)&&s.status>=400&&s.status<500;return $(e,"api_error",s.message,s.fix??(s.status===401?"run `canary login`":a?void 0:`run \`canary run wait ${t}\` again`),a?3:2,{runId:t,httpStatus:s.status})}throw s}let i=qr(o.run,o.run.target?.treeHash??"",o.findings,o.run.reverify);console.log(e?JSON.stringify(i):Yr(i)),process.exitCode=i.exitCode}function _a(t){t.command("run").argument("[runId]").description("Show a verify run: status and every check with its verdict").option("--json","print one JSON document: status, progress, every check with its verdict, and the report fields once the run has finished").action(async(n,r)=>{try{if(!n)return $(r.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await lf(n,r.json===!0)}catch(o){$(r.json===!0,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}}).command("wait <runId>").description("Wait for a run to finish, then print its findings (progress on stderr)").option("--json","print one JSON document").action(async(n,r,o)=>{let i=o.optsWithGlobals().json===!0;try{await ff(n,i)}catch(s){$(i,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}}),t.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(n,r,o)=>{try{let i=[o.fixed?"fixed":null,o.disputed!==void 0?"disputed":null,o.skipped!==void 0?"skipped":null].filter(Boolean);if(i.length>1)return $(o.json===!0,"bad_report","report exactly one of --fixed, --disputed, --skipped",void 0,3);if(i.length===1){let s=(i[0]==="disputed"?o.disputed:i[0]==="skipped"?o.skipped:void 0)?.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").trim();return s!==void 0&&!s?$(o.json===!0,"bad_report",`--${i[0]} needs a reason`,void 0,3):await df(n,r,i[0],s,o.json===!0)}await uf(n,r,o.json===!0)}catch(i){$(o.json===!0,"internal_error",i instanceof Error?i.message:String(i),void 0,2)}})}import{readFileSync as kf,unlinkSync as Sf,writeFileSync as _f}from"node:fs";import{basename as xf,join as vf}from"node:path";import{setTimeout as Cf}from"node:timers/promises";Ge();B();Ye();j();$e();import{emitKeypressEvents as pf}from"node:readline";var hf=36,gf=12,xa=64*1024,co=new Intl.Segmenter(void 0,{granularity:"grapheme"}),mf={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},yf={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function Ln(t){let e=Math.max(0,Math.floor(t));return e<60?`${e}s`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`}function wf(t,e){let n="";for(let{segment:r}of[...co.segment(P(t))].reverse()){if(
|
|
154
|
+
`))}async function df(t,e,n,r,o,i){if(await ao(o,[t,e],`/api/v1/red-team/runs/${t}/checks/${e}/report`,i,{method:"POST",body:{reported:n,...r?{note:r}:{}}})){if(o)return void console.log(JSON.stringify({ok:!0,runId:t,checkRunId:e,reported:n}));console.log(`reported ${n}${r?`: ${b(r)}`:""}`)}}async function ff(t,e,n){let r=H();if(!r)return $(e,"not_logged_in","Not logged in","run `canary login` first",3);if(!De.test(t))return $(e,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let o;try{o=await Vr(t,r,{...n?{baseUrl:n}:{},onProgress:s=>console.error(` ${s}`)})}catch(s){if(s instanceof he)return $(e,s.code,s.message,`run \`canary run wait ${t}\` again to keep waiting`,2,{runId:t});if(s instanceof R){if(s.status===404)return $(e,"not_found","no such run in your workspace",void 0,3,{httpStatus:404});let a=!re(s)&&s.status>=400&&s.status<500;return $(e,"api_error",s.message,s.fix??(s.status===401?"run `canary login`":a?void 0:`run \`canary run wait ${t}\` again`),a?3:2,{runId:t,httpStatus:s.status})}throw s}let i=qr(o.run,o.run.target?.treeHash??"",o.findings,o.run.reverify);console.log(e?JSON.stringify(i):Yr(i)),process.exitCode=i.exitCode}function _a(t){t.command("run").argument("[runId]").description("Show a verify run: status and every check with its verdict").option("--json","print one JSON document: status, progress, every check with its verdict, and the report fields once the run has finished").action(async(n,r)=>{try{if(!n)return $(r.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await lf(n,r.json===!0)}catch(o){$(r.json===!0,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}}).command("wait <runId>").description("Wait for a run to finish, then print its findings (progress on stderr)").option("--json","print one JSON document").action(async(n,r,o)=>{let i=o.optsWithGlobals().json===!0;try{await ff(n,i)}catch(s){$(i,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}}),t.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(n,r,o)=>{try{let i=[o.fixed?"fixed":null,o.disputed!==void 0?"disputed":null,o.skipped!==void 0?"skipped":null].filter(Boolean);if(i.length>1)return $(o.json===!0,"bad_report","report exactly one of --fixed, --disputed, --skipped",void 0,3);if(i.length===1){let s=(i[0]==="disputed"?o.disputed:i[0]==="skipped"?o.skipped:void 0)?.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").trim();return s!==void 0&&!s?$(o.json===!0,"bad_report",`--${i[0]} needs a reason`,void 0,3):await df(n,r,i[0],s,o.json===!0)}await uf(n,r,o.json===!0)}catch(i){$(o.json===!0,"internal_error",i instanceof Error?i.message:String(i),void 0,2)}})}import{readFileSync as kf,unlinkSync as Sf,writeFileSync as _f}from"node:fs";import{basename as xf,join as vf}from"node:path";import{setTimeout as Cf}from"node:timers/promises";Ge();B();Ye();j();$e();import{emitKeypressEvents as pf}from"node:readline";var hf=36,gf=12,xa=64*1024,co=new Intl.Segmenter(void 0,{granularity:"grapheme"}),mf={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},yf={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function Ln(t){let e=Math.max(0,Math.floor(t));return e<60?`${e}s`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`}function wf(t,e){let n="";for(let{segment:r}of[...co.segment(P(t))].reverse()){if(Lt(r+n)>e)break;n=r+n}return n}function va(t,e,n){let r=t.question,o=Math.max(1,e-5),i=(l,c="text")=>` ${Mt(P(l),c,n)}`,s=0;if(r.secret){for(let l of co.segment(t.input??""))if(++s===24)break}let a=r.secret?"\u2022".repeat(s):wf(t.input??"",Math.max(1,o-2));return[i("CANARY \xB7 SETUP","gold"),i(`${t.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${Ln(t.seconds)}`),i(`CLI workspace ${t.workspace}`,"muted"),"",i(r.key,"gold"),...Oe(r.prompt,o).map(l=>i(l)),i(t.inputActive?`\u203A ${a||(r.secret?"(hidden)":"")}`:t.inputSubmitted?"Value captured locally.":"Input deferred","muted"),i(t.inputNotice??(r.secret?"Your value stays hidden.":""),"muted"),i(t.inputActive?"Enter submit \xB7 Esc/Ctrl+C later":t.inputSubmitted?"Waiting for verification to continue.":"Run canary setup to resume.","muted")]}function bf(t,e,n,r){let o=Math.max(1,e-5),i=Math.max(1,n-2),s=t.outcome?yf[t.outcome.status]:t.question?"Your input is needed":mf[t.status],a=t.outcome?.status==="green"?"green":"gold",l=(d,h="text")=>Mt(P(d),h,r),c;if(i<=3)c=[l(s,a),l(`Elapsed ${Ln(t.seconds)}`,"muted")].slice(0,i);else if(t.question&&!t.outcome)c=va(t,e,r);else{let d=t.seconds%1.6,h=!t.outcome&&["pending","running"].includes(t.status)&&d<1.4?Math.sin(d/1.4*Math.PI*2)*Math.sin(d/1.4*Math.PI):0,p=it[Math.max(0,Math.min(16,Math.round(h*10)+8))];if(e>=76&&n>=23){let f={1:l("CANARY \xB7 SETUP","gold"),3:l(s,a),5:l(`Elapsed ${Ln(t.seconds)}`,"muted")};c=["",...p.map((m,g)=>` ${l(m,a)} ${f[g]??""}`)]}else c=[` ${l("CANARY \xB7 SETUP","gold")}`,` ${l(s,a)}`,` ${l(`Elapsed ${Ln(t.seconds)}`,"muted")}`];c.push("",` ${l(`Repository ${t.repository}`)}`,` ${l(`CLI workspace ${t.workspace}`)}`),t.detail&&!t.outcome&&c.push(...Oe(t.detail,o).map(f=>` ${l(f,"muted")}`)),t.outcome||c.push("",` ${l("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(c.length>i?[...c.slice(0,Math.max(0,i-2)),...c.slice(-2)]:c).map(d=>$n(d,Math.max(1,e-1)))}function Ca(t){if(t.json||!t.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,n=process.stdin,r=!process.env.NO_COLOR,o=ot(e),i=performance.now(),s={...t,status:"submitting",seconds:0},a=!1,l=!1,c,u=!1,d,h,p=()=>({columns:e.columns||80,rows:e.rows||24}),f=O=>{try{e.write(O)}catch{}},m=()=>f(`${U}0m${U}?25h`);function g(){if(a||u)return;s.seconds=(performance.now()-i)/1e3;let{columns:O,rows:M}=p();try{o.render(bf(s,O,M,r))}catch{x()}}function w(){let{columns:O,rows:M}=p();return n.isTTY&&O>=hf&&M>=gf&&va(s,O,!1).length<=M-2}function _(){let O=s.question;if(!O)return;u=!0;try{o.render([])}catch{}let M=Math.max(1,p().columns-3);f(`
|
|
155
155
|
Input needed: ${P(O.key)}
|
|
156
156
|
${Oe(O.prompt,M).join(`
|
|
157
157
|
`)}
|
|
158
158
|
|
|
159
159
|
Answer with: canary setup --answer '<value>'
|
|
160
|
-
`)}function
|
|
160
|
+
`)}function y(){h&&!w()?h.settle(null,!0):g()}function k(){!a||h||l||(l=!0,process.off("SIGINT",C),process.off("SIGTERM",D),process.off("exit",x),m(),c!==void 0&&(f(`
|
|
161
161
|
Stopped watching. Run canary setup to resume verification.
|
|
162
|
-
`),process.exit(c)))}function x(){a||(a=!0,clearInterval(d),e.off("resize",
|
|
163
|
-
`)),ye="";else if(le){let Be=(G||A.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(A.sequence??"").includes("\x1B")||(ye.length+Be.length<=xa?ye+=Be:(I=!0,s.inputNotice="Too long. Ctrl+U clears input."));return}else if(A.ctrl&&A.name==="u")Q="",I=!1,s.inputNotice=void 0;else if(A.name==="backspace")Q=[...co.segment(Q)].slice(0,-1).map(Ba=>Ba.segment).join("");else if(A.name==="return"||A.name==="enter"){if(!Q.trim())s.inputNotice="Enter a value, or Esc to answer later.";else if(!I){Vt(Q);return}}else!A.ctrl&&!A.meta&&G&&go(G.replace(/[\x00-\x1f\x7f-\x9f]/g,""));s.input=Q,g()}catch{Je()}}h={settle:Vt};try{if(n.prependListener("data",po),pf(n),n.on("keypress",mo),n.on("data",ho),n.once("end",We),n.once("error",We),n.once("close",We),M?.addEventListener("abort",Je,{once:!0}),M?.aborted){Je();return}n.setRawMode(!0),n.resume(),f(`${U}?2004h${U}?25l`),g()}catch{Je()}}):(s.inputActive=!1,_(),null))}return e.on("resize",
|
|
162
|
+
`),process.exit(c)))}function x(){a||(a=!0,clearInterval(d),e.off("resize",y),h?.settle(null),k())}function E(O){c=O,x(),k()}function C(){h?h.settle(null):E(130)}function D(){E(143)}async function xe(O,M){return a||h||M?.aborted?null:(s.question={...O},s.input="",s.inputActive=!0,s.inputSubmitted=!1,s.inputNotice=void 0,u=!1,w()?new Promise(me=>{let ut=n.isRaw,Bt=n.readableFlowing===!0,Q="",ye="",le=!1,ue=!1,Y="",de=!1,Te=!1,I=!1,ie=!1,K;function Vt(G,A=!1){ie||(K={answer:K&&G!==null?K.answer:G,showStatic:A||K?.showStatic||!1},Te||=!!Y&&!ue,Q=ye="",s.input="",(le||ue||Y||Te)&&(s.inputNotice="Finishing clipboard input.",g()),Un())}function Un(){if(ie||!K||de||le||ue||Y||Te)return;let{answer:G,showStatic:A}=K;ie=!0,n.off("keypress",mo),n.off("data",po),n.off("data",ho),n.off("end",We),n.off("error",We),n.off("close",We),M?.removeEventListener("abort",Je);try{n.setRawMode(ut)}catch{}Bt||n.pause(),f(`${U}?2004l`),Q="",ye="",s.input="",s.inputActive=!1,s.inputSubmitted=G!==null,s.inputNotice=G===null?"You can provide this value later.":"Input received locally.",h=void 0,A&&!a?_():g(),m(),k(),me(G)}function Je(){Vt(null)}function We(){le=ue=de=Te=!1,Y="",Vt(null)}function po(G){de=!0;for(let A of typeof G=="string"?G:G.toString("utf8")){let Be=ue?`${U}201~`:`${U}200~`;Y=A===Be[Y.length]?Y+A:A==="\x1B"?A:"",Y===Be&&(ue=!ue,Y="")}}function ho(){de=!1,Un()}function go(G){Q.length+G.length>xa?(I=!0,s.inputNotice="Too long. Ctrl+U clears input."):(Q+=G,I||(s.inputNotice=void 0))}function mo(G,A){if(!(ie||!A))try{if(!de&&A.name==="escape"&&(Y=""),!Y&&A.sequence?.startsWith("\x1B")&&(Te=!1),K){A.name==="paste-start"?le=!0:A.name==="paste-end"&&(le=!1),Un();return}if(A.name==="paste-start"){le=!0,ye="";return}if(A.name==="escape"||A.ctrl&&["c","d"].includes(A.name??"")){Je();return}if(A.name==="paste-end")le=!1,go(ye.replace(/\r\n?/g,`
|
|
163
|
+
`)),ye="";else if(le){let Be=(G||A.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(A.sequence??"").includes("\x1B")||(ye.length+Be.length<=xa?ye+=Be:(I=!0,s.inputNotice="Too long. Ctrl+U clears input."));return}else if(A.ctrl&&A.name==="u")Q="",I=!1,s.inputNotice=void 0;else if(A.name==="backspace")Q=[...co.segment(Q)].slice(0,-1).map(Ba=>Ba.segment).join("");else if(A.name==="return"||A.name==="enter"){if(!Q.trim())s.inputNotice="Enter a value, or Esc to answer later.";else if(!I){Vt(Q);return}}else!A.ctrl&&!A.meta&&G&&go(G.replace(/[\x00-\x1f\x7f-\x9f]/g,""));s.input=Q,g()}catch{Je()}}h={settle:Vt};try{if(n.prependListener("data",po),pf(n),n.on("keypress",mo),n.on("data",ho),n.once("end",We),n.once("error",We),n.once("close",We),M?.addEventListener("abort",Je,{once:!0}),M?.aborted){Je();return}n.setRawMode(!0),n.resume(),f(`${U}?2004h${U}?25l`),g()}catch{Je()}}):(s.inputActive=!1,_(),null))}return e.on("resize",y),process.on("SIGINT",C),process.on("SIGTERM",D),process.once("exit",x),d=setInterval(g,80),d.unref(),f(`${U}?25l`),g(),{update(O,M){a||(s.status=O,s.detail=M,h||(s.question=void 0,s.input=void 0,u=!1),f(`${U}?25l`),g())},warn(O){if(!a)try{o.render([])}catch{x()}f(`
|
|
164
164
|
Warning: ${O.split(/\r?\n/).map(P).join(`
|
|
165
165
|
`)}
|
|
166
166
|
|
|
167
167
|
`),g()},ask:xe,finish(O){if(a)return;h?.settle(null),s.question=void 0,s.outcome=O,u=!1,g(),x();let M=[O.message,...O.updatedFiles?.length?[`Updated locally: ${O.updatedFiles.join(", ")}`]:[],...O.warning?[`Warning: ${O.warning}`]:[],...O.next?[`Next: ${O.next}`]:[]].filter(me=>!!me);M.length&&f(`
|
|
168
168
|
${M.flatMap(me=>me.split(/\r?\n/).map(P)).join(`
|
|
169
169
|
`)}
|
|
170
|
-
`)},stop:x}}Cr();un();pe();nt();Gr();Ur();var
|
|
171
|
-
`);function jn(t){try{Sf(lo(t))}catch{}}var
|
|
170
|
+
`)},stop:x}}Cr();un();pe();nt();Gr();Ur();var st=3e3,Mn=2,$f=9e4,$a=new Set(["pending","running","needs_input","green","red","error","interrupted"]);function V(t,e){for(let n of[...t.secrets].sort((r,o)=>o.length-r.length))n&&(e=e.split(n).join("[redacted]"));return e}var lo=t=>vf(t,".canary","verify-job.json");function Gt(t){try{let e=JSON.parse(kf(lo(t),"utf8"));if(!e||typeof e.jobId!="string"||!e.jobId)throw new Error("invalid job ID");if(e.sourceUploadId!==void 0&&(typeof e.sourceUploadId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.sourceUploadId)))throw new Error("invalid source upload ID");if(e.scope&&(!e.source||!Sn(e.source)||typeof e.recipeHash!="string"||typeof e.scope.apiUrl!="string"||![e.scope.userId,e.scope.workspaceId,e.scope.repositoryId].every(r=>typeof r=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(r))))throw new Error("invalid scope");let n=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}:{},...n?{workspace:n}:{},...e.scope?{scope:e.scope}:{},...e.source?{source:e.source}:{},...e.sourceUploadId?{sourceUploadId:e.sourceUploadId}:{}}}catch(e){if(e.code==="ENOENT")return null;throw new Z("invalid_setup_receipt","The saved setup job in .canary/verify-job.json is unreadable, so no new job was started.","Fix or remove .canary/verify-job.json, then run canary setup again.")}}function If(t){return Gt(t)?.jobId??null}var Ia=(t,e)=>_f(lo(t),JSON.stringify(e)+`
|
|
171
|
+
`);function jn(t){try{Sf(lo(t))}catch{}}var at=(t,e)=>Cf(t,void 0,{signal:e});function Rf(t){let e=t?.setup?.services;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"?n.name:void 0).filter(n=>typeof n=="string"):[]}function Of(t,e){let n,r;try{n=Re(t),yt(t),r=kt(t).name}catch(d){if(d instanceof Z||d instanceof N){e?console.log(JSON.stringify({ok:!1,error:d.code,message:d.message,..."fix"in d&&d.fix?{fix:d.fix}:{}})):console.error(`\u2717 ${d.message}${"fix"in d&&d.fix?`
|
|
172
172
|
Fix: ${d.fix}`:""}`),process.exitCode=1;return}throw d}let o=r??null,i=n.setupSh.trim().split(`
|
|
173
|
-
`).length,s=Rf(n.runJson),a=[...new Set([...n.envManifest.map(d=>d.name),...Object.keys(n.envValues)])],l=n.envManifest.filter(d=>d.neededAt==="boot").map(d=>d.name),{missing:c}=xr(n.envManifest,n.envValues),u=c.length===0;e?console.log(JSON.stringify({ok:u,repo:o,recipe:{setupShLines:i,services:s,envKeys:a,bootRequired:l,missing:c}})):(console.log(`Repo ${o??"(local repository)"}`),console.log(`Recipe .canary/ \xB7 setup.sh (${i} lines) \xB7 run.json (${s.length} service${s.length===1?"":"s"}${s.length?": "+s.join(", "):""})`),console.log(`Env ${a.length} key${a.length===1?"":"s"} \xB7 ${l.length} boot-required \xB7 ${c.length?`MISSING: ${c.join(", ")}`:"all present"}`),u?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${c.join(", ")} (boot-required) ${c.length===1?"has":"have"} no value.`)),u||(process.exitCode=1)}async function Ra(t,e,n,r,o={}){if(e.status==="green"){let i=Gt(t),s=i?.workspace,a=o.recipeChanged??!1;if(i?.recipeHash)try{a||=He(Re(t))!==i.recipeHash}catch{a=!0}let l=!1;if(i?.source){let d=(p,f)=>p.sha256===f.sha256&&p.treeHash===f.treeHash&&p.baseTreeHash===f.baseTreeHash&&p.baseSha===f.baseSha&&p.provenance.baselineMode===f.provenance.baselineMode&&(p.provenance.baseRef??null)===(f.provenance.baseRef??null);if(e.approved?.source&&!d(e.approved.source,i.source))throw new Error("The approved source does not match the source this job was submitted with. Run canary setup again to verify the current files.");let h;try{h=await
|
|
173
|
+
`).length,s=Rf(n.runJson),a=[...new Set([...n.envManifest.map(d=>d.name),...Object.keys(n.envValues)])],l=n.envManifest.filter(d=>d.neededAt==="boot").map(d=>d.name),{missing:c}=xr(n.envManifest,n.envValues),u=c.length===0;e?console.log(JSON.stringify({ok:u,repo:o,recipe:{setupShLines:i,services:s,envKeys:a,bootRequired:l,missing:c}})):(console.log(`Repo ${o??"(local repository)"}`),console.log(`Recipe .canary/ \xB7 setup.sh (${i} lines) \xB7 run.json (${s.length} service${s.length===1?"":"s"}${s.length?": "+s.join(", "):""})`),console.log(`Env ${a.length} key${a.length===1?"":"s"} \xB7 ${l.length} boot-required \xB7 ${c.length?`MISSING: ${c.join(", ")}`:"all present"}`),u?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${c.join(", ")} (boot-required) ${c.length===1?"has":"have"} no value.`)),u||(process.exitCode=1)}async function Ra(t,e,n,r,o={}){if(e.status==="green"){let i=Gt(t),s=i?.workspace,a=o.recipeChanged??!1;if(i?.recipeHash)try{a||=He(Re(t))!==i.recipeHash}catch{a=!0}let l=!1;if(i?.source){let d=(p,f)=>p.sha256===f.sha256&&p.treeHash===f.treeHash&&p.baseTreeHash===f.baseTreeHash&&p.baseSha===f.baseSha&&p.provenance.baselineMode===f.provenance.baselineMode&&(p.provenance.baseRef??null)===(f.provenance.baseRef??null);if(e.approved?.source&&!d(e.approved.source,i.source))throw new Error("The approved source does not match the source this job was submitted with. Run canary setup again to verify the current files.");let h;try{h=await Rt(t,{baseRef:i.source.provenance.baseRef??void 0}),l=h.manifest.treeHash!==i.source.treeHash||h.manifest.baseTreeHash!==i.source.baseTreeHash||h.manifest.provenance.baselineMode!==i.source.provenance.baselineMode||(h.manifest.provenance.baseRef??null)!==(i.source.provenance.baseRef??null)}catch{l=!0}finally{await h?.dispose()}}if(i?.recipeHash)try{a||=He(Re(t))!==i.recipeHash}catch{a=!0}let c=o.writeBack!==!1&&!a&&!l;if(a||l){let d="This result is for the files as they were when submitted. They changed since, so the approved recipe was not written over your files. Run canary setup again to verify the current files.";r.warnings.push(d),!n&&!r.display&&console.error(`! ${d}`)}jn(t);let u=[];if(e.approved?.healed&&c)try{u=wi(t,e.approved)}catch(d){let h=V(r,`Could not update .canary/ with the approved changes: ${d instanceof Error?d.message:String(d)}`);r.warnings.push(h),r.display||console.error(`! ${h}`)}return n?console.log(JSON.stringify({ok:!0,status:"green",jobId:e.jobId,...s?{workspace:s}:{},...a?{recipeChanged:!0}:{},...l?{sourceChanged:!0}:{},...i?.source?{source:i.source,repositoryId:i.scope?.repositoryId}:{},...e.approved?{approved:{healed:e.approved.healed,...e.approved.recipeId?{recipeId:e.approved.recipeId}:{},...e.approved.recipeVersionId?{recipeVersionId:e.approved.recipeVersionId}:{},...e.approved.version!==void 0?{version:e.approved.version}:{},...u.length?{updatedFiles:u}:{}}}:{}})):r.display?r.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${s?` Workspace: ${s.name}.`:""}`,updatedFiles:u,warning:r.warnings.join(`
|
|
174
174
|
`)||void 0,next:`Open Canary: ${be().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."),u.length?console.log(` Updated locally to match: ${u.join(", ")}`):c||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"){jn(t);let i={phase:e.failure?.phase?V(r,e.failure.phase):null,failingCommand:e.failure?.failingCommand?V(r,e.failure.failingCommand):null,log:e.failure?.log?V(r,e.failure.log):null};return n?console.log(JSON.stringify({ok:!1,status:e.status,jobId:e.jobId,failure:i})):r.display?r.display.finish({status:e.status,message:`Verification ${e.status==="error"?"errored":"failed"}${i.phase?` (${i.phase})`:""}${i.failingCommand?` at: ${i.failingCommand}`:""}${i.log?`
|
|
175
175
|
|
|
176
176
|
${i.log.slice(-2e3)}`:""}`,warning:r.warnings.join(`
|
|
177
177
|
`)||void 0,next:"Fix the recipe in .canary/ and run canary setup again."}):(console.error(`\u2717 Verify ${e.status==="error"?"errored":"failed"}${i.phase?` (${i.phase})`:""}${i.failingCommand?` at: ${i.failingCommand}`:""}`),i.log&&console.error(`
|
|
178
178
|
${i.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 i={...e.needsInput,key:V(r,e.needsInput.key),prompt:V(r,e.needsInput.prompt)};return n?console.log(JSON.stringify({ok:!1,status:"needs_input",jobId:e.jobId,needsInput:i})):(console.log(`? The cloud verifier needs input${i.secret?" (a secret \u2014 pass the real value, don't echo it anywhere else)":""}:`),console.log(` ${i.key}: ${i.prompt}`),console.log(`
|
|
179
|
-
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function Oa(t,e){return t.status==="needs_input"&&t.needsInput?.questionId===e.questionId}async function Ef(t,e,n){let r=new AbortController,o=new AbortController,i=t.display.ask({...e,key:V(t,e.key),prompt:V(t,e.prompt)},r.signal).then(a=>({kind:"answer",value:a})),s=(async()=>{for(;;){await
|
|
179
|
+
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function Oa(t,e){return t.status==="needs_input"&&t.needsInput?.questionId===e.questionId}async function Ef(t,e,n){let r=new AbortController,o=new AbortController,i=t.display.ask({...e,key:V(t,e.key),prompt:V(t,e.prompt)},r.signal).then(a=>({kind:"answer",value:a})),s=(async()=>{for(;;){await at(st,o.signal);let a=await n(o.signal);if(!Oa(a,e))return{kind:"state",view:a}}})();try{return await Promise.race([i,s])}finally{o.abort(),r.abort(),await Promise.allSettled([i,s])}}async function Af(t,e,n,r,o,i){let s="",a=null;async function l(u){for(;;)try{let d=await v(`/api/v1/cli/verify/${e}`,{token:n,baseUrl:o.context?.apiUrl,signal:u});if(!d||!$a.has(d.status))throw new Error("Verification returned an unrecognized state. Run canary setup again to retry.");return a=null,d}catch(d){if(u?.aborted)throw d;if(d instanceof R&&d.status===0&&(a===null&&(a=Date.now(),o.display?o.display.update("retrying","Cloud service unreachable. Retrying the same job."):r||console.log(" \u2026 cloud service unreachable \u2014 retrying")),Date.now()-a<$f)){await at(st,u);continue}throw d}}let c;for(;;){let u=c??await l();if(c=void 0,u.status==="interrupted")return"interrupted";if(u.status==="needs_input"&&i&&u.needsInput?.questionId===i.questionId&&Date.now()<i.until){await at(st);continue}if(u.status==="needs_input"&&u.needsInput&&o.display){let d=u.needsInput,h=await Ef({...o,display:o.display},d,l);if(h.kind==="state"){c=h.view;continue}let p=h.value;if(p===null)return o.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 f=await l();if(!Oa(f,d)){c=f;continue}o.display.update("answering","Sending your answer to the verifier.");try{await Ta(t,e,n,d,p,r,o)}catch(m){if(m instanceof R&&m.status===409)continue;throw m}i={questionId:d.questionId,until:Date.now()+3e4},o.display.update("answering","Answer received. Waiting for verification to continue."),await at(st);continue}if((u.status==="pending"||u.status==="running")&&(o.display?o.display.update(u.status):u.status!==s&&!r&&console.log(` \u2026 ${u.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),s=u.status,await Ra(t,u,r,o))return"terminal";await at(st)}}async function Hn(t,e,n,r,o,i){qe();let s=e;for(let a=0;;){if(await Af(t,s,n,r,o,i)==="terminal")return;if(jn(t),o.freshUpload=!0,a>=Mn){r?console.log(JSON.stringify({ok:!1,status:"interrupted",jobId:s})):o.display?o.display.finish({status:"error",message:"Verification kept getting interrupted by the cloud service.",next:"Run canary setup again in a minute to restart from your local .canary/ files."}):console.error("\u2717 Verification kept getting interrupted (the cloud service may be redeploying). Run `canary setup` again in a minute \u2014 it restarts from your local .canary/ files."),process.exitCode=1;return}a+=1,r?console.error(JSON.stringify({event:"resubmitted",attempt:a,of:Mn})):o.display?o.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${Mn}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${Mn})`);let c=await Aa(t,n,r,o);if(c===null)return;s=c,i=void 0}}async function Ea(t,e,n,r){let o=r.context??=await xt(t,e),i=n.scope;if(i.apiUrl.replace(/\/+$/,"")!==o.apiUrl.replace(/\/+$/,"")||i.userId!==o.userId||i.workspaceId!==o.workspaceId)throw new N("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json was started by a different account, workspace, or Canary server. Switch back to it to resume that job, or remove the file to start over.");if((await _t({...o,token:e})).repositoryId!==i.repositoryId)throw new N("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json belongs to a different repository. Remove the file to start over.");r.baseRef??=n.source?.provenance.baseRef??void 0,Dr(n.source,o,i.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function Aa(t,e,n,r){let o=Re(t);yt(t);let{missing:i}=xr(o.envManifest,o.envValues);if(i.length)return n?console.log(JSON.stringify({ok:!1,error:"missing_boot_env",missing:i})):r.display?r.display.finish({status:"error",message:`Boot-required environment values are missing: ${i.join(", ")}`,next:"Fill .canary/env.json and run canary setup again."}):console.error(`\u2717 Boot-required env without values: ${i.join(", ")} \u2014 fill .canary/env.json first.`),process.exitCode=1,null;let s=r.context??=await xt(t,e),a=await _t({...s,token:e}),l=await Rt(t,{baseRef:r.baseRef});try{r.display?.update("submitting","Uploading your local source and the .canary/ recipe.");let c=He(o),u=await _n(l,s,a.repositoryId,e,{requestKey:`setup:${c}`,fresh:r.freshUpload});r.freshUpload=!1;let d=await v("/api/v1/cli/verify",{method:"POST",token:e,baseUrl:s.apiUrl,body:{workspaceId:s.workspaceId,repositoryId:a.repositoryId,source:u,setupSh:o.setupSh,runJson:JSON.stringify(o.runJson??null),env:{manifest:o.envManifest,values:o.envValues}}});if(!d?.jobId||d.repositoryId!==a.repositoryId||d.workspace&&d.workspace.id!==s.workspaceId||d.source&&d.source.sha256!==l.manifest.sha256)throw new Error("Canary's answer does not match the repository and source that were uploaded. Run canary setup again.");return Ia(t,{jobId:d.jobId,recipeHash:c,workspace:d.workspace??a.workspace,source:l.manifest,sourceUploadId:u.uploadId,scope:{apiUrl:s.apiUrl,userId:s.userId,workspaceId:s.workspaceId,repositoryId:a.repositoryId}}),Dr(l.manifest,s,a.repositoryId,{requestKey:`setup:${c}`,uploadId:u.uploadId}),d.jobId}finally{await l.dispose()}}async function Tf(t,e,n){let r=H();if(!r){e?console.log(JSON.stringify({ok:!1,error:"not_logged_in",fix:"canary login"})):n.display?n.display.finish({status:"error",message:"You're not signed in.",next:"Run canary login first."}):console.error("\u2717 Not logged in \u2014 run `canary login` first."),process.exitCode=1;return}Xt();let o=Gt(t);o?.scope&&await Ea(t,r,o,n);let i=o?.jobId??null;if(i){n.display?.update("submitting","Checking your saved verification job.");let a=null,l=!1,c=Date.now()+3e4;for(;;)try{if(a=await v(`/api/v1/cli/verify/${i}`,{token:r,baseUrl:n.context?.apiUrl}),!a||!$a.has(a.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(u){if(u instanceof R&&u.status===0){if(Date.now()<c){n.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await at(st);continue}l=!0}else if(!(u instanceof R&&u.status===404))throw u;break}if(l){e?console.log(JSON.stringify({ok:!1,error:"unreachable",jobId:i})):n.display?n.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"){n.display?n.display.update(a.status==="needs_input"?"answering":a.status,"Resuming your saved verification job."):e||console.log(`Resuming verify job ${i} \u2026`),await Hn(t,i,r,e,n);return}if(a.status==="green"||a.status==="red"||a.status==="error"){let u=!1;if(o?.recipeHash)try{u=He(Re(t))!==o.recipeHash}catch{u=!0}e?console.error(JSON.stringify({event:"previous_job_result",jobId:i,...u?{recipeChanged:!0}:{}})):n.display?n.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 ${i} finished after the previous run stopped \u2014 applying its result now.
|
|
180
180
|
`+(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.")),await Ra(t,a,e,n,{writeBack:!u,recipeChanged:u});return}}jn(t),n.freshUpload=!0}let s=await Aa(t,r,e,n);s!==null&&(n.display?n.display.update("pending","Recipe sent. Waiting for the cloud verifier."):e||console.log(`Shipped the recipe \u2014 verify job ${s}`),await Hn(t,s,r,e,n))}async function Ta(t,e,n,r,o,i,s){if(r.secret&&o&&s.secrets.add(o),await v(`/api/v1/cli/verify/${e}/answer`,{method:"POST",token:n,baseUrl:s.context?.apiUrl,body:{questionId:r.questionId,value:o}}),r.secret){let a=Gt(t),l=!1;try{l=!!a?.recipeHash&&He(Re(t))===a.recipeHash}catch{}try{if(a?.recipeHash&&!l)throw new Error("Local recipe changed since submission; the answered value was not written over it.");vr(t,[{name:r.key,value:o,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),l&&a&&Ia(t,{...a,recipeHash:He(Re(t))}),!i&&!s.display&&console.log(`Saved ${V(s,r.key)} to .canary/env.json for future runs.`)}catch(c){let u=V(s,`Could not save ${r.key} to .canary/env.json: ${c instanceof Error?c.message:String(c)}`);s.display?s.display.warn(u):console.error(`! ${u}`)}}}async function Nf(t,e,n,r){let o=H(),i=If(t);if(!o||!i){n?console.log(JSON.stringify({ok:!1,error:i?"not_logged_in":"no_active_job",fix:i?"canary login":"canary setup"})):r.display?r.display.finish({status:"error",message:i?"You're not signed in.":"No active verification job.",next:i?"Run canary login first.":"Run canary setup first."}):console.error(i?"\u2717 Not logged in \u2014 run `canary login`.":"\u2717 No active verify job \u2014 run `canary setup` first."),process.exitCode=1;return}let s=Gt(t);s?.scope&&await Ea(t,o,s,r);let a=await v(`/api/v1/cli/verify/${i}`,{token:o,baseUrl:r.context?.apiUrl});if(a.status!=="needs_input"||!a.needsInput){r.display?r.display.update("submitting","Nothing is waiting for input. Checking the saved job."):n||console.log("Nothing is waiting for input \u2014 following the job instead."),await Hn(t,i,o,n,r);return}let l=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await Ta(t,i,o,l,e,n,r),r.display?r.display.update("answering","Answer received. Waiting for verification to continue."):n||console.log(`Answered ${V(r,l.key)} \u2014 resuming \u2026`),await Hn(t,i,o,n,r,{questionId:l.questionId,until:Date.now()+3e4})}function Na(t){t.command("setup").description("Set up this repo on Canary: ship the .canary/ recipe for a cloud verify (boot + heal)").option("--check","validate the .canary/ recipe locally (no cloud)").option("--answer <value>","answer the question the cloud verifier is waiting on").option("--json","output machine-readable JSON").option("--no-animation","use plain progress output and answer questions with --answer").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","locally resolvable baseline for the submitted source snapshot").action(async e=>{let n=e.dir??process.cwd();Ke({cwd:n});let r=e.json===!0;if(e.check){Of(n,r);return}let o={secrets:new Set(e.answer?[e.answer]:[]),warnings:[],baseRef:e.base};try{let i=T().team;o.display=Ca({json:r,animation:e.animation!==!1,repository:xf(n),workspace:i?.name||(i?.id?"Saved workspace":"Select a workspace")}),e.answer!==void 0?await Nf(n,e.answer,r,o):await Tf(n,r,o)}catch(i){if(i instanceof Z||i instanceof ee||i instanceof N){let s=V(o,i.message),a="fix"in i&&i.fix?V(o,i.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:i.code,message:s,...a?{fix:a}:{}})):o.display?o.display.finish({status:"error",message:s,next:a}):console.error(`\u2717 ${s}${a?`
|
|
181
181
|
Fix: ${a}`:""}`)}else if(i instanceof R){let s=V(o,i.message),a="fix"in i&&i.fix?V(o,i.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:"api_error",status:i.status,message:s,...a?{fix:a}:{}})):o.display?o.display.finish({status:"error",message:s,next:a||"Run canary setup in this repository to resume."}):console.error(`\u2717 ${s}${a?`
|
|
182
|
-
Fix: ${a}`:""}`)}else{let s=V(o,i instanceof Error?i.message:String(i));r?console.log(JSON.stringify({ok:!1,error:"setup_error",message:s})):o.display?o.display.finish({status:"error",message:s,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${s}`)}process.exitCode=1}finally{o.display?.stop()}process.exitCode||await
|
|
183
|
-
`,{flag:"w",mode:384})}catch{}}function Ma(t){return t instanceof Error?t.message:String(t)}async function Gf(t,e){let n;try{n=await fetch(t,{headers:{...Ce(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${e}`},signal:AbortSignal.timeout(Mf)})}catch(r){return{kind:"failed",reason:Ma(r)}}if(n.status===404)return{kind:"missing"};if(!n.ok){let r=(await n.text().catch(()=>"")).trim().slice(0,200);return{kind:"failed",reason:`HTTP ${n.status}${r?`: ${r}`:""}`}}try{return{kind:"ok",body:await n.text(),contentVersion:n.headers.get("x-canary-skills-version")??void 0}}catch(r){return{kind:"failed",reason:`response body interrupted: ${Ma(r)}`}}}async function fo(t){let e=await Gf(t.url,t.cliVersion);switch(e.kind){case"ok":{let n={url:t.url,fetchedAt:new Date().toISOString(),cliVersion:t.cliVersion,contentVersion:e.contentVersion};return Df(t.key,{body:e.body,meta:n}),{ok:!0,body:e.body,url:t.url,contentVersion:e.contentVersion,offline:!1}}case"missing":return{ok:!1,error:t.notFound};case"failed":{let n=Uf(t.key);if(n&&n.meta.url===t.url)return{ok:!0,body:n.body,url:t.url,contentVersion:n.meta.contentVersion,offline:!0,reason:e.reason,fetchedAt:n.meta.fetchedAt,savedByCli:n.meta.cliVersion};let r=n?`the saved copy is from ${n.meta.url}, not this server`:"there is no saved copy";return{ok:!1,error:`live fetch of ${t.url} failed (${e.reason}) and ${r} \u2014 retry when the server is reachable`}}}}function Jf(t,e){let n=i=>i.replace(/^v/,"").split("-")[0].split(".").map(s=>Number.parseInt(s,10)||0),r=n(t),o=n(e);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s<0?-1:1}return 0}function Wf(t){let e=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t);if(e)return/^minCli:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m.exec(e[1])?.[1]}function Ha(t){return t.offline?`OFFLINE COPY \u2014 live fetch of ${t.url} failed (${t.reason}). Showing the copy fetched ${t.fetchedAt} by CLI ${t.savedByCli}; it may be outdated.`:`Source: ${t.url}${t.contentVersion?` (content version ${t.contentVersion})`:""}`}function
|
|
182
|
+
Fix: ${a}`:""}`)}else{let s=V(o,i instanceof Error?i.message:String(i));r?console.log(JSON.stringify({ok:!1,error:"setup_error",message:s})):o.display?o.display.finish({status:"error",message:s,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${s}`)}process.exitCode=1}finally{o.display?.stop()}process.exitCode||await Pt({json:r})})}rt();j();$e();import{lstatSync as Pf,mkdirSync as Lf,readFileSync as Pa,writeFileSync as La}from"node:fs";import{join as uo}from"node:path";var Mf=5e3,jf=/^[a-z0-9][a-z0-9-]{0,39}$/,Hf=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,Ff="npm i -g @runcanary/cli@latest";function ja(t){let e=uo(ne(),"skills");return{dir:e,body:uo(e,`${t}.md`),meta:uo(e,`${t}.json`)}}function Uf(t){let e=ja(t);try{let n=JSON.parse(Pa(e.meta,"utf8"));return{body:Pa(e.body,"utf8"),meta:n}}catch{return null}}function Jt(t){try{return Pf(t).isSymbolicLink()}catch{return!1}}function Df(t,e){let n=ja(t);try{if(Jt(ne())||Jt(n.dir)||Jt(n.body)||Jt(n.meta)||(Lf(n.dir,{recursive:!0,mode:448}),Jt(n.dir)))return;La(n.body,e.body,{flag:"w",mode:384}),La(n.meta,JSON.stringify(e.meta,null,2)+`
|
|
183
|
+
`,{flag:"w",mode:384})}catch{}}function Ma(t){return t instanceof Error?t.message:String(t)}async function Gf(t,e){let n;try{n=await fetch(t,{headers:{...Ce(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${e}`},signal:AbortSignal.timeout(Mf)})}catch(r){return{kind:"failed",reason:Ma(r)}}if(n.status===404)return{kind:"missing"};if(!n.ok){let r=(await n.text().catch(()=>"")).trim().slice(0,200);return{kind:"failed",reason:`HTTP ${n.status}${r?`: ${r}`:""}`}}try{return{kind:"ok",body:await n.text(),contentVersion:n.headers.get("x-canary-skills-version")??void 0}}catch(r){return{kind:"failed",reason:`response body interrupted: ${Ma(r)}`}}}async function fo(t){let e=await Gf(t.url,t.cliVersion);switch(e.kind){case"ok":{let n={url:t.url,fetchedAt:new Date().toISOString(),cliVersion:t.cliVersion,contentVersion:e.contentVersion};return Df(t.key,{body:e.body,meta:n}),{ok:!0,body:e.body,url:t.url,contentVersion:e.contentVersion,offline:!1}}case"missing":return{ok:!1,error:t.notFound};case"failed":{let n=Uf(t.key);if(n&&n.meta.url===t.url)return{ok:!0,body:n.body,url:t.url,contentVersion:n.meta.contentVersion,offline:!0,reason:e.reason,fetchedAt:n.meta.fetchedAt,savedByCli:n.meta.cliVersion};let r=n?`the saved copy is from ${n.meta.url}, not this server`:"there is no saved copy";return{ok:!1,error:`live fetch of ${t.url} failed (${e.reason}) and ${r} \u2014 retry when the server is reachable`}}}}function Jf(t,e){let n=i=>i.replace(/^v/,"").split("-")[0].split(".").map(s=>Number.parseInt(s,10)||0),r=n(t),o=n(e);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s<0?-1:1}return 0}function Wf(t){let e=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t);if(e)return/^minCli:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m.exec(e[1])?.[1]}function Ha(t){return t.offline?`OFFLINE COPY \u2014 live fetch of ${t.url} failed (${t.reason}). Showing the copy fetched ${t.fetchedAt} by CLI ${t.savedByCli}; it may be outdated.`:`Source: ${t.url}${t.contentVersion?` (content version ${t.contentVersion})`:""}`}function ct(t,e,n={}){if(!t.ok)return e?{stream:"stdout",text:JSON.stringify({ok:!1,error:t.error,...n})+`
|
|
184
184
|
`,exit:1}:{stream:"stderr",text:`\u2717 ${t.error}
|
|
185
185
|
`,exit:1};if(e){let r={ok:!0,source:t.url,contentVersion:t.contentVersion??null,offline:t.offline,...t.offline?{reason:t.reason,fetchedAt:t.fetchedAt}:{},...n,body:t.body};return{stream:"stdout",text:JSON.stringify(r)+`
|
|
186
186
|
`,exit:0}}return{stream:"stdout",text:`${Ha(t)}
|
|
187
187
|
|
|
188
188
|
${t.body}${t.body.endsWith(`
|
|
189
189
|
`)?"":`
|
|
190
|
-
`}`,exit:0}}function Wt(t){(t.stream==="stdout"?process.stdout:process.stderr).write(t.text),process.exit(t.exit)}function Bf(t,e,n={}){if(!t.ok||e){let r=
|
|
191
|
-
`,exit:0}}function Fn(){return W().replace(/\/+$/,"")}function Fa(t){t.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 n=await fo({key:"index",url:`${Fn()}/llms.txt`,cliVersion:t.version()??"0.0.0",notFound:`this Canary server (${Fn()}) does not publish skills yet`});Wt(
|
|
190
|
+
`}`,exit:0}}function Wt(t){(t.stream==="stdout"?process.stdout:process.stderr).write(t.text),process.exit(t.exit)}function Bf(t,e,n={}){if(!t.ok||e){let r=ct(t,e,n);return r.stream==="stdout"?{stdout:r.text,stderr:"",exit:r.exit}:{stdout:"",stderr:r.text,exit:r.exit}}return{stdout:t.body,stderr:`${Ha(t)}
|
|
191
|
+
`,exit:0}}function Fn(){return W().replace(/\/+$/,"")}function Fa(t){t.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 n=await fo({key:"index",url:`${Fn()}/llms.txt`,cliVersion:t.version()??"0.0.0",notFound:`this Canary server (${Fn()}) does not publish skills yet`});Wt(ct(n,!!e.json))}),t.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,n)=>{let r=!!n.json;jf.test(e)||Wt(ct({ok:!1,error:`invalid operation name "${e.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},r));let o=t.version()??"0.0.0";if(n.asset!==void 0){Hf.test(n.asset)||Wt(ct({ok:!1,error:`invalid asset name "${n.asset.slice(0,80)}" \u2014 assets are lowercase file names ending in .html, .json, .md or .txt`},r));let s=await fo({key:`${e}--${n.asset}`,url:`${Fn()}/skills/${e}/${n.asset}`,cliVersion:o,notFound:`no such asset "${n.asset}" for "${e}" \u2014 run \`canary skill ${e}\` to see which files it publishes`}),a=Bf(s,r,{name:e,asset:n.asset});a.stderr&&process.stderr.write(a.stderr);let l=()=>process.exit(a.exit);a.stdout?process.stdout.write(a.stdout,l):l()}let i=await fo({key:e,url:`${Fn()}/skills/${e}.md`,cliVersion:o,notFound:`no such operation "${e}" \u2014 run \`canary skills\` to list the operations`});if(i.ok){let s=Wf(i.body);if(s&&o!=="0.0.0-dev"&&Jf(o,s)<0){let a=`"${e}" needs Canary CLI ${s} or newer (you have ${o}). Update: ${Ff}`,l=ct({ok:!1,error:a},r,{needsCli:s,cliVersion:o});Wt({...l,exit:2})}}Wt(ct(i,r,{name:e}))})}B();j();Ge();var Vf=3e3;function qf(t){let e=t.periodEnd?` \xB7 resets ${new Date(t.periodEnd).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`:"";return t.limit===null?`Runs this month: ${t.used} \xB7 no limit`:`Runs this month: ${t.used} of ${t.limit}${e}`}function Ua(t){t.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async e=>{let n=e.json===!0,r=H();if(!r){n?console.log(JSON.stringify({ok:!1,error:"not_logged_in"})):console.error("Not logged in. Run `canary login`."),process.exitCode=1;return}try{let o=T().team,i=o?.id&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o.id)?o:void 0,s=await v(`/api/v1/cli/auth/whoami${i?`?workspaceId=${encodeURIComponent(i.id)}`:""}`,{token:r}),a=i?{id:i.id,name:i.name??s.team.name}:void 0,l=Zr(),c=l&&a?await vn({token:r,apiUrl:W().replace(/\/+$/,""),userId:s.user.id},l,a.id,AbortSignal.timeout(Vf)):void 0,u=Xr();if(n)console.log(JSON.stringify({ok:!0,user:s.user,team:s.team,workspace:a,...s.usage?{usage:s.usage}:{},...l?{repository:{name:l,...c?.state?{state:c.state}:{}}}:{},...u.length?{pushCheck:{pending:u}}:{}}));else{console.log(`${s.user.email} (${a?.name??"No workspace selected"})`),s.usage&&console.log(qf(s.usage)),l&&(console.log(In(l,c?.state)),console.log(jt(c?.state)));for(let d of u)console.log(`Push check on ${d.label}: ${d.why} Run \`${d.command}\` in a terminal. ${d.after}`)}}catch(o){let i=o instanceof R&&o.status===401,s=i?"invalid_token":o instanceof Error?o.message:String(o);n?console.log(JSON.stringify({ok:!1,error:s})):console.error(i?"Your CLI session is no longer valid. Run `canary login`.":`Error: ${s}`),process.exitCode=1}})}B();j();async function Ja(){let t=H();if(!t)throw new R(401,"not logged in");let{workspaces:e}=await v("/api/v1/cli/workspaces",{token:t});return e}function lt(t,e,n,r={}){t?console.log(JSON.stringify({ok:!1,error:e,message:n,...r})):console.error(n),process.exitCode=1}function Da(t,e){if(e instanceof R&&e.status===401){lt(t,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}lt(t,"workspace_error",e instanceof Error?e.message:String(e))}async function Yf(t){let e=await Ja(),n=T().team?.id;if(t){console.log(JSON.stringify({workspaces:e,active:n??null}));return}if(e.length===0){console.error("You're not a member of any workspace yet. Set one up at www.runcanary.ai first.");return}let r=String(e.length).length;e.forEach((o,i)=>{let s=o.id===n?"*":" ",a=String(i+1).padStart(r," ");console.log(`${s} ${a} ${o.name}`)})}function Ga(t,e){if(!z(n=>({...n,team:{id:t.id,name:t.name}}))){lt(e,"config_unreadable","The CLI's config file exists but cannot be read, so the workspace was not saved. Repair or remove it, or run: canary login",{fix:"canary login"});return}console.log(e?JSON.stringify({ok:!0,workspace:{id:t.id,name:t.name}}):`Switched to ${t.name}.`)}async function Kf(t,e){let n=await Ja(),r=t.trim();if(/^\d+$/.test(r)){let i=Number(r);if(i<1||i>n.length){lt(e,"workspace_not_found",`No workspace #${i} \u2014 you have ${n.length}. Run: canary workspace list`,{available:n.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}Ga(n[i-1],e);return}let o=n.filter(i=>i.id===r||i.name.toLowerCase()===r.toLowerCase());if(o.length===0){lt(e,"workspace_not_found",`No workspace matching "${t}".`,{available:n.map(i=>({id:i.id,name:i.name})),fix:"canary workspace list"});return}if(o.length>1){lt(e,"workspace_ambiguous",`"${t}" matches multiple workspaces \u2014 use the id.`,{matches:o.map(i=>({id:i.id,name:i.name})),fix:`canary workspace use ${o[0].id}`});return}Ga(o[0],e)}function zf(t){let e=T().team;if(!e){t?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(t?JSON.stringify({workspace:e}):e.name)}function Wa(t){let e=t.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 n=>{let r=n.json===!0;try{await Yf(r)}catch(o){Da(r,o)}}),e.command("use <workspace>").description("Set the active workspace (by number from `list`, name, or id)").option("--json","output machine-readable JSON").action(async(n,r)=>{let o=r.json===!0;try{await Kf(n,o)}catch(i){Da(o,i)}}),e.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>zf(n.json===!0))}Ye();var X=new Eo;X.name("canary").description("Canary \u2014 break the code your AI writes.").version(ve);process.argv[2]!=="hook"&&Qo();Ys(X);Ua(X);ga(X);Fa(X);Wa(X);Na(X);Is(X);_a(X);ea(X);Zs(X);Qr(X);ha(X);X.parseAsync(process.argv).catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
|