@runcanary/cli 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/canary.js +180 -127
- package/package.json +3 -2
package/dist/canary.js
CHANGED
|
@@ -1,88 +1,102 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __canaryCreateRequire } from 'node:module';
|
|
3
3
|
const require = __canaryCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`).replace(/^/gm," ".repeat(i))}let
|
|
6
|
-
`)}padWidth(
|
|
4
|
+
var yl=Object.create;var yr=Object.defineProperty;var wl=Object.getOwnPropertyDescriptor;var bl=Object.getOwnPropertyNames;var kl=Object.getPrototypeOf,Sl=Object.prototype.hasOwnProperty;var $t=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ue=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),xl=(e,t)=>{for(var n in t)yr(e,n,{get:t[n],enumerable:!0})},_l=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of bl(t))!Sl.call(e,o)&&o!==n&&yr(e,o,{get:()=>t[o],enumerable:!(r=wl(t,o))||r.enumerable});return e};var Cl=(e,t,n)=>(n=e!=null?yl(kl(e)):{},_l(t||!e||!e.__esModule?yr(n,"default",{value:e,enumerable:!0}):n,e));var It=Ue(br=>{var fn=class extends Error{constructor(t,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=t,this.nestedError=void 0}},wr=class extends fn{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};br.CommanderError=fn;br.InvalidArgumentError=wr});var pn=Ue(Sr=>{var{InvalidArgumentError:vl}=It(),kr=class{constructor(t,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new vl(`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 $l(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Sr.Argument=kr;Sr.humanReadableArgName=$l});var _r=Ue(li=>{var{humanReadableArgName:Il}=pn(),xr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(t){let n=t.commands.filter(o=>!o._hidden),r=t._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((o,i)=>o.name().localeCompare(i.name())),n}compareOptions(t,n){let r=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return r(t).localeCompare(r(n))}visibleOptions(t){let n=t.options.filter(o=>!o.hidden),r=t._getHelpOption();if(r&&!r.hidden){let o=r.short&&t._findOption(r.short),i=r.long&&t._findOption(r.long);!o&&!i?n.push(r):r.long&&!i?n.push(t.createOption(r.long,r.description)):r.short&&!o&&n.push(t.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let n=[];for(let r=t.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(t){return t._argsDescription&&t.registeredArguments.forEach(n=>{n.description=n.description||t._argsDescription[n.name()]||""}),t.registeredArguments.find(n=>n.description)?t.registeredArguments:[]}subcommandTerm(t){let n=t.registeredArguments.map(r=>Il(r)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,n){return n.visibleCommands(t).reduce((r,o)=>Math.max(r,n.subcommandTerm(o).length),0)}longestOptionTermLength(t,n){return n.visibleOptions(t).reduce((r,o)=>Math.max(r,n.optionTerm(o).length),0)}longestGlobalOptionTermLength(t,n){return n.visibleGlobalOptions(t).reduce((r,o)=>Math.max(r,n.optionTerm(o).length),0)}longestArgumentTermLength(t,n){return n.visibleArguments(t).reduce((r,o)=>Math.max(r,n.argumentTerm(o).length),0)}commandUsage(t){let n=t._name;t._aliases[0]&&(n=n+"|"+t._aliases[0]);let r="";for(let o=t.parent;o;o=o.parent)r=o.name()+" "+r;return r+n+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let n=[];return t.argChoices&&n.push(`choices: ${t.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&n.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&n.push(`env: ${t.envVar}`),n.length>0?`${t.description} (${n.join(", ")})`:t.description}argumentDescription(t){let n=[];if(t.argChoices&&n.push(`choices: ${t.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),t.defaultValue!==void 0&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return t.description?`${t.description} ${r}`:r}return t.description}formatHelp(t,n){let r=n.padWidth(t,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 c(f){return f.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${n.commandUsage(t)}`,""],d=n.commandDescription(t);d.length>0&&(l=l.concat([n.wrap(d,o,0),""]));let u=n.visibleArguments(t).map(f=>a(n.argumentTerm(f),n.argumentDescription(f)));u.length>0&&(l=l.concat(["Arguments:",c(u),""]));let p=n.visibleOptions(t).map(f=>a(n.optionTerm(f),n.optionDescription(f)));if(p.length>0&&(l=l.concat(["Options:",c(p),""])),this.showGlobalOptions){let f=n.visibleGlobalOptions(t).map(m=>a(n.optionTerm(m),n.optionDescription(m)));f.length>0&&(l=l.concat(["Global Options:",c(f),""]))}let h=n.visibleCommands(t).map(f=>a(n.subcommandTerm(f),n.subcommandDescription(f)));return h.length>0&&(l=l.concat(["Commands:",c(h),""])),l.join(`
|
|
6
|
+
`)}padWidth(t,n){return Math.max(n.longestOptionTermLength(t,n),n.longestGlobalOptionTermLength(t,n),n.longestSubcommandTermLength(t,n),n.longestArgumentTermLength(t,n))}wrap(t,n,r,o=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",s=new RegExp(`[\\n][${i}]+`);if(t.match(s))return t;let a=n-r;if(a<o)return t;let c=t.slice(0,r),l=t.slice(r).replace(`\r
|
|
7
7
|
`,`
|
|
8
|
-
`),
|
|
9
|
-
|.{1,${a-1}}([${
|
|
10
|
-
`?"":(g>0?
|
|
11
|
-
`)}}
|
|
8
|
+
`),d=" ".repeat(r),p="\\s\u200B",h=new RegExp(`
|
|
9
|
+
|.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),f=l.match(h)||[];return c+f.map((m,g)=>m===`
|
|
10
|
+
`?"":(g>0?d:"")+m.trimEnd()).join(`
|
|
11
|
+
`)}};li.Help=xr});var Ir=Ue($r=>{var{InvalidArgumentError:Rl}=It(),Cr=class{constructor(t,n){this.flags=t,this.description=n||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let r=Al(t);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(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let n=t;return typeof t=="string"&&(n={[t]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Rl(`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 Ol(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},vr=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.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(t,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===t)}};function Ol(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function Al(e){let t,n,r=e.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(t=r.shift()),n=r.shift(),!t&&/^-[^-]$/.test(n)&&(t=n,n=void 0),{shortFlag:t,longFlag:n}}$r.Option=Cr;$r.DualOptions=vr});var di=Ue(ui=>{function El(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let o=1;o<=e.length;o++){let i=1;e[o-1]===t[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&&e[o-1]===t[r-2]&&e[o-2]===t[r-1]&&(n[o][r]=Math.min(n[o][r],n[o-2][r-2]+1))}return n[e.length][t.length]}function Tl(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");n&&(e=e.slice(2),t=t.map(s=>s.slice(2)));let r=[],o=3,i=.4;return t.forEach(s=>{if(s.length<=1)return;let a=El(e,s),c=Math.max(e.length,s.length);(c-a)/c>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]}?)`:""}
|
|
14
|
-
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=
|
|
15
|
-
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[
|
|
16
|
-
- already used by option '${n.flags}'`)}this.options.push(
|
|
17
|
-
- if '${
|
|
13
|
+
(Did you mean ${r[0]}?)`:""}ui.suggestSimilar=Tl});var mi=Ue(gi=>{var Nl=$t("node:events").EventEmitter,Rr=$t("node:child_process"),$e=$t("node:path"),Or=$t("node:fs"),H=$t("node:process"),{Argument:Pl,humanReadableArgName:Ll}=pn(),{CommanderError:Ar}=It(),{Help:Ml}=_r(),{Option:fi,DualOptions:jl}=Ir(),{suggestSimilar:pi}=di(),Er=class e extends Nl{constructor(t){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=t||"",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=>H.stdout.write(n),writeErr:n=>H.stderr.write(n),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.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(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let n=this;n;n=n.parent)t.push(n);return t}command(t,n,r){let o=n,i=r;typeof o=="object"&&o!==null&&(i=o,o=null),i=i||{};let[,s,a]=t.match(/([^ ]+) *(.*)/),c=this.createCommand(s);return o&&(c.description(o),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(t){return new e(t)}createHelp(){return Object.assign(new Ml,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,n){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
+
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=t._name),(n.noHelp||n.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,n){return new Pl(t,n)}argument(t,n,r,o){let i=this.createArgument(t,n);return typeof r=="function"?i.default(o).argParser(r):i.default(r),this.addArgument(i),this}arguments(t){return t.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(t){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,n){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,r,o]=t.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(t,n){return typeof t!="object"?(this.helpCommand(t,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,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(t,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
15
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(n):this._lifeCycleHooks[t]=[n],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(t,n,r){this._exitCallback&&this._exitCallback(new Ar(t,n,r)),H.exit(t)}action(t){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),t.apply(this,i)};return this._actionHandler=n,this}createOption(t,n){return new fi(t,n)}_callParseArg(t,n,r,o){try{return t.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(t){let n=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(n){let r=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
16
|
+
- already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=o=>[o.name()].concat(o.aliases()),r=n(t).find(o=>this._findCommand(o));if(r){let o=n(this._findCommand(r)).join("|"),i=n(t).join("|");throw new Error(`cannot add command '${i}' as already have command '${o}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),r=t.attributeName();if(t.negate){let i=t.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(r,t.defaultValue,"default");let o=(i,s,a)=>{i==null&&t.presetArg!==void 0&&(i=t.presetArg);let c=this.getOptionValue(r);i!==null&&t.parseArg?i=this._callParseArg(t,i,c,s):i!==null&&t.variadic&&(i=t._concatValue(i,c)),i==null&&(t.negate?i=!1:t.isBoolean()||t.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,a)};return this.on("option:"+n,i=>{let s=`error: option '${t.flags}' argument '${i}' is invalid.`;o(i,s,"cli")}),t.envVar&&this.on("optionEnv:"+n,i=>{let s=`error: option '${t.flags}' value '${i}' from env '${t.envVar}' is invalid.`;o(i,s,"env")}),this}_optionEx(t,n,r,o,i){if(typeof n=="object"&&n instanceof fi)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(n,r);if(s.makeOptionMandatory(!!t.mandatory),typeof o=="function")s.default(i).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let d=a.exec(c);return d?d[0]:l},s.default(i).argParser(o)}else s.default(o);return this.addOption(s)}option(t,n,r,o){return this._optionEx({},t,n,r,o)}requiredOption(t,n,r,o){return this._optionEx({mandatory:!0},t,n,r,o)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,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(t=!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=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,n){return this.setOptionValueWithSource(t,n,void 0)}setOptionValueWithSource(t,n,r){return this._storeOptionsAsProperties?this[t]=n:this._optionValues[t]=n,this._optionValueSources[t]=r,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(t)!==void 0&&(n=r.getOptionValueSource(t))}),n}_prepareUserArgs(t,n){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},t===void 0&&n.from===void 0){H.versions?.electron&&(n.from="electron");let o=H.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(n.from="eval")}t===void 0&&(t=H.argv),this.rawArgs=t.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=t[1],r=t.slice(2);break;case"electron":H.defaultApp?(this._scriptPath=t[1],r=t.slice(2)):r=t.slice(1);break;case"user":r=t.slice(0);break;case"eval":r=t.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(t,n){let r=this._prepareUserArgs(t,n);return this._parseCommand([],r),this}async parseAsync(t,n){let r=this._prepareUserArgs(t,n);return await this._parseCommand([],r),this}_executeSubCommand(t,n){n=n.slice();let r=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,u){let p=$e.resolve(d,u);if(Or.existsSync(p))return p;if(o.includes($e.extname(u)))return;let h=o.find(f=>Or.existsSync(`${p}${f}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Or.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=$e.resolve($e.dirname(d),a)}if(a){let d=i(a,s);if(!d&&!t._executableFile&&this._scriptPath){let u=$e.basename(this._scriptPath,$e.extname(this._scriptPath));u!==this._name&&(d=i(a,`${u}-${t._name}`))}s=d||s}r=o.includes($e.extname(s));let c;H.platform!=="win32"?r?(n.unshift(s),n=hi(H.execArgv).concat(n),c=Rr.spawn(H.argv[0],n,{stdio:"inherit"})):c=Rr.spawn(s,n,{stdio:"inherit"}):(n.unshift(s),n=hi(H.execArgv).concat(n),c=Rr.spawn(H.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{H.on(u,()=>{c.killed===!1&&c.exitCode===null&&c.kill(u)})});let l=this._exitCallback;c.on("close",d=>{d=d??1,l?l(new Ar(d,"commander.executeSubCommandAsync","(close)")):H.exit(d)}),c.on("error",d=>{if(d.code==="ENOENT"){let u=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${s}' does not exist
|
|
17
|
+
- if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
18
18
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
19
|
-
- ${
|
|
19
|
+
- ${u}`;throw new Error(p)}else if(d.code==="EACCES")throw new Error(`'${s}' not executable`);if(!l)H.exit(1);else{let u=new Ar(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=c}_dispatchSubcommand(t,n,r){let o=this._findCommand(t);o||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,o,"preSubcommand"),i=this._chainOrCall(i,()=>{if(o._executableHandler)this._executeSubCommand(o,n.concat(r));else return o._parseCommand(n,r)}),i}_dispatchHelpCommand(t){t||this.help();let n=this._findCommand(t);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,n)=>{t.required&&this.args[n]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(r,o,i)=>{let s=o;if(o!==null&&r.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${r.name()}'.`;s=this._callParseArg(r,o,i,a)}return s};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,o)=>{let i=r.defaultValue;r.variadic?o<this.args.length?(i=this.args.slice(o),r.parseArg&&(i=i.reduce((s,a)=>t(r,a,s),r.defaultValue))):i===void 0&&(i=[]):o<this.args.length&&(i=this.args[o],r.parseArg&&(i=t(r,i,r.defaultValue))),n[o]=i}),this.processedArgs=n}_chainOrCall(t,n){return t&&t.then&&typeof t.then=="function"?t.then(()=>n()):n()}_chainOrCallHooks(t,n){let r=t,o=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(s=>{o.push({hookedCommand:i,callback:s})})}),n==="postAction"&&o.reverse(),o.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(t,n,r){let o=t;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{o=this._chainOrCall(o,()=>i(this,n))}),o}_parseCommand(t,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(r.operands),n=r.unknown,this.args=t.concat(n),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),n);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,t,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(i,t,n)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(i))o(),this._processArguments(),this.parent.emit(i,t,n);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,n);this.listenerCount("command:*")?this.emit("command:*",t,n):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(n=>n._name===t||n._aliases.includes(t))}_findOption(t){return this.options.find(n=>n.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(n=>{n.mandatory&&t.getOptionValue(n.attributeName())===void 0&&t.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(r=>{let o=r.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});t.filter(r=>r.conflictsWith.length>0).forEach(r=>{let o=t.find(i=>r.conflictsWith.includes(i.attributeName()));o&&this._conflictingOption(r,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let n=[],r=[],o=n,i=t.slice();function s(c){return c.length>1&&c[0]==="-"}let a=null;for(;i.length;){let c=i.shift();if(c==="--"){o===r&&o.push(c),o.push(...i);break}if(a&&!s(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,s(c)){let l=this._findOption(c);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!s(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),d=this._findOption(c.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,c.slice(l+1));continue}}if(s(c)&&(o=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){o.push(c),i.length>0&&o.push(...i);break}o.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let t={},n=this.options.length;for(let r=0;r<n;r++){let o=this.options[r].attributeName();t[o]=o===this._versionOptionName?this._version:this[o]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,n)=>Object.assign(t,n.opts()),{})}error(t,n){this._outputConfiguration.outputError(`${t}
|
|
20
20
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
21
21
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
22
|
-
`),this.outputHelp({error:!0}));let r=n||{},o=r.exitCode||1,i=r.code||"commander.error";this._exit(o,i,
|
|
23
|
-
`),this._exit(0,"commander.version",
|
|
24
|
-
Expecting one of '${r.join("', '")}'`);let o=`${
|
|
25
|
-
`)}),this}_outputHelpIfRequested(
|
|
26
|
-
`,{flag:"wx"}),()=>{
|
|
27
|
-
`,{mode:384}),
|
|
28
|
-
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${
|
|
29
|
-
`);if(!n)return{};let i={worktreeId:
|
|
30
|
-
`).filter(Boolean).sort()[0]:void 0;a&&
|
|
31
|
-
`,
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
`):[];if(e==="uninstall"){let l=r.filter(c=>c.trim()!==xt&&c.trim()!==pi);return l.length===r.length?null:(vr(t,l.join(`
|
|
36
|
-
`)
|
|
37
|
-
`)
|
|
38
|
-
|
|
39
|
-
|
|
22
|
+
`),this.outputHelp({error:!0}));let r=n||{},o=r.exitCode||1,i=r.code||"commander.error";this._exit(o,i,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in H.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,H.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new jl(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())&&t.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(t){let n=`error: missing required argument '${t}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(t){let n=`error: option '${t.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let n=`error: required option '${t.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,n){let r=s=>{let a=s.attributeName(),c=this.getOptionValue(a),l=this.options.find(u=>u.negate&&a===u.attributeName()),d=this.options.find(u=>!u.negate&&a===u.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:d||s},o=s=>{let a=r(s),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${o(t)} cannot be used with ${o(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let n="";if(t.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=pi(t,o)}let r=`error: unknown option '${t}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(t){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 ${t.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let t=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=pi(t,o)}let r=`error: unknown command '${t}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(t,n,r){if(t===void 0)return this._version;this._version=t,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(`${t}
|
|
23
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,n){return t===void 0&&n===void 0?this._description:(this._description=t,n&&(this._argsDescription=n),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===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]),t===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(t);if(r){let o=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${o}'`)}return n._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(n=>this.alias(n)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Ll(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=$e.basename(t,$e.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(t){t=t||{};let n={error:!!t.error},r;return n.error?r=o=>this._outputConfiguration.writeErr(o):r=o=>this._outputConfiguration.writeOut(o),n.write=t.write||r,n.command=this,n}outputHelp(t){let n;typeof t=="function"&&(n=t,t=void 0);let r=this._getHelpContext(t);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(t,n){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(t,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let n=H.exitCode||0;n===0&&t&&typeof t!="function"&&t.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(t,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
24
|
+
Expecting one of '${r.join("', '")}'`);let o=`${t}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(t){let n=this._getHelpOption();n&&t.find(o=>n.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function hi(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",o="9229",i;return(i=t.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?o=i[3]:r=i[3]):(i=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],o=i[4]),n&&o!=="0"?`${n}=${r}:${parseInt(o)+1}`:t})}gi.Command=Er});var ki=Ue(le=>{var{Argument:yi}=pn(),{Command:Tr}=mi(),{CommanderError:Fl,InvalidArgumentError:wi}=It(),{Help:Hl}=_r(),{Option:bi}=Ir();le.program=new Tr;le.createCommand=e=>new Tr(e);le.createOption=(e,t)=>new bi(e,t);le.createArgument=(e,t)=>new yi(e,t);le.Command=Tr;le.Option=bi;le.Argument=yi;le.Help=Hl;le.CommanderError=Fl;le.InvalidArgumentError=wi;le.InvalidOptionArgumentError=wi});import{execFileSync as Dl}from"node:child_process";import{randomUUID as Ul}from"node:crypto";import{chmodSync as Gl,mkdirSync as Lr,readFileSync as Mr,renameSync as Jl,rmSync as vi,statSync as Bl,writeFileSync as $i}from"node:fs";import{homedir as Wl}from"node:os";import{dirname as Ii,join as jr}from"node:path";function Z(){return process.env.CANARY_HOME||jr(Wl(),".canary")}function Fr(){return jr(Z(),"config.json")}function Ri(){let{config:e}=Dr();if(e.installId&&_i.test(e.installId))return e.installId;Ci??=Ul();let t=Ci;try{K(n=>n.installId&&_i.test(n.installId)?n:{...n,installId:t})}catch{}return t}function N(){return Dr().config}function Oi(e){return N().repoFingerprints?.[e]}function Ai(e,t){try{K(n=>({...n,repoFingerprints:{...n.repoFingerprints,[e]:t}}))}catch{}}function Ti(e){Ei=e}function Ni(){return`${Fr()}.lock`}function Zl(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function tu(e){try{let t=Dl("ps",["-o","lstart=","-p",String(e)],{env:{...process.env,LC_ALL:"C"},encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=Date.parse(t);return Number.isFinite(n)?n:null}catch{return null}}function nu(e){let t;try{t=Mr(Hr(e),"utf8").trim()}catch{return"unknown"}let[n,r]=t.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=tu(n);return o===null?!0:Math.abs(o-r)<=eu}function Li(e){try{return Mr(Hr(e),"utf8").trim()===Pi}catch{return!1}}function Nr(e){try{vi(e,{recursive:!0,force:!0})}catch{}}function Mi(e=Ni(),t="the config lock"){let n=Date.now()+Xl();for(;;)try{return Lr(Ii(e),{recursive:!0,mode:448}),Lr(e),$i(Hr(e),`${Pi}
|
|
26
|
+
`,{flag:"wx"}),()=>{Li(e)&&Nr(e)}}catch(r){if(r.code!=="EEXIST")throw r;let o=nu(e);if(o===!1){Nr(e);continue}if(o==="unknown")try{if(Date.now()-Bl(e).mtimeMs>Yl){Nr(e);continue}}catch{}if(Date.now()>=n)throw new Ge(`another canary process is holding ${t}`);Zl(zl)}}function ji(e,t,n){let r=Mi(e,t);try{return n()}finally{r()}}function K(e,t={}){let n=()=>{let{config:o,unreadable:i}=Dr();if(i&&!t.overwriteUnreadable)return!1;let s=e(i?{}:o);if(!Li(Ni()))throw new Ge("the config lock changed hands during the write");return ru(s),!0};if(Pr>0)return n();let r=Mi();Pr+=1;try{return n()}finally{Pr-=1,r()}}function Dr(){let e;try{e=Mr(Fr(),"utf8")}catch(t){return{config:{},unreadable:t.code!=="ENOENT"}}try{let t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?{config:{},unreadable:!0}:{config:t,unreadable:!1}}catch{return{config:{},unreadable:!0}}}function ru(e){let t=Fr();Lr(Ii(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;try{$i(n,JSON.stringify(e,null,2)+`
|
|
27
|
+
`,{mode:384}),Gl(n,384),Jl(n,t)}catch(r){throw vi(n,{force:!0}),r}}function Fi(){K(({apiUrl:e,webUrl:t,installId:n,agentSkills:r,repoFingerprints:o,gate:i,hooks:s})=>({...e?{apiUrl:e}:{},...t?{webUrl:t}:{},...n?{installId:n}:{},...r!==void 0?{agentSkills:r}:{},...o?{repoFingerprints:o}:{},...i?{gate:i}:{},...s?{hooks:s}:{}}))}function U(){return process.env.CANARY_TOKEN||N().token}function W(){return process.env.CANARY_API_URL||N().apiUrl||Vl}function Ie(){let e=process.env.CANARY_WEB_URL||N().webUrl;if(e)return e;let t=process.env.CANARY_API_URL||N().apiUrl;return t?t.replace("//api.","//www."):ql}var Vl,ql,_i,Ci,Ge,Kl,Yl,zl,Ei,Xl,Hr,Ql,Pi,eu,Pr,D=L(()=>{"use strict";Vl="https://api.runcanary.ai",ql="https://www.runcanary.ai";_i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ci=null;Ge=class extends Error{constructor(t="another canary process is holding the config lock"){super(`${t}; run the command again`),this.name="ConfigLockError"}},Kl=15e3,Yl=1e4,zl=20;Xl=()=>Ei??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||Kl);Hr=e=>jr(e,"owner");Ql=Math.round(Date.now()-process.uptime()*1e3),Pi=`${process.pid} ${Ql}`,eu=3e3;Pr=0});import{mkdirSync as hu,readFileSync as gu,writeFileSync as mu}from"node:fs";import{homedir as yu}from"node:os";import{dirname as wu,join as Ui}from"node:path";function Ji(){try{return JSON.parse(gu(Br(),"utf8"))}catch{return{}}}function ku(e,t){let n=e.split(".").map(Number),r=t.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 Bi(){if(Ae==="0.0.0-dev")return;let{latest:e}=Ji();e&&ku(e,Ae)&&console.error(`A newer Canary CLI is available (${Ae} -> ${e}): npm install -g ${Gi}`)}function ot(){if(Ae==="0.0.0-dev")return;let e=Ji();e.checkedAt&&Date.now()-e.checkedAt<bu||(async()=>{let t=n=>{try{hu(wu(Br()),{recursive:!0}),mu(Br(),JSON.stringify({checkedAt:Date.now(),latest:n??e.latest})+`
|
|
28
|
+
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${Gi}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t();let{version:r}=await n.json();t(r||void 0)}catch{t()}})()}var Ae,Gi,bu,Br,it=L(()=>{"use strict";Ae="0.1.14",Gi="@runcanary/cli",bu=1440*60*1e3,Br=()=>Ui(process.env.CANARY_HOME||Ui(yu(),".canary"),"update-check.json")});import{createHash as Su}from"node:crypto";import{execFileSync as xu,spawn as _u}from"node:child_process";function Be(e){Ee={...Ee,...e},Rt=null}function Wr(e=process.env){if(e.CLAUDECODE==="1"||e.CLAUDE_CODE_SESSION_ID){let t=e.CLAUDE_CODE_SESSION_ID??e.CLAUDE_CODE_HOST_SESSION_ID;return{harness:"claude-code",...t?{chatId:t}:{}}}return e.CODEX_SANDBOX||e.CODEX_SANDBOX_NETWORK_DISABLED==="1"?{harness:"codex"}:e.CURSOR_AGENT==="1"?{harness:"cursor"}:{harness:"unknown"}}function Cu(e,t){return Su("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}function qi(){return{...Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(e))),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 Wi(e,t){try{let n=qi();return xu("git",e,{cwd:t,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function vu(e,t){let[n,r,o]=(Wi(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],e)??"").split(`
|
|
29
|
+
`);if(!n)return{};let i={worktreeId:Cu(n,t)};if(o!=="true"){let s=Oi(i.worktreeId);s&&Wi(["cat-file","-e",`${s}^{commit}`],n)!==null?i.repoFingerprint=s:$u(n,i.worktreeId)}return i.branch=r&&r!=="HEAD"?r:"HEAD",i}function $u(e,t){Vi.has(t)||Vi.set(t,new Promise(n=>{try{let r=qi(),o=_u("git",["rev-list","--max-parents=0","HEAD"],{cwd:e,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&&Ai(t,a),n()}),o.unref(),o.stdout.unref?.()}catch{n()}}))}function Iu(){if(Rt)return Rt;let e=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",t=Wr(),n=Ee.harness??t.harness,r=t.harness===n?t.chatId:void 0,o="",i={};try{o=Ri(),i=vu(Ee.cwd??process.cwd(),o)}catch{}return Rt={cliVersion:Ae,command:e,installId:o,...i,harness:n,...r?{chatId:r}:{},...Ee.agent!==void 0?{agent:Ee.agent}:{},...Ee.mode?{mode:Ee.mode}:{}},Rt}function Te(){let e=Iu(),t=r=>r.replace(/[^\x20-\x7e]/g,"?").slice(0,200),n={[Q.cli]:e.cliVersion,[Q.harness]:e.harness};return e.installId&&(n[Q.install]=e.installId),e.command&&(n[Q.command]=t(e.command)),e.worktreeId&&(n[Q.worktree]=e.worktreeId),e.repoFingerprint&&(n[Q.repo]=e.repoFingerprint),e.branch&&(n[Q.branch]=t(e.branch)),e.chatId&&(n[Q.chat]=t(e.chatId)),e.agent!==void 0&&(n[Q.agent]=e.agent?"1":"0"),e.mode&&(n[Q.mode]=e.mode),n}var Q,Ee,Rt,Vi,Ne=L(()=>{"use strict";D();it();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"},Ee={},Rt=null;Vi=new Map});async function R(e,t={}){let n=(t.baseUrl||W()).replace(/\/+$/,""),r=Te();t.token&&(r.authorization=`Bearer ${t.token}`),t.body!==void 0&&(r["content-type"]="application/json");let o;try{o=await fetch(n+e,{method:t.method??"GET",headers:r,body:t.body!==void 0?JSON.stringify(t.body):void 0,signal:t.signal})}catch(i){throw new A(0,`could not reach ${n} (${i instanceof Error?i.message:String(i)})`)}if(!o.ok){let i=o.statusText,s,a,c;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),typeof l.code=="string"&&l.code&&(c=l.code)}catch{}throw new A(o.status,i,s,a,c)}return o.status===204?null:await o.json()}var A,ue,Y=L(()=>{"use strict";D();Ne();A=class extends Error{constructor(n,r,o,i,s){super(r);this.status=n;this.fix=o;this.runId=i;this.code=s;this.name="ApiError"}},ue=e=>e instanceof A&&(e.status===0||e.status===408||e.status===429||e.status===502||e.status===503||e.status===504)});function Ki(e){return K(t=>({...t,gate:{...t.gate,mode:e}}))}var We,yn=L(()=>{"use strict";D();We=()=>N().gate?.mode==="off"?"off":"on"});function Ru(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function Ou(e,t,n){let r=e.split(/\r?\n/),o="",i=(Math.log10(t+1)|0)+1;for(let s=t-1;s<=t+1;s++){let a=r[s-1];a&&(o+=s.toString().padEnd(i," "),o+=": ",o+=a,o+=`
|
|
31
|
+
`,s===t&&(o+=" ".repeat(i+n+2),o+=`^
|
|
32
|
+
`))}return o}var C,Ve=L(()=>{C=class e extends Error{line;column;codeblock;constructor(t,n){let[r,o]=Ru(n.toml,n.ptr),i=Ou(n.toml,r,o);super(`Invalid TOML document: ${t}
|
|
33
|
+
|
|
34
|
+
${i}`,n),this.line=r,this.column=o,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}}});function wn(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,o=n===39,i=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);i&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let s="",a=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),i&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c=c&&3;else if(n<32&&n!==9||n===127)C.x("control characters are not allowed in strings",e);else if((!c||c===3)&&n===r&&(!i||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(i&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let l=e.s.slice(a,e.p);s=s?s+l:l}return e.p+=i?3:1,s}else if(!c)!o&&n===92&&(s+=e.s.slice(a,a=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let l=e.p++-1,d=0,u=n===120?2:n===117?4:8;for(let p=0;p<u;p++,e.p++){let h=e.s.charCodeAt(e.p),f=h>=48&&h<=57?h-48:h>=65&&h<=70?h-65+10:h>=97&&h<=102?h-97+10:-1;f<0&&C.x("invalid non-hex character in unicode escape",e),d=d<<4|f}(d<0||d>1114111||d>=55296&&d<=57343)&&C.x("invalid unicode escape",e,l),s+=String.fromCodePoint(d),a=e.p--,c=0}else i&&(n===32||n===9)?c=2:(n===98?s+="\b":n===116?s+=" ":n===110?s+=`
|
|
35
|
+
`:n===102?s+="\f":n===114?s+="\r":n===101?s+="\x1B":n===34?s+='"':n===92?s+="\\":C.x("unrecognised escape sequence",e),a=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&C.x("invalid escape: only line-ending whitespace may be escaped",e,a),c=!o&&n===92?1:0,a=e.p);C.x("unfinished string",e,t)}var Vr=L(()=>{Ve();});var Au,Ot,qr=L(()=>{Au=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,Ot=class e extends Date{#t=!1;#n=!1;#e=null;constructor(t,n,r){let o=!0,i=!0,s="Z",a;if(typeof t=="string")if(n)e:{if(n<3){if(+t.slice(11,13)>23){t="";break e}n===2?(s=null,t+="Z"):(a=t.charCodeAt(t.length-1))!==90&&a!==122&&(s=t.slice(t.length-6)),r&&(t=t.slice(0,10)+"T"+t.slice(11))}else n===4&&(t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`);o=n!==4,i=n!==3}else{let c=t.match(Au);c?(c[1]||(o=!1,t=`0000-01-01T${t}`),i=!!c[2],i&&t[10]===" "&&(t=t.replace(" ","T")),c[2]&&+c[2]>23?t="":(s=c[3]||null,!s&&i&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=o,this.#n=i,this.#e=s)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#e===null)return t.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return t;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#e=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#e=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#t=!1,n.#e=null,n}}});function ie(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Yr(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Et(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||C.x("document contains excessively nested structures. aborting.",e);let o=r===91?Xi(e):zi(e);return e.d++,o}return r===34||r===39?wn(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&C.x("invalid value",e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&C.x("invalid value",e,n),e.p++,!1):r===43||r===45?bn(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?Eu(e,r,t):e.s.charCodeAt(e.p+2)===58?Tu(e,r,t):bn(e,e.p,r,0,t)}function bn(e,t,n,r,o){let i=n,s=0,a=!1;if(i===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&C.x("invalid value",e,t),e.p++,(r||1)/0;if(i===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&C.x("invalid value",e,t),e.p++,NaN;if(i===48){if(++e.p>=e.s.length||Yr(i=e.s.charCodeAt(e.p),o))return e.bi===!0?0n:0;if(!r){if(i===120)return Kr(e,t,16,o);if(i===98)return Kr(e,t,2,o);if(i===111)return Kr(e,t,8,o)}i===46?s=2:i===101||i===69?s=4:C.x("illegal leading zero",e,t)}else ie(i)||C.x("invalid value",e,t);for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Yr(i,o));)s||(s=1),i===95?(s&1||C.x("illegal underscore",e),s+=11,a=!0):s===1&&i===46?s=2:(s===1||s===3)&&(i===101||i===69)?s=4:s===4&&(i===43||i===45)||(ie(i)?s>9?s-=11:s&1||s++:C.x("illegal character in numeric literal",e));if(!s){let l=(n-48)*(r||1);return e.bi===!0?BigInt(l):l}s&1||C.x("unfinished numeric value",e,t);let c=e.s.slice(t,e.p);return a&&(c=c.replaceAll("_","")),s>1?parseFloat(c):Yi(e,c,10,t)}function Kr(e,t,n,r){let o,i=1;for(;++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!Yr(o,r));)o===95?(i&1&&C.x("illegal underscore",e),i=3):ie(o,n)?i&1&&i--:C.x("illegal character in numeric literal",e);i&1&&C.x("unfinished numeric value",e);let s=e.s.slice(t+2,e.p);return i&&(s=s.replaceAll("_","")),Yi(e,s,n,t)}function Yi(e,t,n,r){if(e.bi!==!0)e:{let o=parseInt(t,n);if(!Number.isSafeInteger(o)){if(e.bi)break e;C.x("integer value cannot be represented losslessly",e,r)}return o}return BigInt(n===10?t:(n===2?"0b":n===8?"0o":"0x")+t)}function Eu(e,t,n){let r=e.p++,o;if(!ie(t)||!ie(e.s.charCodeAt(e.p++))||!ie(e.s.charCodeAt(e.p++))||!ie(e.s.charCodeAt(e.p++)))return bn(e,e.p=r,t,0,n);if(e.p+=5,ie(e.s.charCodeAt(e.p++))||C.x("invalid date-time: date part is malformed",e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(o=!0,!ie(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let s=e.s.slice(r,e.p);return At(e,s,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58&&C.x("invalid date-time: time part is malformed",e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;ie(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let s=e.s.slice(r,++e.p);return At(e,s,1,o,r,"[+00:00]")}if(t===43||t===45){let s=e.s.slice(r,e.p+=6);return At(e,s,1,o,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let i=e.s.slice(r,e.p);return At(e,i,2,o,r)}function Tu(e,t,n){let r=e.p;if(!ie(t)||!ie(e.s.charCodeAt(++e.p)))return bn(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;ie(e.s.charCodeAt(++e.p)););let o=e.s.slice(r,e.p);return At(e,o,4,!1,r)}function At(e,t,n,r,o,i){if(e.ld){let s=new Ot(t,n,r);return s.isValid()||C.x("invalid date",e,o),s}try{switch(i&&(t+=i),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(s){C.x(s instanceof Error?s.message:""+s,e,o)}}var zr=L(()=>{Vr();Xr();Ve();qr();});function Nu(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&C.x("control characters are not allowed in comments",e)}}function pe(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;Nu(e)}}var Zr=L(()=>{Ve();});function kn(e,t=61){let n,r=0,o=[],i,s=e.s.charCodeAt(n=e.p);do{if(s===t)return r||C.x("unexpected end of key",e),r===1&&o.push(e.s.slice(i,e.p)),e.p++,o;s===46?(r||C.x("illegal empty bare key",e),r===1&&o.push(e.s.slice(i,e.p)),r=0):!r&&(s===34||s===39)?(s===e.s.charCodeAt(e.p+1)&&s===e.s.charCodeAt(e.p+2)&&C.x("illegal quoted key: multiline strings are not allowed",e),o.push(wn(e)),r=2,e.p--):s===32||s===9?r===1&&(o.push(e.s.slice(i,e.p)),r=2):r===2||s<48&&s!==45||s>57&&s<65||s>90&&s<97&&s!==95||s>122?C.x("illegal character in key",e):r||(r=1,i=e.p)}while(s=e.s.charCodeAt(++e.p));C.x("incomplete key-value: cannot find end of key",e,n)}function zi(e){let t=e.p++,n=Object.create(null),r=new Set,o;for(;e.p<e.s.length;){if(pe(e),(o=e.s.charCodeAt(e.p))===125)return e.p++,n;let i,s=n,a=!1,c=e.p,l=kn(e);for(let u=0;u<l.length;u++){u&&(s=a?s[i]:s[i]=Object.create(null)),i=l[u],(a=Object.hasOwn(s,i))&&(typeof s[i]!="object"||r.has(s[i]))&&C.x("trying to redefine an already defined value",e,c);let p=i==="__proto__";if(e.uk&&(p||i==="constructor")){s=e.uk!==1&&C.x("document contains an unsafe property",e,c);break}!a&&p&&Object.defineProperty(s,i,{enumerable:!0,configurable:!0,writable:!0})}a&&C.x("trying to redefine an already defined value",e,c),pe(e,!0,!0);let d=Et(e,125);if(s&&typeof(s[i]=d)=="object"&&r.add(d),pe(e),(o=e.s.charCodeAt(e.p++))===125)return n;o!==44&&C.x("expected comma or end of structure",e,e.p-1)}C.x("unfinished table",e,t)}function Xi(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(pe(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Et(e,93)),pe(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&C.x("expected comma or end of structure",e,e.p-1)}C.x("unfinished array",e,t)}var Xr=L(()=>{Vr();zr();Zr();Ve();});function Zi(e,t,n,r,o){let i=n,s=r,a,c=!1,l;for(let d=0;d<t.length;d++){if(d){if(i=c?i[a]:i[a]=Object.create(null),s=(l=s[a]).c,o===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=i.length-1;i=i[u],s=s[u].c}}if(a=t[d],(c=Object.hasOwn(i,a))&&s[a]?.t===0&&s[a]?.d)return null;if(!c){let u=a==="__proto__";if(e.uk&&(u||a==="constructor"))return!1;u&&(Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0})),s[a]={t:d<t.length-1&&o===2?3:o,d:!1,i:0,c:Object.create(null)}}}if(l=s[a],l.t!==o&&!(o===1&&l.t===3)||(o===2&&(l.d||(l.d=!0,i[a]=[]),i[a].push(i=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,o===1)i=c?i[a]:i[a]=Object.create(null);else if(o===0&&c)return null;return[a,i,l.c]}function Qi(e,t,n){(t===null||e.uk===2)&&C.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function Qr(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),o=Object.create(null),i,s=!1,a=r,c=o;for(e.charCodeAt(0)===65279&&n.p++,pe(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let l=e.charCodeAt(++n.p)===91;i=n.p+=+l,s=!1;let d=kn(n,93);l&&(e.charCodeAt(n.p)!==93&&C.x("expected end of table array declaration",n),n.p++);let u=Zi(n,d,r,o,l?2:1);u?(c=u[2],a=u[1]):(Qi(n,u,i),s=!0)}else{i=n.p;let l=kn(n),d=Zi(n,l,a,c,0);!d&&!s&&Qi(n,d,i),pe(n,!0,!0);let u=Et(n,void 0);d&&!s&&(d[1][d[0]]=u)}pe(n,!0),n.p<e.length&&(i=e.charCodeAt(n.p))!==10&&(i!==13||e.charCodeAt(n.p+1)!==10)&&C.x("each key-value declaration must be followed by an end-of-line",n),pe(n)}return r}var es=L(()=>{Xr();zr();Zr();Ve();});var Im,ts=L(()=>{Im=!!"".isWellFormed});var ns=L(()=>{es();ts();qr();Ve();});import{spawnSync as Pu}from"node:child_process";import{createHash as Lu,randomBytes as Mu,randomUUID as ju}from"node:crypto";import{accessSync as to,chmodSync as Fu,chownSync as Hu,closeSync as Du,constants as no,existsSync as Uu,fstatSync as Gu,lstatSync as as,mkdirSync as Ju,mkdtempSync as Bu,openSync as Wu,readFileSync as cs,readlinkSync as Vu,realpathSync as rs,renameSync as qu,rmSync as Pe,statSync as Sn,writeFileSync as ro}from"node:fs";import{tmpdir as Ku}from"node:os";import{basename as Yu,delimiter as zu,dirname as xn,join as st,resolve as Xu}from"node:path";function at(e){try{return{doc:Qr(e,{integersAsBigInt:"asNeeded"})}}catch(t){let n=(t instanceof Error?t.message:String(t)).split(`
|
|
36
|
+
`)[0].replace(/^Invalid TOML document:\s*/,"");return{problem:{line:t instanceof C?t.line:0,message:n}}}}function Qu(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!as(t).isSymbolicLink())return t;r=Vu(t)}catch{return t}t=Xu(xn(t),r)}throw new Error("its symlinks do not end anywhere")}function _n(e){let t;try{t=Qu(e)}catch(d){return{unreadable:d.message}}let n=null,r=null;try{let d=Wu(t,"r");try{r=Zu(Gu(d,{bigint:!0})),n=cs(d)}finally{Du(d)}}catch(d){let u=d.code;if(u!=="ENOENT")return{unreadable:`it cannot be read (${u??"error"})`};n=null,r=null}let o="";if(n)try{o=ed.decode(n)}catch{return{unreadable:"it is not UTF-8 text, which TOML requires"}}let i=o.startsWith("\uFEFF"),s=i?o.slice(1):o,a=s.indexOf(`
|
|
37
|
+
`),c=a>0&&s[a-1]==="\r"?`\r
|
|
38
|
+
`:`
|
|
39
|
+
`,l=n?at(s):{doc:{}};return{path:e,target:t,raw:n,identity:r,dangling:!n&&t!==e,text:s,bom:i,eol:c,doc:"doc"in l?l.doc:null,problem:"problem"in l?l.problem:null}}function he(e){return e===void 0?"undefined":e instanceof Date?`{"$date":${JSON.stringify(e.toISOString())}}`:typeof e=="bigint"?`{"$int":"${e}"}`:typeof e=="number"&&(!Number.isFinite(e)||Object.is(e,-0))?`{"$num":"${Object.is(e,-0)?"-0":String(e)}"}`:Array.isArray(e)?`[${e.map(he).join(",")}]`:V(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${he(e[t])}`).join(",")}}`:JSON.stringify(e)}function us(e,t,n=[]){return V(e)&&V(t)?[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>us(e[r],t[r],[...n,r])):he(e)===he(t)?[]:[{path:n,a:e,b:t}]}function Tt(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
|
|
40
|
+
`,n);if(r<0){t.push({content:e.slice(n),eol:""});break}let o=r>n&&e[r-1]==="\r";t.push({content:e.slice(n,o?r-1:r),eol:o?`\r
|
|
41
|
+
`:`
|
|
42
|
+
`}),n=r+1}return t}function ds(e,t){let n=e.filter((r,o)=>o!==t);return t===e.length-1&&!e[t].eol&&t>0&&(n[t-1]={...n[t-1],eol:""}),oo(n)}function sd(e,t){if(!e.doc)return null;let n=t[t.length-1],r=new RegExp(`(?:^|[\\s.{,])${Cn(n)}[ \\t]*=`),o=he(os(e.doc,t)),i=Tt(e.text);for(let[s,a]of i.entries()){if(!r.test(a.content))continue;let c=at(ds(i,s));if("doc"in c&&he(os(c.doc,t))!==o)return s+1}return null}function os(e,t){let n=e;for(let r of t){if(!V(n))return;n=n[r]}return n}function ad(e){let t=e.doc;if(!t)return[];let n=[],r=(o,i,s)=>{if(V(o))for(let a of["hooks","codex_hooks"])a in o&&n.push({key:a,value:o[a],profile:s,line:sd(e,[...i,a])})};if(r(t.features,["features"],null),V(t.profiles))for(let[o,i]of Object.entries(t.profiles))V(i)&&r(i.features,["profiles",o,"features"],o);return n}function cd(e){if(!e.doc)return{refused:"it does not parse as TOML"};if(!e.raw)return{text:`[features]
|
|
43
|
+
${z}
|
|
44
|
+
`,line:2,added:`[features]
|
|
45
|
+
${z}
|
|
46
|
+
`,shape:"new_file"};let t=he(td(e.doc)),n=d=>{let u=at(d);return"doc"in u&&he(u.doc)===t},r=Tt(e.text),o=(d,u,p)=>{let h=oo(r.slice(0,d+1)),f=oo(r.slice(d+1)),m=r[d].eol?u+r[d].eol:e.eol+u;return{text:h+m+f,line:d+2,added:m,shape:p}},i=[];if(V(e.doc.features)){for(let[d,u]of r.entries())rd.test(u.content)&&i.push(o(d,z,"under_header"));for(let[d,u]of r.entries())od.test(u.content)&&i.push(o(d,Nt,"dotted"))}let s=e.text,a=e.eol,c=s?/\n\s*\n$/.test(s)?`[features]${a}${z}${a}`:s.endsWith(`
|
|
47
|
+
`)?`${a}[features]${a}${z}${a}`:`${a}${a}[features]${a}${z}`:`[features]${a}${z}${a}`;i.push({text:s+c,line:nd(s+c.slice(0,c.indexOf(z)))+1,added:c,shape:"new_table"});for(let d of i)if(n(d.text))return d;let l=r.findIndex(d=>id.test(d.content));return l>=0?{inline:!0,refused:`Codex's features are an inline \`features = { \u2026 }\` table (line ${l+1}), which TOML does not let another line add to: add \`codex_hooks = true\` inside it yourself`}:{refused:"no place for the line keeps the rest of the file meaning what it means now: add `codex_hooks = true` under `[features]` yourself"}}function fs(e,t){if(!e.raw)return null;if(!e.doc)return Tt(e.text).some(c=>[z,Nt].includes(c.content.trim()))?{refused:`Codex can't load it (line ${e.problem?.line??"?"}: ${e.problem?.message??"invalid TOML"}), so Canary cannot tell its own line apart`}:null;let n=t&&t.file===e.target?t:null,r=e.text,o=e.doc,i=Tt(r),s=[];for(let c=i.length-1;c>=0;c--){let l=i[c].content.trim();if(l!==z&&l!==Nt)continue;let d=ds(i,c),u=at(d);if(!("doc"in u))continue;let p=us(o,u.doc);p.length!==1||p[0].path.join("\0")!=="features\0codex_hooks"||p[0].a!==!0||p[0].b!==void 0||(s.push(c+1),r=d,o=u.doc,i=Tt(r))}if(!s.length)return null;let a=!1;if(n?.added.includes("[features]")&&V(o.features)){let c=new Set([he(o),...Object.keys(o.features).length?[]:[he(Object.fromEntries(Object.entries(o).filter(([p])=>p!=="features")))]]),l=e.text.lastIndexOf(n.added),d=l<0?null:e.text.slice(0,l)+e.text.slice(l+n.added.length),u=d===null?null:at(d);d!==null&&u&&"doc"in u&&c.has(he(u.doc))&&(r=d,a=!0)}return{text:n?.created&&!r.trim()?null:r,lines:s.sort((c,l)=>c-l),header:a}}function hs(e){if(e.dangling)return"it is a symlink to a file that does not exist";if(e.raw){let t;try{t=Sn(e.target)}catch(n){return`it cannot be read (${n.code??"error"})`}if(t.nlink>1)return`it has ${t.nlink} hard links, and replacing it would split them apart`;if(typeof process.getuid=="function"&&t.uid!==process.getuid())return"it belongs to another user";try{to(e.target,no.W_OK)}catch{return"it is read-only"}}try{to(xn(e.target),no.W_OK)}catch{return`its folder (${xn(e.target)}) is read-only`}return null}function ld(e){let t;try{t=as(e.target,{bigint:!0})}catch(n){return n.code==="ENOENT"&&e.raw===null}if(e.raw===null||!e.identity||!t.isFile()||t.dev!==e.identity.dev||t.ino!==e.identity.ino||t.nlink!==1n)return!1;try{return cs(e.target).equals(e.raw)}catch{return!1}}function io(e,t,n){let r=hs(e);if(r)return{refused:r};let o=e.identity?e.identity.mode&4095:384,i=null;if(e.raw)try{Ju(n,{recursive:!0,mode:448}),i=st(n,`codex-config.toml.${new Date().toISOString().replace(/[:.]/g,"-")}.${Mu(3).toString("hex")}.bak`),ro(i,e.raw,{flag:"wx",mode:384})}catch(a){return{refused:`no backup of it could be kept in ${n} (${a.code??"error"})`}}let s=st(xn(e.target),`.${Yu(e.target)}.${ju()}.canary.tmp`);try{if(t!==null){if(ro(s,Buffer.from((e.bom?"\uFEFF":"")+t,"utf8"),{flag:"wx",mode:o}),e.identity&&Sn(s).gid!==e.identity.gid)try{Hu(s,-1,e.identity.gid)}catch{}Fu(s,o);let a=Sn(s);if(e.identity&&(a.gid!==e.identity.gid||(a.mode&4095)!==o))return Pe(s,{force:!0}),i&&Pe(i,{force:!0}),{refused:"its group or permissions could not be kept on a replacement"}}return ld(e)?(t===null?Pe(e.target):qu(s,e.target),{backup:i}):(Pe(s,{force:!0}),i&&Pe(i,{force:!0}),{refused:"it changed while Canary was editing it",changed:!0})}catch(a){Pe(s,{force:!0}),i&&Pe(i,{force:!0});let c=a.code;return{refused:c==="EACCES"||c==="EPERM"||c==="EROFS"?`its folder cannot be written (${c})`:`it cannot be written (${c??"error"})`}}}function so(e=process.env,t=process.platform){let n=[],r=t==="win32"?["codex.cmd","codex.exe","codex"]:["codex"];e:for(let o of(e.PATH??"").split(zu).filter(Boolean))for(let i of r){let s=st(o,i);try{if(to(s,no.X_OK),Sn(s).isFile()){n.push(s);break e}}catch{}}return t==="darwin"&&Uu(eo)&&!n.some(o=>ud(o,eo))&&n.push(eo),n}function ud(e,t){try{return rs(e)===rs(t)}catch{return e===t}}function ss(e,t,n){let r=`${e}\0${t?Lu("sha256").update(t).digest("hex"):"-"}`,o=is.get(r);if(o)return o;let i=Bu(st(Ku(),"canary-codex-")),s;try{t&&ro(st(i,"config.toml"),t,{mode:384});let a=process.platform==="win32"&&/\.(cmd|bat)$/i.test(e),c=Pu(a?`"${e}"`:e,["features","list"],{cwd:i,env:{...process.env,CODEX_HOME:i},encoding:"utf8",timeout:n,stdio:["ignore","pipe","pipe"],windowsHide:!0,shell:a}),l=/^(hooks|codex_hooks)\s.*?\s(true|false)\s*$/m.exec(c.stdout??"");s=c.error?{why:c.error.code==="ETIMEDOUT"?"it did not answer in time":c.error.message}:c.status!==0?{why:(c.stderr??"").trim().split(`
|
|
48
|
+
`)[0]||`it exited ${c.status}`}:l?{key:l[1],on:l[2]==="true"}:{why:"it lists no hooks feature"}}catch(a){s={why:a.message}}finally{Pe(i,{recursive:!0,force:!0})}return is.set(r,s),s}function fd(e,t,n){let r=e,o=n&&typeof n.profile=="string"&&V(n.profiles)?n.profiles[n.profile]:void 0;for(let i of[n?.features,V(o)?o.features:void 0])V(i)&&(typeof i.codex_hooks=="boolean"&&(r=i.codex_hooks),t==="hooks"&&typeof i.hooks=="boolean"&&(r=i.hooks));return r}function gs(e,t=dd){return({raw:n,doc:r})=>{let o={answers:[],unanswered:[]};for(let i of e){let s=ss(i,n,t);if("key"in s){o.answers.push({binary:i,...s,derived:!1});continue}let a=n?ss(i,null,t):s;"key"in a?o.answers.push({binary:i,key:a.key,on:fd(a.on,a.key,r),derived:!0}):o.unanswered.push({binary:i,why:s.why})}return o}}function ao(e,t){if("unreadable"in e)return{kind:"unreadable",why:e.unreadable};if(!e.doc)return{kind:"broken",problem:e.problem??{line:0,message:"invalid TOML"}};let{answers:n,unanswered:r}=t({raw:e.raw,doc:e.doc});if(n.length&&!r.length&&n.every(a=>a.on))return{kind:"on",answers:n};let o=ad(e).filter(a=>a.profile!==null||a.key==="codex_hooks"||a.value!==!0);if(o.length)return{kind:"person",settings:o,answers:n,unanswered:r};let i=cd(e);if("refused"in i)return{kind:"cannot",why:i.refused,answers:n,unanswered:r,...i.inline?{inline:!0}:{}};let s=hs(e);if(s)return{kind:"cannot",why:s,answers:n,unanswered:r,edit:i};if(n.length){let a=Buffer.from((e.bom?"\uFEFF":"")+i.text,"utf8"),c=t({raw:a,doc:at(i.text).doc}),l=(u,p)=>p.binary===u.binary&&(u.derived||!p.derived),d=n.filter(u=>!c.answers.some(p=>l(u,p)&&p.on));if(d.length)return{kind:"cannot",answers:n,unanswered:r,edit:i,why:c.answers.some(u=>l(d[0],u))?`Codex (${d[0].binary}) still reports its hooks off with the line added, so something outside this file switches them off`:`Codex (${d[0].binary}) could not load the file with the line added`}}return{kind:"edit",edit:i,answers:n,unanswered:r}}var ls,z,Nt,Zu,V,ed,td,oo,nd,Cn,rd,od,id,vn,ps,eo,dd,is,ms=L(()=>{"use strict";ns();ls="# added by canary",z=`codex_hooks = true ${ls}`,Nt=`features.codex_hooks = true ${ls}`,Zu=e=>({dev:e.dev,ino:e.ino,mode:Number(e.mode),uid:Number(e.uid),gid:Number(e.gid)}),V=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Date);ed=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});td=e=>({...e,features:{...V(e.features)?e.features:{},codex_hooks:!0}});oo=e=>e.map(t=>t.content+t.eol).join("");nd=e=>e.split(`
|
|
49
|
+
`).length-1,Cn=e=>`(?:${e}|"${e}"|'${e}')`,rd=new RegExp(`^[ \\t]*\\[[ \\t]*${Cn("features")}[ \\t]*\\][ \\t]*(?:#.*)?$`),od=new RegExp(`^[ \\t]*${Cn("features")}[ \\t]*\\.`),id=new RegExp(`^[ \\t]*${Cn("features")}[ \\t]*=[ \\t]*\\{`);vn=e=>`${e.line?`line ${e.line}`:"a line"}: \`${e.key} = ${typeof e.value=="string"?JSON.stringify(e.value):String(e.value)}\`${e.profile!==null?` (profile "${e.profile}")`:""}`;ps=e=>st(e,"backups");eo="/Applications/ChatGPT.app/Contents/Resources/codex";dd=3e3,is=new Map});import{accessSync as pd,constants as hd,existsSync as Mt,lstatSync as gd,readFileSync as $n,readlinkSync as md,renameSync as yd,rmSync as ys,statSync as _s,writeFileSync as wd}from"node:fs";import{randomUUID as bd}from"node:crypto";import{homedir as uo}from"node:os";import{delimiter as kd,dirname as co,join as ke,resolve as Sd}from"node:path";function On(e,t=process.env,n=process.platform){let r=n==="win32"?[e,...(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(o=>e+o.toLowerCase())]:[e];for(let o of(t.PATH??"").split(kd).filter(Boolean))for(let i of r)try{if(pd(ke(o,i),hd.X_OK),_s(ke(o,i)).isFile())return!0}catch{}return!1}function xd(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!gd(t).isSymbolicLink())return t;r=md(t)}catch{return t}t=Sd(co(t),r)}throw new Re("its symlinks do not end anywhere")}function In(e,t){for(let n=0;n<3;n++){let r;try{r=$n(e,"utf8")}catch(c){if(c.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(!Se(o))return{result:"refused",detail:"the file does not hold a JSON object"};try{if(!t(o))return{result:"unchanged"}}catch(c){if(c instanceof Re)return{result:"refused",detail:c.message};throw c}let i=r?/^([ \t]+)"/m.exec(r)?.[1]??" ":" ",s;try{s=xd(e)}catch(c){return{result:"refused",detail:c.message}}if(s!==e&&!Mt(co(s)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let a=ke(co(s),`.${bd()}.canary.tmp`);try{wd(a,JSON.stringify(o,null,i)+`
|
|
50
|
+
`,{flag:"wx",mode:r===null?384:_s(s).mode&511});let c;try{c=$n(e,"utf8")}catch{c=null}if(c!==r){ys(a,{force:!0});continue}return yd(a,s),{result:"written"}}catch(c){return ys(a,{force:!0}),{result:"refused",detail:`the file cannot be written (${c.code??"error"})`}}}return{result:"refused",detail:"the file kept changing while it was being edited"}}function Cd(e,t,n){for(let r of e){if(!Se(r))throw new Re(`its \`hooks.${t}\` list holds an entry that is not an object`);if(n&&r[n]!==void 0&&!(Array.isArray(r[n])&&r[n].every(Se)))throw new Re(`its \`hooks.${t}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Le(e,t,n,r="hooks"){if(e.hooks===void 0){if(!n)return null;e.hooks={}}if(!Se(e.hooks))throw new Re("its `hooks` entry is not an object");if(e.hooks[t]===void 0){if(!n)return null;e.hooks[t]=[]}if(!Array.isArray(e.hooks[t]))throw new Re(`its \`hooks.${t}\` entry is not a list`);return Cd(e.hooks[t],t,r),e.hooks[t]}function Cs(e,t){Se(e.hooks)&&(Array.isArray(e.hooks[t])&&!e.hooks[t].length&&delete e.hooks[t],Object.keys(e.hooks).length||delete e.hooks)}function vs(e){let t;try{t=JSON.parse($n(e,"utf8"))}catch(n){return n.code==="ENOENT"?{state:"missing"}:{state:"unreadable",detail:"the file cannot be read as JSON"}}return Se(t)?{doc:t}:{state:"unreadable",detail:"the file does not hold a JSON object"}}function $s(e){let t=_d(e.harness),n=fo(e.harness),r=()=>({matcher:e.matcher,hooks:[{type:"command",command:t,timeout:Rn}]}),o=c=>Se(c)&&Array.isArray(c.hooks)&&c.hooks.some(n),i=c=>{let l=c.filter(o);return l.length===1&&JSON.stringify(l[0])===JSON.stringify(r())},s=c=>{let l=Le(c,"PreToolUse",!1);if(!l)return!1;let d=!1;for(let u=l.length-1;u>=0;u--){let p=l[u];if(!Se(p)||!Array.isArray(p.hooks))continue;let h=p.hooks.filter(f=>!n(f));h.length!==p.hooks.length&&(d=!0,h.length?p.hooks=h:l.splice(u,1))}return d&&Cs(c,"PreToolUse"),d},a={harness:e.harness,file:e.file,summary:`a PreToolUse hook that runs \`${t}\` before shell and MCP tool calls (${Rn} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[r()]}},null,2)};return{detected:()=>Mt(e.dir),plan:()=>[a],install:()=>[{...a,...In(e.file,c=>i(Le(c,"PreToolUse",!0))?!1:(s(c),Le(c,"PreToolUse",!0).push(r()),!0))}],uninstall:()=>{if(!Mt(e.file))return[{...a,result:"unchanged"}];let c=In(e.file,s);return[{...a,...c.result==="written"?{result:"removed"}:c}]},status:()=>{let c=vs(e.file);if(!("doc"in c))return[{harness:e.harness,file:e.file,...c}];let l;try{l=Le(c.doc,"PreToolUse",!1)}catch(d){return[{harness:e.harness,file:e.file,state:"unreadable",detail:d.message}]}return l?.some(o)?e.disabledKey&&c.doc[e.disabledKey]===!0?[{harness:e.harness,file:e.file,state:"disabled",detail:`\`${e.disabledKey}\` is set, so no hooks run`}]:i(l)?[{harness:e.harness,file:e.file,state:"registered"}]:[{harness:e.harness,file:e.file,state:"modified",detail:"the entry differs from what `canary hooks install` writes; install again to restore it"}]:[{harness:e.harness,file:e.file,state:"missing"}]}}}function vd(e){let t=ke(e,"hooks.json"),n=fo("cursor"),r=()=>({command:"canary hook cursor",timeout:Rn}),o=a=>Pt.every(c=>{let l=(Le(a,c,!1,null)??[]).filter(n);return l.length===1&&JSON.stringify(l[0])===JSON.stringify(r())}),i=a=>{let c=!1;for(let l of Pt){let d=Le(a,l,!1,null);if(!d)continue;let u=d.filter(p=>!n(p));u.length!==d.length&&(c=!0,a.hooks[l]=u,Cs(a,l))}return c},s={harness:"cursor",file:t,summary:`a command that runs \`canary hook cursor\` before shell commands and MCP tool calls (${Rn} s limit)`,snippet:JSON.stringify({version:1,hooks:Object.fromEntries(Pt.map(a=>[a,[r()]]))},null,2)};return{detected:()=>Mt(e),plan:()=>[s],install:()=>[{...s,...In(t,a=>{if(a.version!==void 0&&a.version!==1)throw new Re(`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 c of Pt)Le(a,c,!0,null).push(r());return!0})}],uninstall:()=>{if(!Mt(t))return[{...s,result:"unchanged"}];let a=In(t,i);return[{...s,...a.result==="written"?{result:"removed"}:a}]},status:()=>{let a=vs(t);if(!("doc"in a))return[{harness:"cursor",file:t,...a}];try{return Pt.some(c=>(Le(a.doc,c,!1,null)??[]).some(n))?[o(a.doc)?{harness:"cursor",file:t,state:"registered"}:{harness:"cursor",file:t,state:"modified",detail:"the entries differ from what `canary hooks install` writes; install again to restore them"}]:[{harness:"cursor",file:t,state:"missing"}]}catch(c){return[{harness:"cursor",file:t,state:"unreadable",detail:c.message}]}}}}function Id(e=process.env){let t=e.CLAUDE_CONFIG_DIR||ke(uo(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...$s({harness:"claude",dir:t,file:ke(t,"settings.json"),matcher:$d,disabledKey:"disableAllHooks"})}}function Rd(e=process.env,t=process.platform){let[n]=so(e,t);return n===void 0?null:/[\s"']/.test(n)?`"${n}"`:n}function Ad(e,t,n){if("unreadable"in e||!e.doc)return null;let r=e.doc.hooks,o=V(r)&&V(r.state)?r.state[`${t}:pre_tool_use:${n}:0`]:void 0;return V(o)&&typeof o.trusted_hash=="string"}function xs(e){let t=e.settings.filter(n=>n.value!==!0);return t.length?`Codex's hooks are switched off in its config.toml (${t.map(vn).join("; ")}); the check runs once they are on`:e.settings.every(n=>n.profile!==null)?`Codex's hooks are set only in ${[...new Set(e.settings.map(n=>`profile "${n.profile}"`))].join(" and ")} of its config.toml (${e.settings.map(vn).join("; ")}); the check runs only where they are on`:e.answers.some(n=>!n.on)?`${Is(e.answers)} reports its hooks off although its config.toml switches them on (${e.settings.map(vn).join("; ")}), so a setting outside that file switches them off`:null}function Nd(e=process.env,t={}){let n=e.CODEX_HOME||ke(uo(),".codex"),r=ke(n,"hooks.json"),o=$s({harness:"codex",dir:n,file:r,matcher:".*"}),i=ke(n,"config.toml"),s=Od(Rd(e)),a=t.ask??gs(so(e)),c=fo("codex"),l=()=>ps(Z()),d=()=>{try{return JSON.parse($n(r,"utf8")).hooks.PreToolUse.findIndex(b=>Se(b)&&Array.isArray(b.hooks)&&b.hooks.some(c))}catch{return-1}},u=()=>{let y=_n(i);return{read:y,verdict:ao(y,a)}},p=()=>{try{return N().hooks?.codex??null}catch{return null}},h=y=>{try{K(b=>{let{codex:S,...x}=b.hooks??{};return{...b,hooks:y?{...x,codex:y}:x}})}catch{}},f=(y,b)=>({harness:"codex",file:i,summary:`the line \`${qe(y)}\` ${Ed(y)}${b?`, because ${Lt(b)}`:""}`,snippet:y.shape==="new_table"||y.shape==="new_file"?`[features]
|
|
51
|
+
${z}`:qe(y)}),m={harness:"codex",file:i,summary:`the line \`${z}\` under \`[features]\``,snippet:`[features]
|
|
52
|
+
${z}`},g={harness:"codex",file:i,summary:"`codex_hooks = true` inside the inline `features = { \u2026 }` table",snippet:"features = { \u2026, codex_hooks = true }"},k=(y,b)=>b.kind==="cannot"?{...b.edit?f(b.edit):b.inline?g:m,result:"refused",detail:`${b.why}; ${Lt(b)}`}:b.kind==="broken"?{...m,result:"refused",detail:Ss(y)}:b.kind==="unreadable"?{...m,result:"refused",detail:b.why}:null,v=()=>{for(let y=0;y<3;y++){let{read:b,verdict:S}=u();if(S.kind!=="edit")return k(b,S);let x=S.edit,I=io(b,x.text,l());if("backup"in I)return h({file:b.target,added:x.added,line:qe(x),at:new Date().toISOString(),...x.shape==="new_file"?{created:!0}:{},...I.backup?{backup:I.backup}:{}}),{...f(x,S),result:"written",detail:`line ${x.line} now reads \`${qe(x)}\`, because ${Lt(S)}`,edit:{line:x.line,text:qe(x),backup:I.backup,created:x.shape==="new_file"}};if(!I.changed)return{...f(x),result:"refused",detail:`${I.refused}; ${Lt(S)}`}}return{...m,result:"refused",detail:"it kept changing while Canary was editing it"}},w=()=>{let y=p(),b=y?.line??z;for(let S=0;S<3;S++){let x=_n(i);if("unreadable"in x)return y?{...m,result:"refused",detail:`${x.unreadable}: if it still holds \`${b}\`, take that line out yourself`}:null;let I=fs(x,y);if(!I)return y&&h(null),null;if("refused"in I)return{...m,result:"refused",detail:`${I.refused}: take \`${b}\` out of it yourself`};let q=io(x,I.text,l());if("backup"in q){h(null);let O=I.text===null,F=O?"deleted it: Canary had created it, and nothing else was in it":`took out line${I.lines.length===1?"":"s"} ${I.lines.join(", ")} (\`${b}\`${I.header?" and the `[features]` header Canary added with it":""})`;return{...m,result:"removed",detail:F,removed:{lines:I.lines,header:I.header,deleted:O,backup:q.backup}}}if(!q.changed)return{...m,result:"refused",detail:`${q.refused}: take \`${b}\` out of it yourself`}}return{...m,result:"refused",detail:"it kept changing while Canary was editing it"}};return{id:"codex",label:"Codex",byDefault:!0,afterInstall:ws(s),detected:o.detected,plan:()=>{let{verdict:y}=u();return y.kind==="edit"?[...o.plan(),f(y.edit,y)]:o.plan()},install:()=>{let{verdict:y}=u(),[b]=o.install();if(b.result==="refused")return[b];let S=y.kind==="person"?xs(y):null,x=v();return[S?{...b,detail:b.detail?`${b.detail}; ${S}`:S}:b,...x?[x]:[]]},uninstall:()=>{let[y]=o.uninstall();if(y.result==="refused")return[y];let b=w();return b?[y,b]:[y]},status:()=>{let[y]=o.status();if(y.state!=="registered")return[y];let b=_n(i),S="unreadable"in b?null:ao(b,a),x=S?S.kind==="broken"?Ss(b):S.kind==="person"?xs(S):S.kind==="edit"&&bs(S)?`Codex's hooks feature is off: ${Lt(S)} (\`${qe(S.edit)}\` ${lo(S.edit)} in its config.toml); \`canary hooks install\` adds it`:S.kind==="cannot"&&bs(S)?`Codex's hooks feature is off, and Canary cannot switch it on: ${S.why}${ks(S)}`:null:null;if(x)return[{...y,state:"disabled",detail:x}];let I=S?.kind==="edit"?`Codex before 0.124 also runs no hooks until \`${qe(S.edit)}\` is ${lo(S.edit)} in its config.toml, and it is not there: \`canary hooks install\` adds it.`:S?.kind==="cannot"?`Codex before 0.124 also runs no hooks until \`codex_hooks = true\` is in its config.toml, and Canary cannot add it: ${S.why}${ks(S)}.`:null,q=d();if(q<0)return[I?{...y,detail:I}:y];let O=Ad(b,r,q);if(O===!0)return[I?{...y,detail:I}:y];let F=[O===null?"Codex's config.toml could not be read, so whether the hook is trusted is unknown.":null,ws(s),I].filter(Boolean).join(" ");return[{...y,state:"untrusted",detail:F,pending:s}]}}}function Pd(e=process.env){let t=e.CURSOR_CONFIG_DIR||ke(uo(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...vd(t)}}var Se,Re,Rn,_d,fo,Pt,$d,Od,ws,qe,Is,Lt,bs,Ed,Td,lo,ks,Ss,jt,Rs=L(()=>{"use strict";ms();D();Se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Re=class extends Error{};Rn=10,_d=(e,t=process.platform)=>t==="win32"?`canary hook ${e}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${e}`,fo=e=>t=>Se(t)&&typeof t.command=="string"&&new RegExp(`^\\s*(?:command -v canary >/dev/null 2>&1 \\|\\| exit 0;\\s*)?(?:node\\s+)?["']?(?:[^"'\\s]*[\\\\/])?canary(?:\\.js)?["']?\\s+hook\\s+${e}\\s*$`).test(t.command);Pt=["beforeShellExecution","beforeMCPExecution"];$d="^(Bash|PowerShell|Monitor|mcp__.*)$";Od=e=>({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:e??"npm i -g @openai/codex && codex",after:'In Codex, choose "Review hooks", accept the Canary entry, then quit.'}),ws=e=>`${e.why} Run \`${e.command}\` in a terminal. ${e.after}`;qe=e=>e.shape==="dotted"?Nt:z,Is=e=>{let t=e.find(n=>!n.on)??e[0];return t?`your Codex (${t.binary})`:"Codex"},Lt=e=>e.answers.some(t=>!t.on)?`${Is(e.answers)} runs no hooks without it`:e.unanswered?.length?`the Codex at ${e.unanswered[0].binary} could not be asked (${e.unanswered[0].why}), and Codex before 0.124 runs no hooks without it`:"no Codex CLI could be asked here, and Codex before 0.124 runs no hooks without it",bs=e=>e.answers.some(t=>!t.on),Ed=e=>e.shape==="under_header"?`under \`[features]\`, line ${e.line}`:e.shape==="dotted"?`beside the other \`features.\` keys, line ${e.line}`:e.shape==="new_table"?`in a new \`[features]\` table at the end, line ${e.line}`:"in a new config.toml",Td=e=>e.shape==="dotted"?"features.codex_hooks = true":"codex_hooks = true",lo=e=>e.shape==="dotted"?"beside the other `features.` keys":e.shape==="under_header"?"under `[features]`":"in a `[features]` table",ks=e=>e.edit?`; add \`${Td(e.edit)}\` ${lo(e.edit)} yourself`:"",Ss=e=>`Codex can't load its config.toml (line ${e.problem?.line??"?"}: ${e.problem?.message??"invalid TOML"}), so it runs no hooks at all; fix that line`;jt=(e=process.env)=>[Id(e),Nd(e),Pd(e)]});var Ym,An,Ld,zm,Os=L(()=>{"use strict";Ym=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:e=>`canary verify: tree ${e}`}),An=e=>`tree:${e.slice(0,12)}`,Ld=[["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"]],zm=Ld.flatMap(([e,t])=>["-c",`${e}=${t}`])});import{createHash as Md}from"node:crypto";import{existsSync as jd,mkdirSync as po,readFileSync as ct,writeFileSync as En}from"node:fs";import{join as Oe}from"node:path";function lt(e){return Oe(e,".canary")}function Ts(e){let t=e.trim();if(!t)return null;if(!t.includes("://")){let n=t.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(t),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 Ft(e){let t=lt(e),n=Oe(t,".gitignore");try{let r=ct(n,"utf8").split(`
|
|
53
|
+
`).map(o=>o.trim()).filter(o=>o.length>0);if(r[r.length-1]==="*")return}catch{}try{po(t,{recursive:!0});let r="";try{r=ct(n,"utf8"),r&&!r.endsWith(`
|
|
40
54
|
`)&&(r+=`
|
|
41
|
-
`)}catch{}
|
|
42
|
-
`)}catch{}}function
|
|
43
|
-
`),
|
|
44
|
-
`}catch{}
|
|
45
|
-
`,{flag:"wx",mode:384});try{
|
|
46
|
-
`,{flag:"wx",mode:384}),
|
|
47
|
-
`,{flag:"wx",mode:384}),
|
|
48
|
-
`)||
|
|
49
|
-
`))
|
|
55
|
+
`)}catch{}En(n,`${r}*
|
|
56
|
+
`)}catch{}}function Me(e){let t=lt(e),n;try{n=ct(Oe(t,"setup.sh"),"utf8")}catch{throw new se("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 se("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(ct(Oe(t,"run.json"),"utf8"))}catch(a){throw new se("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let o=[],i={},s=Oe(t,"env.json");if(jd(s)){let a;try{a=JSON.parse(ct(s,"utf8"))}catch(l){throw new se("recipe_invalid",`Cannot read .canary/env.json: ${l instanceof Error?l.message:String(l)}`)}if(a===null||typeof a!="object"||Array.isArray(a))throw new se("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let c=a;o=Ps(c.manifest),i=Ls(c.values),Hd(o)}return{setupSh:n,runJson:r,envManifest:o,envValues:i}}function Ke(e){return Md("sha256").update(JSON.stringify([e.setupSh,e.runJson,e.envManifest,e.envValues])).digest("hex")}function ho(e,t){let n=e.filter(r=>r.neededAt==="boot").map(r=>r.name).filter(r=>!Object.prototype.hasOwnProperty.call(t,r)||t[r]==="");return{missing:[...new Set(n)]}}function Ps(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.name=="string"):[]}function Hd(e){for(let t of e){if(!As.has(String(t.class)))throw new se("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has unknown class "${String(t.class)}"`,`use one of: ${[...As].join(", ")}`);if(!Fd.has(String(t.neededAt)))throw new se("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has invalid neededAt "${String(t.neededAt)}"`,'use "boot" or "runtime"')}}function Ls(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Dd(e){try{let t=JSON.parse(ct(Oe(lt(e),"env.json"),"utf8"));return{manifest:Ps(t.manifest),values:Ls(t.values)}}catch{return{manifest:[],values:{}}}}function Ud(e,t){po(lt(e),{recursive:!0}),En(Oe(lt(e),"env.json"),JSON.stringify(t,null,2)+`
|
|
57
|
+
`),Ft(e)}function go(e,t){if(t.length===0)return;let n=Dd(e),r=new Map(n.manifest.map(o=>[o.name,o]));for(let o of t){n.values[o.name]=o.value;let i=r.get(o.name);if(i)o.class&&Es.has(o.class)&&!Es.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)}}Ud(e,n)}function Ms(e,t){let n=[],r=lt(e);if(po(r,{recursive:!0}),typeof t.setupSh=="string"&&t.setupSh.trim()&&(En(Oe(r,"setup.sh"),t.setupSh),n.push(".canary/setup.sh")),typeof t.runJson=="string"&&t.runJson.trim()){let i=t.runJson;try{i=JSON.stringify(JSON.parse(t.runJson),null,2)+`
|
|
58
|
+
`}catch{}En(Oe(r,"run.json"),i),n.push(".canary/run.json")}let o=Object.entries(t.envOverrides??{});return o.length>0&&(go(e,o.map(([i,s])=>({name:i,value:s,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),Ft(e),n}var se,Ns,As,Fd,Es,mo=L(()=>{"use strict";se=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="RecipeError"}};Ns=new Set(["github.com","ssh.github.com"]);As=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),Fd=new Set(["boot","runtime"]);Es=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as Gd}from"node:child_process";import{createHash as Hs,randomUUID as Nn}from"node:crypto";import{linkSync as Jd,lstatSync as Ds,mkdirSync as Pn,readdirSync as Bd,readFileSync as wo,realpathSync as Tn,renameSync as Us,rmSync as Ln,writeFileSync as bo}from"node:fs";import{basename as ko,dirname as Gs,isAbsolute as Wd,join as ae,relative as Vd,resolve as So,sep as qd}from"node:path";function Kd(e){let t=Ts(e);if(!(!t||!Ns.has(t.host.toLowerCase().replace(/:\d+$/,"")))&&!(!js.test(t.owner)||!js.test(t.name)))return`${t.owner}/${t.name}`}function dt(e=process.cwd()){let t={...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=>Gd("git",a,{cwd:e,env:t,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").replace(/\r?\n$/,""),r,o;try{r=Tn(n(["rev-parse","--show-toplevel"])),o=Tn(So(Tn(e),n(["rev-parse","--git-common-dir"])))}catch{throw new M("not_a_git_repository","Run this command inside the Git repository you want Canary to use.")}let i;try{i=Kd(n(["remote","get-url","origin"]))}catch{}if(i)return{root:r,commonDirectory:o,name:i,githubFullName:i};let s=ko(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:o,name:s}}function Yd(e){let t;try{t=new URL(e)}catch{throw new M("invalid_api_url","The Canary API URL is invalid.")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new M("invalid_api_url","The Canary API URL must be HTTP(S) without credentials, a query, or a fragment.");return t.href.replace(/\/+$/,"")}function Mn(e){try{return Tn(e)}catch(t){if(t.code!=="ENOENT")throw t;if(Ds(e,{throwIfNoEntry:!1})?.isSymbolicLink())throw new M("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=Gs(e);if(n===e)throw t;return ae(Mn(n),ko(e))}}function yo(e,t){let n=Vd(e,t);return n===""||!Wd(n)&&n!==".."&&!n.startsWith(`..${qd}`)}function ft(e,t){let n=Mn(t);if(!yo(e,n))throw new M("cache_outside_home","Something under CANARY_HOME/local-repositories links outside CANARY_HOME. Remove that link, then run the command again.");return n}function pt(e){if(!ut.test(e.userId)||!ut.test(e.workspaceId))throw new M("invalid_account_context","Sign in with canary login and select a workspace with canary workspace use <id>, then run the command again.");let t=dt(e.directory),n=Yd(e.apiUrl),r=Mn(So(Z())),o=ko(t.commonDirectory)===".git"?Gs(t.commonDirectory):t.commonDirectory,i=Hs("sha256").update(JSON.stringify([Ht,n,e.userId,e.workspaceId,t.githubFullName?`github:${t.githubFullName.toLowerCase()}`:t.commonDirectory])).digest("hex"),s=ae(r,"local-repositories"),a=ft(s,ae(s,i));if([t.root,t.commonDirectory,o].some(c=>yo(c,r)||yo(c,a)))throw new M("cache_inside_checkout","CANARY_HOME is inside this repository. Point it at a directory outside the checkout, then run the command again.");return{...t,apiUrl:n,scope:i,cacheRoot:s,cacheDirectory:a}}function Fs(e,t){let n=ft(e.cacheRoot,ae(e.cacheDirectory,t)),r;try{r=wo(n,"utf8")}catch(s){if(s.code==="ENOENT")return null;throw new M("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=t==="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!==Ht||o.scope!==e.scope||typeof o.localKey!="string"||!ut.test(o.localKey)||t==="repository.json"&&(typeof o.repositoryId!="string"||!ut.test(o.repositoryId)))throw new M("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 Ye(e){let t=Fs(e,"identity.json"),n=Fs(e,"repository.json");if(!t&&!n)return null;if(!t||n&&n.localKey!==t.localKey)throw new M("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:t.localKey,...n?{repositoryId:n.repositoryId}:{}}}function xo(e,t,n){Pn(e.cacheDirectory,{recursive:!0,mode:448});let r=ae(e.cacheDirectory,`${t}.${Nn()}.tmp`);try{bo(r,JSON.stringify({version:Ht,scope:e.scope,...n})+`
|
|
59
|
+
`,{flag:"wx",mode:384});try{Jd(r,ae(e.cacheDirectory,t))}catch(o){if(o.code!=="EEXIST")throw o}}finally{Ln(r,{force:!0})}}function Js(e,t){Pn(e.cacheDirectory,{recursive:!0,mode:448});let n=ae(e.cacheDirectory,`repository.json.${Nn()}.tmp`);bo(n,JSON.stringify({version:Ht,scope:e.scope,...t})+`
|
|
60
|
+
`,{flag:"wx",mode:384}),Us(n,ae(e.cacheDirectory,"repository.json"))}function Bs(e){return Ye(pt(e))}function jn(e,t){let n=pt(e),r=Ye(n);!r?.repositoryId||r.repositoryId===t||Js(n,{localKey:r.localKey,repositoryId:t})}function ge(e,t){if(!/^[a-z0-9-]+\.json(?:\.gz)?$/.test(t))throw new M("invalid_receipt_name","Invalid cache file name.");let n=pt(e);return Pn(n.cacheDirectory,{recursive:!0,mode:448}),ft(n.cacheRoot,ae(n.cacheDirectory,t))}function zd(e){return Ws(pt(e))}function Ws(e){let t=Ye(e);return t||(xo(e,"identity.json",{localKey:Nn()}),Ye(e))}function Xd(e){try{let t=JSON.parse(wo(ft(e.cacheRoot,ae(e.cacheDirectory,_o)),"utf8"));return t.version===1&&t.checkout===Co(e.githubFullName)}catch{return!1}}function Zd(e){Pn(e.cacheDirectory,{recursive:!0,mode:448});let t=ft(e.cacheRoot,ae(e.cacheDirectory,_o)),n=`${t}.${Nn()}.tmp`;try{bo(n,JSON.stringify({version:1,at:new Date().toISOString(),checkout:Co(e.githubFullName)})+`
|
|
61
|
+
`,{flag:"wx",mode:384}),Us(n,t)}finally{Ln(n,{force:!0})}}async function Vs(e,t){let n=pt(e),r=Ye(n);if(r?.repositoryId)return r;let{githubFullName:o}=n;if(!o||Xd({...n,githubFullName:o}))return null;let i=await t(o);if(!i)return null;if("notConnected"in i)return Zd({...n,githubFullName:o}),null;if(!ut.test(i.repositoryId))return null;let s=Ws(n);return s.repositoryId||xo(n,"repository.json",{localKey:s.localKey,repositoryId:i.repositoryId}),Ye(n)}function qs(){let e=ae(Mn(So(Z())),"local-repositories"),t=ft(e,e),n;try{n=Bd(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}return n.map(r=>ae(t,r,_o)).filter(r=>Ds(r,{throwIfNoEntry:!1})?.isFile())}function Fn(){try{for(let e of qs())Ln(e,{force:!0})}catch{}}function Dt(e){try{let t=qs();if(!t.length)return;let{githubFullName:n}=dt(e??process.cwd());if(!n)return;let r=Co(n);for(let o of t)try{JSON.parse(wo(o,"utf8")).checkout===r&&Ln(o,{force:!0})}catch{}}catch{}}function Qd(e,t,n,r){let o=e,i=n.githubFullName?"github":"local";if(!o||typeof o.repositoryId!="string"||!ut.test(o.repositoryId)||o.provider!==i||t.repositoryId&&o.repositoryId!==t.repositoryId&&i!=="github"||(i==="local"?o.localKey!==t.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 M("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 Ut(e,t=R){if(!e.token)throw new M("not_logged_in","Run canary login first.");let n=pt(e),r=zd(e),o={token:e.token,baseUrl:n.apiUrl},i=r.repositoryId?await t(`/api/v1/cli/local-repositories/${r.repositoryId}?workspaceId=${encodeURIComponent(e.workspaceId)}`,o):await t("/api/v1/cli/local-repositories",{...o,method:"POST",body:{workspaceId:e.workspaceId,localKey:r.localKey,name:n.name,...n.githubFullName?{githubFullName:n.githubFullName}:{}}}),s=Qd(i,r,n,e.workspaceId);r.repositoryId&&r.repositoryId!==s.repositoryId?Js(n,{localKey:r.localKey,repositoryId:s.repositoryId}):xo(n,"repository.json",{localKey:r.localKey,repositoryId:s.repositoryId});let a=Ye(n);if(a?.repositoryId!==s.repositoryId||a.localKey!==r.localKey)throw new M("binding_conflict","Another canary process registered this repository at the same time. Run the command again.");return s}var ut,Ht,js,M,_o,Co,ne=L(()=>{"use strict";Y();D();mo();ut=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ht=2,js=/^[A-Za-z0-9_.-]+$/,M=class extends Error{constructor(n,r){super(r);this.code=n;this.name="LocalRepositoryError"}};_o="not-connected.json",Co=e=>Hs("sha256").update(JSON.stringify([Ht,`github:${e.toLowerCase()}`])).digest("hex")});async function Gt(e,t,n=W()){let r=N().team?.id;if(!r)throw new M("workspace_selection_required","Select a workspace with canary workspace list and canary workspace use <id>, then run the command again.");let o=await R("/api/v1/cli/auth/whoami",{token:t,baseUrl:n});if(!o?.user?.id)throw new M("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:e}}async function Hn(e,t,n){let r=Bs(e);if(!r?.repositoryId)return;let o=await R(`/api/v1/cli/local-repositories/${r.repositoryId}/status?workspaceId=${encodeURIComponent(e.workspaceId)}`,{token:t,baseUrl:e.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 M("invalid_readiness_response","Canary returned an unexpected answer about this repository's setup. Run the command again.");return o.repositoryId!==r.repositoryId&&jn(e,o.repositoryId),o}function Ks(e=process.cwd()){try{return dt(e).name}catch{return}}var Dn=L(()=>{"use strict";Y();D();ne()});import{spawn as ef}from"node:child_process";import{createHash as Oo}from"node:crypto";import{constants as Ys}from"node:fs";import{lstat as tf,mkdir as Xs,mkdtemp as Zs,open as Qs,readFile as nf,readdir as rf,readlink as of,realpath as Jt,rm as ea,writeFile as sf}from"node:fs/promises";import{tmpdir as ta}from"node:os";import{basename as af,isAbsolute as cf,join as me,relative as lf,resolve as na,sep as uf}from"node:path";import{promisify as df}from"node:util";import{deflate as ff}from"node:zlib";function Ao(e,t){let n=e.split("/");(!e||Buffer.byteLength(e)>t.maxPathBytes||n.length>t.maxDepth||n.some(r=>!r||Buffer.byteLength(r)>255||r==="."||r===".."||oa(r)||r.includes("\0")||r.includes("\\")))&&$("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(e)}.`)}function gf(e){return{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")||!e&&["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",...e?{GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"}:{}}}function ia(e,t){return Wt(e).map(n=>{let r=n.indexOf(" "),[o,i,s]=n.slice(0,r).split(" ");return r<0||!(t?vo.test(i):vo.test(s))?$("git_source_error","Git returned an invalid source entry."):(t&&s!=="0"&&$("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(r+1),mode:o,oid:t?i:s})})}function gt(e){return(e??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function zs(e,t){let n=await e.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await $o(e),o={headSha:n,branch:r,baseRef:null,baseSha:null,baselineMode:"whole-project"};if(t!==void 0){(!t||t.startsWith("-")||t.length>1024||/[\x00-\x1f\x7f]/.test(t))&&$("invalid_base","--base must name a local Git commit or ref.");let a=await e.text(["rev-parse","--verify","--quiet",`${t}^{commit}`],!0);return vo.test(a)||$("invalid_base",`--base ${JSON.stringify(t)} is not a local commit or ref. Canary does not fetch; pass one that exists locally.`),{...o,baseRef:t,baseSha:a,baselineMode:"explicit"}}if(!n)return o;let i=await e.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(c=>c!==r).map(c=>`refs/heads/${c}`)]){for(let c of[...new Set(a.filter(Boolean))]){let l=await e.text(["rev-parse","--verify","--quiet",`${c}^{commit}`],!0);if(!l)continue;let d=await e.text(["merge-base",n,l],!0);if(!d)continue;let u=Number(await e.text(["rev-list","--count",`${d}..${n}`]));(!s||u<s.distance)&&(s={ref:c,base:d,distance:u})}if(s)break}return s?{...o,baseRef:s.ref,baseSha:s.base,baselineMode:"merge-base"}:o}async function Io(e){return new Set(Wt(await e.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function ze(e,t,n){if(!t.length)return;let r=Wt(await e.run(["check-attr",...n?["--cached"]:[],"-z","--stdin","filter"],{input:`${t.join("\0")}\0`}));for(let o=0;o<r.length;o+=3)r[o+2]==="lfs"&&$("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[o])}. Remove the LFS attribute for it, or ignore the file.`)}function yf(e,t){(e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
|
|
62
|
+
`)||e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
|
|
63
|
+
`))&&$("unsupported_lfs",`${JSON.stringify(t)} is a Git LFS pointer. Canary needs the real file contents.`)}function Ro(e,t){(e.length>t.maxTreeFiles||e.reduce((i,s)=>i+s.size,0)>t.maxTreeBytes)&&$("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 e){Ao(i.path,t),i.link!==void 0&&o.set(i.path,i.link);let s=i.path.split("/");for(let a=1;a<=s.length;a++){let c=s.slice(0,a).join("/"),l=c.normalize("NFC").toLowerCase();n.has(l)&&n.get(l)!==c&&$("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(c)}.`),n.set(l,c);let d=a<s.length;r.has(c)&&r.get(c)!==d&&$("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(c)}.`),r.set(c,d)}}[...r.values()].filter(Boolean).length+1>t.maxObjects&&$("snapshot_limit","This repository has too many directories to upload.");for(let[i,s]of o){(!s||Buffer.byteLength(s)>t.maxSymlinkBytes||s.startsWith("/")||s.includes("\0")||s.includes("\\")||/^[a-z]:/i.test(s))&&$("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(i)}.`);let a=s.split("/"),c=i.split("/").slice(0,-1),l=0;for(;a.length;){let d=a.shift();if(!d||d===".")continue;if(d===".."){c.length||$("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(i)}.`),c.pop();continue}oa(d)&&$("unsafe_symlink",`Symlink enters Git metadata: ${JSON.stringify(i)}.`),c.push(d);let u=n.get(c.join("/").normalize("NFC").toLowerCase());if(u!==void 0&&o.has(u)){++l>t.maxDepth&&$("unsafe_symlink",`Symlink cycle or excessive chain depth at ${JSON.stringify(i)}.`);let p=o.get(u);(p.startsWith("/")||p.includes("\\")||/^[a-z]:/i.test(p))&&$("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(i)}.`),c.pop(),a.unshift(...p.split("/"))}a.length+c.length>t.maxPathBytes&&$("unsafe_symlink","Symlink expansion exceeds the source limit.")}}}async function Bn(e,t){let n=new Map;for(let o of e){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"?"/":"")))),t.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 sa(e,t){let n=t.split("/");for(let r=1;r<=n.length;r++)try{let o=await tf(me(e,...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 wf(e,t,n,r){let o=await sa(e,t);if(n.set(t,o?ht(o):null),!o||o.isDirectory())return null;if(!o.isFile()&&!o.isSymbolicLink()&&$("unsupported_file",`This is not a regular file or symlink and cannot be uploaded: ${JSON.stringify(t)}.`),o.size>(o.isSymbolicLink()?r.maxSymlinkBytes:r.maxObjectBytes)&&$("snapshot_limit",`This file is too large to upload: ${JSON.stringify(t)}.`),o.isSymbolicLink())return{data:await of(me(e,t),{encoding:"buffer"}),mode:"120000"};let i=await Qs(me(e,t),Ys.O_RDONLY|Ys.O_NOFOLLOW);try{ht(await i.stat())!==ht(o)&&$("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 l=await i.read(s,a,s.length-a);if(!l.bytesRead)break;a+=l.bytesRead}return(a!==o.size||ht(await i.stat())!==ht(o))&&$("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 bf(e,t,n,r,o){let i=Buffer.from(`# v2 git bundle
|
|
50
64
|
${n} refs/canary/base
|
|
51
65
|
${r} refs/canary/head
|
|
52
66
|
|
|
53
|
-
`),s=await
|
|
54
|
-
`);for await(let
|
|
55
|
-
`).some(
|
|
56
|
-
`).some(
|
|
57
|
-
author ${
|
|
58
|
-
committer ${
|
|
67
|
+
`),s=await Qs(t,"wx",384);try{let a=e.child(["pack-objects","--stdout","--revs","--no-reuse-delta","--no-reuse-object","--window=0","--threads=1","--compression=6"]),c=Oo("sha256"),l=0,d="";a.stderr.on("data",h=>{d.length<8192&&(d+=h.toString())}),a.stdin.on("error",()=>{});let u=new Promise((h,f)=>{a.on("close",h),a.on("error",f)});u.catch(()=>{});let p=async h=>{l+=h.length,l>o.maxBundleBytes&&$("snapshot_limit","This repository is too large to upload, even compressed."),c.update(h),await s.writeFile(h)};try{await p(i),a.stdin.end(`${r}
|
|
68
|
+
`);for await(let h of a.stdout)await p(h);return await u!==0&&$("git_source_error",`Cannot package source: ${d.trim()}`),{bytes:l,sha256:c.digest("hex")}}finally{a.kill(),await u.catch(()=>{})}}finally{await s.close()}}function aa(e){let t={...Bt,...e};for(let[n,r]of Object.entries(t))(!Object.hasOwn(Bt,n)||!Number.isSafeInteger(r)||r<=0||r>Bt[n])&&$("invalid_limit",`Invalid source snapshot limit ${n}.`);return t}async function ca(e,t){let n=await Jt(e),r=new Xe(n,t),o;try{o=await Jt(await r.text(["rev-parse","--show-toplevel"]))}catch(c){if(t?.aborted)throw c;return $("not_a_git_repository","Run this command inside a Git repository.")}let i=new Xe(o,t),s=await Jt(na(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(`
|
|
69
|
+
`).some(c=>/^extensions\.objectformat\s+(?!sha1$)/i.test(c))&&$("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(a.split(`
|
|
70
|
+
`).some(c=>/^extensions\.partialclone\s/i.test(c)||/^remote\..*\.promisor(?:\s|$)/i.test(c)&&!/\s(false|no|off|0)$/i.test(c))||(await rf(me(s,"objects","pack")).catch(()=>[])).some(c=>c.endsWith(".promisor")))&&$("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 Wn(e){let t=ia(await e.run(["ls-files","--stage","-z"]),!0),n=await Io(e),r=t.filter(s=>ua(s,n)),o=Wt(await e.run(["ls-files","--others","--exclude-standard","-z"])).filter(s=>!la(s)),i=new Set(Wt(await e.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 da(e,t){let n=na(t,await e.text(["rev-parse","--git-path","index"]));return async()=>{try{return Oo("sha256").update(await nf(n)).digest("hex")}catch(r){if(r.code==="ENOENT")return"missing";throw r}}}function fa(e,t){for(let n of e)Ao(n.path,t),n.mode==="160000"&&$("unsupported_submodule",`Submodules cannot be uploaded: ${JSON.stringify(n.path)}.`),["100644","100755","120000"].includes(n.mode)||$("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function pa(e,t){for(let n of e)n.endsWith("/")&&$("unsupported_submodule",`Nested Git repositories cannot be uploaded: ${JSON.stringify(n)}.`),Ao(n,t)}function ha(e,t){let n=new Map;return async(r,o,i)=>{yf(o,r.path);let s=await e.put("blob",o);r.oid&&r.oid!==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>t.maxTreeBytes&&$("snapshot_limit","This repository has too many bytes to upload."),i.push({...r,oid:s,size:o.length,...r.mode==="120000"?{link:ra(o)}:{}})}}async function ga(e){let{root:t,current:n,trustFileMode:r,limits:o,stamps:i,capture:s,out:a}=e,c=new Map(n.tracked.map(l=>[l.path,l]));for(let l of n.paths){e.signal?.throwIfAborted();let d=await wf(t,l,i,o);if(d){let u=c.get(l),p=!r&&d.mode!=="120000"&&u&&["100644","100755"].includes(u.mode)?u.mode:d.mode;await s({path:l,mode:p,oid:""},d.data,a)}else if(i.get(l)===null&&n.skip.has(l)){let u=c.get(l);await s(u,await e.blob(u.oid),a)}}}async function ma(e,t){for(let[n,r]of t){let o=await sa(e,n);(o?ht(o):null)!==r&&$("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function qt(e,t={}){let n=aa(t.limits),{root:r,common:o,git:i}=await ca(e,t.signal),s=await Jt(ta());(Gn(r,s)||Gn(o,s))&&$("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Zs(me(s,"canary-source-")),c,l=()=>ea(a,{recursive:!0,force:!0});try{let d=await zs(i,t.baseRef),u=await da(i,r),p=await u(),h=new Xe(r,t.signal,!1,{GIT_INDEX_FILE:me(a,"baseline-index")});await h.run(["read-tree",d.baseSha??"--empty"]);let f=d.baseSha?ia(await i.run(["ls-tree","-r","-z","--full-tree",d.baseSha]),!1):[],m=await Io(h),g=f.filter(T=>ua(T,m)),k=await Wn(i),v=await i.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(g.length>n.maxTreeFiles||k.paths.length>n.maxTreeFiles)&&$("snapshot_limit","This repository has too many files to upload."),fa([...g,...k.tracked],n),pa(k.paths,n),await ze(h,g.map(T=>T.path),!0),await ze(i,k.paths,!1);let w=me(a,"repository.git");await Xs(w);let y=new Xe(w,t.signal,!0);await y.run(["init","--bare","--quiet","--template="]);let b=new Vt(w,n,t.signal);c=new Jn(i,n);let S=[],x=[],I=ha(b,n),q=c;for(let T of g)await I(T,await c.get(T.oid),S);let O=new Map;await ga({root:r,current:k,trustFileMode:v,limits:n,signal:t.signal,stamps:O,capture:I,blob:T=>q.get(T),out:x}),Ro(S,n),Ro(x,n);let F=await Bn(S,b),Ce=await Bn(x,b);for(let[T,fe]of[[F,S],[Ce,x]])await y.run(["read-tree",T]),await ze(y,fe.map(te=>te.path),!0);let vt=await b.put("commit",Buffer.from(`tree ${F}
|
|
71
|
+
author ${Un}
|
|
72
|
+
committer ${Un}
|
|
59
73
|
|
|
60
74
|
Canary snapshot baseline
|
|
61
|
-
`)),
|
|
62
|
-
parent ${
|
|
63
|
-
author ${
|
|
64
|
-
committer ${
|
|
75
|
+
`)),un=await b.put("commit",Buffer.from(`tree ${Ce}
|
|
76
|
+
parent ${vt}
|
|
77
|
+
author ${Un}
|
|
78
|
+
committer ${Un}
|
|
65
79
|
|
|
66
80
|
Canary snapshot current
|
|
67
|
-
`)),
|
|
81
|
+
`)),oe=me(a,"source.bundle"),ve=await bf(y,oe,vt,un,n),ye=await Wn(i);(p!==await u()||JSON.stringify(k.paths)!==JSON.stringify(ye.paths)||JSON.stringify([...m].sort())!==JSON.stringify([...await Io(h)].sort())||JSON.stringify(d)!==JSON.stringify(await zs(i,t.baseRef)))&&$("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await ma(r,O),await ze(h,g.map(T=>T.path),!0),await ze(i,k.paths,!1);let we=new Map(S.map(T=>[T.path,T])),ee=new Map(x.map(T=>[T.path,T])),be=[];for(let T of[...new Set([...we.keys(),...ee.keys()])].sort()){let fe=we.get(T),te=ee.get(T);fe?te?(fe.oid!==te.oid||fe.mode!==te.mode)&&be.push({path:T,status:fe.mode==="120000"!=(te.mode==="120000")?"T":"M"}):be.push({path:T,status:"D"}):be.push({path:T,status:"A"})}await c.close(),c=void 0;let De=x.map(T=>({path:T.path,mode:T.mode,oid:T.oid}));return{bundlePath:oe,manifest:{kind:"local_snapshot",version:2,...ve,baseTreeHash:F,treeHash:Ce,baseSha:vt,headSha:un,provenance:d},files:be,entries:De,dispose:l}}catch(d){throw await c?.close(),await l(),d}}async function kf(e,t,n,r,o,i){let s=await Jt(ta());(Gn(e,s)||Gn(t,s))&&$("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Zs(me(s,"canary-identity-"));try{let c=new Xe(a,i,!0);await c.run(["init","--bare","--quiet","--template="]);let l=new Vt(a,o,i);for(let d of r.values())await l.put("blob",d);await c.run(["read-tree",await Bn(n,l)]),await ze(c,n.map(d=>d.path),!0)}finally{await ea(a,{recursive:!0,force:!0})}}async function Vn(e,t={}){let n=aa(t.limits),{root:r,common:o,git:i}=await ca(e,t.signal),s;try{let a=await $o(i),c=await da(i,r),l=await c(),d=await Wn(i),u=await i.text(["config","--bool","--get","core.fileMode"],!0)!=="false";d.paths.length>n.maxTreeFiles&&$("snapshot_limit","This repository has too many files to upload."),fa(d.tracked,n),pa(d.paths,n),await ze(i,d.paths,!1);let p=new Vt(null,n,t.signal),h=[],f=new Map,m=new Map,g=ha(p,n),k=(y,b,S)=>(af(y.path)===".gitattributes"&&m.set(y.path,b),g(y,b,S));await ga({root:r,current:d,trustFileMode:u,limits:n,signal:t.signal,stamps:f,capture:k,blob:y=>(s??=new Jn(i,n)).get(y),out:h}),Ro(h,n);let v=await Bn(h,p);[...m.values()].some(y=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(y.toString("utf8")))&&await kf(r,o,h,m,n,t.signal);let w=await Wn(i);return(l!==await c()||JSON.stringify(d.paths)!==JSON.stringify(w.paths)||a!==await $o(i))&&$("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await ma(r,f),{root:r,treeHash:v,branch:a,files:h.map(y=>({path:y.path,mode:y.mode,oid:y.oid}))}}finally{await s?.close()}}var Bt,ce,$,pf,hf,vo,Un,Gn,ra,Wt,oa,mf,Xe,$o,Jn,Vt,ht,la,ua,mt=L(()=>{"use strict";Bt={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},ce=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="SourceSnapshotError"}},$=(e,t)=>{throw new ce(e,t)},pf=df(ff),hf=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),vo=/^[a-f0-9]{40}$/,Un="Canary Snapshot <snapshot@runcanary.ai> 0 +0000",Gn=(e,t)=>{let n=lf(e,t);return n===""||!n.startsWith(`..${uf}`)&&n!==".."&&!cf(n)},ra=e=>{try{return hf.decode(e)}catch{return $("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},Wt=e=>e.length?ra(e).split("\0").filter(Boolean):[],oa=e=>{let t=e.normalize("NFC").replace(/[\u200c-\u200f\u202a-\u202e\u206a-\u206f\ufeff]/g,"").toLowerCase().replace(/[ .]+$/g,"");return t===".git"||t.startsWith(".git:")||/^git~[0-9]+(?:\.|$)/.test(t)};mf=["-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"],Xe=class{constructor(t,n,r=!1,o={}){this.cwd=t;this.signal=n;this.isolated=r;this.extra=o}child(t){return this.signal?.throwIfAborted(),ef("git",[...mf,...t],{cwd:this.cwd,env:{...gf(this.isolated),...this.extra},signal:this.signal,stdio:"pipe"})}async run(t,n={}){let r=this.child(t),o=[],i=0,s="",a;r.on("error",l=>{a=l}),r.stdout.on("data",l=>{i+=l.length,i>(n.maxBytes??256*1024*1024)?(a=new ce("snapshot_limit","This repository's Git metadata is too large to upload."),r.kill()):o.push(l)}),r.stderr.on("data",l=>{s.length<8192&&(s+=l.toString("utf8"))}),r.stdin.on("error",()=>{}),r.stdin.end(n.input);let c=await new Promise(l=>r.on("close",l));if(a)throw a;return c!==0&&!(n.optional&&c===1)&&$("git_source_error",`Cannot read local Git source: ${s.trim()||`git ${t[0]} failed`}`),c===1?Buffer.alloc(0):Buffer.concat(o)}async text(t,n=!1){return(await this.run(t,{optional:n})).toString("utf8").trim()}};$o=async e=>await e.text(["symbolic-ref","--quiet","--short","HEAD"],!0)||null;Jn=class{constructor(t,n){this.limits=n;this.child=t.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(t){let n=[],r=t;for(;r;){if(!this.pending.length){let i=await this.iterator.next();if(i.done)throw this.error??new ce("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,t)}async get(t){this.child.stdin.write(`${t}
|
|
68
82
|
`);let n="";for(;!n.endsWith(`
|
|
69
|
-
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[r,o,i]=n.trim().split(" "),s=Number(i);(r!==
|
|
70
|
-
`,{flag:"wx",mode:384}),
|
|
71
|
-
`,{flag:"wx",mode:384}),
|
|
72
|
-
`);let n=[
|
|
73
|
-
(${
|
|
74
|
-
${
|
|
75
|
-
`)}function
|
|
76
|
-
fix: ${
|
|
77
|
-
run: ${
|
|
78
|
-
${
|
|
79
|
-
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${
|
|
80
|
-
`)}function
|
|
81
|
-
${
|
|
82
|
-
`));return}if(
|
|
83
|
-
Canary added its push check to ${
|
|
84
|
-
${
|
|
85
|
-
${
|
|
83
|
+
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[r,o,i]=n.trim().split(" "),s=Number(i);(r!==t||o!=="blob"||!Number.isSafeInteger(s)||s<0)&&$("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&&$("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&&$("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(t=>this.child.on("close",()=>t())))}},Vt=class{constructor(t,n,r){this.directory=t;this.limits=n;this.signal=r}sizes=new Map;expanded=0;async put(t,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&$("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.from(`${t} ${n.length}\0`),o=Oo("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)&&$("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=me(this.directory,"objects",o.slice(0,2));await Xs(i,{recursive:!0}),await sf(me(i,o.slice(2)),await pf(Buffer.concat([r,n]),{level:6}),{mode:384,flag:"wx"})}return o}};ht=e=>`${e.dev}:${e.ino}:${e.mode}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`;la=e=>e.split("/").some(t=>t.toLowerCase()===".git"),ua=(e,t)=>!t.has(e.path)&&!la(e.path)});import{randomUUID as Sf}from"node:crypto";import{readFileSync as xf,renameSync as _f,rmSync as ya,writeFileSync as Cf}from"node:fs";async function Kt(e,t,n={}){try{await R("/api/v1/cli/events",{method:"POST",token:t.token,baseUrl:t.apiUrl,body:{outcome:e,...n.runId?{runId:n.runId}:{}},signal:AbortSignal.timeout(n.timeoutMs??1500)})}catch{}}function wa(e,t){return!t||e.decision!=="allow"||!vf.has(e.cause)?Promise.resolve():Kt(`gate_allow:${e.cause}`,t,{timeoutMs:500})}function ka(e,t){try{let n=ge(e,ba),r=`${n}.${Sf()}.tmp`;try{Cf(r,JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t})+`
|
|
84
|
+
`,{flag:"wx",mode:384}),_f(r,n)}catch(o){throw ya(r,{force:!0}),o}}catch{}}function qn(e,t=Date.now()){try{let n=ge(e,ba),r=Date.parse(JSON.parse(xf(n,"utf8")).at??"");return ya(n,{force:!0}),Number.isFinite(r)&&t-r>=0&&t-r<$f}catch{return!1}}var vf,ba,$f,Kn=L(()=>{"use strict";Y();ne();vf=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);ba="last-denial.json",$f=1440*60*1e3});import{randomUUID as If}from"node:crypto";import{readdirSync as Rf,readFileSync as Of,renameSync as Af,rmSync as Sa,statSync as _a,writeFileSync as Ef}from"node:fs";import{dirname as xa,join as Tf}from"node:path";import{gunzipSync as Nf,gzipSync as Pf}from"node:zlib";function $a(e,t,n){try{let r=ge(e,va(t)),o=`${r}.${If()}.tmp`,i=Pf(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t,entries:n.map(s=>[s.path,s.mode,s.oid])})));try{Ef(o,i,{flag:"wx",mode:384}),Af(o,r)}catch(s){throw Sa(o,{force:!0}),s}for(let s of Rf(xa(r))){if(!s.startsWith("tree-")||!s.endsWith(".json.gz"))continue;let a=Tf(xa(r),s);try{Date.now()-_a(a).mtimeMs>Ca&&Sa(a,{force:!0})}catch{}}}catch{}}function Mf(e,t){try{let n=ge(e,va(t));if(Date.now()-_a(n).mtimeMs>Ca)return null;let r=JSON.parse(Nf(Of(n)).toString("utf8"));if(r.version!==1||r.treeHash!==t||!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 Ia(e,t,n){let r=Mf(e,t);if(!r)return null;let o=new Map;for(let a of n){let c=r.get(a.path);c!==`${a.mode}:${a.oid}`&&o.set(a.path,c===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,Lf),total:s.length}}var Lf,Ca,va,Eo=L(()=>{"use strict";ne();Lf=8,Ca=720*60*60*1e3,va=e=>`tree-${e}.json.gz`});import{createHash as jf}from"node:crypto";import{constants as Ra}from"node:fs";import{open as Ff}from"node:fs/promises";import{Readable as Hf}from"node:stream";function Xn(e){if(!To(e,Pa))return!1;let t=e.provenance;return e.kind==="local_snapshot"&&e.version===2&&typeof e.sha256=="string"&&/^[a-f0-9]{64}$/.test(e.sha256)&&typeof e.bytes=="number"&&Number.isSafeInteger(e.bytes)&&e.bytes>0&&e.bytes<=Bt.maxBundleBytes&&[e.baseTreeHash,e.treeHash,e.baseSha,e.headSha].every(n=>typeof n=="string"&&Oa.test(n))&&To(t,La)&&[t.headSha,t.baseSha].every(n=>n===null||typeof n=="string"&&Oa.test(n))&&[t.branch,t.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(t.baselineMode)}function Df(e,t){return Pa.filter(n=>n!=="provenance").every(n=>e[n]===t[n])&&La.every(n=>e.provenance[n]===t.provenance[n])}function Yt(e,t){if(!To(e,["uploadId","expiresAt","status","source"])||typeof e.uploadId!="string"||!zn.test(e.uploadId)||typeof e.expiresAt!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.expiresAt)||!Number.isFinite(Date.parse(e.expiresAt))||!["pending","uploading","completed","cancelled"].includes(e.status)||!Xn(e.source)||t?.uploadId!==void 0&&t.uploadId!==e.uploadId||t?.manifest!==void 0&&!Df(t.manifest,e.source))throw new G(502,"invalid_upload_response","Canary's answer does not match the upload in progress.","Run the command again to continue the upload.",t?.uploadId);return e}function Ma(e){if(!zn.test(e))throw new G(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${Na}/${e}`}function Uf(e,t){return e instanceof G?new G(e.status,e.code,e.message,e.fix,t):e instanceof A?new G(e.status,"source_upload_failed",e.message,e.fix,t):new G(0,"source_upload_failed",e instanceof Error?e.message:"The source upload failed.","Run the command again to continue the upload.",t)}function Yn(e){if(e.status==="completed")return e;throw e.status==="cancelled"?new G(410,"source_upload_cancelled","This upload was cancelled.",void 0,e.uploadId):new G(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",e.uploadId)}async function Aa(e,t,n={}){let r=await(n.request??R)(Ma(e),{...t});return Yt(r,{uploadId:e})}async function*ja(e,t,n){let r=0;for(;r<t;){n?.throwIfAborted();let o=Buffer.allocUnsafe(Math.min(64*1024,t-r)),i=await e.read(o,0,o.length,r);if(!i.bytesRead)throw new G(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 Ea(e,t,n){let r=await e.stat();if(!r.isFile()||r.size!==t.bytes)throw new G(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let o=jf("sha256");for await(let s of ja(e,t.bytes,n))o.update(s);let i=await e.stat();if(o.digest("hex")!==t.sha256||i.size!==r.size||i.mtimeMs!==r.mtimeMs||i.ctimeMs!==r.ctimeMs)throw new G(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function Ta(e,t,n,r){let o=Hf.from(ja(e,t.manifest.bytes,t.signal));try{let i=await(r.fetch??fetch)(`${t.baseUrl.replace(/\/+$/,"")}${Ma(n)}/content`,{method:"PUT",headers:{...(r.headers??Te)(),authorization:`Bearer ${t.token}`,"content-type":"application/octet-stream","content-length":String(t.manifest.bytes)},body:o,duplex:"half",signal:t.signal,redirect:"error"});if(!i.ok){let s={};try{s=await i.json()}catch{}throw new G(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 Yn(Yt(await i.json(),{uploadId:n,manifest:t.manifest}))}catch(i){throw i instanceof G?i:new G(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 Fa(e,t={}){if(!Xn(e.manifest)||!zn.test(e.workspaceId)||!zn.test(e.repositoryId))throw new G(0,"invalid_source_receipt","A captured source, a workspace, and a repository are required before uploading.");let n={token:e.token,baseUrl:e.baseUrl,signal:e.signal},r;if(e.uploadId&&(r=Yt(await Aa(e.uploadId,n,t),{uploadId:e.uploadId,manifest:e.manifest}),r.status!=="pending"))return Yn(r);let o=await Ff(e.bundlePath,Ra.O_RDONLY|Ra.O_NOFOLLOW);try{if(await Ea(o,e.manifest,e.signal),r||(r=Yt(await(t.request??R)(Na,{...n,method:"POST",body:{workspaceId:e.workspaceId,repositoryId:e.repositoryId,source:e.manifest}}),{manifest:e.manifest})),e.onReceipt?.(r),r.status!=="pending")return Yn(r);try{return await Ta(o,e,r.uploadId,t)}catch(i){if(e.signal?.aborted||!(ue(i)||i instanceof A&&i.status===409))throw i;let s=Yt(await Aa(r.uploadId,n,t),{uploadId:r.uploadId,manifest:e.manifest});return s.status!=="pending"?Yn(s):(await Ea(o,e.manifest,e.signal),await Ta(o,e,r.uploadId,t))}}catch(i){throw r?Uf(i,r.uploadId):i}finally{await o.close()}}var G,Na,zn,Oa,Pa,La,To,No=L(()=>{"use strict";Y();Ne();mt();G=class extends A{constructor(n,r,o,i,s){super(n,o,i);this.code=r;this.uploadId=s;this.name="SourceUploadError"}},Na="/api/v1/cli/source-uploads",zn=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,Oa=/^[a-f0-9]{40}$/,Pa=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],La=["headSha","branch","baseRef","baseSha","baselineMode"],To=(e,t)=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))});import{createHash as Gf,randomUUID as Jf}from"node:crypto";import{readFileSync as Bf,renameSync as Wf,rmSync as Ha,writeFileSync as Vf}from"node:fs";function Da(e,t,n,r="verify"){let o=Gf("sha256").update(JSON.stringify([n,e,r])).digest("hex");return ge(t,`source-upload-${o}.json`)}function Ua(e){try{let t=JSON.parse(Bf(e,"utf8"));if(typeof t.uploadId!="string"||!/^[a-f0-9-]{36}$/i.test(t.uploadId)||typeof t.expiresAt!="string"||!Number.isFinite(Date.parse(t.expiresAt)))throw new Error("invalid upload record");return{uploadId:t.uploadId,expiresAt:t.expiresAt}}catch(t){if(t.code!=="ENOENT")throw new G(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 Po(e,t,n,r){let o=Da(e,t,n,r.requestKey),i=Ua(o);i&&(!r.uploadId||i.uploadId===r.uploadId)&&Ha(o,{force:!0})}async function Zn(e,t,n,r,o={}){let i=Da(e.manifest,t,n,o.requestKey),s=o.fresh?void 0:Ua(i),a=s&&Date.parse(s.expiresAt)>Date.now()?s.uploadId:void 0,c=await Fa({bundlePath:e.bundlePath,manifest:e.manifest,workspaceId:t.workspaceId,repositoryId:n,token:r,baseUrl:t.apiUrl,...a?{uploadId:a}:{},onReceipt:({uploadId:l,expiresAt:d})=>{let u=`${i}.${Jf()}.tmp`;try{Vf(u,JSON.stringify({uploadId:l,expiresAt:d})+`
|
|
85
|
+
`,{flag:"wx",mode:384}),Wf(u,i)}finally{Ha(u,{force:!0})}}});return{...c.source,uploadId:c.uploadId}}var Lo=L(()=>{"use strict";ne();No()});import{readFileSync as Ga}from"node:fs";function zf(e){if(e===void 0)return;let t=e;try{e==="-"?t=Ga(0,"utf8"):e.startsWith("@")&&(t=Ga(e.slice(1),"utf8"))}catch(n){throw new xe("brief_unreadable",`could not read the brief from ${e==="-"?"stdin":e.slice(1)}: ${n instanceof Error?n.message:String(n)}`,"pass the brief as text, @<file>, or - (stdin)")}return t.trim()===""?void 0:t}function _e(e){return e==="P3"?null:e==="P0"||e==="P1"?e:"P2"}function Xf(e,t){if(_e(e.materiality)===null)return null;let r=t??null;return e.result==="fail"?{checkRunId:e.checkRunId,kind:"fail",proof:r?.isStatic===!1?"runtime":"source",headline:_(r?.finding?.headline)||_(e.title),summary:_(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:Va(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:_(r?.finding?.reproduce)||null}:e.result==="blocked"?{checkRunId:e.checkRunId,kind:"blocked",proof:"none",headline:_(e.title),summary:_(r?.verdict?.reasonOneLiner)||(Xt[e.blockedReason??""]??""),location:Va(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}function Fo(e,t,n){let r=U();R("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...n?{baseUrl:n}:{},body:{outcome:e,...t?{runId:t}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function Ka(e){if(e.status!=="completed"||e.stageB.status==="failed")return 2;let t=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;return t>0&&e.stageC.checks.length===t?2:0}async function Ho(e,t,n={}){let r=u=>R(u,{token:t,...n.baseUrl?{baseUrl:n.baseUrl}:{}}),o=new Map,i="",s=new Set,a=!1,c=!1,l=null,d=Date.now();for(;;){let u;try{u=(await r(`/api/v1/red-team/runs/${e}`)).run,l=null}catch(f){if(ue(f)&&(l??=Date.now(),Date.now()-l<qf)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await zt(Mo);continue}throw f}for(let f of u.stageC.checks)if(!(!(f.status==="completed"&&(f.result==="fail"||f.result==="blocked"))||o.has(f.checkRunId))){if(!Ze.test(f.checkRunId)){o.set(f.checkRunId,null);continue}try{o.set(f.checkRunId,await r(`/api/v1/red-team/runs/${e}/checks/${f.checkRunId}/finding`))}catch(g){ue(g)||o.set(f.checkRunId,null)}}for(let f of u.stageC.checks){if(s.has(f.checkRunId)||!(f.status==="completed"||f.status==="failed"||f.status==="cancelled")||_e(f.materiality)===null)continue;s.add(f.checkRunId);let g=o.get(f.checkRunId),k=f.status!=="completed"?"!":f.result==="pass"?"\u2713":f.result==="fail"?"\u2717":"\u23F8",v=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?.(`${k} ${v}: ${_(f.title)}`)}u.stageB.status!=="completed"&&(c=!0);let p=u.stageC.checks.length>0||u.stageB.finalChecksCount===0||jo.has(u.status);!a&&u.stageB.status==="completed"&&p&&(a=!0,n.onProgress?.(Qf(u,c?Date.now()-d:null,o)));let h=Zf(u);if(h!==i&&(n.onProgress?.(h),i=h),jo.has(u.status)){for(let m=0;m<3;m++){let g=u.stageC.checks.filter(k=>k.status==="completed"&&(k.result==="fail"||k.result==="blocked")&&!o.has(k.checkRunId));if(g.length===0)break;await zt(Math.min(Mo,1e3));for(let k of g)try{o.set(k.checkRunId,await r(`/api/v1/red-team/runs/${e}/checks/${k.checkRunId}/finding`))}catch(v){(!ue(v)||m===2)&&o.set(k.checkRunId,null)}}let f=u.stageC.checks.filter(m=>m.status==="completed"&&(m.result==="fail"||m.result==="blocked")).sort((m,g)=>qa[_e(m.materiality)??"P2"]-qa[_e(g.materiality)??"P2"]).map(m=>Xf(m,o.get(m.checkRunId)??null)).filter(m=>m!==null);return{run:u,findings:f}}if(Date.now()-d>Ja)throw new xe("still_running",`run ${e} is still ${u.status} after ${Math.round(Ja/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await zt(Mo)}}function Zf(e){if(e.status==="queued")return"\u2026 queued";if(e.phase==="stage_b"||e.stageC.checks.length===0){let n=e.stageB.risksFound??0;return`\u2026 analyzing the change${n?` \xB7 ${n} risk${n===1?"":"s"} found`:""}`}return`\u2026 ${e.stageC.completedCheckRuns+e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns}/${e.stageC.checks.length} checks done \xB7 ${e.stageC.results.fail} failed`}function Qf(e,t,n=new Map){let r=e.stageC.checks.filter(u=>_e(u.materiality)!==null),o=u=>u.result==="fail"&&n.get(u.checkRunId)?.isStatic!==!1,i=r.filter(o).length,s=e.stageC.checks.filter(u=>u.status==="failed"||u.status==="cancelled").length,a=r.filter(u=>!o(u)&&u.status!=="failed"&&u.status!=="cancelled").length,c=e.stageC.results.pass+e.stageC.results.blocked+r.filter(u=>u.result==="fail"&&n.get(u.checkRunId)?.isStatic===!1).length,l=jo.has(e.status)?c>0?"verified in sandboxes":"not run":"verifying in sandboxes";return`${t===null?"analysis done":`analysis done in ${Math.max(1,Math.round(t/6e4))} min`} \xB7 ${de(i,"finding")} from the code \xB7 ${a} runtime check${a===1?"":"s"}${s?` \xB7 ${s} errored`:""} \xB7 ${l}`}function ep(e,t,n){let r=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;if(Ka(e)===2)return`Verification did not complete (${e.status})${r?`: ${de(r,"check")} errored`:""}; nothing was verified.`;let o=t.filter(d=>d.kind==="fail"&&d.proof==="runtime").length,i=t.filter(d=>d.kind==="fail"&&d.proof==="source").length,s=t.filter(d=>d.kind==="blocked").length,a=e.stageC.results.pass,c=[`${de(o,"verified failure")}`,`${de(a,"check")} passed`,`${de(i,"finding")} from the code (source-reasoned, not run)`,...s?[`${s} could not be verified`]:[],`${de(r,"check")} errored`],l=a===0&&o===0&&s===0&&r===0;return`${c.join("; ")}.${l?" Nothing in this change was executed.":""}${tp(n)}`}function tp(e){let t=e?e.reverifiable-e.carried:0;return!e||t<=0?"":` ${t} of run ${e.sourceRunId.slice(0,8)}'s ${de(e.reverifiable,"failed check")} ${t===1?"was":"were"} not re-run (reported disputed or skipped).`}function np(e,t){let n=e.slice(0,8);if(!t)return`re-checking the failed set of run ${n} \u2014`;let r=`of run ${n}'s ${de(t.reverifiable,"failed check")}`;return t.excludedReported>0?`re-checking ${t.carried} ${r} (${t.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${t.reverifiable} failed checks of run ${n} \u2014`}function Do(e,t,n,r){return{ok:!0,runId:e.runId,treeHash:t,status:e.status,findings:n,summary:ep(e,n,r),failed:n.filter(o=>o.kind==="fail").length,passed:e.stageC.results.pass,blocked:n.filter(o=>o.kind==="blocked").length,errored:e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns,exitCode:Ka(e),failureMessage:e.failure?.publicMessage??null,...r?{reverify:r}:{}}}function Uo(e){let t=[];if(t.push(`Receipt ${An(e.treeHash)} \xB7 run ${_(e.runId)}`),e.exitCode===2)return t.push(`\u2717 Verification did not complete (${_(e.status)})${e.failureMessage?`: ${_(e.failureMessage)}`:""}`),e.errored>0&&t.push(` ${de(e.errored,"check")} errored \u2014 nothing was verified; this is not a clean result.`),t.push(` Run \`canary verify\` again; if it repeats, report run ${_(e.runId)}.`),t.join(`
|
|
86
|
+
`);let n=[e.failed?`\u2717 ${de(e.failed,"finding")}`:"",e.passed?`\u2713 ${e.passed} passed`:"",e.blocked?`\u23F8 ${e.blocked} could not be verified`:""].filter(Boolean);e.findings.length===0&&e.errored===0?t.push(`\u2713 Clean \u2014 no findings in this change${e.passed?` \xB7 ${e.passed} passed`:""}.`):t.push(`${e.failed?"":"\u2713 No verified findings"}${e.failed||n.length===0?"":" \xB7 "}${n.join(" \xB7 ")}`);for(let r of e.findings)t.push(""),t.push(`${rp[r.kind]} ${_(r.headline)}${op[r.kind]}`),r.summary&&t.push(` ${_(r.summary)}`),r.location&&t.push(` \u2192 ${_(r.location)}`),r.fix&&t.push(` reproduce: ${_(r.fix)}`);return e.errored>0&&t.push(`
|
|
87
|
+
(${de(e.errored,"check")} errored and could not be verified.)`),t.push(`
|
|
88
|
+
${e.summary}`),t.join(`
|
|
89
|
+
`)}function ip(e){let t=e;return!t||!["EPERM","EACCES","EROFS"].includes(t.code??"")||typeof t.path!="string"||!t.path.startsWith(Z())?null:{message:`Canary keeps its records under ${Z()} and cannot write there from here (${t.code})`,fix:"run the command outside the sandbox, or let it write under that folder"}}function E(e,t,n,r,o,i={}){if(e)console.log(JSON.stringify({ok:!1,error:t,message:n,...r?{fix:r}:{},exitCode:o,...i}));else{let s=typeof i.runId=="string"?i.runId:null;console.error(`\u2717 ${_(n)}${r?`
|
|
90
|
+
fix: ${_(r)}`:""}${s?`
|
|
91
|
+
run: ${_(s)}`:""}`)}process.exitCode=o}async function sp(e,t,n,r,o={}){let i={baseUrl:o.baseUrl??W()};Be({cwd:e,agent:n,mode:r!==void 0?"reverify_failed":"full"});let s=(w,y,b,S=3,x={})=>{E(n,w,y,b,S,x),Fo(`exit${S}:${w}`,x.runId,i.baseUrl)},a=U();if(!a)return s("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!Ze.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 c,l;try{c=zf(t),l=await qt(e,{baseRef:o.baseRef})}catch(w){if(w instanceof ce||w instanceof xe)return s(w.code,w.message,w.fix);throw w}if(l.manifest.treeHash===l.manifest.baseTreeHash&&r===void 0)return await l.dispose(),s("nothing_to_verify","The current source matches the selected baseline","make a change, or choose a different baseline with --base <ref>");let d,u,p;try{d=await Gt(e,a,i.baseUrl),u=await Ut({...d,token:a});let w=AbortSignal.timeout(3e3);if((await Hn(d,a,w).catch(b=>{throw w.aborted?new A(0,"Checking this repository's setup timed out","run `canary verify` again"):b}))?.state!=="ready")throw new xe("setup_required",`This repository isn't set up for you in ${_(u.workspace.name)} yet`,"run `canary setup`");p=await Zn(l,d,u.repositoryId,a,{fresh:!0}),$a(d,l.manifest.treeHash,l.entries)}catch(w){if(w instanceof M||w instanceof xe)return s(w.code,w.message,"fix"in w?w.fix:void 0);if(w instanceof A)return s("api_error",w.message,w.fix,w.status>=400&&w.status<500?3:2);throw w}finally{await l.dispose()}c===void 0&&r===void 0&&console.error("! No --brief given \u2014 Canary will attack the change using the submitted source and baseline. A brief with acceptance criteria and must-not-break finds more."),ot();let h=w=>{n?console.error(` ${w}`):console.log(` ${w}`)};l.manifest.provenance.baselineMode==="whole-project"?h("No comparison branch found: reviewing the whole eligible project against an empty baseline."):h(`Baseline: ${_(l.manifest.provenance.baseRef)} \xB7 source ${An(l.manifest.treeHash)}`);let f,m,g;{let w,y=gt(l.manifest.provenance.branch),b=()=>R("/api/v1/cli/runs",{method:"POST",token:a,...i,body:{repositoryId:u.repositoryId,workspaceId:d.workspaceId,source:p,...c!==void 0?{brief:c}:{},...y?{branch:y}:{},...r!==void 0?{reverifySourceRunId:r}:{}}});try{for(let x=1;;x+=1)try{w=await b();break}catch(I){if(x>=Ba||!ue(I)||I instanceof A&&I.runId&&Ze.test(I.runId))throw I;h(`${I.message} \u2014 retrying (${x}/${Ba-1})`),await zt(Wa*x)}}catch(x){if(x instanceof A){let I=!ue(x)&&x.status>=400&&x.status<500,q=x.fix??(x.status===401||x.status===403?"run `canary login`":I?void 0:"run `canary verify` again in a minute"),O={httpStatus:x.status,...x.runId?{runId:x.runId}:{}};return I?E(n,"api_error",x.message,q,3,O):s("api_error",x.message,q,2,O)}throw x}if(w.treeHash!==l.manifest.treeHash||w.headSha!==l.manifest.headSha)return E(n,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!Ze.test(w.runId))return E(n,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);f=w.runId;let S=r?np(r,w.reverify):w.created?"submitted":"same verification inputs as an existing run \u2014 following it:";h(`${S} ${An(l.manifest.treeHash)} \xB7 run ${f} \xB7 ${de(l.files.length,"file")}`),m=w.reverify,g=w.created,g&&Kt(`started_by:${qn(d)?"hook":n||Wr().harness!=="unknown"?"skill":"manual"}`,{token:a,apiUrl:i.baseUrl},{runId:f})}if(o.noWait){let w=!1;if(r!==void 0&&!m&&!g)for(let b=0;b<3&&!m;b++)try{m=(await R(`/api/v1/red-team/runs/${f}`,{token:a,...i})).run.reverify;break}catch(S){if(!ue(S)||b===2){w=!0;break}await zt(Wa*(b+1))}let y={ok:!0,runId:f,runUrl:Kf(f),treeHash:l.manifest.treeHash,created:g,...m?{reverify:m}:{},next:`${Yf(f)}${w?" What this re-check carried could not be read just now; the document from `canary run wait` will say.":""}`};console.log(n?JSON.stringify(y):`Run ${f} is under way: ${y.runUrl}
|
|
92
|
+
${y.next}`);return}let k;try{k=await Ho(f,a,{...i,onProgress:h})}catch(w){if(w instanceof xe)return s(w.code,w.message,w.fix,2,{runId:f});if(w instanceof A){let y=w.status===401||w.status===403;return s("api_error",`${w.message} \u2014 run ${f} may still be running`,w.fix??(y?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:f,httpStatus:w.status})}throw w}let v={...Do(k.run,l.manifest.treeHash,k.findings,m),source:l.manifest,repositoryId:u.repositoryId};console.log(n?JSON.stringify(v):Uo(v)),process.exitCode=v.exitCode}function Ya(e){e.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 t=>{try{U()&&await(await Promise.resolve().then(()=>(Qe(),za))).installByDefault({json:t.json===!0}),await sp(t.dir??process.cwd(),t.brief,t.json===!0,t.failed,{baseRef:t.base,noWait:t.wait===!1})}catch(n){let r=ip(n);if(r){E(t.json===!0,"home_not_writable",r.message,r.fix,2),Fo("exit2:home_not_writable");return}E(t.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),Fo("exit2:internal_error")}})}var Mo,qf,Ja,jo,xe,_,Ze,Kf,Yf,zt,Ba,Wa,Va,qa,Xt,rp,op,de,yt=L(()=>{"use strict";Y();Ne();D();Os();Dn();ne();mt();Kn();Eo();Lo();it();Mo=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,qf=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Ja=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,jo=new Set(["completed","failed","cancelled"]),xe=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="VerifyError"}},_=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g," ").trim(),Ze=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Kf=e=>`${Ie().replace(/\/+$/,"")}/runs/${e}`,Yf=e=>`Collect the result with \`canary run wait ${e}\` (it returns when the run has finished; run it in the background where your shell allows).`,zt=e=>new Promise(t=>setTimeout(t,e)),Ba=3,Wa=1e3;Va=e=>e?e.startLine?`${e.file}:${e.startLine}`:e.file:null;qa={P0:0,P1:1,P2:2},Xt={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"};rp={fail:"\u2717",blocked:"\u23F8"},op={fail:"",blocked:" (could not be verified)"},de=(e,t)=>`${e} ${t}${e===1?"":"s"}`});var za={};xl(za,{hooksStatus:()=>Zt,installByDefault:()=>Qt,pendingPushCheck:()=>Bo,registerHooks:()=>Wo,runHooksInstall:()=>ec,runHooksUninstall:()=>tc,statusLines:()=>Qn});function Jo(e,t=[]){try{K(n=>({...n,hooks:{...n.hooks?.codex?{codex:n.hooks.codex}:{},state:e,at:new Date().toISOString(),...t.length?{refused:t}:{}}}))}catch{}}function ap(e){return[Go,"It is a hook in the agent's own settings, which the agent runs. `canary hooks install` adds:","",...e.flatMap(t=>[` ${t.file}`,` ${t.summary}`,...t.snippet.split(`
|
|
93
|
+
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${Xa}`].join(`
|
|
94
|
+
`)}function Qa(e){for(let t of e)t.result==="refused"?console.log(`\u2717 ${t.file} was left alone: ${t.detail}. To do it by hand:
|
|
95
|
+
${t.snippet}`):console.log(`${t.result==="unchanged"?"\xB7":"\u2713"} ${t.file}: ${t.result==="written"?"added":t.result==="removed"?"removed":"nothing to change"}${t.detail?`; ${t.detail}`:""}${Za(t.edit?.backup??t.removed?.backup)}`)}function cp(e,t){for(let n of t)n.afterInstall&&e.some(r=>r.harness===n.id&&r.result==="written")&&console.log(`${n.label}: ${n.afterInstall}`);On("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."),e.some(n=>n.result==="written")&&We()==="off"&&console.log("The check itself is switched off (`canary gate on` turns it on).")}function lp(e,t){return t?.length?{targets:e.filter(n=>t.includes(n.id)&&n.detected()),unknown:t.filter(n=>!e.some(r=>r.id===n&&r.detected()))}:{targets:e.filter(n=>n.byDefault&&n.detected()),unknown:[]}}async function ec(e){let t=e.targets??jt(),{targets:n,unknown:r}=lp(t,e.harnesses),o=n.flatMap(s=>s.plan());if(r.length)return E(e.json,"harness_not_found",`not found on this machine: ${r.join(", ")}`,`known: ${t.map(s=>s.id).join(", ")}; one counts as found once its settings folder exists`,3);if(!n.length){let s=t.filter(a=>!a.byDefault&&a.detected()).map(a=>`\`canary hooks install --harness ${a.id}\` registers ${a.label}, which is not covered by default yet.`);e.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 ${t.filter(a=>a.byDefault).map(a=>a.label).join(", ")}).`,...s].join(`
|
|
96
|
+
`));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:o}):ap(o));return}let i=n.flatMap(s=>s.install());i.some(s=>s.result!=="refused")&&Jo("installed"),e.json?console.log(JSON.stringify({ok:!i.some(s=>s.result==="refused"),outcomes:i,canaryOnPath:On("canary"),mode:We(),notes:n.filter(s=>s.afterInstall&&i.some(a=>a.harness===s.id&&a.result==="written")).map(s=>`${s.label}: ${s.afterInstall}`)})):(Qa(i),cp(i,n)),i.some(s=>s.result==="refused")&&(process.exitCode=2)}function tc(e){let t=(e.targets??jt()).flatMap(n=>n.uninstall());Jo("removed"),e.json?console.log(JSON.stringify({ok:!t.some(n=>n.result==="refused"),outcomes:t})):Qa(t),t.some(n=>n.result==="refused")&&(process.exitCode=2)}function Zt(e=jt()){return{mode:We(),registration:N().hooks?.state??null,canaryOnPath:On("canary"),harnesses:e.map(t=>({harness:t.id,label:t.label,detected:t.detected(),items:t.status()}))}}function Bo(e){try{return We()==="off"?[]:Zt(e).harnesses.flatMap(t=>t.items.filter(n=>n.state==="untrusted"&&n.pending).map(n=>({harness:t.harness,label:t.label,...n.pending})))}catch{return[]}}function Qn(e){let t=[];for(let n of e.harnesses){if(!n.detected&&n.items.every(r=>r.state==="missing")){t.push(`${n.label}: not found on this machine`);continue}for(let r of n.items)t.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 e.harnesses.some(n=>n.items.some(r=>r.state!=="missing"))&&!e.canaryOnPath&&t.push("`canary` is not on PATH in this shell; a harness that cannot find it runs no check."),e.harnesses.some(n=>n.items.some(r=>r.state!=="missing"))&&t.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)."),t}async function Qt(e){try{if(process.env.CI||!e.targets&&process.env.NODE_TEST_CONTEXT)return;let t=N();if(t.agentSkills===!1||t.hooks?.state==="removed")return;let n=new Set(t.hooks?.refused??[]);if(t.hooks?.state==="installed"&&!n.size)return;let r=(e.targets??jt()).filter(u=>u.byDefault&&u.detected());if(!r.length)return;let o=r.flatMap(u=>u.install()),i=o.filter(u=>u.result==="written"),s=o.filter(u=>u.result==="refused"&&!n.has(u.file)),a=o.filter(u=>u.result==="refused").map(u=>u.file);if(o.some(u=>u.result!=="refused")||t.hooks?.state==="installed")Jo("installed",a);else if(a.length)try{K(u=>({...u,hooks:{...u.hooks,refused:a}}))}catch{}let c=r.filter(u=>u.afterInstall&&i.some(p=>p.harness===u.id)).map(u=>`${u.label}: ${u.afterInstall}`),l=i.filter(u=>!u.edit),d=i.filter(u=>u.edit);if(e.json){(i.length||s.length)&&console.error(JSON.stringify({notice:"push_check",added:i.map(u=>u.file),leftAlone:s.map(u=>({file:u.file,why:u.detail})),...d.length?{edits:d.map(u=>({file:u.file,line:u.edit.line,text:u.edit.text,backup:u.edit.backup,created:u.edit.created}))}:{},message:Go,off:"canary gate off",remove:"canary hooks uninstall",notes:c}));return}if(l.length){let u=r.filter(p=>l.some(h=>h.harness===p.id)).map(p=>p.label).join(" and ");console.error(`
|
|
97
|
+
Canary added its push check to ${u} (${l.map(p=>p.file).join(", ")}).
|
|
98
|
+
${Go}
|
|
99
|
+
${Xa}`)}for(let u of d)console.error(`Canary ${u.edit.created?"created":"edited"} ${u.file}: ${u.detail}${Za(u.edit.backup)}. \`canary hooks uninstall\` takes it out again.`);for(let u of c)console.error(u);for(let u of s)console.error(`Canary left ${u.file} alone (${u.detail}): not added there: ${u.summary}. \`canary hooks install --plan\` shows what to add by hand.`)}catch{}}function Wo(e){let t=e.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");t.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 ec({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(r){E(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),t.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{tc({json:n.json===!0})}catch(r){E(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),t.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=Zt();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(`The push check is ${r.mode}.`);for(let o of Qn(r))console.log(o)}})}var Go,Xa,Za,Qe=L(()=>{"use strict";D();yn();Rs();yt();Go="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.",Xa="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`.";Za=e=>e?` (the file as it was: ${e})`:""});var Si=Cl(ki(),1),{program:bg,createCommand:kg,createArgument:Sg,createOption:xg,CommanderError:_g,InvalidArgumentError:Cg,InvalidOptionArgumentError:vg,Command:xi,Argument:$g,Option:Ig,Help:Rg}=Si.default;import{createHash as bp,randomBytes as pc}from"node:crypto";import{spawn as kp}from"node:child_process";import{createServer as Sp}from"node:http";D();import{existsSync as Jr,lstatSync as iu,mkdirSync as su,readFileSync as Hi,rmSync as au,rmdirSync as cu,writeFileSync as lu}from"node:fs";import{homedir as Gr}from"node:os";import{join as Je}from"node:path";var rt="Onboard this repository to Canary.",hn="Verify my changes with Canary.";var Ur=`---
|
|
86
100
|
name: canary
|
|
87
101
|
description: >-
|
|
88
102
|
Use whenever you finish a code change and are about to report it done, or whenever a change
|
|
@@ -121,75 +135,114 @@ If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then start at step
|
|
|
121
135
|
"Getting started" section covers logging in.
|
|
122
136
|
Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
|
|
123
137
|
you act on it.
|
|
124
|
-
`;var
|
|
125
|
-
`)===
|
|
126
|
-
`))return;let r=Math.max(2,
|
|
138
|
+
`;var uu="canary",du="canary-setup";function fu(e){let t=Je(e,"skills",du),n=Je(t,"SKILL.md");if(gn(t)||gn(n)||!Jr(n))return;let r;try{r=Hi(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{au(n,{force:!1})}catch{return}try{cu(t)}catch{}}}function gn(e){try{return iu(e).isSymbolicLink()}catch{return!1}}function pu(){return[Je(Gr(),".claude"),Je(Gr(),".agents"),Je(Gr(),".codex")].filter(e=>Jr(e))}function mn(){let e={installed:[],refreshed:[],current:[],skipped:[]};if(N().agentSkills===!1)return e;for(let t of pu()){fu(t);let n=Je(t,"skills",uu),r=Je(n,"SKILL.md");try{if(gn(n)||gn(r)){e.skipped.push(r);continue}let o=Jr(r)?Hi(r,"utf8"):null;if(o===Ur){e.current.push(r);continue}su(n,{recursive:!0}),lu(r,Ur),(o===null?e.installed:e.refreshed).push(r)}catch{}}return e}var Di=`Open your coding agent inside the repo you want to onboard and say: "${rt}"`;Y();it();D();Qe();ne();Y();Dn();function nc(e){try{return new URL(e).href.replace(/\/+$/,"")}catch{return}}var Vo=Ks;async function rc(e,t,n,r){let o=await R("/api/v1/cli/workspaces",{token:e.token,baseUrl:r,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(o?.workspaces)||o.workspaces.some(u=>!u||typeof u.id!="string"||!u.id||typeof u.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let i=[...new Map(o.workspaces.map(({id:u,name:p})=>[u,{id:u,name:p}])).values()],a=t.user?.id===e.user.id&&nc(n)===nc(r)?i.find(u=>u.id===t.team?.id):void 0,c=i.length===1?i[0]:void 0,l=a??c??i.find(u=>u.id===e.team.id)??i[0]??{id:"",name:"No workspace selected"},d=Vo();return{workspace:l,workspaces:i,source:a?"saved in CLI":c?"only workspace":"active on platform",selectionRequired:!a&&!c,...d?{repository:d}:{},...i.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function er(e,t,n,r=AbortSignal.timeout(3e3)){try{let o=await Hn({apiUrl:e.apiUrl,userId:e.userId,workspaceId:n},e.token,r);return o?{state:o.state}:void 0}catch{return}}function tr(e,t){let n=/^\d+$/.test(t)?Number(t)-1:-1,r=n>=0?e.workspaces.filter((o,i)=>i===n):e.workspaces.filter(o=>o.id===t||o.name.toLowerCase()===t.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 oc}from"node:util";var J="\x1B[";function tn(e,t,n){let r={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[t];return n?`${J}${r}m${e}${J}0m`:e}function j(e){return oc(e).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var qo=new Intl.Segmenter(void 0,{granularity:"grapheme"});function ic(e){if(/^[\p{Mark}\u200d\ufe0f]+$/u.test(e))return 0;if(new RegExp("\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\u20e3","u").test(e))return 2;let t=e.codePointAt(0);return t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=131072)?2:1}function en(e){return[...qo.segment(oc(e))].reduce((t,n)=>t+ic(n.segment),0)}function nr(e,t){let n=0,r="";for(let o of e.split(/(\x1b\[[0-9;]*m)/)){if(o.startsWith(J)){r+=o;continue}for(let{segment:i}of qo.segment(o))n+=ic(i),n<=t&&(r+=i)}return r}function je(e,t){let n=[],r="";for(let o of j(e).split(/\s+/)){r&&en(r+" "+o)>t&&(n.push(r),r="");for(let{segment:i}of qo.segment((r?" ":"")+o))en(r+i)>t&&r&&(n.push(r),r=""),r+=i}return r&&n.push(r),n}function wt(e){let t=[];return{render(n){if(n.join(`
|
|
139
|
+
`)===t.join(`
|
|
140
|
+
`))return;let r=Math.max(2,e.columns||80),o=Math.max(3,e.rows||24),i=Math.min(o-1,t.reduce((s,a)=>s+Math.max(1,Math.ceil(en(a)/r)),0));e.write((i?`\r${J}${i}A`:"")+`${J}0J`+(n.length?n.join(`\r
|
|
127
141
|
`)+`\r
|
|
128
|
-
`:"")),
|
|
142
|
+
`:"")),t=n}}}function sc(e,t,n){return e?[JSON.stringify({authorizeUrl:n})]:[t?"Opening your browser to authorize the Canary CLI...":"Open this URL in your browser to authorize the Canary CLI:",(t?`If it doesn't open, visit:
|
|
129
143
|
`:" ")+n+`
|
|
130
|
-
`]}function ta(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 Pn(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 Gt(t){return`Next: in your coding agent, say "${t==="ready"?Zt:Ke}"`}import{stripVTControlCharacters as bd}from"node:util";var dt=[[" "," \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 Jt="\x1B[",kd={gold:"33",text:"39",muted:"90",green:"32"};function Sd(t,e,n){if(!n)return t;let r=e==="gold"?"38;2;255;212;0":kd[e];return`${Jt}${r}m${t}${Jt}0m`}function na(t){return bd(t).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var ra=1.4;function xd(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<ra?d(a):0,p=dt[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")=>Sd(y,k,i),w=e==="success"?"green":e==="failed"?"muted":"gold",x;if(o<5)x=[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")};x=["",...p.map((k,_)=>` ${g(k,w)} ${y[_]??""}`)]}else r>=42&&o>=23?x=["",...p.map(y=>` ${g(y,w)}`),` ${g("CANARY","gold")}`,"",` ${g(f)}`,` ${g(m,"muted")}`]:x=["",` ${g("CANARY","gold")}`,` ${g(f)}`];return o>=10&&(x.push("",` ${g("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(e==="waiting"||e==="saving")&&x.push(` ${g("Ctrl+C","muted")} ${g("cancel sign-in","muted")}`),x.push("")),x.slice(0,Math.max(1,o-2)).map(y=>{let k=0;return y.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,_=>_.startsWith("\x1B")||++k<r?_:"")})}function oa(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=ut(e),l=!1;function c(){if(l)return;let g=Math.max(2,e.columns||80),w=Math.max(3,e.rows||24),x=performance.now(),y=xd({phase:o,seconds:(x-r)/1e3,phaseSeconds:(x-i)/1e3,columns:g,rows:w,color:n,open:t.open});a.render(y)}let u=()=>e.write(`${Jt}0m${Jt}?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.
|
|
131
|
-
`),process.exit(g)}let
|
|
132
|
-
Workspace ${
|
|
133
|
-
|
|
134
|
-
`)},fail(){s("failed"),
|
|
135
|
-
`),
|
|
136
|
-
`)});let o=
|
|
137
|
-
Workspace (number or name): `)}}finally{process.off("SIGINT",i),o.close(),r||
|
|
138
|
-
${
|
|
139
|
-
`);return}let a=
|
|
140
|
-
${
|
|
141
|
-
|
|
142
|
-
`),p()}function m(){e.setRawMode(a),l||e.pause(),n.write(`${D}0m${D}?25h`)}function g(){process.exitCode=143,f()}function w(){(n.rows||24)<16||(n.columns||80)<30?f():s()}function x(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 _=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)<=_)r.highlighted=Number(k.sequence)-1;else if(k.name==="up")r.highlighted=(r.highlighted+_-1)%_;else if(k.name==="down")r.highlighted=(r.highlighted+1)%_;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 U=++h;t.repositoryState(E.id).then(_e=>{if(!u){if(!t.sessionCurrent()){f();return}U!==h||r.context.workspace.id!==E.id||(r.context={...r.context,repositoryState:_e?.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"&&fo(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(_=>_.id===r.context.workspace.id));else if(k.name==="c"&&!d){let _=Wt(r.context),E=new AbortController;d=E,c.signal.addEventListener("abort",()=>E.abort(),{once:!0}),Id(_,E.signal).then(C=>{d===E&&(d=void 0),!u&&(r.message=E.signal.aborted||_!==Wt(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()}}}Cd(e),e.setRawMode(!0),e.resume(),e.on("keypress",x),e.once("end",f),n.on("resize",w),process.once("SIGINT",f),process.once("SIGTERM",g),process.once("exit",m),n.write(`${D}?25l`),s()})}var Ad=900*1e3,Td=6e4;var ca=t=>t.toString("base64url");function Nd(t){let e=process.platform,[n,r]=e==="darwin"?["open",[t]]:e==="win32"?["explorer.exe",[t]]:["xdg-open",[t]];try{let o=Od(n,r,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function Pd(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 Ld(t){return new Promise((e,n)=>{let r,o,i=new Promise((c,u)=>{r=c,o=u}),s=Ed((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(Pd(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")),Ad);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 Md(t,e){let n=T(),r=n.apiUrl||W(),o=(e.apiUrl||W()).replace(/\/+$/,""),i=ca(aa(32)),s=Rd("sha256").update(i).digest("base64url"),a=ca(aa(16)),{port:l,code:c,close:u}=await Ld(a),d=`http://127.0.0.1:${l}/callback`,h=(e.webUrl||ke()).replace(/\/+$/,""),p=`${h}/cli/authorize?challenge=${encodeURIComponent(s)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(d)}`;for(let w of ea(t,e.open,p))console.error(w);let f=oa({json:t,animation:e.animation,open:e.open}),m=Date.now(),g=f?void 0:setInterval(()=>console.error(ta(t,Math.round((Date.now()-m)/1e3))),Td);g?.unref?.();try{e.open&&Nd(p);let w=await c;g&&clearInterval(g),f?.saving();let x=await v("/api/v1/cli/auth/token",{method:"POST",body:{code:w,codeVerifier:i},baseUrl:o});return f&&await f.celebrate(),f?.clear(),await ua(x,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 ua(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}),gn();let s=await Xs(t,e,n,r);i.workspace!==void 0&&(s.workspace=Tn(s,i.workspace),s.source="selected in CLI",s.selectionRequired=!1),s.selectionRequired||z(f=>({...f,team:s.workspace}));let a=i.agentSkills?tn():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=>An({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 sa({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 ia(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 ${ke()}, 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(Pn(p.name,p.state)),a?jd(!1,a,Gt(p?.state)):console.log(Gt(p?.state))),d}async function la(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 ua({...s,token:t,tokenType:"Bearer",expiresAt:null},r,o,i,e,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function jd(t,e,n=ri){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 da(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 la(o,n,{...e,agentSkills:e.agentSkills!==!1})}else{let o=(process.env.CANARY_TOKEN??"").trim();o?r=await la(o,n,{...e,agentSkills:e.agentSkills!==!1}):(r=await Md(n,{webUrl:e.webUrl,apiUrl:e.apiUrl,workspace:e.workspace,open:e.open!==!1,animation:e.animation!==!1,agentSkills:e.agentSkills!==!1}),ze())}r&&e.agentSkills!==!1&&e.hooks!==!1&&await Ft({json:n})}catch(r){let o=r instanceof $?`${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();nn();Be();B();j();X();B();X();var ft=5e3,Hd=new Set(["verified","open","running","failed","none"]);function fa(t,e){if(!e)return t;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,e]);let n=new AbortController;for(let r of[t,e])r.aborted?n.abort(r.reason):r.addEventListener("abort",()=>n.abort(r.reason),{once:!0});return n.signal}async function Ln(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??ft);try{let i=await v(`/api/v1/cli/runs/status?${r.toString()}`,{token:t.token,baseUrl:t.apiUrl,signal:fa(o,n.signal)});if(!i||typeof i!="object"||!Hd.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{hn(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??ft)/1e3)} s`}:i instanceof $&&i.status>=400&&i.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${i.status}: ${i.message}${i.fix?` (${i.fix})`:""}`}:i instanceof $&&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)}}}async function pa(t,e,n,r={}){let o=AbortSignal.timeout(r.timeoutMs??ft);try{let i=await v(`/api/v1/cli/local-repositories/lookup?${new URLSearchParams({workspaceId:e,githubFullName:n}).toString()}`,{token:t.token,baseUrl:t.apiUrl,signal:fa(o,r.signal)});return i&&typeof i.repositoryId=="string"?{repositoryId:i.repositoryId}:null}catch(i){return i instanceof $&&i.status===404&&i.code==="repository_not_connected"?{notConnected:!0}:null}}async function Bt(t,e={}){let{signal:n}=e,r=H();if(!r)return{ok:!1,cause:"not_logged_in"};let o=T(),i=o.team?.id;if(!i)return{ok:!1,cause:"no_workspace"};let s=W();try{let a=r===o.token?o.user?.id:void 0;if(a||(a=(await v("/api/v1/cli/auth/whoami",{token:r,baseUrl:s,signal:n}))?.user?.id),!a)return{ok:!1,cause:"not_logged_in"};let l={apiUrl:s,userId:a,workspaceId:i,directory:t},c=await Ui(l,u=>pa({token:r,apiUrl:s},i,u,e));return c?.repositoryId?{ok:!0,context:{token:r,apiUrl:s,repository:l,repositoryId:c.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(a){return{ok:!1,cause:a.code==="not_a_git_repository"?"no_binding":"context_error"}}}Cn();X();j();X();import{randomUUID as Fd}from"node:crypto";import{readFileSync as Dd,renameSync as Ud,rmSync as Gd,writeFileSync as Jd}from"node:fs";var ha="skips.json",Wd=720*60*60*1e3,Bd=1440*60*1e3,Vd=(t,e)=>{let n=Date.parse(t.at);return Number.isFinite(n)&&e-n<Wd&&n-e<Bd};function Mn(t,e=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(Dd(le(t,ha),"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"&&Vd(s,e)&&(n.skips[i]={reason:s.reason,at:s.at,...typeof s.branch=="string"?{branch:s.branch}:{}});return n}function ga(t,e,n=Date.now()){return Mn(t,n).skips[e]??null}function ma(t,e,n,r=Date.now()){let o=le(t,ha);return ei(`${o}.lock`,"this repository's skip records",()=>{let i=Mn(t,r),s={reason:n.reason,at:new Date(r).toISOString(),...n.branch?{branch:n.branch}:{}};i.skips[e]=s;let a=`${o}.${Fd()}.tmp`;try{Jd(a,JSON.stringify(i,null,2)+`
|
|
143
|
-
`,{flag:"wx",mode:384}),
|
|
144
|
-
This covers exactly the code on disk now; any further edit is a new tree.`)}async function
|
|
145
|
-
|
|
146
|
-
`)}function
|
|
147
|
-
`)}var
|
|
148
|
-
`:n==="t"?" ":n);function
|
|
149
|
-
`||(i+=m??"",s=!0),
|
|
150
|
-
`;)
|
|
151
|
-
`){
|
|
152
|
-
`),
|
|
153
|
-
`,
|
|
154
|
-
`)}catch{}let
|
|
144
|
+
`]}function ac(e,t){return e?JSON.stringify({waiting:!0,elapsedSeconds:t}):`Still waiting for the sign-in to finish in your browser (${Math.max(1,Math.round(t/60))} min). The link above is still valid.`}function rr(e,t){let n=t==="ready"?"your setup is ready":t==="setup_required"?"not set up yet":"detected locally";return`Repository ${j(e)} \xB7 ${n}`}function nn(e){return`Next: in your coding agent, say "${e==="ready"?hn:rt}"`}import{stripVTControlCharacters as up}from"node:util";var bt=[[" "," \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 rn="\x1B[",dp={gold:"33",text:"39",muted:"90",green:"32"};function fp(e,t,n){if(!n)return e;let r=t==="gold"?"38;2;255;212;0":dp[t];return`${rn}${r}m${e}${rn}0m`}function cc(e){return up(e).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var lc=1.4;function pp(e){let{phase:t,seconds:n,columns:r,rows:o,color:i,open:s}=e,a=e.phaseSeconds??n,c=1.4,d=n%(c+.2),u=w=>Math.sin(w/c*Math.PI*2)*Math.sin(w/c*Math.PI),p=t==="waiting"&&d<c?u(d):t==="success"&&a<lc?u(a):0,h=bt[Math.max(0,Math.min(16,Math.round(p*10)+8))],f=t==="success"?"You're signed in.":t==="failed"?"Sign-in didn't finish.":t==="saving"?"Securing your CLI session":n<1.5?"Let's get you connected.":"Waiting for browser approval",m=t==="success"?"Your terminal is ready for the next step.":t==="failed"?"Run canary login to try again.":t==="saving"?"Exchanging authorization and saving credentials.":s&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",g=(w,y="text")=>fp(w,y,i),k=t==="success"?"green":t==="failed"?"muted":"gold",v;if(o<5)v=[g(f)];else if(r>=72&&o>=18){let w={1:g("CANARY","gold"),3:g(f,t==="success"?"green":"text"),5:g(m,"muted")};v=["",...h.map((y,b)=>` ${g(y,k)} ${w[b]??""}`)]}else r>=42&&o>=23?v=["",...h.map(w=>` ${g(w,k)}`),` ${g("CANARY","gold")}`,"",` ${g(f)}`,` ${g(m,"muted")}`]:v=["",` ${g("CANARY","gold")}`,` ${g(f)}`];return o>=10&&(v.push("",` ${g("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(t==="waiting"||t==="saving")&&v.push(` ${g("Ctrl+C","muted")} ${g("cancel sign-in","muted")}`),v.push("")),v.slice(0,Math.max(1,o-2)).map(w=>{let y=0;return w.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,b=>b.startsWith("\x1B")||++y<r?b:"")})}function uc(e){if(e.json||!e.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let t=process.stderr,n=!process.env.NO_COLOR,r=performance.now(),o="waiting",i=r,s=g=>{o=g,i=performance.now()},a=wt(t),c=!1;function l(){if(c)return;let g=Math.max(2,t.columns||80),k=Math.max(3,t.rows||24),v=performance.now(),w=pp({phase:o,seconds:(v-r)/1e3,phaseSeconds:(v-i)/1e3,columns:g,rows:k,color:n,open:e.open});a.render(w)}let d=()=>t.write(`${rn}0m${rn}?25h`);function u(){c||(c=!0,clearInterval(m),t.removeListener("resize",l),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",f),process.removeListener("exit",d),d())}function p(g){s("failed"),l(),u(),t.write(`Sign-in cancelled.
|
|
145
|
+
`),process.exit(g)}let h=()=>p(130),f=()=>p(143),m=setInterval(l,80);return m.unref(),t.on("resize",l),process.once("SIGINT",h),process.once("SIGTERM",f),process.once("exit",d),t.write(`${rn}?25l`),l(),{saving(){s("saving"),l()},celebrate(){return s("success"),l(),new Promise(g=>setTimeout(g,lc*1e3+100))},succeed(g,k){s("success"),l(),u(),process.stdout.write(` Account ${cc(g)}
|
|
146
|
+
Workspace ${cc(k)}
|
|
147
|
+
|
|
148
|
+
`)},fail(){s("failed"),l(),u()},clear(){a.render([]),u()},stop:u}}import{spawn as hp}from"node:child_process";import{createInterface as gp,emitKeypressEvents as mp}from"node:readline";function Ko(e){return e?e.installed.length+e.refreshed.length+e.current.length?`Installed \xB7 available to your coding agent${e.skipped.length?" (some locations skipped)":""}`:"Not installed \xB7 no writable agent location found":"Skipped \xB7 --no-agent-skills"}function Yo(e){return e.workspaces.length>1}function on(e){return e.repositoryState==="ready"?hn:rt}async function dc(e){let t=process.stdin,n=process.stderr,r=t.readableFlowing===!0;n.write(`Choose a workspace:
|
|
149
|
+
`),e.workspaces.forEach((s,a)=>{let c=e.workspaces.some(l=>l.id!==s.id&&l.name===s.name);n.write(` ${a+1}. ${j(s.name)}${c?` (${j(s.id)})`:""}
|
|
150
|
+
`)});let o=gp({input:t,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 tr(e,s.trim())}catch(a){n.write(`${a instanceof Error?a.message:"Choose a listed workspace."}
|
|
151
|
+
Workspace (number or name): `)}}finally{process.off("SIGINT",i),o.close(),r||t.pause()}}function yp(e,t,n,r){let{context:o}=e,i=Math.max(1,t-5),s=(p,h="text")=>tn(j(p),h,r),a=(p="",h="text")=>` ${s(p,h)}`,c=[];if(t>=90&&n>=36&&!e.picker){let p={1:s("CANARY","gold"),3:s("You're connected."),5:s("Let's give your agent the next step.","muted")};c.push("",...bt[8].map((h,f)=>` ${s(h,"green")} ${p[f]??""}`),"")}else c.push(a("CANARY","gold"),a("You're connected."),"");if(c.push(a(`Account ${j(e.email)}`)),c.push(a(`Workspace ${o.selectionRequired?"Choose below":j(o.workspace.name)}`)),c.push(a(` ${o.source}${!e.done&&Yo(o)?" \xB7 [w] Change":""}`,"muted")),e.picker){c.push("",a("Choose a workspace","gold"));let p=Math.max(1,Math.min(8,n-c.length-5)),h=Math.max(0,Math.min(e.highlighted-Math.floor(p/2),o.workspaces.length-p));for(let f=h;f<Math.min(h+p,o.workspaces.length);f++){let m=o.workspaces[f],k=o.workspaces.some(w=>w.id!==m.id&&w.name===m.name)?` \xB7 ${j(m.id)}`:"",v=!o.selectionRequired&&m.id===o.workspace.id?" \xB7 current":"";c.push(a(`${f===e.highlighted?"\u203A":" "} ${f+1}. ${j(m.name)}${k}${v}`,f===e.highlighted?"gold":"text"))}c.push(a(`${e.highlighted+1} of ${o.workspaces.length}`,"muted"),"",a("\u2191 \u2193 choose \xB7 number highlight \xB7 Enter select \xB7 Esc back","muted"))}else{let p=o.repositoryState==="ready",h=o.repository?j(o.repository):void 0;h?p?c.push(a(`Repository ${h} \xB7 your setup is ready`,"green")):o.repositoryState==="setup_required"?c.push(a(`Repository ${h} \xB7 not set up yet`)):c.push(a(`Repository ${h} \xB7 detected locally`)):c.push(a("Repository Open a local Git repository to continue")),c.push(a(`Agent skill ${Ko(e.skill)}`,e.skill&&Ko(e.skill).startsWith("Installed")?"green":"muted")),o.workspaceNotice&&c.push(...je(o.workspaceNotice,i).map(m=>a(m,"muted"))),c.push("",a("\u2500".repeat(Math.min(68,i)),"muted"),a(p?"NEXT \xB7 VERIFY A CHANGE":"NEXT \xB7 SET UP THIS REPOSITORY","gold"));let f=!!e.skill&&Ko(e.skill).startsWith("Installed");c.push(a(f?"Open your coding agent in this repository and say:":"In your coding agent, run canary skills, then say:","muted")),c.push(...je(on(o),i-2).map(m=>a(`\u2502 ${m}`))),e.done||c.push("",a(`${Yo(o)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),e.message&&c.push(...je(e.message,i).map(m=>a(m,"muted"))),c.push("",a(p?"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",p?"green":"muted"))}let d=Math.max(1,n-2);return(d<=3?c.slice(0,d):c.length>d?[...c.slice(0,Math.max(0,d-3)),...c.slice(-3)]:c).map(p=>nr(p,Math.max(1,t-1)))}async function wp(e,t){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(t.aborted)return!1;if(await new Promise(s=>{let a=hp(r,o,{stdio:["pipe","ignore","ignore"],signal:t}),c=setTimeout(()=>{a.kill(),s(!1)},1e3),l=d=>{clearTimeout(c),s(d)};a.on("error",()=>l(!1)),a.on("close",d=>l(d===0)),a.stdin.on("error",()=>{}),a.stdin.end(e)}))return!0}return!1}async function fc(e){let t=process.stdin,n=process.stderr,r={...e,picker:e.context.workspaces.length>1,highlighted:Math.max(0,e.context.workspaces.findIndex(h=>h.id===e.context.workspace.id))},o=!process.env.NO_COLOR,i=wt(n),s=()=>i.render(yp(r,n.columns||80,n.rows||24,o));if(!t.isTTY||!n.isTTY||(n.rows||24)<16||(n.columns||80)<30){r.done=!0,s(),n.write(`
|
|
152
|
+
${on(r.context)}
|
|
153
|
+
`);return}let a=t.isRaw,c=t.readableFlowing===!0,l=new AbortController,d=!1,u,p=0;await new Promise(h=>{function f(){if(d)return;d=!0,l.abort(),t.off("keypress",v),t.off("end",f),n.off("resize",k),process.off("SIGINT",f),process.off("SIGTERM",g),process.off("exit",m),r.picker=!1,r.done=!0,r.message=void 0;let w=e.sessionCurrent();w?s():i.render(["CLI session changed in another process. Run canary whoami to check the active account."]),m(),w&&!r.context.selectionRequired&&n.write(`
|
|
154
|
+
${on(r.context)}
|
|
155
|
+
|
|
156
|
+
`),h()}function m(){t.setRawMode(a),c||t.pause(),n.write(`${J}0m${J}?25h`)}function g(){process.exitCode=143,f()}function k(){(n.rows||24)<16||(n.columns||80)<30?f():s()}function v(w,y){if(!(!y||d)){if(!e.sessionCurrent()){f();return}if(y.ctrl&&["c","d"].includes(y.name??"")){f();return}if(!(y.ctrl||y.meta)){if(r.picker){let b=r.context.workspaces.length;if(y.name==="escape"){if(r.context.selectionRequired){f();return}r.picker=!1}else if(/^[1-9]$/.test(y.sequence??"")&&Number(y.sequence)<=b)r.highlighted=Number(y.sequence)-1;else if(y.name==="up")r.highlighted=(r.highlighted+b-1)%b;else if(y.name==="down")r.highlighted=(r.highlighted+1)%b;else if(y.name==="return"){let S=r.context.workspaces[r.highlighted];try{e.selectWorkspace(S);let x=S.id!==r.context.workspace.id;if(r.context={...r.context,workspace:S,source:"selected in CLI",selectionRequired:!1,...x?{repositoryState:void 0}:{}},r.picker=!1,r.message="Workspace saved for future CLI commands.",(x||!r.context.repositoryState)&&(u?.abort(),e.repositoryState&&r.context.repository)){let I=++p;e.repositoryState(S.id).then(q=>{if(!d){if(!e.sessionCurrent()){f();return}I!==p||r.context.workspace.id!==S.id||(r.context={...r.context,repositoryState:q?.state},s())}})}}catch{if(!e.sessionCurrent()){f();return}r.picker=!1,r.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(y.name??"")){f();return}else if(y.name==="w"&&Yo(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(b=>b.id===r.context.workspace.id));else if(y.name==="c"&&!u){let b=on(r.context),S=new AbortController;u=S,l.signal.addEventListener("abort",()=>S.abort(),{once:!0}),wp(b,S.signal).then(x=>{u===S&&(u=void 0),!d&&(r.message=S.signal.aborted||b!==on(r.context)?"The next step changed while copying. Press [c] to copy the current one.":x?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",s())})}s()}}}mp(t),t.setRawMode(!0),t.resume(),t.on("keypress",v),t.once("end",f),n.on("resize",k),process.once("SIGINT",f),process.once("SIGTERM",g),process.once("exit",m),n.write(`${J}?25l`),s()})}var xp=900*1e3,_p=6e4;var hc=e=>e.toString("base64url");function Cp(e){let t=process.platform,[n,r]=t==="darwin"?["open",[e]]:t==="win32"?["explorer.exe",[e]]:["xdg-open",[e]];try{let o=kp(n,r,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function vp(e,t){return`<!doctype html><meta charset="utf-8"><title>${e}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${e}</h2><p style="color:#555">${t}</p></body>`}function $p(e){return new Promise((t,n)=>{let r,o,i=new Promise((l,d)=>{r=l,o=d}),s=Sp((l,d)=>{let u=new URL(l.url??"/","http://127.0.0.1"),p=(m,g,k)=>{d.writeHead(k,{"content-type":"text/html",connection:"close"}),d.end(vp(m,g))};if(u.pathname!=="/callback"){d.writeHead(404,{connection:"close"}),d.end("not found");return}if(u.searchParams.get("state")!==e){p("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let h=u.searchParams.get("error");if(h){p("Authorization failed","You can close this tab and return to your terminal.",400),o(new Error(`authorization failed: ${h}`));return}let f=u.searchParams.get("code");if(!f){p("Authorization failed","No authorization code was returned. Please run canary login again.",400),o(new Error("callback returned no code"));return}p("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")),xp);a.unref?.();let c=()=>{clearTimeout(a),s.closeAllConnections?.(),s.close()};i.then(c,c),s.on("error",l=>{clearTimeout(a),n(l)}),s.listen(0,"127.0.0.1",()=>{t({port:s.address().port,code:i,close:c})})})}async function Ip(e,t){let n=N(),r=n.apiUrl||W(),o=(t.apiUrl||W()).replace(/\/+$/,""),i=hc(pc(32)),s=bp("sha256").update(i).digest("base64url"),a=hc(pc(16)),{port:c,code:l,close:d}=await $p(a),u=`http://127.0.0.1:${c}/callback`,p=(t.webUrl||Ie()).replace(/\/+$/,""),h=`${p}/cli/authorize?challenge=${encodeURIComponent(s)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(u)}`;for(let k of sc(e,t.open,h))console.error(k);let f=uc({json:e,animation:t.animation,open:t.open}),m=Date.now(),g=f?void 0:setInterval(()=>console.error(ac(e,Math.round((Date.now()-m)/1e3))),_p);g?.unref?.();try{t.open&&Cp(h);let k=await l;g&&clearInterval(g),f?.saving();let v=await R("/api/v1/cli/auth/token",{method:"POST",body:{code:k,codeVerifier:i},baseUrl:o});return f&&await f.celebrate(),f?.clear(),await mc(v,n,r,o,e,{webUrl:p,agentSkills:t.agentSkills,workspace:t.workspace,interactive:!!f&&!!process.stdin.isTTY&&(process.stderr.rows||24)>=16&&(process.stderr.columns||80)>=30,promptWorkspace:!e&&!process.env.CI&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&!!process.stderr.isTTY})}catch(k){throw f?.fail(),k}finally{g&&clearInterval(g),f?.stop(),d()}}async function mc(e,t,n,r,o,i){K(({team:f,...m})=>({...m,token:e.token,user:e.user,apiUrl:r,...i.webUrl?{webUrl:i.webUrl}:{},agentSkills:i.agentSkills}),{overwriteUnreadable:!0}),Fn();let s=await rc(e,t,n,r);i.workspace!==void 0&&(s.workspace=tr(s,i.workspace),s.source="selected in CLI",s.selectionRequired=!1),s.selectionRequired||K(f=>({...f,team:s.workspace}));let a=i.agentSkills?mn():void 0,c=()=>{let f=N();return f.token===e.token&&f.apiUrl===r},l=f=>{K(m=>{if(m.token!==e.token||m.apiUrl!==r)throw new Error("CLI session changed");return{...m,team:f}}),s.selectionRequired=!1},d=s.repository?f=>er({token:e.token,apiUrl:r,userId:e.user.id},s.repository,f):void 0;if(!s.selectionRequired&&d&&(s.repositoryState=(await d(s.workspace.id))?.state),i.interactive&&s.workspaces.length)await fc({email:e.user.email,context:s,skill:a,selectWorkspace:l,sessionCurrent:c,repositoryState:d});else if(i.promptWorkspace&&s.selectionRequired&&s.workspaces.length){console.error(`Signed in as ${j(e.user.email)}.`);let f=await dc(s);f&&(l(f),s.workspace=f,s.source="selected in CLI",d&&(s.repositoryState=(await d(f.id))?.state))}if(!c())throw new Error("CLI session changed in another process. Run canary whoami.");let u=!process.exitCode,p=N().team;if(!p){let f=s.workspaces.length?"workspace_selection_required":"workspace_required",m=s.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${Ie()}, then run canary login.`;return o?console.log(JSON.stringify({ok:!1,authenticated:!0,error:f,user:e.user,workspaces:s.workspaces,fix:m})):(console.log(`Signed in as ${j(e.user.email)}. Select a workspace to continue.`),s.workspaces.forEach((g,k)=>console.log(` ${k+1}. ${j(g.name)} (${j(g.id)})`)),console.log(m)),process.exitCode=1,u}let h=s.repository?{name:s.repository,state:s.repositoryState}:void 0;return o?console.log(JSON.stringify({ok:!0,user:e.user,team:p,workspace:p,...h?{repository:h}:{}})):i.interactive||(console.log(`Logged in as ${j(e.user.email)} (${j(p.name??p.id)}).`),h&&console.log(rr(h.name,h.state)),a?Rp(!1,a,nn(h?.state)):console.log(nn(h?.state))),u}async function gc(e,t,n){let r=N(),o=r.apiUrl||W(),i=(n.apiUrl||W()).replace(/\/+$/,""),s=await R("/api/v1/cli/auth/whoami",{token:e,baseUrl:i});return mc({...s,token:e,tokenType:"Bearer",expiresAt:null},r,o,i,t,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function Rp(e,t,n=Di){if(e)return;let r=[...t.installed,...t.refreshed];r.length&&console.log(`Canary skill ${t.installed.length?"installed":"updated"} for your coding agents (${r.join(", ")}).`),console.log(n)}function yc(e){e.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 t=>{let n=t.json===!0;try{let r;if(t.token!==void 0){let o=t.token.trim();if(!o)throw new Error("--token was provided but is empty");r=await gc(o,n,{...t,agentSkills:t.agentSkills!==!1})}else{let o=(process.env.CANARY_TOKEN??"").trim();o?r=await gc(o,n,{...t,agentSkills:t.agentSkills!==!1}):(r=await Ip(n,{webUrl:t.webUrl,apiUrl:t.apiUrl,workspace:t.workspace,open:t.open!==!1,animation:t.animation!==!1,agentSkills:t.agentSkills!==!1}),ot())}r&&t.agentSkills!==!1&&t.hooks!==!1&&await Qt({json:n})}catch(r){let o=r instanceof A?`${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}})}D();yn();Qe();Y();D();ne();Y();ne();var kt=5e3,Op=new Set(["verified","open","running","failed","none"]);function wc(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let n=new AbortController;for(let r of[e,t])r.aborted?n.abort(r.reason):r.addEventListener("abort",()=>n.abort(r.reason),{once:!0});return n.signal}async function or(e,t,n={}){let r=new URLSearchParams({repositoryId:e.repositoryId,workspaceId:e.repository.workspaceId,treeHash:t.treeHash});t.branch&&r.set("branch",t.branch);let o=AbortSignal.timeout(n.timeoutMs??kt);try{let i=await R(`/api/v1/cli/runs/status?${r.toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:wc(o,n.signal)});if(!i||typeof i!="object"||!Op.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!==e.repositoryId)try{jn(e.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??kt)/1e3)} s`}:i instanceof A&&i.status>=400&&i.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${i.status}: ${i.message}${i.fix?` (${i.fix})`:""}`}:i instanceof A&&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)}}}async function bc(e,t,n,r={}){let o=AbortSignal.timeout(r.timeoutMs??kt);try{let i=await R(`/api/v1/cli/local-repositories/lookup?${new URLSearchParams({workspaceId:t,githubFullName:n}).toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:wc(o,r.signal)});return i&&typeof i.repositoryId=="string"?{repositoryId:i.repositoryId}:null}catch(i){return i instanceof A&&i.status===404&&i.code==="repository_not_connected"?{notConnected:!0}:null}}async function sn(e,t={}){let{signal:n}=t,r=U();if(!r)return{ok:!1,cause:"not_logged_in"};let o=N(),i=o.team?.id;if(!i)return{ok:!1,cause:"no_workspace"};let s=W();try{let a=r===o.token?o.user?.id:void 0;if(a||(a=(await R("/api/v1/cli/auth/whoami",{token:r,baseUrl:s,signal:n}))?.user?.id),!a)return{ok:!1,cause:"not_logged_in"};let c={apiUrl:s,userId:a,workspaceId:i,directory:e},l=await Vs(c,d=>bc({token:r,apiUrl:s},i,d,t));return l?.repositoryId?{ok:!0,context:{token:r,apiUrl:s,repository:c,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(a){return{ok:!1,cause:a.code==="not_a_git_repository"?"no_binding":"context_error"}}}Kn();ne();D();ne();import{randomUUID as Ap}from"node:crypto";import{readFileSync as Ep,renameSync as Tp,rmSync as Np,writeFileSync as Pp}from"node:fs";var kc="skips.json",Lp=720*60*60*1e3,Mp=1440*60*1e3,jp=(e,t)=>{let n=Date.parse(e.at);return Number.isFinite(n)&&t-n<Lp&&n-t<Mp};function ir(e,t=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(Ep(ge(e,kc),"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"&&jp(s,t)&&(n.skips[i]={reason:s.reason,at:s.at,...typeof s.branch=="string"?{branch:s.branch}:{}});return n}function Sc(e,t,n=Date.now()){return ir(e,n).skips[t]??null}function xc(e,t,n,r=Date.now()){let o=ge(e,kc);return ji(`${o}.lock`,"this repository's skip records",()=>{let i=ir(e,r),s={reason:n.reason,at:new Date(r).toISOString(),...n.branch?{branch:n.branch}:{}};i.skips[t]=s;let a=`${o}.${Ap()}.tmp`;try{Pp(a,JSON.stringify(i,null,2)+`
|
|
157
|
+
`,{flag:"wx",mode:384}),Tp(a,o)}catch(c){throw Np(a,{force:!0}),c}return s})}mt();yt();var Fp=500,sr={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 _c(e){return e==="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 Hp(e,t){try{if(!Ki(e))return E(t,"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 Ge)return E(t,"config_busy",n.message,void 0,2);throw n}console.log(t?JSON.stringify({ok:!0,mode:e}):_c(e))}async function Dp(e,t,n){let r=(t??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,Fp);if(!r)return E(n,"reason_required","a skip needs a reason",'canary skip --reason "<why this change needs no run>"',3);Dt(e);let o=await sn(e);if(!o.ok){let[l,d]=sr[o.cause]??sr.context_error;return E(n,o.cause,l,d,3)}let i;try{i=await Vn(e)}catch(l){if(l instanceof ce)return E(n,l.code,l.message,l.fix,3);throw l}let s=gt(i.branch),a;try{a=xc(o.context.repository,i.treeHash,{reason:r,...s?{branch:s}:{}})}catch(l){if(l instanceof Ge)return E(n,"config_busy",l.message,void 0,2);throw l}qn(o.context.repository);let c=await or(o.context,{treeHash:i.treeHash,branch:s},{timeoutMs:3e3});await Kt(c.ok?`gate_skip:${c.state}:${c.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 ${_(s)}`:""}: ${_(a.reason)}
|
|
158
|
+
This covers exactly the code on disk now; any further edit is a new tree.`)}async function Up(e,t){Dt(e);let n=await sn(e);if(!n.ok){let[o,i]=sr[n.cause]??sr.context_error;return E(t,n.cause,o,i,3)}let r=Object.entries(ir(n.context.repository).skips).map(([o,i])=>({treeHash:o,...i})).sort((o,i)=>i.at.localeCompare(o.at));if(t)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?_(o.branch):"(detached)"} ${_(o.reason)}`)}function Cc(e){let t=e.command("gate").description("The check on an agent's push or pull request: on, off, status");for(let n of["on","off"])t.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=>Hp(n,r.json===!0));t.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=Zt();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(_c(r.mode));for(let o of Qn(r))console.log(o)}}),e.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 Up(n.dir??process.cwd(),r):await Dp(n.dir??process.cwd(),n.reason,r)}catch(o){E(r,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}})}Qe();Ne();var Gp={[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 vc(e){e.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(t=>{let n=Te();if(t.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)":Gp[r]??"";console.log(`${r.padEnd(18)} ${o}${i?` ${i}`:""}`)}})}D();yn();Ne();mt();import{appendFileSync as lh,existsSync as uh}from"node:fs";import{join as Fc}from"node:path";var Fe=(e,t)=>({decision:"allow",cause:e,...t?{message:t}:{}}),zo=e=>e.replace(/[\x00-\x1f\x7f]+/g,"?");function ar(e){if(e.mode==="off")return Fe("mode_off");if(!e.trigger)return Fe("not_a_trigger");if(e.trigger.dir===null)return Fe("unknown_directory");if(!e.context)return null;if(!e.context.ok)return Fe(e.context.cause);if(e.trigger.editsFirst)return{decision:"deny",cause:"edits_first",message:Wp(e.trigger)};if(!e.tree)return null;if(!e.tree.ok)return Fe("hash_failed",$c(`this checkout could not be read (${e.tree.detail})`));if(e.skip===void 0)return null;if(e.skip)return Fe("skipped",`Canary: this exact code goes out on a recorded skip, not a run (${zo(e.skip.reason)}). Tell the user it was published without a Canary run, and why.`);if(!e.lookup)return null;if(!e.lookup.ok)return Fe(e.lookup.cause,$c(e.lookup.detail));let{state:t}=e.lookup;return t==="verified"?e.leftOut?Fe("verified",e.leftOut.length?Jp(e.leftOut):void 0):null:t==="none"&&e.lookup.newestRun?.treeHash&&e.since===void 0?null:{decision:"deny",cause:t,message:Vp(e.trigger,e.tree,e.lookup,e.since)}}var $c=e=>`Canary did not check this: ${e}. Nothing was blocked.`;function Jp(e){let t=e.slice(0,8).map(zo).join(", "),n=e.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: ${t}${n>8?`, and ${n-8} more`:""}.`}function Bp(e,t){let n=`Newest run on this branch: ${e.runId.slice(0,8)} (${e.state})`;if(t&&t.total>0){let r=t.total>t.files.length?` and ${t.total-t.files.length} more`:"";return`${n}. Changed since it: ${t.total} file${t.total===1?"":"s"}: ${t.files.map(zo).join(", ")}${r}.`}return e.headSha?`${n}, taken from commit ${e.headSha.slice(0,7)}; \`git diff ${e.headSha.slice(0,7)}..HEAD --stat\` shows what was committed since.`:`${n}.`}function Wp(e){let t=e.action==="push"?"push":"pull request",n=e.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 ${t}: 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(`
|
|
159
|
+
|
|
160
|
+
`)}function Vp(e,t,n,r){let o=e.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 ${t.treeHash.slice(0,12)}${t.branch?` on ${t.branch}`:""}`,a=n.runId?`run ${n.runId}${n.runUrl?` (${n.runUrl})`:""}`:"",c=`Skip it: \`canary skip --reason "<why this change needs no run>"\`, then repeat the ${o}.`,l=[];if(n.state==="running")l.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. ${c}`);else if(n.state==="open"){let d=n.open??0;l.push(`Canary held this ${o}: ${a} found ${d} finding${d===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. ${c}`)}else l.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 ${t.branch?"on this branch":"here"} has one`:`nothing ${t.branch?"on this branch":"here"} has been verified yet`}.`,...n.newestRun?[Bp(n.newestRun,r)]:[],"",i,`1. Verify it: \`canary verify\`, wait for the run, close what it finds, then repeat the ${o}.`,`2. ${c}`);return l.push("","`canary skill gate` says when each one fits."),l.join(`
|
|
161
|
+
`)}var Ic=["claude","codex","cursor"];function Rc(e,t=0,n=[]){if(typeof e=="string")e&&n.push(e);else if(t<3&&e&&typeof e=="object")for(let r of Object.values(e))Rc(r,t+1,n);return n}var cr=e=>typeof e=="string"&&e?e:void 0,qp=new Set(["Bash","PowerShell","Monitor"]);function Oc(e,t,n=process.env,r=process.platform){if(!t||typeof t!="object"||Array.isArray(t))return null;let o=t;if(e==="cursor"){let c=Array.isArray(o.workspace_roots)?o.workspace_roots:[],l=cr(o.cwd)??cr(c[0])??cr(n.CURSOR_PROJECT_DIR)??process.cwd();return o.hook_event_name==="beforeShellExecution"&&typeof o.command=="string"?{kind:"shell",command:o.command,cwd:l,shell:r==="win32"?"powershell":"posix"}:o.hook_event_name==="beforeMCPExecution"&&typeof o.tool_name=="string"?{kind:"tool",toolName:o.tool_name,cwd:l}:null}if(o.hook_event_name!=="PreToolUse"||typeof o.tool_name!="string")return null;let i=cr(o.cwd)??process.cwd(),s=o.tool_input&&typeof o.tool_input=="object"?o.tool_input:{};if(qp.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=e==="codex"&&o.tool_name==="exec"?Rc(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 Ac(e,t){if(e==="cursor"){if(t.decision!=="deny")return"";let n=t.message??"Canary held this call.";return JSON.stringify({permission:"deny",user_message:n,agent_message:n})}return t.decision==="deny"?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message??"Canary held this call."}}):t.message?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t.message}}):""}Kn();import{execFile as Kp}from"node:child_process";function Ec(e,t){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=>{Kp("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","status","--porcelain=v1","-z"],{cwd:e,env:n,signal:t,timeout:3e3,maxBuffer:16*1024*1024,encoding:"buffer"},(o,i)=>{if(o)return r([]);let s=i.toString("utf8").split("\0"),a=[];for(let c=0;c<s.length;c++){let l=s[c];l.length<4||(a.push(l.slice(3)),(l[0]==="R"||l[0]==="C")&&c++)}r(a)})})}Eo();import{homedir as Yp}from"node:os";import{basename as zp,isAbsolute as Xp,resolve as Zp}from"node:path";var Qp=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),eh=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,Tc=e=>e.replace(/\\(.)/g,(t,n)=>n==="n"?`
|
|
162
|
+
`:n==="t"?" ":n);function Mc(e,t){for(let n of e)for(let r of n.matchAll(eh)){let o=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(s=>Tc(s[1]??s[2]??"")).join(" "):Tc(r[1]??r[2]??r[3]??""),i=Qo(o,t);if(i)return i}return null}function jc(e,t){let n=!e.includes("__");if(!n&&!e.startsWith("mcp__"))return null;let r=Qp.get(n?e:e.slice(e.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:t}:null}function th(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]==="\\"){n++;continue}let r=e[n]==="$"&&e[n+1]==="("?2:e[n]==="`"?1:0;if(!r)continue;let o=ur(e,n+r,r===2?")":"`");t.push(o.tokens),n=o.end-1}return t}var lr=!1;function ur(e,t,n){let r=[],o=[],i="",s=!1,a=!1,c=!0,l=t,d=0,u=()=>{s&&r.push({word:i,quoted:a,bare:c}),i="",s=!1,a=!1,c=!0},p=f=>{u(),r.push({op:f})},h=(f,m)=>{let g=ur(e,f,m);return r.push({sub:g.tokens}),i+="$()",s=!0,g.end};for(;l<e.length;){let f=e[l],m=e[l+1];if(n==="`"&&f==="`")return u(),{tokens:r,end:l+1};if(n===")"&&f===")"&&d===0)return u(),{tokens:r,end:l+1};if(f==="\\"&&!lr){m===`
|
|
163
|
+
`||(i+=m??"",s=!0),l+=2;continue}if(f==="'"){s||(c=!1);let g=e.indexOf("'",l+1);i+=e.slice(l+1,g<0?void 0:g),s=!0,a=!0,l=g<0?e.length:g+1;continue}if(f==='"'){for(s||(c=!1),s=!0,a=!0,l++;l<e.length&&e[l]!=='"';)e[l]==="\\"&&!lr&&l+1<e.length&&/[$`"\\\n]/.test(e[l+1])?(i+=e[l+1],l+=2):e[l]==="$"&&e[l+1]==="("?l=h(l+2,")"):e[l]==="`"?l=h(l+1,"`"):(i+=e[l],l++);l++;continue}if(f==="#"&&!s){for(;l<e.length&&e[l]!==`
|
|
164
|
+
`;)l++;continue}if(f==="<"&&m==="<"&&e[l+2]!=="<"){let g=/^<<(-?)[ \t]*(?:'([^']*)'|"([^"]*)"|\\?([^\s;&|<>()]+))/.exec(e.slice(l));if(g){u(),o.push({end:g[2]??g[3]??g[4]??"",stripTabs:g[1]==="-",literal:g[4]===void 0||g[0].includes("\\")}),l+=g[0].length;continue}}if(f===`
|
|
165
|
+
`){p(`
|
|
166
|
+
`),l++;for(let g of o.splice(0))for(;;){let k=e.indexOf(`
|
|
167
|
+
`,l),v=e.slice(l,k<0?void 0:k);if(l=k<0?e.length:k+1,(g.stripTabs?v.replace(/^\t+/,""):v)===g.end||k<0)break;if(!g.literal)for(let w of th(v))r.push({sub:w})}continue}if(f===" "||f===" "||f==="\r"){u(),l++;continue}if(f===">"||f==="<"){let g=f===">";u(),l++;let k=!1;for(;l<e.length&&(e[l]===">"||e[l]==="&"||e[l]==="|");)e[l]==="&"&&(k=!0),l++;for(;l<e.length&&(e[l]===" "||e[l]===" ");)l++;let v=l;for(;l<e.length&&!/[\s;&|()<>`]/.test(e[l]);)l++;if(g&&!k){let w=e.slice(v,l);w&&r.push({write:w})}continue}if(f==="&"&&m===">"){u(),l++;continue}if((f==="&"||f==="|")&&m===f){p(f+f),l+=2;continue}if(f==="$"&&m==="("){l=h(l+2,")");continue}if(f==="`"){l=h(l+1,"`");continue}if(f==="("){d++,p(f),l++;continue}if(f===")"){d=Math.max(0,d-1),p(f),l++;continue}if(f===";"||f==="&"||f==="|"){p(f),l++;continue}if(/[0-9]/.test(f)&&!s&&/^[0-9]+[<>]/.test(e.slice(l))){l++;continue}i+=f,s=!0,l++}return u(),{tokens:r,end:e.length}}var nh=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),rh=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),Nc=e=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(e),He=!1,oh=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),Pc=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),ih=new Set(["sh","bash","zsh","dash","ksh"]),Lc=6,sh=new Set(["-c","--exec-path","--namespace","--super-prefix","--config-env","--attr-source"]);function Xo(e,t){if(t===null||/[$`*?[]/.test(e.word))return null;let n=e.bare&&(e.word==="~"||e.word.startsWith("~/"))?Yp()+e.word.slice(1):e.word;return e.bare&&n.startsWith("~")?null:Xp(n)?n:Zp(t,n)}function ah(e,t){let n=t,r=0;for(;r<e.length;r++){let i=e[r].word;if(i==="-C"){n=e[r+1]?Xo(e[r+1],n):null,r++;continue}if(i.startsWith("-C")&&i.length>2){n=Xo({...e[r],word:i.slice(2)},n);continue}if(/^--(git-dir|work-tree)(=|$)/.test(i)){n=null,i.includes("=")||r++;continue}if(sh.has(i)){r++;continue}if(!i.startsWith("-"))break}if(e[r]?.word!=="push")return null;let o=[];for(let{word:i}of e.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 ch(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].word;if(r==="--help"||r==="-h"||r==="--dry-run")return!1;if(r==="-R"||r==="--repo"){n++;continue}r.startsWith("-")||t.push(r)}return t[0]==="pr"&&(t[1]==="create"||t[1]==="new")}function Zo(e,t,n){let r=t,o=[],i=!1,s=()=>{let a=o;o=[];let c=i;i=!1;let l=g=>(!g&&c&&(He=!0),g),d=0,u=(g,k)=>g.bare&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(g.word)||!g.quoted&&(oh.has(g.word)||Pc.has(g.word)||!!k&&Pc.has(k.word)&&g.word.startsWith("-"));for(;d<a.length&&u(a[d],a[d-1]);)d++;let p=a[d];if(!p)return l(null);let h=zp(p.word.replace(/\\/g,"/")).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase(),f=a.slice(d+1);if(h==="cd"||h==="pushd")return r=f[0]&&!f[0].word.startsWith("-")?Xo(f[0],r):null,l(null);let m=(g,k)=>({action:g,via:"shell",dir:k,...He?{editsFirst:!0}:{}});if(h==="git"){let g=ah(f,r);if(g)return m("push",g.dir);let k=f.find(w=>!w.word.startsWith("-"))?.word,v=(k==="checkout"||k==="switch")&&f.some(w=>/^-(b|B|c|C|-orphan)$/.test(w.word));return k&&rh.has(k)&&!v&&(He=!0),l(null)}if(h==="gh")return ch(f)?m("pr_create",r):l(null);if(h==="tee"?f.some(g=>!g.word.startsWith("-")&&!Nc(g.word))&&(He=!0):(nh.has(h)||(h==="sed"||h==="perl")&&f.some(g=>/^-[a-zA-Z]*i/.test(g.word)))&&(He=!0),(h==="npm"||h==="pnpm"||h==="yarn")&&f[0]?.word==="version"&&(He=!0),n<Lc&&(ih.has(h)||h==="eval")){let g=h==="eval"?0:f.findIndex(v=>/^-[a-zA-Z]*c[a-zA-Z]*$/.test(v.word))+1,k=h==="eval"?f.map(v=>v.word).join(" "):g>0?f[g]?.word:void 0;if(k)return l(Zo(ur(k,0,null).tokens,r,n+1))}return l(null)};for(let a of e){if("word"in a){o.push(a);continue}if("write"in a){i=i||!Nc(a.write);continue}if("sub"in a){let l=n<Lc?Zo(a.sub,r,n+1):null;if(l)return l;continue}let c=s();if(c)return c}return s()}function Qo(e,t,n={}){if(!/\bpush\b/.test(e)&&!/\bpr\b/.test(e))return null;lr=n.shell==="powershell",He=!1;try{return Zo(ur(e,0,null).tokens,t,0)}finally{lr=!1,He=!1}}var dh=8e3,fh=64*1024*1024;async function ph(e,t={}){let n=e.kind==="shell"?Qo(e.command,e.cwd,{shell:e.shell}):e.kind==="script"?Mc(e.texts,e.cwd):jc(e.toolName,e.cwd);if(!n)return ar({mode:"on",trigger:null});let r={mode:We(),trigger:n},o,i="",s,a=[],c=()=>Math.max(250,Math.min(kt,t.deadline?t.deadline-Date.now()-500:kt)),l=[async()=>{Be({cwd:n.dir,agent:!0});let u=await sn(n.dir,{signal:t.signal,timeoutMs:c()});u.ok?(o=u.context,t.seen&&(t.seen.context=o),r.context={ok:!0}):r.context=u},async()=>{try{let u=await Vn(n.dir,{signal:t.signal});i=u.root,a=u.files,s={treeHash:u.treeHash,branch:gt(u.branch)},r.tree={ok:!0,...s}}catch(u){if(t.signal?.aborted)throw u;r.tree={ok:!1,detail:u instanceof ce?u.message:"the working tree could not be read"}}},async()=>{r.skip=Sc(o.repository,s.treeHash)},async()=>{r.lookup=await or(o,s,{timeoutMs:c(),signal:t.signal})},async()=>{let u=r.lookup?.ok?r.lookup.newestRun:void 0;r.since=u?.treeHash&&o?Ia(o.repository,u.treeHash,a):null},async()=>{r.leftOut=await Ec(i,t.signal)}],d=null;for(let u of l){if(d=ar(r),d)break;await u()}return d??=ar(r)??{decision:"allow",cause:"crash"},d.decision==="deny"&&o&&s&&ka(o.repository,s.treeHash),d}async function hh(e){let t=[],n=0;for await(let r of e){let o=typeof r=="string"?Buffer.from(r):r;if(n+=o.length,n>fh)throw new Error("event too large");t.push(o)}return JSON.parse(Buffer.concat(t).toString("utf8").replace(/^\uFEFF/,""))}var gh={claude:"claude-code",codex:"codex",cursor:"cursor"};async function mh(e,t){Be({harness:gh[e]});let n=t.ceilingMs??dh;Ti(250);let r=new AbortController,o,i=new Promise(d=>{o=setTimeout(()=>{r.abort(),d({decision:"allow",cause:"ceiling"})},n)}),s={},a=(async()=>{let d=await hh(t.stdin);try{uh(Fc(Z(),"hook-debug"))&&lh(Fc(Z(),"hook-events.log"),`${new Date().toISOString()} ${e} ${JSON.stringify(d)}
|
|
168
|
+
`)}catch{}let u=Oc(e,d);return u?ph(u,{signal:r.signal,deadline:Date.now()+n,seen:s}):{decision:"allow",cause:"not_a_trigger"}})().catch(()=>({decision:"allow",cause:r.signal.aborted?"ceiling":"crash"})),c=await Promise.race([a,i]);clearTimeout(o);let l=Ac(e,c);return l&&await t.write(l),c.cause!=="not_a_trigger"&&t.note(`canary hook: ${c.decision} (${c.cause})`),await wa(c,s.context),c}function Hc(e){e.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 t=>{if(Ic.includes(t)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await mh(t,{stdin:process.stdin,ceilingMs:n,note:r=>process.stderr.write(r+`
|
|
155
169
|
`),write:r=>new Promise(o=>process.stdout.write(r+`
|
|
156
|
-
`,()=>o()))})}process.exit(0)})}
|
|
157
|
-
`))}async function
|
|
158
|
-
`))}async function
|
|
159
|
-
Input needed: ${
|
|
160
|
-
${
|
|
170
|
+
`,()=>o()))})}process.exit(0)})}Y();D();function Dc(e){e.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0,r=U();if(r)try{await R("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}Fi();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."))})}Y();D();yt();Y();yt();var yh={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"},wh=15e3;function bh(e){return e&&yh[e]||"Other"}var kh=e=>{let t=e?.finding?.nextActionCodeRef??e?.codeRefs?.[0]??e?.checkReadback?.codeRefs?.[0]??null;return t?{file:t.file,line:t.startLine??null}:null},Sh=e=>(Array.isArray(e?.evidence)?e.evidence:[]).filter(t=>t&&t.media&&typeof t.media.url=="string").map(t=>({kind:_(t.modality)||"evidence",caption:_(t.caption),url:t.media.url,expiresAt:t.media.expiresAt??null}));function xh(e,t,n){if(e.status!=="completed"||_e(e.materiality)===null)return null;let r=t??null,o=r?.isStatic===!0?"source":"runtime",i=e.result==="pass"?"passed":e.result==="fail"?"failed":"could_not_run",s=_(r?.assertion)||null;return{checkRunId:e.checkRunId,checkUrl:`${n}/checks/${e.checkRunId}`,scenarioId:e.stageBCheckId??e.checkRunId,category:bh(r?.lane),title:_(e.title),proof:o,status:i,whatWasTried:o==="source"?_(r?.finding?.whatWasTested)||null:_(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:s||_(r?.finding?.whatWasTested)||null,observed:_(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:s,location:kh(r),evidence:Sh(r),fix:o==="source"&&_(r?.finding?.reproduce)||null,reason:i==="could_not_run"&&(_(r?.verdict?.reasonOneLiner)||Xt[e.blockedReason??""])||null}}async function Uc(e,t,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 t)if(!(i.status!=="completed"||r.has(i.checkRunId)||!o.test(i.checkRunId)))try{r.set(i.checkRunId,await R(`/api/v1/red-team/runs/${e}/checks/${i.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(wh),...n.baseUrl?{baseUrl:n.baseUrl}:{}}))}catch{r.set(i.checkRunId,null)}return r}function Gc(e,t,n){let r=e.stageC.checks.map(o=>xh(o,t.get(o.checkRunId)??null,n.runUrl)).filter(o=>o!==null);return{runId:e.runId,runUrl:n.runUrl,repo:n.repo,treeHash:e.target.treeHash??"",files:n.files,reverifySourceRunId:e.reverifySourceRunId??null,startedAt:e.startedAt??null,completedAt:e.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:e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns}}var Vc=new Set(["completed","failed","cancelled"]);function Jc(e){return Vc.has(e.status)?null:e.status==="queued"?"queued":e.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function Bc(e){return e.status==="failed"||e.status==="cancelled"?"errored":e.status!=="completed"?e.status==="running"?"running":"pending":e.result==="pass"?"passed":e.result==="fail"?"failed":"could_not_run"}async function ei(e,t,n,r,o={}){let i=U();if(!i)return E(e,"not_logged_in","Not logged in","run `canary login` first",3),null;if(t.some(s=>!Ze.test(s)))return E(e,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await R(n,{token:i,...r?{baseUrl:r}:{},...o})}catch(s){if(s instanceof A){if(s.status===404)return E(e,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let a=!ue(s)&&s.status>=400&&s.status<500,c=s.fix??(s.status===401?"run `canary login`":a?void 0:"run the command again in a minute");return E(e,"api_error",s.message,c,a?3:2,{httpStatus:s.status}),null}throw s}}var Wc=e=>{if(!e?.file)return"";let t=e.startLine?`:${e.startLine}`:"",n=e.startLine&&e.endLine&&e.endLine>e.startLine?`-${e.endLine}`:"";return`${_(e.file)}${t}${n}`};async function _h(e,t,n){let r=await ei(t,[e],`/api/v1/red-team/runs/${e}`,n);if(!r)return;let o=r.run,i=r.repository?.fullName??"";if(t){let l=o.stageC.checks.filter(h=>_e(h.materiality)!==null).map(h=>({checkRunId:h.checkRunId,scenarioId:h.stageBCheckId??h.checkRunId,title:_(h.title),status:Bc(h)})),d={runId:o.runId,status:o.status,progress:Jc(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:l,passed:l.filter(h=>h.status==="passed").length,failed:l.filter(h=>h.status==="failed").length,couldNotRun:l.filter(h=>h.status==="could_not_run").length,errored:o.stageC.failedCheckRuns+o.stageC.cancelledCheckRuns},u={},p=U();if(Vc.has(o.status)&&p){let h=await Uc(e,o.stageC.checks,{token:p,...n?{baseUrl:n}:{}});u=Gc(o,h,{runUrl:`${Ie().replace(/\/+$/,"")}/runs/${e}`,repo:i,files:null})}return void console.log(JSON.stringify({ok:!0,...d,...u}))}let s=Jc(o),a=[`run ${_(o.runId)} \xB7 ${_(o.status)}${s?` \xB7 ${s}`:""}${o.target.treeHash?` \xB7 tree ${_(o.target.treeHash).slice(0,12)}`:""}`];o.failure?.publicMessage&&a.push(` ${_(o.failure.publicMessage)}`);let c=o.stageC;a.push(`checks ${c.checks.length} \xB7 ${c.results.pass} passed \xB7 ${c.results.fail} failed \xB7 ${c.results.blocked} could not verify \xB7 ${c.failedCheckRuns+c.cancelledCheckRuns} errored`);for(let l of c.checks){let d=Bc(l),u=d==="could_not_run"?"could not verify":d,p=l.result==="blocked"?Xt[l.blockedReason??""]:void 0;a.push(` ${_e(l.materiality)??"P3"} ${u.padEnd(16)} ${_(l.title)} ${_(l.checkRunId)}${p?` (${p})`:""}`)}console.log(a.join(`
|
|
171
|
+
`))}async function Ch(e,t,n,r){let o=await ei(n,[e,t],`/api/v1/red-team/runs/${e}/checks/${t}/finding`,r);if(!o)return;if(n)return void console.log(JSON.stringify({ok:!0,runId:e,checkRunId:t,...o}));let i=[];i.push(_(o.finding?.headline)||"(no finding written for this check yet)"),o.verdict&&i.push(`verdict: ${_(o.verdict.result)}${o.verdict.reasonOneLiner?` \u2014 ${_(o.verdict.reasonOneLiner)}`:""}${o.isStatic?" (reasoned from the code, not run)":""}`),o.assertion&&i.push(`assertion: ${_(o.assertion)}`),o.observable&&i.push(`observable: ${_(o.observable)}`),o.checkReadback?.whyThisCheck&&i.push(`why this check: ${_(o.checkReadback.whyThisCheck)}`),o.finding?.whatWasTested&&i.push(`tested: ${_(o.finding.whatWasTested)}`),o.finding?.reproduce&&i.push(`reproduce: ${_(o.finding.reproduce)}`),o.finding?.nextActionCodeRef&&i.push(`\u2192 ${Wc(o.finding.nextActionCodeRef)}`);for(let s of o.codeRefs??[])i.push(` ref ${Wc(s)}${s.reason?` \u2014 ${_(s.reason)}`:""}`);for(let s of o.evidence??[])i.push(` evidence ${_(s.modality)}: ${_(s.caption)}${s.media?` ${_(s.media.url)}`:s.failureReason?` (${_(s.failureReason)})`:""}`);for(let s of o.verdict?.limitations??[])i.push(` limitation: ${_(s)}`);o.network?.failures?.length&&i.push(` network failures: ${o.network.failures.length}`),console.log(i.join(`
|
|
172
|
+
`))}async function vh(e,t,n,r,o,i){if(await ei(o,[e,t],`/api/v1/red-team/runs/${e}/checks/${t}/report`,i,{method:"POST",body:{reported:n,...r?{note:r}:{}}})){if(o)return void console.log(JSON.stringify({ok:!0,runId:e,checkRunId:t,reported:n}));console.log(`reported ${n}${r?`: ${_(r)}`:""}`)}}async function $h(e,t,n){let r=U();if(!r)return E(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!Ze.test(e))return E(t,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let o;try{o=await Ho(e,r,{...n?{baseUrl:n}:{},onProgress:s=>console.error(` ${s}`)})}catch(s){if(s instanceof xe)return E(t,s.code,s.message,`run \`canary run wait ${e}\` again to keep waiting`,2,{runId:e});if(s instanceof A){if(s.status===404)return E(t,"not_found","no such run in your workspace",void 0,3,{httpStatus:404});let a=!ue(s)&&s.status>=400&&s.status<500;return E(t,"api_error",s.message,s.fix??(s.status===401?"run `canary login`":a?void 0:`run \`canary run wait ${e}\` again`),a?3:2,{runId:e,httpStatus:s.status})}throw s}let i=Do(o.run,o.run.target?.treeHash??"",o.findings,o.run.reverify);console.log(t?JSON.stringify(i):Uo(i)),process.exitCode=i.exitCode}function qc(e){e.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 E(r.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await _h(n,r.json===!0)}catch(o){E(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 $h(n,i)}catch(s){E(i,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}}),e.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 E(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?E(o.json===!0,"bad_report",`--${i[0]} needs a reason`,void 0,3):await vh(n,r,i[0],s,o.json===!0)}await Ch(n,r,o.json===!0)}catch(i){E(o.json===!0,"internal_error",i instanceof Error?i.message:String(i),void 0,2)}})}import{readFileSync as Ph,unlinkSync as Lh,writeFileSync as Mh}from"node:fs";import{basename as jh,join as Fh}from"node:path";import{setTimeout as Hh}from"node:timers/promises";Qe();Y();it();D();Ne();import{emitKeypressEvents as Ih}from"node:readline";var Rh=36,Oh=12,Kc=64*1024,ti=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ah={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},Eh={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function dr(e){let t=Math.max(0,Math.floor(e));return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}function Th(e,t){let n="";for(let{segment:r}of[...ti.segment(j(e))].reverse()){if(en(r+n)>t)break;n=r+n}return n}function Yc(e,t,n){let r=e.question,o=Math.max(1,t-5),i=(c,l="text")=>` ${tn(j(c),l,n)}`,s=0;if(r.secret){for(let c of ti.segment(e.input??""))if(++s===24)break}let a=r.secret?"\u2022".repeat(s):Th(e.input??"",Math.max(1,o-2));return[i("CANARY \xB7 SETUP","gold"),i(`${e.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${dr(e.seconds)}`),i(`CLI workspace ${e.workspace}`,"muted"),"",i(r.key,"gold"),...je(r.prompt,o).map(c=>i(c)),i(e.inputActive?`\u203A ${a||(r.secret?"(hidden)":"")}`:e.inputSubmitted?"Value captured locally.":"Input deferred","muted"),i(e.inputNotice??(r.secret?"Your value stays hidden.":""),"muted"),i(e.inputActive?"Enter submit \xB7 Esc/Ctrl+C later":e.inputSubmitted?"Waiting for verification to continue.":"Run canary setup to resume.","muted")]}function Nh(e,t,n,r){let o=Math.max(1,t-5),i=Math.max(1,n-2),s=e.outcome?Eh[e.outcome.status]:e.question?"Your input is needed":Ah[e.status],a=e.outcome?.status==="green"?"green":"gold",c=(u,p="text")=>tn(j(u),p,r),l;if(i<=3)l=[c(s,a),c(`Elapsed ${dr(e.seconds)}`,"muted")].slice(0,i);else if(e.question&&!e.outcome)l=Yc(e,t,r);else{let u=e.seconds%1.6,p=!e.outcome&&["pending","running"].includes(e.status)&&u<1.4?Math.sin(u/1.4*Math.PI*2)*Math.sin(u/1.4*Math.PI):0,h=bt[Math.max(0,Math.min(16,Math.round(p*10)+8))];if(t>=76&&n>=23){let f={1:c("CANARY \xB7 SETUP","gold"),3:c(s,a),5:c(`Elapsed ${dr(e.seconds)}`,"muted")};l=["",...h.map((m,g)=>` ${c(m,a)} ${f[g]??""}`)]}else l=[` ${c("CANARY \xB7 SETUP","gold")}`,` ${c(s,a)}`,` ${c(`Elapsed ${dr(e.seconds)}`,"muted")}`];l.push("",` ${c(`Repository ${e.repository}`)}`,` ${c(`CLI workspace ${e.workspace}`)}`),e.detail&&!e.outcome&&l.push(...je(e.detail,o).map(f=>` ${c(f,"muted")}`)),e.outcome||l.push("",` ${c("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(l.length>i?[...l.slice(0,Math.max(0,i-2)),...l.slice(-2)]:l).map(u=>nr(u,Math.max(1,t-1)))}function zc(e){if(e.json||!e.animation||!process.stdin.isTTY||!process.stdout.isTTY||!process.stderr.isTTY||process.env.CI||process.env.TERM==="dumb"||process.env.CANARY_NO_ANIMATION)return;let t=process.stderr,n=process.stdin,r=!process.env.NO_COLOR,o=wt(t),i=performance.now(),s={...e,status:"submitting",seconds:0},a=!1,c=!1,l,d=!1,u,p,h=()=>({columns:t.columns||80,rows:t.rows||24}),f=O=>{try{t.write(O)}catch{}},m=()=>f(`${J}0m${J}?25h`);function g(){if(a||d)return;s.seconds=(performance.now()-i)/1e3;let{columns:O,rows:F}=h();try{o.render(Nh(s,O,F,r))}catch{b()}}function k(){let{columns:O,rows:F}=h();return n.isTTY&&O>=Rh&&F>=Oh&&Yc(s,O,!1).length<=F-2}function v(){let O=s.question;if(!O)return;d=!0;try{o.render([])}catch{}let F=Math.max(1,h().columns-3);f(`
|
|
173
|
+
Input needed: ${j(O.key)}
|
|
174
|
+
${je(O.prompt,F).join(`
|
|
161
175
|
`)}
|
|
162
176
|
|
|
163
177
|
Answer with: canary setup --answer '<value>'
|
|
164
|
-
`)}function
|
|
178
|
+
`)}function w(){p&&!k()?p.settle(null,!0):g()}function y(){!a||p||c||(c=!0,process.off("SIGINT",x),process.off("SIGTERM",I),process.off("exit",b),m(),l!==void 0&&(f(`
|
|
165
179
|
Stopped watching. Run canary setup to resume verification.
|
|
166
|
-
`),process.exit(
|
|
167
|
-
`)),
|
|
168
|
-
Warning: ${O.split(/\r?\n/).map(
|
|
180
|
+
`),process.exit(l)))}function b(){a||(a=!0,clearInterval(u),t.off("resize",w),p?.settle(null),y())}function S(O){l=O,b(),y()}function x(){p?p.settle(null):S(130)}function I(){S(143)}async function q(O,F){return a||p||F?.aborted?null:(s.question={...O},s.input="",s.inputActive=!0,s.inputSubmitted=!1,s.inputNotice=void 0,d=!1,k()?new Promise(Ce=>{let vt=n.isRaw,un=n.readableFlowing===!0,oe="",ve="",ye=!1,we=!1,ee="",be=!1,De=!1,T=!1,fe=!1,te;function dn(B,P=!1){fe||(te={answer:te&&B!==null?te.answer:B,showStatic:P||te?.showStatic||!1},De||=!!ee&&!we,oe=ve="",s.input="",(ye||we||ee||De)&&(s.inputNotice="Finishing clipboard input.",g()),mr())}function mr(){if(fe||!te||be||ye||we||ee||De)return;let{answer:B,showStatic:P}=te;fe=!0,n.off("keypress",ci),n.off("data",ii),n.off("data",si),n.off("end",tt),n.off("error",tt),n.off("close",tt),F?.removeEventListener("abort",et);try{n.setRawMode(vt)}catch{}un||n.pause(),f(`${J}?2004l`),oe="",ve="",s.input="",s.inputActive=!1,s.inputSubmitted=B!==null,s.inputNotice=B===null?"You can provide this value later.":"Input received locally.",p=void 0,P&&!a?v():g(),m(),y(),Ce(B)}function et(){dn(null)}function tt(){ye=we=be=De=!1,ee="",dn(null)}function ii(B){be=!0;for(let P of typeof B=="string"?B:B.toString("utf8")){let nt=we?`${J}201~`:`${J}200~`;ee=P===nt[ee.length]?ee+P:P==="\x1B"?P:"",ee===nt&&(we=!we,ee="")}}function si(){be=!1,mr()}function ai(B){oe.length+B.length>Kc?(T=!0,s.inputNotice="Too long. Ctrl+U clears input."):(oe+=B,T||(s.inputNotice=void 0))}function ci(B,P){if(!(fe||!P))try{if(!be&&P.name==="escape"&&(ee=""),!ee&&P.sequence?.startsWith("\x1B")&&(De=!1),te){P.name==="paste-start"?ye=!0:P.name==="paste-end"&&(ye=!1),mr();return}if(P.name==="paste-start"){ye=!0,ve="";return}if(P.name==="escape"||P.ctrl&&["c","d"].includes(P.name??"")){et();return}if(P.name==="paste-end")ye=!1,ai(ve.replace(/\r\n?/g,`
|
|
181
|
+
`)),ve="";else if(ye){let nt=(B||P.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(P.sequence??"").includes("\x1B")||(ve.length+nt.length<=Kc?ve+=nt:(T=!0,s.inputNotice="Too long. Ctrl+U clears input."));return}else if(P.ctrl&&P.name==="u")oe="",T=!1,s.inputNotice=void 0;else if(P.name==="backspace")oe=[...ti.segment(oe)].slice(0,-1).map(ml=>ml.segment).join("");else if(P.name==="return"||P.name==="enter"){if(!oe.trim())s.inputNotice="Enter a value, or Esc to answer later.";else if(!T){dn(oe);return}}else!P.ctrl&&!P.meta&&B&&ai(B.replace(/[\x00-\x1f\x7f-\x9f]/g,""));s.input=oe,g()}catch{et()}}p={settle:dn};try{if(n.prependListener("data",ii),Ih(n),n.on("keypress",ci),n.on("data",si),n.once("end",tt),n.once("error",tt),n.once("close",tt),F?.addEventListener("abort",et,{once:!0}),F?.aborted){et();return}n.setRawMode(!0),n.resume(),f(`${J}?2004h${J}?25l`),g()}catch{et()}}):(s.inputActive=!1,v(),null))}return t.on("resize",w),process.on("SIGINT",x),process.on("SIGTERM",I),process.once("exit",b),u=setInterval(g,80),u.unref(),f(`${J}?25l`),g(),{update(O,F){a||(s.status=O,s.detail=F,p||(s.question=void 0,s.input=void 0,d=!1),f(`${J}?25l`),g())},warn(O){if(!a)try{o.render([])}catch{b()}f(`
|
|
182
|
+
Warning: ${O.split(/\r?\n/).map(j).join(`
|
|
169
183
|
`)}
|
|
170
184
|
|
|
171
|
-
`),g()},ask:
|
|
172
|
-
${
|
|
185
|
+
`),g()},ask:q,finish(O){if(a)return;p?.settle(null),s.question=void 0,s.outcome=O,d=!1,g(),b();let F=[O.message,...O.updatedFiles?.length?[`Updated locally: ${O.updatedFiles.join(", ")}`]:[],...O.warning?[`Warning: ${O.warning}`]:[],...O.next?[`Next: ${O.next}`]:[]].filter(Ce=>!!Ce);F.length&&f(`
|
|
186
|
+
${F.flatMap(Ce=>Ce.split(/\r?\n/).map(j)).join(`
|
|
173
187
|
`)}
|
|
174
|
-
`)},stop:
|
|
175
|
-
`);function
|
|
176
|
-
Fix: ${
|
|
177
|
-
`).length,s=
|
|
178
|
-
`)||void 0,next:`Open Canary: ${
|
|
188
|
+
`)},stop:b}}mo();Dn();ne();mt();Lo();No();var St=3e3,fr=2,Dh=9e4,Xc=new Set(["pending","running","needs_input","green","red","error","interrupted"]);function X(e,t){for(let n of[...e.secrets].sort((r,o)=>o.length-r.length))n&&(t=t.split(n).join("[redacted]"));return t}var ni=e=>Fh(e,".canary","verify-job.json");function an(e){try{let t=JSON.parse(Ph(ni(e),"utf8"));if(!t||typeof t.jobId!="string"||!t.jobId)throw new Error("invalid job ID");if(t.sourceUploadId!==void 0&&(typeof t.sourceUploadId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t.sourceUploadId)))throw new Error("invalid source upload ID");if(t.scope&&(!t.source||!Xn(t.source)||typeof t.recipeHash!="string"||typeof t.scope.apiUrl!="string"||![t.scope.userId,t.scope.workspaceId,t.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=t.workspace&&typeof t.workspace.id=="string"&&typeof t.workspace.name=="string"?{id:t.workspace.id,name:t.workspace.name}:void 0;return{jobId:t.jobId,...typeof t.recipeHash=="string"?{recipeHash:t.recipeHash}:{},...n?{workspace:n}:{},...t.scope?{scope:t.scope}:{},...t.source?{source:t.source}:{},...t.sourceUploadId?{sourceUploadId:t.sourceUploadId}:{}}}catch(t){if(t.code==="ENOENT")return null;throw new se("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 Uh(e){return an(e)?.jobId??null}var Zc=(e,t)=>Mh(ni(e),JSON.stringify(t)+`
|
|
189
|
+
`);function pr(e){try{Lh(ni(e))}catch{}}var xt=(e,t)=>Hh(e,void 0,{signal:t});function Gh(e){let t=e?.setup?.services;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?n.name:void 0).filter(n=>typeof n=="string"):[]}function Jh(e,t){let n,r;try{n=Me(e),Ft(e),r=dt(e).name}catch(u){if(u instanceof se||u instanceof M){t?console.log(JSON.stringify({ok:!1,error:u.code,message:u.message,..."fix"in u&&u.fix?{fix:u.fix}:{}})):console.error(`\u2717 ${u.message}${"fix"in u&&u.fix?`
|
|
190
|
+
Fix: ${u.fix}`:""}`),process.exitCode=1;return}throw u}let o=r??null,i=n.setupSh.trim().split(`
|
|
191
|
+
`).length,s=Gh(n.runJson),a=[...new Set([...n.envManifest.map(u=>u.name),...Object.keys(n.envValues)])],c=n.envManifest.filter(u=>u.neededAt==="boot").map(u=>u.name),{missing:l}=ho(n.envManifest,n.envValues),d=l.length===0;t?console.log(JSON.stringify({ok:d,repo:o,recipe:{setupShLines:i,services:s,envKeys:a,bootRequired:c,missing:l}})):(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 ${c.length} boot-required \xB7 ${l.length?`MISSING: ${l.join(", ")}`:"all present"}`),d?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${l.join(", ")} (boot-required) ${l.length===1?"has":"have"} no value.`)),d||(process.exitCode=1)}async function Qc(e,t,n,r,o={}){if(t.status==="green"){let i=an(e),s=i?.workspace,a=o.recipeChanged??!1;if(i?.recipeHash)try{a||=Ke(Me(e))!==i.recipeHash}catch{a=!0}let c=!1;if(i?.source){let u=(h,f)=>h.sha256===f.sha256&&h.treeHash===f.treeHash&&h.baseTreeHash===f.baseTreeHash&&h.baseSha===f.baseSha&&h.provenance.baselineMode===f.provenance.baselineMode&&(h.provenance.baseRef??null)===(f.provenance.baseRef??null);if(t.approved?.source&&!u(t.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 p;try{p=await qt(e,{baseRef:i.source.provenance.baseRef??void 0}),c=p.manifest.treeHash!==i.source.treeHash||p.manifest.baseTreeHash!==i.source.baseTreeHash||p.manifest.provenance.baselineMode!==i.source.provenance.baselineMode||(p.manifest.provenance.baseRef??null)!==(i.source.provenance.baseRef??null)}catch{c=!0}finally{await p?.dispose()}}if(i?.recipeHash)try{a||=Ke(Me(e))!==i.recipeHash}catch{a=!0}let l=o.writeBack!==!1&&!a&&!c;if(a||c){let u="This result is for the files as they were when submitted. They changed since, so the approved recipe was not written over your files. Run canary setup again to verify the current files.";r.warnings.push(u),!n&&!r.display&&console.error(`! ${u}`)}pr(e);let d=[];if(t.approved?.healed&&l)try{d=Ms(e,t.approved)}catch(u){let p=X(r,`Could not update .canary/ with the approved changes: ${u instanceof Error?u.message:String(u)}`);r.warnings.push(p),r.display||console.error(`! ${p}`)}return n?console.log(JSON.stringify({ok:!0,status:"green",jobId:t.jobId,...s?{workspace:s}:{},...a?{recipeChanged:!0}:{},...c?{sourceChanged:!0}:{},...i?.source?{source:i.source,repositoryId:i.scope?.repositoryId}:{},...t.approved?{approved:{healed:t.approved.healed,...t.approved.recipeId?{recipeId:t.approved.recipeId}:{},...t.approved.recipeVersionId?{recipeVersionId:t.approved.recipeVersionId}:{},...t.approved.version!==void 0?{version:t.approved.version}:{},...d.length?{updatedFiles:d}:{}}}:{}})):r.display?r.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${s?` Workspace: ${s.name}.`:""}`,updatedFiles:d,warning:r.warnings.join(`
|
|
192
|
+
`)||void 0,next:`Open Canary: ${Ie().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}`),t.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),d.length?console.log(` Updated locally to match: ${d.join(", ")}`):l||console.log(" Its approved version was not written over your newer files."))),!0}if(t.status==="interrupted")return!1;if(t.status==="red"||t.status==="error"){pr(e);let i={phase:t.failure?.phase?X(r,t.failure.phase):null,failingCommand:t.failure?.failingCommand?X(r,t.failure.failingCommand):null,log:t.failure?.log?X(r,t.failure.log):null};return n?console.log(JSON.stringify({ok:!1,status:t.status,jobId:t.jobId,failure:i})):r.display?r.display.finish({status:t.status,message:`Verification ${t.status==="error"?"errored":"failed"}${i.phase?` (${i.phase})`:""}${i.failingCommand?` at: ${i.failingCommand}`:""}${i.log?`
|
|
179
193
|
|
|
180
194
|
${i.log.slice(-2e3)}`:""}`,warning:r.warnings.join(`
|
|
181
|
-
`)||void 0,next:"Fix the recipe in .canary/ and run canary setup again."}):(console.error(`\u2717 Verify ${
|
|
182
|
-
${i.log.slice(-2e3)}`),console.error("\nFix the recipe in .canary/ and run `canary setup` again.")),process.exitCode=1,!0}if(
|
|
183
|
-
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function
|
|
184
|
-
`+(
|
|
185
|
-
Fix: ${a}`:""}`)}else if(i instanceof
|
|
186
|
-
Fix: ${a}`:""}`)}else{let s=
|
|
187
|
-
`,{flag:"w",mode:384})}catch{}}function
|
|
188
|
-
`,exit:1}:{stream:"stderr",text:`\u2717 ${
|
|
189
|
-
`,exit:1};if(
|
|
190
|
-
`,exit:0}}return{stream:"stdout",text:`${
|
|
191
|
-
|
|
192
|
-
${
|
|
195
|
+
`)||void 0,next:"Fix the recipe in .canary/ and run canary setup again."}):(console.error(`\u2717 Verify ${t.status==="error"?"errored":"failed"}${i.phase?` (${i.phase})`:""}${i.failingCommand?` at: ${i.failingCommand}`:""}`),i.log&&console.error(`
|
|
196
|
+
${i.log.slice(-2e3)}`),console.error("\nFix the recipe in .canary/ and run `canary setup` again.")),process.exitCode=1,!0}if(t.status==="needs_input"&&t.needsInput){let i={...t.needsInput,key:X(r,t.needsInput.key),prompt:X(r,t.needsInput.prompt)};return n?console.log(JSON.stringify({ok:!1,status:"needs_input",jobId:t.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(`
|
|
197
|
+
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function el(e,t){return e.status==="needs_input"&&e.needsInput?.questionId===t.questionId}async function Bh(e,t,n){let r=new AbortController,o=new AbortController,i=e.display.ask({...t,key:X(e,t.key),prompt:X(e,t.prompt)},r.signal).then(a=>({kind:"answer",value:a})),s=(async()=>{for(;;){await xt(St,o.signal);let a=await n(o.signal);if(!el(a,t))return{kind:"state",view:a}}})();try{return await Promise.race([i,s])}finally{o.abort(),r.abort(),await Promise.allSettled([i,s])}}async function Wh(e,t,n,r,o,i){let s="",a=null;async function c(d){for(;;)try{let u=await R(`/api/v1/cli/verify/${t}`,{token:n,baseUrl:o.context?.apiUrl,signal:d});if(!u||!Xc.has(u.status))throw new Error("Verification returned an unrecognized state. Run canary setup again to retry.");return a=null,u}catch(u){if(d?.aborted)throw u;if(u instanceof A&&u.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<Dh)){await xt(St,d);continue}throw u}}let l;for(;;){let d=l??await c();if(l=void 0,d.status==="interrupted")return"interrupted";if(d.status==="needs_input"&&i&&d.needsInput?.questionId===i.questionId&&Date.now()<i.until){await xt(St);continue}if(d.status==="needs_input"&&d.needsInput&&o.display){let u=d.needsInput,p=await Bh({...o,display:o.display},u,c);if(p.kind==="state"){l=p.view;continue}let h=p.value;if(h===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 c();if(!el(f,u)){l=f;continue}o.display.update("answering","Sending your answer to the verifier.");try{await rl(e,t,n,u,h,r,o)}catch(m){if(m instanceof A&&m.status===409)continue;throw m}i={questionId:u.questionId,until:Date.now()+3e4},o.display.update("answering","Answer received. Waiting for verification to continue."),await xt(St);continue}if((d.status==="pending"||d.status==="running")&&(o.display?o.display.update(d.status):d.status!==s&&!r&&console.log(` \u2026 ${d.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),s=d.status,await Qc(e,d,r,o))return"terminal";await xt(St)}}async function hr(e,t,n,r,o,i){ot();let s=t;for(let a=0;;){if(await Wh(e,s,n,r,o,i)==="terminal")return;if(pr(e),o.freshUpload=!0,a>=fr){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:fr})):o.display?o.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${fr}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${fr})`);let l=await nl(e,n,r,o);if(l===null)return;s=l,i=void 0}}async function tl(e,t,n,r){let o=r.context??=await Gt(e,t),i=n.scope;if(i.apiUrl.replace(/\/+$/,"")!==o.apiUrl.replace(/\/+$/,"")||i.userId!==o.userId||i.workspaceId!==o.workspaceId)throw new M("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 Ut({...o,token:t})).repositoryId!==i.repositoryId)throw new M("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,Po(n.source,o,i.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function nl(e,t,n,r){let o=Me(e);Ft(e);let{missing:i}=ho(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 Gt(e,t),a=await Ut({...s,token:t}),c=await qt(e,{baseRef:r.baseRef});try{r.display?.update("submitting","Uploading your local source and the .canary/ recipe.");let l=Ke(o),d=await Zn(c,s,a.repositoryId,t,{requestKey:`setup:${l}`,fresh:r.freshUpload});r.freshUpload=!1;let u=await R("/api/v1/cli/verify",{method:"POST",token:t,baseUrl:s.apiUrl,body:{workspaceId:s.workspaceId,repositoryId:a.repositoryId,source:d,setupSh:o.setupSh,runJson:JSON.stringify(o.runJson??null),env:{manifest:o.envManifest,values:o.envValues}}});if(!u?.jobId||u.repositoryId!==a.repositoryId||u.workspace&&u.workspace.id!==s.workspaceId||u.source&&u.source.sha256!==c.manifest.sha256)throw new Error("Canary's answer does not match the repository and source that were uploaded. Run canary setup again.");return Zc(e,{jobId:u.jobId,recipeHash:l,workspace:u.workspace??a.workspace,source:c.manifest,sourceUploadId:d.uploadId,scope:{apiUrl:s.apiUrl,userId:s.userId,workspaceId:s.workspaceId,repositoryId:a.repositoryId}}),Po(c.manifest,s,a.repositoryId,{requestKey:`setup:${l}`,uploadId:d.uploadId}),u.jobId}finally{await c.dispose()}}async function Vh(e,t,n){let r=U();if(!r){t?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}mn();let o=an(e);o?.scope&&await tl(e,r,o,n);let i=o?.jobId??null;if(i){n.display?.update("submitting","Checking your saved verification job.");let a=null,c=!1,l=Date.now()+3e4;for(;;)try{if(a=await R(`/api/v1/cli/verify/${i}`,{token:r,baseUrl:n.context?.apiUrl}),!a||!Xc.has(a.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(d){if(d instanceof A&&d.status===0){if(Date.now()<l){n.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await xt(St);continue}c=!0}else if(!(d instanceof A&&d.status===404))throw d;break}if(c){t?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."):t||console.log(`Resuming verify job ${i} \u2026`),await hr(e,i,r,t,n);return}if(a.status==="green"||a.status==="red"||a.status==="error"){let d=!1;if(o?.recipeHash)try{d=Ke(Me(e))!==o.recipeHash}catch{d=!0}t?console.error(JSON.stringify({event:"previous_job_result",jobId:i,...d?{recipeChanged:!0}:{}})):n.display?n.warnings.push(d?"This is your earlier verification result, and .canary/ changed since it was submitted: its approved version was not written over your files. Run canary setup again to verify the current files.":"This is your earlier verification result. If you changed .canary/ since then, run canary setup again to verify the current files."):console.log(`Your earlier verify job ${i} finished after the previous run stopped \u2014 applying its result now.
|
|
198
|
+
`+(d?" .canary/ changed since it was submitted, so its approved version was NOT written over your files. Run `canary setup` again to verify the current files.":" If you changed .canary/ since then, run `canary setup` again to verify the current files.")),await Qc(e,a,t,n,{writeBack:!d,recipeChanged:d});return}}pr(e),n.freshUpload=!0}let s=await nl(e,r,t,n);s!==null&&(n.display?n.display.update("pending","Recipe sent. Waiting for the cloud verifier."):t||console.log(`Shipped the recipe \u2014 verify job ${s}`),await hr(e,s,r,t,n))}async function rl(e,t,n,r,o,i,s){if(r.secret&&o&&s.secrets.add(o),await R(`/api/v1/cli/verify/${t}/answer`,{method:"POST",token:n,baseUrl:s.context?.apiUrl,body:{questionId:r.questionId,value:o}}),r.secret){let a=an(e),c=!1;try{c=!!a?.recipeHash&&Ke(Me(e))===a.recipeHash}catch{}try{if(a?.recipeHash&&!c)throw new Error("Local recipe changed since submission; the answered value was not written over it.");go(e,[{name:r.key,value:o,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),c&&a&&Zc(e,{...a,recipeHash:Ke(Me(e))}),!i&&!s.display&&console.log(`Saved ${X(s,r.key)} to .canary/env.json for future runs.`)}catch(l){let d=X(s,`Could not save ${r.key} to .canary/env.json: ${l instanceof Error?l.message:String(l)}`);s.display?s.display.warn(d):console.error(`! ${d}`)}}}async function qh(e,t,n,r){let o=U(),i=Uh(e);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=an(e);s?.scope&&await tl(e,o,s,r);let a=await R(`/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 hr(e,i,o,n,r);return}let c=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await rl(e,i,o,c,t,n,r),r.display?r.display.update("answering","Answer received. Waiting for verification to continue."):n||console.log(`Answered ${X(r,c.key)} \u2014 resuming \u2026`),await hr(e,i,o,n,r,{questionId:c.questionId,until:Date.now()+3e4})}function ol(e){e.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 t=>{let n=t.dir??process.cwd();Be({cwd:n});let r=t.json===!0;if(t.check){Jh(n,r);return}let o={secrets:new Set(t.answer?[t.answer]:[]),warnings:[],baseRef:t.base};try{let i=N().team;o.display=zc({json:r,animation:t.animation!==!1,repository:jh(n),workspace:i?.name||(i?.id?"Saved workspace":"Select a workspace")}),t.answer!==void 0?await qh(n,t.answer,r,o):await Vh(n,r,o)}catch(i){if(i instanceof se||i instanceof ce||i instanceof M){let s=X(o,i.message),a="fix"in i&&i.fix?X(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?`
|
|
199
|
+
Fix: ${a}`:""}`)}else if(i instanceof A){let s=X(o,i.message),a="fix"in i&&i.fix?X(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?`
|
|
200
|
+
Fix: ${a}`:""}`)}else{let s=X(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 Qt({json:r})})}yt();D();Ne();import{lstatSync as Kh,mkdirSync as Yh,readFileSync as il,writeFileSync as sl}from"node:fs";import{join as ri}from"node:path";var zh=5e3,Xh=/^[a-z0-9][a-z0-9-]{0,39}$/,Zh=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,Qh="npm i -g @runcanary/cli@latest";function cl(e){let t=ri(Z(),"skills");return{dir:t,body:ri(t,`${e}.md`),meta:ri(t,`${e}.json`)}}function eg(e){let t=cl(e);try{let n=JSON.parse(il(t.meta,"utf8"));return{body:il(t.body,"utf8"),meta:n}}catch{return null}}function cn(e){try{return Kh(e).isSymbolicLink()}catch{return!1}}function tg(e,t){let n=cl(e);try{if(cn(Z())||cn(n.dir)||cn(n.body)||cn(n.meta)||(Yh(n.dir,{recursive:!0,mode:448}),cn(n.dir)))return;sl(n.body,t.body,{flag:"w",mode:384}),sl(n.meta,JSON.stringify(t.meta,null,2)+`
|
|
201
|
+
`,{flag:"w",mode:384})}catch{}}function al(e){return e instanceof Error?e.message:String(e)}async function ng(e,t){let n;try{n=await fetch(e,{headers:{...Te(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${t}`},signal:AbortSignal.timeout(zh)})}catch(r){return{kind:"failed",reason:al(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: ${al(r)}`}}}async function oi(e){let t=await ng(e.url,e.cliVersion);switch(t.kind){case"ok":{let n={url:e.url,fetchedAt:new Date().toISOString(),cliVersion:e.cliVersion,contentVersion:t.contentVersion};return tg(e.key,{body:t.body,meta:n}),{ok:!0,body:t.body,url:e.url,contentVersion:t.contentVersion,offline:!1}}case"missing":return{ok:!1,error:e.notFound};case"failed":{let n=eg(e.key);if(n&&n.meta.url===e.url)return{ok:!0,body:n.body,url:e.url,contentVersion:n.meta.contentVersion,offline:!0,reason:t.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 ${e.url} failed (${t.reason}) and ${r} \u2014 retry when the server is reachable`}}}}function rg(e,t){let n=i=>i.replace(/^v/,"").split("-")[0].split(".").map(s=>Number.parseInt(s,10)||0),r=n(e),o=n(t);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 og(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);if(t)return/^minCli:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m.exec(t[1])?.[1]}function ll(e){return e.offline?`OFFLINE COPY \u2014 live fetch of ${e.url} failed (${e.reason}). Showing the copy fetched ${e.fetchedAt} by CLI ${e.savedByCli}; it may be outdated.`:`Source: ${e.url}${e.contentVersion?` (content version ${e.contentVersion})`:""}`}function _t(e,t,n={}){if(!e.ok)return t?{stream:"stdout",text:JSON.stringify({ok:!1,error:e.error,...n})+`
|
|
202
|
+
`,exit:1}:{stream:"stderr",text:`\u2717 ${e.error}
|
|
203
|
+
`,exit:1};if(t){let r={ok:!0,source:e.url,contentVersion:e.contentVersion??null,offline:e.offline,...e.offline?{reason:e.reason,fetchedAt:e.fetchedAt}:{},...n,body:e.body};return{stream:"stdout",text:JSON.stringify(r)+`
|
|
204
|
+
`,exit:0}}return{stream:"stdout",text:`${ll(e)}
|
|
205
|
+
|
|
206
|
+
${e.body}${e.body.endsWith(`
|
|
193
207
|
`)?"":`
|
|
194
|
-
`}`,exit:0}}function
|
|
195
|
-
`,exit:0}}function
|
|
208
|
+
`}`,exit:0}}function ln(e){(e.stream==="stdout"?process.stdout:process.stderr).write(e.text),process.exit(e.exit)}function ig(e,t,n={}){if(!e.ok||t){let r=_t(e,t,n);return r.stream==="stdout"?{stdout:r.text,stderr:"",exit:r.exit}:{stdout:"",stderr:r.text,exit:r.exit}}return{stdout:e.body,stderr:`${ll(e)}
|
|
209
|
+
`,exit:0}}function gr(){return W().replace(/\/+$/,"")}function ul(e){e.command("skills").description("List the operations a coding agent can perform with Canary (hosted index)").option("--json","output machine-readable JSON").action(async t=>{let n=await oi({key:"index",url:`${gr()}/llms.txt`,cliVersion:e.version()??"0.0.0",notFound:`this Canary server (${gr()}) does not publish skills yet`});ln(_t(n,!!t.json))}),e.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(t,n)=>{let r=!!n.json;Xh.test(t)||ln(_t({ok:!1,error:`invalid operation name "${t.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},r));let o=e.version()??"0.0.0";if(n.asset!==void 0){Zh.test(n.asset)||ln(_t({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 oi({key:`${t}--${n.asset}`,url:`${gr()}/skills/${t}/${n.asset}`,cliVersion:o,notFound:`no such asset "${n.asset}" for "${t}" \u2014 run \`canary skill ${t}\` to see which files it publishes`}),a=ig(s,r,{name:t,asset:n.asset});a.stderr&&process.stderr.write(a.stderr);let c=()=>process.exit(a.exit);a.stdout?process.stdout.write(a.stdout,c):c()}let i=await oi({key:t,url:`${gr()}/skills/${t}.md`,cliVersion:o,notFound:`no such operation "${t}" \u2014 run \`canary skills\` to list the operations`});if(i.ok){let s=og(i.body);if(s&&o!=="0.0.0-dev"&&rg(o,s)<0){let a=`"${t}" needs Canary CLI ${s} or newer (you have ${o}). Update: ${Qh}`,c=_t({ok:!1,error:a},r,{needsCli:s,cliVersion:o});ln({...c,exit:2})}}ln(_t(i,r,{name:t}))})}Y();D();Qe();var sg=3e3;function ag(e){let t=e.periodEnd?` \xB7 resets ${new Date(e.periodEnd).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`:"";return e.limit===null?`Runs this month: ${e.used} \xB7 no limit`:`Runs this month: ${e.used} of ${e.limit}${t}`}function dl(e){e.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0,r=U();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=N().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 R(`/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,c=Vo(),l=c&&a?await er({token:r,apiUrl:W().replace(/\/+$/,""),userId:s.user.id},c,a.id,AbortSignal.timeout(sg)):void 0,d=Bo();if(n)console.log(JSON.stringify({ok:!0,user:s.user,team:s.team,workspace:a,...s.usage?{usage:s.usage}:{},...c?{repository:{name:c,...l?.state?{state:l.state}:{}}}:{},...d.length?{pushCheck:{pending:d}}:{}}));else{console.log(`${s.user.email} (${a?.name??"No workspace selected"})`),s.usage&&console.log(ag(s.usage)),c&&(console.log(rr(c,l?.state)),console.log(nn(l?.state)));for(let u of d)console.log(`Push check on ${u.label}: ${u.why} Run \`${u.command}\` in a terminal. ${u.after}`)}}catch(o){let i=o instanceof A&&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}})}Y();D();ne();async function hl(){let e=U();if(!e)throw new A(401,"not logged in");let{workspaces:t}=await R("/api/v1/cli/workspaces",{token:e});return t}function Ct(e,t,n,r={}){e?console.log(JSON.stringify({ok:!1,error:t,message:n,...r})):console.error(n),process.exitCode=1}function fl(e,t){if(t instanceof A&&t.status===401){Ct(e,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}Ct(e,"workspace_error",t instanceof Error?t.message:String(t))}async function cg(e){let t=await hl(),n=N().team?.id;if(e){console.log(JSON.stringify({workspaces:t,active:n??null}));return}if(t.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(t.length).length;t.forEach((o,i)=>{let s=o.id===n?"*":" ",a=String(i+1).padStart(r," ");console.log(`${s} ${a} ${o.name}`)})}function pl(e,t){if(!K(n=>({...n,team:{id:e.id,name:e.name}}))){Ct(t,"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}Fn(),console.log(t?JSON.stringify({ok:!0,workspace:{id:e.id,name:e.name}}):`Switched to ${e.name}.`)}async function lg(e,t){let n=await hl(),r=e.trim();if(/^\d+$/.test(r)){let i=Number(r);if(i<1||i>n.length){Ct(t,"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}pl(n[i-1],t);return}let o=n.filter(i=>i.id===r||i.name.toLowerCase()===r.toLowerCase());if(o.length===0){Ct(t,"workspace_not_found",`No workspace matching "${e}".`,{available:n.map(i=>({id:i.id,name:i.name})),fix:"canary workspace list"});return}if(o.length>1){Ct(t,"workspace_ambiguous",`"${e}" 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}pl(o[0],t)}function ug(e){let t=N().team;if(!t){e?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(e?JSON.stringify({workspace:t}):t.name)}function gl(e){let t=e.command("workspace").description("List and switch Canary workspaces");t.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 cg(r)}catch(o){fl(r,o)}}),t.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 lg(n,o)}catch(i){fl(o,i)}}),t.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>ug(n.json===!0))}ne();it();var re=new xi;re.name("canary").description("Canary \u2014 break the code your AI writes.").version(Ae);process.argv[2]!=="hook"&&Bi();process.argv[2]!=="hook"&&Dt();yc(re);dl(re);Dc(re);ul(re);gl(re);ol(re);Ya(re);qc(re);vc(re);Cc(re);Wo(re);Hc(re);re.parseAsync(process.argv).catch(e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)});
|
|
210
|
+
/*! Bundled license information:
|
|
211
|
+
|
|
212
|
+
smol-toml/dist/error.js:
|
|
213
|
+
smol-toml/dist/primitive.js:
|
|
214
|
+
smol-toml/dist/date.js:
|
|
215
|
+
smol-toml/dist/extract.js:
|
|
216
|
+
smol-toml/dist/util.js:
|
|
217
|
+
smol-toml/dist/struct.js:
|
|
218
|
+
smol-toml/dist/parse.js:
|
|
219
|
+
smol-toml/dist/stringify.js:
|
|
220
|
+
smol-toml/dist/index.js:
|
|
221
|
+
(*!
|
|
222
|
+
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
223
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
224
|
+
*
|
|
225
|
+
* Redistribution and use in source and binary forms, with or without
|
|
226
|
+
* modification, are permitted provided that the following conditions are met:
|
|
227
|
+
*
|
|
228
|
+
* 1. Redistributions of source code must retain the above copyright notice, this
|
|
229
|
+
* list of conditions and the following disclaimer.
|
|
230
|
+
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
231
|
+
* this list of conditions and the following disclaimer in the
|
|
232
|
+
* documentation and/or other materials provided with the distribution.
|
|
233
|
+
* 3. Neither the name of the copyright holder nor the names of its contributors
|
|
234
|
+
* may be used to endorse or promote products derived from this software without
|
|
235
|
+
* specific prior written permission.
|
|
236
|
+
*
|
|
237
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
238
|
+
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
239
|
+
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
240
|
+
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
241
|
+
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
242
|
+
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
243
|
+
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
244
|
+
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
245
|
+
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
246
|
+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
247
|
+
*)
|
|
248
|
+
*/
|