@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.
Files changed (3) hide show
  1. package/README.md +7 -0
  2. package/dist/canary.js +180 -127
  3. 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 dc=Object.create;var Yn=Object.defineProperty;var fc=Object.getOwnPropertyDescriptor;var pc=Object.getOwnPropertyNames;var hc=Object.getPrototypeOf,gc=Object.prototype.hasOwnProperty;var wt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var Pe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),mc=(t,e)=>{for(var n in e)Yn(t,n,{get:e[n],enumerable:!0})},yc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pc(e))!gc.call(t,o)&&o!==n&&Yn(t,o,{get:()=>e[o],enumerable:!(r=fc(e,o))||r.enumerable});return t};var wc=(t,e,n)=>(n=t!=null?dc(hc(t)):{},yc(e||!t||!t.__esModule?Yn(n,"default",{value:t,enumerable:!0}):n,t));var bt=Pe(zn=>{var Xt=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Kn=class extends Xt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};zn.CommanderError=Xt;zn.InvalidArgumentError=Kn});var Qt=Pe(Qn=>{var{InvalidArgumentError:bc}=bt(),Xn=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new bc(`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 kc(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Qn.Argument=Xn;Qn.humanReadableArgName=kc});var er=Pe($o=>{var{humanReadableArgName:Sc}=Qt(),Zn=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(o=>!o._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((o,i)=>o.name().localeCompare(i.name())),n}compareOptions(e,n){let r=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(o=>!o.hidden),r=e._getHelpOption();if(r&&!r.hidden){let o=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!o&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!o&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let o=r.options.filter(i=>!i.hidden);n.push(...o)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>Sc(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,o)=>Math.max(r,n.subcommandTerm(o).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,o)=>Math.max(r,n.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,o)=>Math.max(r,n.optionTerm(o).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,o)=>Math.max(r,n.argumentTerm(o).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let o=e.parent;o;o=o.parent)r=o.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),o=n.helpWidth||80,i=2,s=2;function a(f,m){if(m){let g=`${f.padEnd(r+s)}${m}`;return n.wrap(g,o-i,r+s)}return f}function l(f){return f.join(`
5
- `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${n.commandUsage(e)}`,""],u=n.commandDescription(e);u.length>0&&(c=c.concat([n.wrap(u,o,0),""]));let d=n.visibleArguments(e).map(f=>a(n.argumentTerm(f),n.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let h=n.visibleOptions(e).map(f=>a(n.optionTerm(f),n.optionDescription(f)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let f=n.visibleGlobalOptions(e).map(m=>a(n.optionTerm(m),n.optionDescription(m)));f.length>0&&(c=c.concat(["Global Options:",l(f),""]))}let p=n.visibleCommands(e).map(f=>a(n.subcommandTerm(f),n.subcommandDescription(f)));return p.length>0&&(c=c.concat(["Commands:",l(p),""])),c.join(`
6
- `)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,o=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",s=new RegExp(`[\\n][${i}]+`);if(e.match(s))return e;let a=n-r;if(a<o)return e;let l=e.slice(0,r),c=e.slice(r).replace(`\r
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
- `),u=" ".repeat(r),h="\\s\u200B",p=new RegExp(`
9
- |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=c.match(p)||[];return l+f.map((m,g)=>m===`
10
- `?"":(g>0?u:"")+m.trimEnd()).join(`
11
- `)}};$o.Help=Zn});var or=Pe(rr=>{var{InvalidArgumentError:xc}=bt(),tr=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=vc(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new xc(`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 _c(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},nr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let o=this.negativeOptions.get(r).presetArg,i=o!==void 0?o:!1;return n.negate===(i===e)}};function _c(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function vc(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}rr.Option=tr;rr.DualOptions=nr});var Ro=Pe(Io=>{function Cc(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let i=1;t[o-1]===e[r-1]?i=0:i=1,n[o][r]=Math.min(n[o-1][r]+1,n[o][r-1]+1,n[o-1][r-1]+i),o>1&&r>1&&t[o-1]===e[r-2]&&t[o-2]===e[r-1]&&(n[o][r]=Math.min(n[o][r],n[o-2][r-2]+1))}return n[t.length][e.length]}function $c(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let r=[],o=3,i=.4;return e.forEach(s=>{if(s.length<=1)return;let a=Cc(t,s),l=Math.max(t.length,s.length);(l-a)/l>i&&(a<o?(o=a,r=[s]):a===o&&r.push(s))}),r.sort((s,a)=>s.localeCompare(a)),n&&(r=r.map(s=>`--${s}`)),r.length>1?`
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]}?)`:""}Io.suggestSimilar=$c});var No=Pe(To=>{var Ic=wt("node:events").EventEmitter,ir=wt("node:child_process"),be=wt("node:path"),sr=wt("node:fs"),L=wt("node:process"),{Argument:Rc,humanReadableArgName:Oc}=Qt(),{CommanderError:ar}=bt(),{Help:Ec}=er(),{Option:Oo,DualOptions:Ac}=or(),{suggestSimilar:Eo}=Ro(),cr=class t extends Ic{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:n=>L.stdout.write(n),writeErr:n=>L.stderr.write(n),getOutHelpWidth:()=>L.stdout.isTTY?L.stdout.columns:void 0,getErrHelpWidth:()=>L.stderr.isTTY?L.stderr.columns:void 0,outputError:(n,r)=>r(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let o=n,i=r;typeof o=="object"&&o!==null&&(i=o,o=null),i=i||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return o&&(l.description(o),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),o?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Ec,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
14
- - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new Rc(e,n)}argument(e,n,r,o){let i=this.createArgument(e,n);return typeof r=="function"?i.default(o).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,o]=e.match(/([^ ]+) *(.*)/),i=n??"display help for command",s=this.createCommand(r);return s.helpOption(!1),o&&s.arguments(o),i&&s.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
- Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new ar(e,n,r)),L.exit(e)}action(e){let n=r=>{let o=this.registeredArguments.length,i=r.slice(0,o);return this._storeOptionsAsProperties?i[o]=this:i[o]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new Oo(e,n)}_callParseArg(e,n,r,o){try{return e.parseArg(n,r)}catch(i){if(i.code==="commander.invalidArgument"){let s=`${o} ${i.message}`;this.error(s,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
16
- - already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=o=>[o.name()].concat(o.aliases()),r=n(e).find(o=>this._findCommand(o));if(r){let o=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let o=(i,s,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,s):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,a)};return this.on("option:"+n,i=>{let s=`error: option '${e.flags}' argument '${i}' is invalid.`;o(i,s,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let s=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;o(i,s,"env")}),this}_optionEx(e,n,r,o,i){if(typeof n=="object"&&n instanceof Oo)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(n,r);if(s.makeOptionMandatory(!!e.mandatory),typeof o=="function")s.default(i).argParser(o);else if(o instanceof RegExp){let a=o;o=(l,c)=>{let u=a.exec(l);return u?u[0]:c},s.default(i).argParser(o)}else s.default(o);return this.addOption(s)}option(e,n,r,o){return this._optionEx({},e,n,r,o)}requiredOption(e,n,r,o){return this._optionEx({mandatory:!0},e,n,r,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){L.versions?.electron&&(n.from="electron");let o=L.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(n.from="eval")}e===void 0&&(e=L.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":L.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let h=be.resolve(u,d);if(sr.existsSync(h))return h;if(o.includes(be.extname(d)))return;let p=o.find(f=>sr.existsSync(`${h}${f}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=sr.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=be.resolve(be.dirname(u),a)}if(a){let u=i(a,s);if(!u&&!e._executableFile&&this._scriptPath){let d=be.basename(this._scriptPath,be.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}s=u||s}r=o.includes(be.extname(s));let l;L.platform!=="win32"?r?(n.unshift(s),n=Ao(L.execArgv).concat(n),l=ir.spawn(L.argv[0],n,{stdio:"inherit"})):l=ir.spawn(s,n,{stdio:"inherit"}):(n.unshift(s),n=Ao(L.execArgv).concat(n),l=ir.spawn(L.execPath,n,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{L.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new ar(u,"commander.executeSubCommandAsync","(close)")):L.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${s}' does not exist
17
- - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
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
- - ${d}`;throw new Error(h)}else if(u.code==="EACCES")throw new Error(`'${s}' not executable`);if(!c)L.exit(1);else{let d=new ar(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,n,r){let o=this._findCommand(e);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(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,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)=>e(r,a,s),r.defaultValue))):i===void 0&&(i=[]):o<this.args.length&&(i=this.args[o],r.parseArg&&(i=e(r,i,r.defaultValue))),n[o]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,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(e,n,r){let o=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{o=this._chainOrCall(o,()=>i(this,n))}),o}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,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,e,n)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(i))o(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let o=r.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let o=e.find(i=>r.conflictsWith.includes(i.attributeName()));o&&this._conflictingOption(r,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],r=[],o=n,i=e.slice();function s(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){o===r&&o.push(l),o.push(...i);break}if(a&&!s(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let c=this._findOption(l);if(c){if(c.required){let u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!s(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(s(l)&&(o=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(l)){n.push(l),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){n.push(l),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(l),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){o.push(l),i.length>0&&o.push(...i);break}o.push(l)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;r++){let o=this.options[r].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
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,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in L.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,L.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ac(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(o=>!n(o)).forEach(o=>{this.setOptionValueWithSource(o,r.implied[o],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=s=>{let a=s.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||s},o=s=>{let a=r(s),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${o(e)} cannot be used with ${o(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],i=this;do{let s=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);o=o.concat(s),i=i.parent}while(i&&!i._enablePositionalOptions);n=Eo(e,o)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(i=>{o.push(i.name()),i.alias()&&o.push(i.alias())}),n=Eo(e,o)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let o=this.createOption(n,r);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
23
- `),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let o=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Oc(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=be.basename(e,be.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=o=>this._outputConfiguration.writeErr(o):r=o=>this._outputConfiguration.writeOut(o),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation(r);if(n&&(o=n(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let n=L.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
24
- Expecting one of '${r.join("', '")}'`);let o=`${e}Help`;return this.on(o,i=>{let s;typeof n=="function"?s=n({error:i.error,command:i.command}):s=n,s&&i.write(`${s}
25
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(o=>n.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ao(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",o="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?o=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],o=i[4]),n&&o!=="0"?`${n}=${r}:${parseInt(o)+1}`:e})}To.Command=cr});var jo=Pe(oe=>{var{Argument:Po}=Qt(),{Command:lr}=No(),{CommanderError:Tc,InvalidArgumentError:Lo}=bt(),{Help:Nc}=er(),{Option:Mo}=or();oe.program=new lr;oe.createCommand=t=>new lr(t);oe.createOption=(t,e)=>new Mo(t,e);oe.createArgument=(t,e)=>new Po(t,e);oe.Command=lr;oe.Option=Mo;oe.Argument=Po;oe.Help=Nc;oe.CommanderError=Tc;oe.InvalidArgumentError=Lo;oe.InvalidOptionArgumentError=Lo});import{execFileSync as Pc}from"node:child_process";import{randomUUID as Lc}from"node:crypto";import{chmodSync as Mc,mkdirSync as fr,readFileSync as pr,renameSync as jc,rmSync as Go,statSync as Hc,writeFileSync as Jo}from"node:fs";import{homedir as Fc}from"node:os";import{dirname as Wo,join as hr}from"node:path";function ee(){return process.env.CANARY_HOME||hr(Fc(),".canary")}function gr(){return hr(ee(),"config.json")}function Bo(){let{config:t}=yr();if(t.installId&&Do.test(t.installId))return t.installId;Uo??=Lc();let e=Uo;try{z(n=>n.installId&&Do.test(n.installId)?n:{...n,installId:e})}catch{}return e}function T(){return yr().config}function Vo(t){return T().repoFingerprints?.[t]}function qo(t,e){try{z(n=>({...n,repoFingerprints:{...n.repoFingerprints,[t]:e}}))}catch{}}function Ko(t){Yo=t}function zo(){return`${gr()}.lock`}function Vc(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Kc(t){try{let e=Pc("ps",["-o","lstart=","-p",String(t)],{env:{...process.env,LC_ALL:"C"},encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=Date.parse(e);return Number.isFinite(n)?n:null}catch{return null}}function zc(t){let e;try{e=pr(mr(t),"utf8").trim()}catch{return"unknown"}let[n,r]=e.split(" ").map(Number);if(!Number.isInteger(n)||n<=0||!Number.isFinite(r))return"unknown";try{process.kill(n,0)}catch(i){if(i.code==="ESRCH")return!1}let o=Kc(n);return o===null?!0:Math.abs(o-r)<=Yc}function Qo(t){try{return pr(mr(t),"utf8").trim()===Xo}catch{return!1}}function ur(t){try{Go(t,{recursive:!0,force:!0})}catch{}}function Zo(t=zo(),e="the config lock"){let n=Date.now()+Bc();for(;;)try{return fr(Wo(t),{recursive:!0,mode:448}),fr(t),Jo(mr(t),`${Xo}
26
- `,{flag:"wx"}),()=>{Qo(t)&&ur(t)}}catch(r){if(r.code!=="EEXIST")throw r;let o=zc(t);if(o===!1){ur(t);continue}if(o==="unknown")try{if(Date.now()-Hc(t).mtimeMs>Jc){ur(t);continue}}catch{}if(Date.now()>=n)throw new Le(`another canary process is holding ${e}`);Vc(Wc)}}function ei(t,e,n){let r=Zo(t,e);try{return n()}finally{r()}}function z(t,e={}){let n=()=>{let{config:o,unreadable:i}=yr();if(i&&!e.overwriteUnreadable)return!1;let s=t(i?{}:o);if(!Qo(zo()))throw new Le("the config lock changed hands during the write");return Xc(s),!0};if(dr>0)return n();let r=Zo();dr+=1;try{return n()}finally{dr-=1,r()}}function yr(){let t;try{t=pr(gr(),"utf8")}catch(e){return{config:{},unreadable:e.code!=="ENOENT"}}try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?{config:{},unreadable:!0}:{config:e,unreadable:!1}}catch{return{config:{},unreadable:!0}}}function Xc(t){let e=gr();fr(Wo(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;try{Jo(n,JSON.stringify(t,null,2)+`
27
- `,{mode:384}),Mc(n,384),jc(n,e)}catch(r){throw Go(n,{force:!0}),r}}function ti(){z(({apiUrl:t,webUrl:e,installId:n,agentSkills:r,repoFingerprints:o,gate:i,hooks:s})=>({...t?{apiUrl:t}:{},...e?{webUrl:e}:{},...n?{installId:n}:{},...r!==void 0?{agentSkills:r}:{},...o?{repoFingerprints:o}:{},...i?{gate:i}:{},...s?{hooks:s}:{}}))}function H(){return process.env.CANARY_TOKEN||T().token}function W(){return process.env.CANARY_API_URL||T().apiUrl||Dc}function ke(){let t=process.env.CANARY_WEB_URL||T().webUrl;if(t)return t;let e=process.env.CANARY_API_URL||T().apiUrl;return e?e.replace("//api.","//www."):Uc}var Dc,Uc,Do,Uo,Le,Gc,Jc,Wc,Yo,Bc,mr,qc,Xo,Yc,dr,j=J(()=>{"use strict";Dc="https://api.runcanary.ai",Uc="https://www.runcanary.ai";Do=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Uo=null;Le=class extends Error{constructor(e="another canary process is holding the config lock"){super(`${e}; run the command again`),this.name="ConfigLockError"}},Gc=15e3,Jc=1e4,Wc=20;Bc=()=>Yo??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||Gc);mr=t=>hr(t,"owner");qc=Math.round(Date.now()-process.uptime()*1e3),Xo=`${process.pid} ${qc}`,Yc=3e3;dr=0});import{mkdirSync as cl,readFileSync as ll,writeFileSync as ul}from"node:fs";import{homedir as dl}from"node:os";import{dirname as fl,join as oi}from"node:path";function si(){try{return JSON.parse(ll(Sr(),"utf8"))}catch{return{}}}function hl(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o+=1){let i=(n[o]||0)-(r[o]||0);if(i!==0)return i>0}return!1}function ai(){if(ve==="0.0.0-dev")return;let{latest:t}=si();t&&hl(t,ve)&&console.error(`A newer Canary CLI is available (${ve} -> ${t}): npm install -g ${ii}`)}function ze(){if(ve==="0.0.0-dev")return;let t=si();t.checkedAt&&Date.now()-t.checkedAt<pl||(async()=>{let e=n=>{try{cl(fl(Sr()),{recursive:!0}),ul(Sr(),JSON.stringify({checkedAt:Date.now(),latest:n??t.latest})+`
28
- `)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${ii}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return e();let{version:r}=await n.json();e(r||void 0)}catch{e()}})()}var ve,ii,pl,Sr,Xe=J(()=>{"use strict";ve="0.1.13",ii="@runcanary/cli",pl=1440*60*1e3,Sr=()=>oi(process.env.CANARY_HOME||oi(dl(),".canary"),"update-check.json")});import{createHash as gl}from"node:crypto";import{execFileSync as ml,spawn as yl}from"node:child_process";function je(t){Ce={...Ce,...t},kt=null}function xr(t=process.env){if(t.CLAUDECODE==="1"||t.CLAUDE_CODE_SESSION_ID){let e=t.CLAUDE_CODE_SESSION_ID??t.CLAUDE_CODE_HOST_SESSION_ID;return{harness:"claude-code",...e?{chatId:e}:{}}}return t.CODEX_SANDBOX||t.CODEX_SANDBOX_NETWORK_DISABLED==="1"?{harness:"codex"}:t.CURSOR_AGENT==="1"?{harness:"cursor"}:{harness:"unknown"}}function wl(t,e){return gl("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function ui(){return{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(t))),GIT_OPTIONAL_LOCKS:"0",GIT_NO_LAZY_FETCH:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_TERMINAL_PROMPT:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"}}function ci(t,e){try{let n=ui();return ml("git",t,{cwd:e,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function bl(t,e){let[n,r,o]=(ci(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],t)??"").split(`
29
- `);if(!n)return{};let i={worktreeId:wl(n,e)};if(o!=="true"){let s=Vo(i.worktreeId);s&&ci(["cat-file","-e",`${s}^{commit}`],n)!==null?i.repoFingerprint=s:kl(n,i.worktreeId)}return i.branch=r&&r!=="HEAD"?r:"HEAD",i}function kl(t,e){li.has(e)||li.set(e,new Promise(n=>{try{let r=ui(),o=yl("git",["rev-list","--max-parents=0","HEAD"],{cwd:t,env:r,stdio:["ignore","pipe","ignore"],timeout:6e4}),i="";o.stdout.on("data",s=>{i+=s.toString("utf8")}),o.on("error",()=>n()),o.on("close",s=>{let a=s===0?i.trim().split(`
30
- `).filter(Boolean).sort()[0]:void 0;a&&qo(e,a),n()}),o.unref(),o.stdout.unref?.()}catch{n()}}))}function Sl(){if(kt)return kt;let t=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",e=xr(),n=Ce.harness??e.harness,r=e.harness===n?e.chatId:void 0,o="",i={};try{o=Bo(),i=bl(Ce.cwd??process.cwd(),o)}catch{}return kt={cliVersion:ve,command:t,installId:o,...i,harness:n,...r?{chatId:r}:{},...Ce.agent!==void 0?{agent:Ce.agent}:{},...Ce.mode?{mode:Ce.mode}:{}},kt}function $e(){let t=Sl(),e=r=>r.replace(/[^\x20-\x7e]/g,"?").slice(0,200),n={[q.cli]:t.cliVersion,[q.harness]:t.harness};return t.installId&&(n[q.install]=t.installId),t.command&&(n[q.command]=e(t.command)),t.worktreeId&&(n[q.worktree]=t.worktreeId),t.repoFingerprint&&(n[q.repo]=t.repoFingerprint),t.branch&&(n[q.branch]=e(t.branch)),t.chatId&&(n[q.chat]=e(t.chatId)),t.agent!==void 0&&(n[q.agent]=t.agent?"1":"0"),t.mode&&(n[q.mode]=t.mode),n}var q,Ce,kt,li,Ie=J(()=>{"use strict";j();Xe();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"},Ce={},kt=null;li=new Map});async function v(t,e={}){let n=(e.baseUrl||W()).replace(/\/+$/,""),r=$e();e.token&&(r.authorization=`Bearer ${e.token}`),e.body!==void 0&&(r["content-type"]="application/json");let o;try{o=await fetch(n+t,{method:e.method??"GET",headers:r,body:e.body!==void 0?JSON.stringify(e.body):void 0,signal:e.signal})}catch(i){throw new $(0,`could not reach ${n} (${i instanceof Error?i.message:String(i)})`)}if(!o.ok){let i=o.statusText,s,a,l;try{let c=await o.json();i=c.error||c.message||i,typeof c.fix=="string"&&c.fix&&(s=c.fix),typeof c.runId=="string"&&c.runId&&(a=c.runId),typeof c.code=="string"&&c.code&&(l=c.code)}catch{}throw new $(o.status,i,s,a,l)}return o.status===204?null:await o.json()}var $,ie,B=J(()=>{"use strict";j();Ie();$=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"}},ie=t=>t instanceof $&&(t.status===0||t.status===408||t.status===429||t.status===502||t.status===503||t.status===504)});function di(t){return z(e=>({...e,gate:{...e.gate,mode:t}}))}var He,nn=J(()=>{"use strict";j();He=()=>T().gate?.mode==="off"?"off":"on"});import{accessSync as hi,constants as gi,existsSync as Qe,lstatSync as xl,readFileSync as Fe,readlinkSync as _l,renameSync as vl,rmSync as fi,statSync as $r,writeFileSync as vr}from"node:fs";import{randomUUID as Cl}from"node:crypto";import{homedir as Ir}from"node:os";import{delimiter as mi,dirname as Cr,join as ce,resolve as $l}from"node:path";function sn(t,e=process.env,n=process.platform){let r=n==="win32"?[t,...(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(o=>t+o.toLowerCase())]:[t];for(let o of(e.PATH??"").split(mi).filter(Boolean))for(let i of r)try{if(hi(ce(o,i),gi.X_OK),$r(ce(o,i)).isFile())return!0}catch{}return!1}function Il(t){let e=t;for(let n=0;n<16;n++){let r;try{if(!xl(e).isSymbolicLink())return e;r=_l(e)}catch{return e}e=$l(Cr(e),r)}throw new Se("its symlinks do not end anywhere")}function rn(t,e){for(let n=0;n<3;n++){let r;try{r=Fe(t,"utf8")}catch(l){if(l.code!=="ENOENT")return{result:"refused",detail:"the file cannot be read"};r=null}let o={};if(r!==null&&r.trim())try{o=JSON.parse(r)}catch{return{result:"refused",detail:"the file is not valid JSON"}}if(!he(o))return{result:"refused",detail:"the file does not hold a JSON object"};try{if(!e(o))return{result:"unchanged"}}catch(l){if(l instanceof Se)return{result:"refused",detail:l.message};throw l}let i=r?/^([ \t]+)"/m.exec(r)?.[1]??" ":" ",s;try{s=Il(t)}catch(l){return{result:"refused",detail:l.message}}if(s!==t&&!Qe(Cr(s)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let a=ce(Cr(s),`.${Cl()}.canary.tmp`);try{vr(a,JSON.stringify(o,null,i)+`
31
- `,{flag:"wx",mode:r===null?384:$r(s).mode&511});let l;try{l=Fe(t,"utf8")}catch{l=null}if(l!==r){fi(a,{force:!0});continue}return vl(a,s),{result:"written"}}catch(l){return fi(a,{force:!0}),{result:"refused",detail:`the file cannot be written (${l.code??"error"})`}}}return{result:"refused",detail:"the file kept changing while it was being edited"}}function Ol(t,e,n){for(let r of t){if(!he(r))throw new Se(`its \`hooks.${e}\` list holds an entry that is not an object`);if(n&&r[n]!==void 0&&!(Array.isArray(r[n])&&r[n].every(he)))throw new Se(`its \`hooks.${e}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Re(t,e,n,r="hooks"){if(t.hooks===void 0){if(!n)return null;t.hooks={}}if(!he(t.hooks))throw new Se("its `hooks` entry is not an object");if(t.hooks[e]===void 0){if(!n)return null;t.hooks[e]=[]}if(!Array.isArray(t.hooks[e]))throw new Se(`its \`hooks.${e}\` entry is not a list`);return Ol(t.hooks[e],e,r),t.hooks[e]}function yi(t,e){he(t.hooks)&&(Array.isArray(t.hooks[e])&&!t.hooks[e].length&&delete t.hooks[e],Object.keys(t.hooks).length||delete t.hooks)}function wi(t){let e;try{e=JSON.parse(Fe(t,"utf8"))}catch(n){return n.code==="ENOENT"?{state:"missing"}:{state:"unreadable",detail:"the file cannot be read as JSON"}}return he(e)?{doc:e}:{state:"unreadable",detail:"the file does not hold a JSON object"}}function bi(t){let e=Rl(t.harness),n=Rr(t.harness),r=()=>({matcher:t.matcher,hooks:[{type:"command",command:e,timeout:on}]}),o=l=>he(l)&&Array.isArray(l.hooks)&&l.hooks.some(n),i=l=>{let c=l.filter(o);return c.length===1&&JSON.stringify(c[0])===JSON.stringify(r())},s=l=>{let c=Re(l,"PreToolUse",!1);if(!c)return!1;let u=!1;for(let d=c.length-1;d>=0;d--){let h=c[d];if(!he(h)||!Array.isArray(h.hooks))continue;let p=h.hooks.filter(f=>!n(f));p.length!==h.hooks.length&&(u=!0,p.length?h.hooks=p:c.splice(d,1))}return u&&yi(l,"PreToolUse"),u},a={harness:t.harness,file:t.file,summary:`a PreToolUse hook that runs \`${e}\` before shell and MCP tool calls (${on} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[r()]}},null,2)};return{detected:()=>Qe(t.dir),plan:()=>[a],install:()=>[{...a,...rn(t.file,l=>i(Re(l,"PreToolUse",!0))?!1:(s(l),Re(l,"PreToolUse",!0).push(r()),!0))}],uninstall:()=>{if(!Qe(t.file))return[{...a,result:"unchanged"}];let l=rn(t.file,s);return[{...a,...l.result==="written"?{result:"removed"}:l}]},status:()=>{let l=wi(t.file);if(!("doc"in l))return[{harness:t.harness,file:t.file,...l}];let c;try{c=Re(l.doc,"PreToolUse",!1)}catch(u){return[{harness:t.harness,file:t.file,state:"unreadable",detail:u.message}]}return c?.some(o)?t.disabledKey&&l.doc[t.disabledKey]===!0?[{harness:t.harness,file:t.file,state:"disabled",detail:`\`${t.disabledKey}\` is set, so no hooks run`}]:i(c)?[{harness:t.harness,file:t.file,state:"registered"}]:[{harness:t.harness,file:t.file,state:"modified",detail:"the entry differs from what `canary hooks install` writes; install again to restore it"}]:[{harness:t.harness,file:t.file,state:"missing"}]}}}function El(t){let e=ce(t,"hooks.json"),n=Rr("cursor"),r=()=>({command:"canary hook cursor",timeout:on}),o=a=>St.every(l=>{let c=(Re(a,l,!1,null)??[]).filter(n);return c.length===1&&JSON.stringify(c[0])===JSON.stringify(r())}),i=a=>{let l=!1;for(let c of St){let u=Re(a,c,!1,null);if(!u)continue;let d=u.filter(h=>!n(h));d.length!==u.length&&(l=!0,a.hooks[c]=d,yi(a,c))}return l},s={harness:"cursor",file:e,summary:`a command that runs \`canary hook cursor\` before shell commands and MCP tool calls (${on} s limit)`,snippet:JSON.stringify({version:1,hooks:Object.fromEntries(St.map(a=>[a,[r()]]))},null,2)};return{detected:()=>Qe(t),plan:()=>[s],install:()=>[{...s,...rn(e,a=>{if(a.version!==void 0&&a.version!==1)throw new Se(`it is version ${JSON.stringify(a.version)} of Cursor's hooks file, which this CLI does not know`);if(o(a))return!1;i(a),a.version===void 0&&(a.version=1);for(let l of St)Re(a,l,!0,null).push(r());return!0})}],uninstall:()=>{if(!Qe(e))return[{...s,result:"unchanged"}];let a=rn(e,i);return[{...s,...a.result==="written"?{result:"removed"}:a}]},status:()=>{let a=wi(e);if(!("doc"in a))return[{harness:"cursor",file:e,...a}];try{return St.some(l=>(Re(a.doc,l,!1,null)??[]).some(n))?[o(a.doc)?{harness:"cursor",file:e,state:"registered"}:{harness:"cursor",file:e,state:"modified",detail:"the entries differ from what `canary hooks install` writes; install again to restore them"}]:[{harness:"cursor",file:e,state:"missing"}]}catch(l){return[{harness:"cursor",file:e,state:"unreadable",detail:l.message}]}}}}function Tl(t=process.env){let e=t.CLAUDE_CONFIG_DIR||ce(Ir(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...bi({harness:"claude",dir:e,file:ce(e,"settings.json"),matcher:Al,disabledKey:"disableAllHooks"})}}function jl(t){let e=new Map,n=null,r="",o=0,i="",s=l=>l.trim().replace(/^"(.*)"$|^'(.*)'$/s,"$1$2"),a=()=>{n!==null&&e.set(s(n),r.trim()),n=null,r=""};for(let l=0;l<t.length;l++){let c=t[l];if(i){r+=c,c==="\\"&&i.startsWith('"')?r+=t[++l]??"":t.startsWith(i,l)&&(r+=i.slice(1),l+=i.length-1,i="");continue}if(c==='"'||c==="'"){i=t.startsWith(c.repeat(3),l)?c.repeat(3):c,r+=i,l+=i.length-1;continue}if(c==="#"){let u=t.indexOf(`
32
- `,l);if(u<0)break;l=u;continue}if(o===0&&c==="}")break;if(o===0&&c===","){a();continue}if(o===0&&c==="="&&n===null){n=r,r="";continue}(c==="{"||c==="[")&&o++,(c==="}"||c==="]")&&o--,r+=c}return a(),e}function Si(t){let e="top";for(let[n,r]of t.entries()){if(/^\s*\[/.test(r)){e=ki.test(r)?"features":"other";continue}let o=e==="top"?Ml.exec(r):null;if(o){let s=jl([r.slice(o[0].length),...t.slice(n+1)].join(`
33
- `)).get("codex_hooks");return{value:s===void 0?"missing":s==="true"?"on":"off",inline:!0}}let i=e==="features"?Nl.exec(r):e==="top"?Pl.exec(r):null;if(i)return{value:i[1]==="true"?"on":"off",inline:!1}}return{value:"missing",inline:!1}}function Hl(t){let e;try{e=Fe(t,"utf8")}catch(n){return n.code==="ENOENT"?{value:"missing",inline:!1}:null}return Si(e.split(`
34
- `))}function Fl(t,e){let n;try{n=Fe(t,"utf8")}catch(l){if(l.code!=="ENOENT"||e==="uninstall")return null;n=""}let r=n?n.split(`
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
- `)),"switched Codex's hooks feature back off")}let o=Si(r);if(o.value!=="missing")return o.value==="on"?null:xi(o);if(o.inline)throw Object.assign(new Error("inline features table"),{code:"inline_features_table"});let i=r.findIndex(l=>ki.test(l)),s=r.findIndex(l=>/^\s*\[/.test(l)),a=r.slice(0,s<0?r.length:s).findIndex(l=>Ll.test(l));return i>=0?r.splice(i+1,0,xt):a>=0?r.splice(a+1,0,pi):r.push(...n.trim()?[""]:[],"[features]",xt,""),vr(t,r.join(`
37
- `)),"switched on Codex's hooks feature (`codex_hooks = true` in its config.toml)"}function Dl(t=process.env,e=process.platform){let n=i=>/[\s"']/.test(i)?`"${i}"`:i,r=e==="win32"?["codex.cmd","codex.exe","codex"]:["codex"];for(let i of(t.PATH??"").split(mi).filter(Boolean))for(let s of r){let a=ce(i,s);try{if(hi(a,gi.X_OK),$r(a).isFile())return n(a)}catch{}}let o="/Applications/ChatGPT.app/Contents/Resources/codex";return e==="darwin"&&Qe(o)?n(o):null}function Gl(t,e,n){let r;try{r=Fe(t,"utf8")}catch(a){return a.code==="ENOENT"?!1:null}let o=`[hooks.state."${e}:pre_tool_use:${n}:0"]`,i=r.split(`
38
- `),s=i.findIndex(a=>a.trim()===o);if(s<0)return!1;for(let a of i.slice(s+1)){if(/^\s*\[/.test(a))break;if(/^\s*trusted_hash\s*=/.test(a))return!0}return!1}function Jl(t=process.env){let e=t.CODEX_HOME||ce(Ir(),".codex"),n=ce(e,"hooks.json"),r=bi({harness:"codex",dir:e,file:n,matcher:".*"}),o=ce(e,"config.toml"),i=Ul(Dl(t)),s=Rr("codex"),a=()=>{try{return JSON.parse(Fe(n,"utf8")).hooks.PreToolUse.findIndex(u=>he(u)&&Array.isArray(u.hooks)&&u.hooks.some(s))}catch{return-1}},l=(c,u)=>{let d=c[0];if(!d||d.result==="refused")return c;let h=null;try{h=Fl(o,u)}catch(p){let f=p.code==="inline_features_table",m=u==="uninstall"?`the hook was removed, but the line \`${xt}\` could not be taken out of ${o}: remove it yourself`:f?`the hook was added, but Codex's features are an inline \`features = { \u2026 }\` table in ${o}: add \`codex_hooks = true\` to it yourself`:`the hook was added, but Codex's hooks feature could not be switched on: add \`${xt}\` under \`[features]\` in ${o} yourself`;return[{...d,result:"refused",detail:`${m} (${p.code??"error"})`},...c.slice(1)]}return h?[{...d,detail:d.detail?`${d.detail}; ${h}`:h},...c.slice(1)]:c};return{id:"codex",label:"Codex",byDefault:!0,afterInstall:_r(i),...r,plan:()=>r.plan().map(c=>({...c,summary:`${c.summary}; switches on Codex's hooks feature in its config.toml`})),install:()=>l(r.install(),"install"),uninstall:()=>l(r.uninstall(),"uninstall"),status:()=>r.status().map(c=>{if(c.state!=="registered")return c;let u=Hl(o);if(u&&u.value!=="on")return{...c,state:"disabled",detail:xi(u)};let d=a();if(d<0)return c;let h=Gl(o,n,d);if(h===!0)return c;let p=h===null?`Codex's config.toml could not be read, so whether the hook is trusted is unknown. ${_r(i)}`:_r(i);return{...c,state:"untrusted",detail:p,pending:i}})}}function Wl(t=process.env){let e=t.CURSOR_CONFIG_DIR||ce(Ir(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...El(e)}}var he,Se,on,Rl,Rr,St,Al,xt,pi,Ze,ki,Nl,Pl,Ll,Ml,xi,Ul,_r,_t,_i=J(()=>{"use strict";he=t=>!!t&&typeof t=="object"&&!Array.isArray(t),Se=class extends Error{};on=10,Rl=(t,e=process.platform)=>e==="win32"?`canary hook ${t}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${t}`,Rr=t=>e=>he(e)&&typeof e.command=="string"&&new RegExp(`^\\s*(?:command -v canary >/dev/null 2>&1 \\|\\| exit 0;\\s*)?(?:node\\s+)?["']?(?:[^"'\\s]*[\\\\/])?canary(?:\\.js)?["']?\\s+hook\\s+${t}\\s*$`).test(e.command);St=["beforeShellExecution","beforeMCPExecution"];Al="^(Bash|PowerShell|Monitor|mcp__.*)$";xt="codex_hooks = true # added by canary",pi="features.codex_hooks = true # added by canary",Ze=t=>`(?:${t}|"${t}"|'${t}')`,ki=new RegExp(`^\\s*\\[\\s*${Ze("features")}\\s*\\]\\s*(?:#.*)?$`),Nl=new RegExp(`^\\s*${Ze("codex_hooks")}\\s*=\\s*(true|false)?`),Pl=new RegExp(`^\\s*${Ze("features")}\\s*\\.\\s*${Ze("codex_hooks")}\\s*=\\s*(true|false)?`),Ll=new RegExp(`^\\s*${Ze("features")}\\s*\\.`),Ml=new RegExp(`^\\s*${Ze("features")}\\s*=\\s*\\{`);xi=t=>`Codex's hooks feature is switched off in its config.toml (${t.value==="off"?"`codex_hooks = false`); the check runs once it is on":t.inline?"no `codex_hooks` in its `features = { \u2026 }` table); add `codex_hooks = true` to that table":"no `codex_hooks` line); `canary hooks install` switches it on"}`;Ul=t=>({why:"Canary's push check runs before your agent pushes code or opens a pull request: the push is held until the exact code has a Canary run with nothing open, or the agent records a reason to skip. Codex runs a hook only after you have trusted it once, and Codex Desktop has no screen for that yet, so the check does nothing until then.",command:t??"npm i -g @openai/codex && codex",after:'In Codex, choose "Review hooks", accept the Canary entry, then quit.'}),_r=t=>`${t.why} Run \`${t.command}\` in a terminal. ${t.after}`;_t=(t=process.env)=>[Tl(t),Jl(t),Wl(t)]});var Sh,an,Bl,xh,vi=J(()=>{"use strict";Sh=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:t=>`canary verify: tree ${t}`}),an=t=>`tree:${t.slice(0,12)}`,Bl=[["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"]],xh=Bl.flatMap(([t,e])=>["-c",`${t}=${e}`])});import{createHash as Vl}from"node:crypto";import{existsSync as ql,mkdirSync as Or,readFileSync as et,writeFileSync as cn}from"node:fs";import{join as xe}from"node:path";function tt(t){return xe(t,".canary")}function Ii(t){let e=t.trim();if(!e)return null;if(!e.includes("://")){let n=e.match(/^[^@]+@([^:]+):(.+)$/);if(n){let r=n[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return r.length>=2?{host:n[1],owner:r[0],name:r.slice(1).join("/")}:null}}try{let n=new URL(e),r=n.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(r.length>=2)return{host:n.host,owner:r[0],name:r.slice(1).join("/")}}catch{}return null}function vt(t){let e=tt(t),n=xe(e,".gitignore");try{let r=et(n,"utf8").split(`
39
- `).map(o=>o.trim()).filter(o=>o.length>0);if(r[r.length-1]==="*")return}catch{}try{Or(e,{recursive:!0});let r="";try{r=et(n,"utf8"),r&&!r.endsWith(`
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{}cn(n,`${r}*
42
- `)}catch{}}function Oe(t){let e=tt(t),n;try{n=et(xe(e,"setup.sh"),"utf8")}catch{throw new te("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 te("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(et(xe(e,"run.json"),"utf8"))}catch(a){throw new te("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let o=[],i={},s=xe(e,"env.json");if(ql(s)){let a;try{a=JSON.parse(et(s,"utf8"))}catch(c){throw new te("recipe_invalid",`Cannot read .canary/env.json: ${c instanceof Error?c.message:String(c)}`)}if(a===null||typeof a!="object"||Array.isArray(a))throw new te("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let l=a;o=Oi(l.manifest),i=Ei(l.values),Kl(o)}return{setupSh:n,runJson:r,envManifest:o,envValues:i}}function De(t){return Vl("sha256").update(JSON.stringify([t.setupSh,t.runJson,t.envManifest,t.envValues])).digest("hex")}function Er(t,e){let n=t.filter(r=>r.neededAt==="boot").map(r=>r.name).filter(r=>!Object.prototype.hasOwnProperty.call(e,r)||e[r]==="");return{missing:[...new Set(n)]}}function Oi(t){return Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.name=="string"):[]}function Kl(t){for(let e of t){if(!Ci.has(String(e.class)))throw new te("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has unknown class "${String(e.class)}"`,`use one of: ${[...Ci].join(", ")}`);if(!Yl.has(String(e.neededAt)))throw new te("recipe_invalid",`.canary/env.json: manifest entry "${e.name}" has invalid neededAt "${String(e.neededAt)}"`,'use "boot" or "runtime"')}}function Ei(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function zl(t){try{let e=JSON.parse(et(xe(tt(t),"env.json"),"utf8"));return{manifest:Oi(e.manifest),values:Ei(e.values)}}catch{return{manifest:[],values:{}}}}function Xl(t,e){Or(tt(t),{recursive:!0}),cn(xe(tt(t),"env.json"),JSON.stringify(e,null,2)+`
43
- `),vt(t)}function Ar(t,e){if(e.length===0)return;let n=zl(t),r=new Map(n.manifest.map(o=>[o.name,o]));for(let o of e){n.values[o.name]=o.value;let i=r.get(o.name);if(i)o.class&&$i.has(o.class)&&!$i.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)}}Xl(t,n)}function Ai(t,e){let n=[],r=tt(t);if(Or(r,{recursive:!0}),typeof e.setupSh=="string"&&e.setupSh.trim()&&(cn(xe(r,"setup.sh"),e.setupSh),n.push(".canary/setup.sh")),typeof e.runJson=="string"&&e.runJson.trim()){let i=e.runJson;try{i=JSON.stringify(JSON.parse(e.runJson),null,2)+`
44
- `}catch{}cn(xe(r,"run.json"),i),n.push(".canary/run.json")}let o=Object.entries(e.envOverrides??{});return o.length>0&&(Ar(t,o.map(([i,s])=>({name:i,value:s,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),vt(t),n}var te,Ri,Ci,Yl,$i,Tr=J(()=>{"use strict";te=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="RecipeError"}};Ri=new Set(["github.com","ssh.github.com"]);Ci=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),Yl=new Set(["boot","runtime"]);$i=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as Ql}from"node:child_process";import{createHash as Pi,randomUUID as un}from"node:crypto";import{linkSync as Zl,lstatSync as Li,mkdirSync as dn,readdirSync as eu,readFileSync as Pr,realpathSync as ln,renameSync as Mi,rmSync as fn,writeFileSync as Lr}from"node:fs";import{basename as Mr,dirname as ji,isAbsolute as tu,join as ne,relative as nu,resolve as jr,sep as ru}from"node:path";function ou(t){let e=Ii(t);if(!(!e||!Ri.has(e.host.toLowerCase().replace(/:\d+$/,"")))&&!(!Ti.test(e.owner)||!Ti.test(e.name)))return`${e.owner}/${e.name}`}function rt(t=process.cwd()){let e={...Object.fromEntries(Object.entries(process.env).filter(([a])=>!a.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(a))),GIT_OPTIONAL_LOCKS:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"},n=a=>Ql("git",a,{cwd:t,env:e,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").replace(/\r?\n$/,""),r,o;try{r=ln(n(["rev-parse","--show-toplevel"])),o=ln(jr(ln(t),n(["rev-parse","--git-common-dir"])))}catch{throw new N("not_a_git_repository","Run this command inside the Git repository you want Canary to use.")}let i;try{i=ou(n(["remote","get-url","origin"]))}catch{}if(i)return{root:r,commonDirectory:o,name:i,githubFullName:i};let s=Mr(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:o,name:s}}function iu(t){let e;try{e=new URL(t)}catch{throw new N("invalid_api_url","The Canary API URL is invalid.")}if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new N("invalid_api_url","The Canary API URL must be HTTP(S) without credentials, a query, or a fragment.");return e.href.replace(/\/+$/,"")}function pn(t){try{return ln(t)}catch(e){if(e.code!=="ENOENT")throw e;if(Li(t,{throwIfNoEntry:!1})?.isSymbolicLink())throw new N("cache_path_unresolvable","A symlink under CANARY_HOME/local-repositories points at a missing target. Remove or fix that link, then run the command again.");let n=ji(t);if(n===t)throw e;return ne(pn(n),Mr(t))}}function Nr(t,e){let n=nu(t,e);return n===""||!tu(n)&&n!==".."&&!n.startsWith(`..${ru}`)}function ot(t,e){let n=pn(e);if(!Nr(t,n))throw new N("cache_outside_home","Something under CANARY_HOME/local-repositories links outside CANARY_HOME. Remove that link, then run the command again.");return n}function it(t){if(!nt.test(t.userId)||!nt.test(t.workspaceId))throw new N("invalid_account_context","Sign in with canary login and select a workspace with canary workspace use <id>, then run the command again.");let e=rt(t.directory),n=iu(t.apiUrl),r=pn(jr(ee())),o=Mr(e.commonDirectory)===".git"?ji(e.commonDirectory):e.commonDirectory,i=Pi("sha256").update(JSON.stringify([Ct,n,t.userId,t.workspaceId,e.githubFullName?`github:${e.githubFullName.toLowerCase()}`:e.commonDirectory])).digest("hex"),s=ne(r,"local-repositories"),a=ot(s,ne(s,i));if([e.root,e.commonDirectory,o].some(l=>Nr(l,r)||Nr(l,a)))throw new N("cache_inside_checkout","CANARY_HOME is inside this repository. Point it at a directory outside the checkout, then run the command again.");return{...e,apiUrl:n,scope:i,cacheRoot:s,cacheDirectory:a}}function Ni(t,e){let n=ot(t.cacheRoot,ne(t.cacheDirectory,e)),r;try{r=Pr(n,"utf8")}catch(s){if(s.code==="ENOENT")return null;throw new N("binding_unreadable","Could not read Canary's saved record for this repository under CANARY_HOME/local-repositories. Check its permissions, then run the command again.")}let o;try{o=JSON.parse(r)}catch{}let i=e==="identity.json"?["version","scope","localKey"]:["version","scope","localKey","repositoryId"];if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(s=>!i.includes(s))||o.version!==Ct||o.scope!==t.scope||typeof o.localKey!="string"||!nt.test(o.localKey)||e==="repository.json"&&(typeof o.repositoryId!="string"||!nt.test(o.repositoryId)))throw new N("invalid_binding","Canary's saved record for this repository under CANARY_HOME/local-repositories is damaged. Canary left it in place: restore it, or remove it to register this repository as new.");return o}function Ue(t){let e=Ni(t,"identity.json"),n=Ni(t,"repository.json");if(!e&&!n)return null;if(!e||n&&n.localKey!==e.localKey)throw new N("invalid_binding","Canary's saved records for this repository under CANARY_HOME/local-repositories disagree with each other. Canary left them in place: restore them, or remove them to register this repository as new.");return{localKey:e.localKey,...n?{repositoryId:n.repositoryId}:{}}}function Hr(t,e,n){dn(t.cacheDirectory,{recursive:!0,mode:448});let r=ne(t.cacheDirectory,`${e}.${un()}.tmp`);try{Lr(r,JSON.stringify({version:Ct,scope:t.scope,...n})+`
45
- `,{flag:"wx",mode:384});try{Zl(r,ne(t.cacheDirectory,e))}catch(o){if(o.code!=="EEXIST")throw o}}finally{fn(r,{force:!0})}}function Hi(t,e){dn(t.cacheDirectory,{recursive:!0,mode:448});let n=ne(t.cacheDirectory,`repository.json.${un()}.tmp`);Lr(n,JSON.stringify({version:Ct,scope:t.scope,...e})+`
46
- `,{flag:"wx",mode:384}),Mi(n,ne(t.cacheDirectory,"repository.json"))}function Fi(t){return Ue(it(t))}function hn(t,e){let n=it(t),r=Ue(n);!r?.repositoryId||r.repositoryId===e||Hi(n,{localKey:r.localKey,repositoryId:e})}function le(t,e){if(!/^[a-z0-9-]+\.json(?:\.gz)?$/.test(e))throw new N("invalid_receipt_name","Invalid cache file name.");let n=it(t);return dn(n.cacheDirectory,{recursive:!0,mode:448}),ot(n.cacheRoot,ne(n.cacheDirectory,e))}function su(t){return Di(it(t))}function Di(t){let e=Ue(t);return e||(Hr(t,"identity.json",{localKey:un()}),Ue(t))}function au(t){try{let e=JSON.parse(Pr(ot(t.cacheRoot,ne(t.cacheDirectory,Fr)),"utf8"));return e.version===1&&e.checkout===Dr(t.githubFullName)}catch{return!1}}function cu(t){dn(t.cacheDirectory,{recursive:!0,mode:448});let e=ot(t.cacheRoot,ne(t.cacheDirectory,Fr)),n=`${e}.${un()}.tmp`;try{Lr(n,JSON.stringify({version:1,at:new Date().toISOString(),checkout:Dr(t.githubFullName)})+`
47
- `,{flag:"wx",mode:384}),Mi(n,e)}finally{fn(n,{force:!0})}}async function Ui(t,e){let n=it(t),r=Ue(n);if(r?.repositoryId)return r;let{githubFullName:o}=n;if(!o||au({...n,githubFullName:o}))return null;let i=await e(o);if(!i)return null;if("notConnected"in i)return cu({...n,githubFullName:o}),null;if(!nt.test(i.repositoryId))return null;let s=Di(n);return s.repositoryId||Hr(n,"repository.json",{localKey:s.localKey,repositoryId:i.repositoryId}),Ue(n)}function Gi(){let t=ne(pn(jr(ee())),"local-repositories"),e=ot(t,t),n;try{n=eu(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}return n.map(r=>ne(e,r,Fr)).filter(r=>Li(r,{throwIfNoEntry:!1})?.isFile())}function gn(){try{for(let t of Gi())fn(t,{force:!0})}catch{}}function $t(t){try{let e=Gi();if(!e.length)return;let{githubFullName:n}=rt(t??process.cwd());if(!n)return;let r=Dr(n);for(let o of e)try{JSON.parse(Pr(o,"utf8")).checkout===r&&fn(o,{force:!0})}catch{}}catch{}}function lu(t,e,n,r){let o=t,i=n.githubFullName?"github":"local";if(!o||typeof o.repositoryId!="string"||!nt.test(o.repositoryId)||o.provider!==i||e.repositoryId&&o.repositoryId!==e.repositoryId&&i!=="github"||(i==="local"?o.localKey!==e.localKey:o.localKey!==void 0)||typeof o.name!="string"||!o.name.trim()||o.name.length>512||/[\u0000-\u001f\u007f]/.test(o.name)||!o.workspace||o.workspace.id!==r||typeof o.workspace.name!="string")throw new N("invalid_repository_response","Canary returned an unexpected answer while looking up this repository. Run the command again; if it repeats, update the CLI.");return o}async function It(t,e=v){if(!t.token)throw new N("not_logged_in","Run canary login first.");let n=it(t),r=su(t),o={token:t.token,baseUrl:n.apiUrl},i=r.repositoryId?await e(`/api/v1/cli/local-repositories/${r.repositoryId}?workspaceId=${encodeURIComponent(t.workspaceId)}`,o):await e("/api/v1/cli/local-repositories",{...o,method:"POST",body:{workspaceId:t.workspaceId,localKey:r.localKey,name:n.name,...n.githubFullName?{githubFullName:n.githubFullName}:{}}}),s=lu(i,r,n,t.workspaceId);r.repositoryId&&r.repositoryId!==s.repositoryId?Hi(n,{localKey:r.localKey,repositoryId:s.repositoryId}):Hr(n,"repository.json",{localKey:r.localKey,repositoryId:s.repositoryId});let a=Ue(n);if(a?.repositoryId!==s.repositoryId||a.localKey!==r.localKey)throw new N("binding_conflict","Another canary process registered this repository at the same time. Run the command again.");return s}var nt,Ct,Ti,N,Fr,Dr,X=J(()=>{"use strict";B();j();Tr();nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ct=2,Ti=/^[A-Za-z0-9_.-]+$/,N=class extends Error{constructor(n,r){super(r);this.code=n;this.name="LocalRepositoryError"}};Fr="not-connected.json",Dr=t=>Pi("sha256").update(JSON.stringify([Ct,`github:${t.toLowerCase()}`])).digest("hex")});async function Rt(t,e,n=W()){let r=T().team?.id;if(!r)throw new N("workspace_selection_required","Select a workspace with canary workspace list and canary workspace use <id>, then run the command again.");let o=await v("/api/v1/cli/auth/whoami",{token:e,baseUrl:n});if(!o?.user?.id)throw new N("invalid_identity_response","Canary could not tell which account this token belongs to. Run canary login again.");return{apiUrl:n,userId:o.user.id,workspaceId:r,directory:t}}async function mn(t,e,n){let r=Fi(t);if(!r?.repositoryId)return;let o=await v(`/api/v1/cli/local-repositories/${r.repositoryId}/status?workspaceId=${encodeURIComponent(t.workspaceId)}`,{token:e,baseUrl:t.apiUrl,signal:n});if(typeof o?.repositoryId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o.repositoryId)||!["setup_required","ready"].includes(o.state))throw new N("invalid_readiness_response","Canary returned an unexpected answer about this repository's setup. Run the command again.");return o.repositoryId!==r.repositoryId&&hn(t,o.repositoryId),o}function Ji(t=process.cwd()){try{return rt(t).name}catch{return}}var yn=J(()=>{"use strict";B();j();X()});import{spawn as uu}from"node:child_process";import{createHash as Br}from"node:crypto";import{constants as Wi}from"node:fs";import{lstat as du,mkdir as Vi,mkdtemp as qi,open as Yi,readFile as fu,readdir as pu,readlink as hu,realpath as Ot,rm as Ki,writeFile as gu}from"node:fs/promises";import{tmpdir as zi}from"node:os";import{basename as mu,isAbsolute as yu,join as ue,relative as wu,resolve as Xi,sep as bu}from"node:path";import{promisify as ku}from"node:util";import{deflate as Su}from"node:zlib";function Vr(t,e){let n=t.split("/");(!t||Buffer.byteLength(t)>e.maxPathBytes||n.length>e.maxDepth||n.some(r=>!r||Buffer.byteLength(r)>255||r==="."||r===".."||Zi(r)||r.includes("\0")||r.includes("\\")))&&S("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(t)}.`)}function vu(t){return{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")||!t&&["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(n))),GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_NO_LAZY_FETCH:"1",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0",...t?{GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"}:{}}}function es(t,e){return At(t).map(n=>{let r=n.indexOf(" "),[o,i,s]=n.slice(0,r).split(" ");return r<0||!(e?Ur.test(i):Ur.test(s))?S("git_source_error","Git returned an invalid source entry."):(e&&s!=="0"&&S("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(r+1),mode:o,oid:e?i:s})})}function at(t){return(t??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function Bi(t,e){let n=await t.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await Gr(t),o={headSha:n,branch:r,baseRef:null,baseSha:null,baselineMode:"whole-project"};if(e!==void 0){(!e||e.startsWith("-")||e.length>1024||/[\x00-\x1f\x7f]/.test(e))&&S("invalid_base","--base must name a local Git commit or ref.");let a=await t.text(["rev-parse","--verify","--quiet",`${e}^{commit}`],!0);return Ur.test(a)||S("invalid_base",`--base ${JSON.stringify(e)} is not a local commit or ref. Canary does not fetch; pass one that exists locally.`),{...o,baseRef:e,baseSha:a,baselineMode:"explicit"}}if(!n)return o;let i=await t.text(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"],!0),s;for(let a of[[i],["refs/remotes/origin/main","refs/remotes/origin/master"],["main","master"].filter(l=>l!==r).map(l=>`refs/heads/${l}`)]){for(let l of[...new Set(a.filter(Boolean))]){let c=await t.text(["rev-parse","--verify","--quiet",`${l}^{commit}`],!0);if(!c)continue;let u=await t.text(["merge-base",n,c],!0);if(!u)continue;let d=Number(await t.text(["rev-list","--count",`${u}..${n}`]));(!s||d<s.distance)&&(s={ref:l,base:u,distance:d})}if(s)break}return s?{...o,baseRef:s.ref,baseSha:s.base,baselineMode:"merge-base"}:o}async function Jr(t){return new Set(At(await t.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function Ge(t,e,n){if(!e.length)return;let r=At(await t.run(["check-attr",...n?["--cached"]:[],"-z","--stdin","filter"],{input:`${e.join("\0")}\0`}));for(let o=0;o<r.length;o+=3)r[o+2]==="lfs"&&S("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[o])}. Remove the LFS attribute for it, or ignore the file.`)}function $u(t,e){(t.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
48
- `)||t.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
49
- `))&&S("unsupported_lfs",`${JSON.stringify(e)} is a Git LFS pointer. Canary needs the real file contents.`)}function Wr(t,e){(t.length>e.maxTreeFiles||t.reduce((i,s)=>i+s.size,0)>e.maxTreeBytes)&&S("snapshot_limit","This repository has too many files, or too many bytes, to upload.");let n=new Map,r=new Map,o=new Map;for(let i of t){Vr(i.path,e),i.link!==void 0&&o.set(i.path,i.link);let s=i.path.split("/");for(let a=1;a<=s.length;a++){let l=s.slice(0,a).join("/"),c=l.normalize("NFC").toLowerCase();n.has(c)&&n.get(c)!==l&&S("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(l)}.`),n.set(c,l);let u=a<s.length;r.has(l)&&r.get(l)!==u&&S("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(l)}.`),r.set(l,u)}}[...r.values()].filter(Boolean).length+1>e.maxObjects&&S("snapshot_limit","This repository has too many directories to upload.");for(let[i,s]of o){(!s||Buffer.byteLength(s)>e.maxSymlinkBytes||s.startsWith("/")||s.includes("\0")||s.includes("\\")||/^[a-z]:/i.test(s))&&S("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(i)}.`);let a=s.split("/"),l=i.split("/").slice(0,-1),c=0;for(;a.length;){let u=a.shift();if(!u||u===".")continue;if(u===".."){l.length||S("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(i)}.`),l.pop();continue}Zi(u)&&S("unsafe_symlink",`Symlink enters Git metadata: ${JSON.stringify(i)}.`),l.push(u);let d=n.get(l.join("/").normalize("NFC").toLowerCase());if(d!==void 0&&o.has(d)){++c>e.maxDepth&&S("unsafe_symlink",`Symlink cycle or excessive chain depth at ${JSON.stringify(i)}.`);let h=o.get(d);(h.startsWith("/")||h.includes("\\")||/^[a-z]:/i.test(h))&&S("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(i)}.`),l.pop(),a.unshift(...h.split("/"))}a.length+l.length>e.maxPathBytes&&S("unsafe_symlink","Symlink expansion exceeds the source limit.")}}}async function Sn(t,e){let n=new Map;for(let o of t){let i=o.path.split("/"),s=n;for(let a of i.slice(0,-1))s.has(a)||s.set(a,new Map),s=s.get(a);s.set(i.at(-1),o)}let r=async o=>{let i=[];for(let[s,a]of o)i.push(a instanceof Map?{name:s,mode:"40000",oid:await r(a)}:{name:s,mode:a.mode,oid:a.oid});return i.sort((s,a)=>Buffer.compare(Buffer.from(s.name+(s.mode==="40000"?"/":"")),Buffer.from(a.name+(a.mode==="40000"?"/":"")))),e.put("tree",Buffer.concat(i.map(s=>Buffer.concat([Buffer.from(`${s.mode} ${s.name}\0`),Buffer.from(s.oid,"hex")]))))};return r(n)}async function ts(t,e){let n=e.split("/");for(let r=1;r<=n.length;r++)try{let o=await du(ue(t,...n.slice(0,r)));if(r===n.length)return o;if(!o.isDirectory())return null}catch(o){if(["ENOENT","ENOTDIR"].includes(o.code??""))return null;throw o}return null}async function Iu(t,e,n,r){let o=await ts(t,e);if(n.set(e,o?st(o):null),!o||o.isDirectory())return null;if(!o.isFile()&&!o.isSymbolicLink()&&S("unsupported_file",`This is not a regular file or symlink and cannot be uploaded: ${JSON.stringify(e)}.`),o.size>(o.isSymbolicLink()?r.maxSymlinkBytes:r.maxObjectBytes)&&S("snapshot_limit",`This file is too large to upload: ${JSON.stringify(e)}.`),o.isSymbolicLink())return{data:await hu(ue(t,e),{encoding:"buffer"}),mode:"120000"};let i=await Yi(ue(t,e),Wi.O_RDONLY|Wi.O_NOFOLLOW);try{st(await i.stat())!==st(o)&&S("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.");let s=Buffer.alloc(o.size+1),a=0;for(;a<s.length;){let c=await i.read(s,a,s.length-a);if(!c.bytesRead)break;a+=c.bytesRead}return(a!==o.size||st(await i.stat())!==st(o))&&S("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped."),{data:s.subarray(0,a),mode:o.mode&73?"100755":"100644"}}finally{await i.close()}}async function Ru(t,e,n,r,o){let i=Buffer.from(`# v2 git bundle
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 Yi(e,"wx",384);try{let a=t.child(["pack-objects","--stdout","--revs","--no-reuse-delta","--no-reuse-object","--window=0","--threads=1","--compression=6"]),l=Br("sha256"),c=0,u="";a.stderr.on("data",p=>{u.length<8192&&(u+=p.toString())}),a.stdin.on("error",()=>{});let d=new Promise((p,f)=>{a.on("close",p),a.on("error",f)});d.catch(()=>{});let h=async p=>{c+=p.length,c>o.maxBundleBytes&&S("snapshot_limit","This repository is too large to upload, even compressed."),l.update(p),await s.writeFile(p)};try{await h(i),a.stdin.end(`${r}
54
- `);for await(let p of a.stdout)await h(p);return await d!==0&&S("git_source_error",`Cannot package source: ${u.trim()}`),{bytes:c,sha256:l.digest("hex")}}finally{a.kill(),await d.catch(()=>{})}}finally{await s.close()}}function ns(t){let e={...Et,...t};for(let[n,r]of Object.entries(e))(!Object.hasOwn(Et,n)||!Number.isSafeInteger(r)||r<=0||r>Et[n])&&S("invalid_limit",`Invalid source snapshot limit ${n}.`);return e}async function rs(t,e){let n=await Ot(t),r=new Je(n,e),o;try{o=await Ot(await r.text(["rev-parse","--show-toplevel"]))}catch(l){if(e?.aborted)throw l;return S("not_a_git_repository","Run this command inside a Git repository.")}let i=new Je(o,e),s=await Ot(Xi(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(`
55
- `).some(l=>/^extensions\.objectformat\s+(?!sha1$)/i.test(l))&&S("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(a.split(`
56
- `).some(l=>/^extensions\.partialclone\s/i.test(l)||/^remote\..*\.promisor(?:\s|$)/i.test(l)&&!/\s(false|no|off|0)$/i.test(l))||(await pu(ue(s,"objects","pack")).catch(()=>[])).some(l=>l.endsWith(".promisor")))&&S("partial_clone","This is a partial clone. Canary needs every Git object on disk and will not fetch them; use a full clone."),{root:o,common:s,git:i}}async function xn(t){let e=es(await t.run(["ls-files","--stage","-z"]),!0),n=await Jr(t),r=e.filter(s=>is(s,n)),o=At(await t.run(["ls-files","--others","--exclude-standard","-z"])).filter(s=>!os(s)),i=new Set(At(await t.run(["ls-files","-t","-z"])).filter(s=>s.startsWith("S ")).map(s=>s.slice(2)));return{tracked:r,paths:[...new Set([...r.map(s=>s.path),...o])].sort(),skip:i}}async function ss(t,e){let n=Xi(e,await t.text(["rev-parse","--git-path","index"]));return async()=>{try{return Br("sha256").update(await fu(n)).digest("hex")}catch(r){if(r.code==="ENOENT")return"missing";throw r}}}function as(t,e){for(let n of t)Vr(n.path,e),n.mode==="160000"&&S("unsupported_submodule",`Submodules cannot be uploaded: ${JSON.stringify(n.path)}.`),["100644","100755","120000"].includes(n.mode)||S("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function cs(t,e){for(let n of t)n.endsWith("/")&&S("unsupported_submodule",`Nested Git repositories cannot be uploaded: ${JSON.stringify(n)}.`),Vr(n,e)}function ls(t,e){let n=new Map;return async(r,o,i)=>{$u(o,r.path);let s=await t.put("blob",o);r.oid&&r.oid!==s&&S("invalid_source_object",`Git blob contents do not match their hash: ${JSON.stringify(r.path)}.`);let a=(n.get(i)??0)+o.length;n.set(i,a),a>e.maxTreeBytes&&S("snapshot_limit","This repository has too many bytes to upload."),i.push({...r,oid:s,size:o.length,...r.mode==="120000"?{link:Qi(o)}:{}})}}async function us(t){let{root:e,current:n,trustFileMode:r,limits:o,stamps:i,capture:s,out:a}=t,l=new Map(n.tracked.map(c=>[c.path,c]));for(let c of n.paths){t.signal?.throwIfAborted();let u=await Iu(e,c,i,o);if(u){let d=l.get(c),h=!r&&u.mode!=="120000"&&d&&["100644","100755"].includes(d.mode)?d.mode:u.mode;await s({path:c,mode:h,oid:""},u.data,a)}else if(i.get(c)===null&&n.skip.has(c)){let d=l.get(c);await s(d,await t.blob(d.oid),a)}}}async function ds(t,e){for(let[n,r]of e){let o=await ts(t,n);(o?st(o):null)!==r&&S("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function Nt(t,e={}){let n=ns(e.limits),{root:r,common:o,git:i}=await rs(t,e.signal),s=await Ot(zi());(bn(r,s)||bn(o,s))&&S("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await qi(ue(s,"canary-source-")),l,c=()=>Ki(a,{recursive:!0,force:!0});try{let u=await Bi(i,e.baseRef),d=await ss(i,r),h=await d(),p=new Je(r,e.signal,!1,{GIT_INDEX_FILE:ue(a,"baseline-index")});await p.run(["read-tree",u.baseSha??"--empty"]);let f=u.baseSha?es(await i.run(["ls-tree","-r","-z","--full-tree",u.baseSha]),!1):[],m=await Jr(p),g=f.filter(R=>is(R,m)),w=await xn(i),x=await i.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(g.length>n.maxTreeFiles||w.paths.length>n.maxTreeFiles)&&S("snapshot_limit","This repository has too many files to upload."),as([...g,...w.tracked],n),cs(w.paths,n),await Ge(p,g.map(R=>R.path),!0),await Ge(i,w.paths,!1);let y=ue(a,"repository.git");await Vi(y);let k=new Je(y,e.signal,!0);await k.run(["init","--bare","--quiet","--template="]);let _=new Tt(y,n,e.signal);l=new kn(i,n);let E=[],C=[],U=ls(_,n),_e=l;for(let R of g)await U(R,await l.get(R.oid),E);let O=new Map;await us({root:r,current:w,trustFileMode:x,limits:n,signal:e.signal,stamps:O,capture:U,blob:R=>_e.get(R),out:C}),Wr(E,n),Wr(C,n);let M=await Sn(E,_),ye=await Sn(C,_);for(let[R,ae]of[[M,E],[ye,C]])await k.run(["read-tree",R]),await Ge(k,ae.map(K=>K.path),!0);let yt=await _.put("commit",Buffer.from(`tree ${M}
57
- author ${wn}
58
- committer ${wn}
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
- `)),Kt=await _.put("commit",Buffer.from(`tree ${ye}
62
- parent ${yt}
63
- author ${wn}
64
- committer ${wn}
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
- `)),Z=ue(a,"source.bundle"),we=await Ru(k,Z,yt,Kt,n),de=await xn(i);(h!==await d()||JSON.stringify(w.paths)!==JSON.stringify(de.paths)||JSON.stringify([...m].sort())!==JSON.stringify([...await Jr(p)].sort())||JSON.stringify(u)!==JSON.stringify(await Bi(i,e.baseRef)))&&S("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await ds(r,O),await Ge(p,g.map(R=>R.path),!0),await Ge(i,w.paths,!1);let fe=new Map(E.map(R=>[R.path,R])),Y=new Map(C.map(R=>[R.path,R])),pe=[];for(let R of[...new Set([...fe.keys(),...Y.keys()])].sort()){let ae=fe.get(R),K=Y.get(R);ae?K?(ae.oid!==K.oid||ae.mode!==K.mode)&&pe.push({path:R,status:ae.mode==="120000"!=(K.mode==="120000")?"T":"M"}):pe.push({path:R,status:"D"}):pe.push({path:R,status:"A"})}await l.close(),l=void 0;let Ne=C.map(R=>({path:R.path,mode:R.mode,oid:R.oid}));return{bundlePath:Z,manifest:{kind:"local_snapshot",version:2,...we,baseTreeHash:M,treeHash:ye,baseSha:yt,headSha:Kt,provenance:u},files:pe,entries:Ne,dispose:c}}catch(u){throw await l?.close(),await c(),u}}async function Ou(t,e,n,r,o,i){let s=await Ot(zi());(bn(t,s)||bn(e,s))&&S("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await qi(ue(s,"canary-identity-"));try{let l=new Je(a,i,!0);await l.run(["init","--bare","--quiet","--template="]);let c=new Tt(a,o,i);for(let u of r.values())await c.put("blob",u);await l.run(["read-tree",await Sn(n,c)]),await Ge(l,n.map(u=>u.path),!0)}finally{await Ki(a,{recursive:!0,force:!0})}}async function _n(t,e={}){let n=ns(e.limits),{root:r,common:o,git:i}=await rs(t,e.signal),s;try{let a=await Gr(i),l=await ss(i,r),c=await l(),u=await xn(i),d=await i.text(["config","--bool","--get","core.fileMode"],!0)!=="false";u.paths.length>n.maxTreeFiles&&S("snapshot_limit","This repository has too many files to upload."),as(u.tracked,n),cs(u.paths,n),await Ge(i,u.paths,!1);let h=new Tt(null,n,e.signal),p=[],f=new Map,m=new Map,g=ls(h,n),w=(k,_,E)=>(mu(k.path)===".gitattributes"&&m.set(k.path,_),g(k,_,E));await us({root:r,current:u,trustFileMode:d,limits:n,signal:e.signal,stamps:f,capture:w,blob:k=>(s??=new kn(i,n)).get(k),out:p}),Wr(p,n);let x=await Sn(p,h);[...m.values()].some(k=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(k.toString("utf8")))&&await Ou(r,o,p,m,n,e.signal);let y=await xn(i);return(c!==await l()||JSON.stringify(u.paths)!==JSON.stringify(y.paths)||a!==await Gr(i))&&S("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await ds(r,f),{root:r,treeHash:x,branch:a,files:p.map(k=>({path:k.path,mode:k.mode,oid:k.oid}))}}finally{await s?.close()}}var Et,re,S,xu,_u,Ur,wn,bn,Qi,At,Zi,Cu,Je,Gr,kn,Tt,st,os,is,ct=J(()=>{"use strict";Et={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},re=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="SourceSnapshotError"}},S=(t,e)=>{throw new re(t,e)},xu=ku(Su),_u=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),Ur=/^[a-f0-9]{40}$/,wn="Canary Snapshot <snapshot@runcanary.ai> 0 +0000",bn=(t,e)=>{let n=wu(t,e);return n===""||!n.startsWith(`..${bu}`)&&n!==".."&&!yu(n)},Qi=t=>{try{return _u.decode(t)}catch{return S("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},At=t=>t.length?Qi(t).split("\0").filter(Boolean):[],Zi=t=>{let e=t.normalize("NFC").replace(/[\u200c-\u200f\u202a-\u202e\u206a-\u206f\ufeff]/g,"").toLowerCase().replace(/[ .]+$/g,"");return e===".git"||e.startsWith(".git:")||/^git~[0-9]+(?:\.|$)/.test(e)};Cu=["-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"],Je=class{constructor(e,n,r=!1,o={}){this.cwd=e;this.signal=n;this.isolated=r;this.extra=o}child(e){return this.signal?.throwIfAborted(),uu("git",[...Cu,...e],{cwd:this.cwd,env:{...vu(this.isolated),...this.extra},signal:this.signal,stdio:"pipe"})}async run(e,n={}){let r=this.child(e),o=[],i=0,s="",a;r.on("error",c=>{a=c}),r.stdout.on("data",c=>{i+=c.length,i>(n.maxBytes??256*1024*1024)?(a=new re("snapshot_limit","This repository's Git metadata is too large to upload."),r.kill()):o.push(c)}),r.stderr.on("data",c=>{s.length<8192&&(s+=c.toString("utf8"))}),r.stdin.on("error",()=>{}),r.stdin.end(n.input);let l=await new Promise(c=>r.on("close",c));if(a)throw a;return l!==0&&!(n.optional&&l===1)&&S("git_source_error",`Cannot read local Git source: ${s.trim()||`git ${e[0]} failed`}`),l===1?Buffer.alloc(0):Buffer.concat(o)}async text(e,n=!1){return(await this.run(e,{optional:n})).toString("utf8").trim()}};Gr=async t=>await t.text(["symbolic-ref","--quiet","--short","HEAD"],!0)||null;kn=class{constructor(e,n){this.limits=n;this.child=e.child(["cat-file","--batch"]),this.child.on("error",r=>{this.error=r}),this.child.stdin.on("error",()=>{}),this.child.stderr.resume(),this.iterator=this.child.stdout[Symbol.asyncIterator]()}child;iterator;pending=Buffer.alloc(0);error;async read(e){let n=[],r=e;for(;r;){if(!this.pending.length){let i=await this.iterator.next();if(i.done)throw this.error??new re("missing_source_object","A Git object this repository needs is missing on disk. Canary does not fetch; restore it, then run the command again.");this.pending=i.value}let o=Math.min(r,this.pending.length);n.push(this.pending.subarray(0,o)),this.pending=this.pending.subarray(o),r-=o}return Buffer.concat(n,e)}async get(e){this.child.stdin.write(`${e}
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!==e||o!=="blob"||!Number.isSafeInteger(s)||s<0)&&S("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),s>this.limits.maxObjectBytes&&S("snapshot_limit","A file in this repository is too large to upload.");let a=await this.read(s);return(await this.read(1))[0]!==10&&S("git_source_error","Invalid Git object framing."),a}async close(){this.child.exitCode!==null||this.child.signalCode!==null||(this.child.stdin.end(),this.child.kill(),await new Promise(e=>this.child.on("close",()=>e())))}},Tt=class{constructor(e,n,r){this.directory=e;this.limits=n;this.signal=r}sizes=new Map;expanded=0;async put(e,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&S("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.from(`${e} ${n.length}\0`),o=Br("sha1").update(r).update(n).digest("hex");if(!this.sizes.has(o)&&((this.sizes.size+1>this.limits.maxObjects||this.expanded+n.length>this.limits.maxExpandedBytes)&&S("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(o,n.length),this.expanded+=n.length,this.directory!==null)){let i=ue(this.directory,"objects",o.slice(0,2));await Vi(i,{recursive:!0}),await gu(ue(i,o.slice(2)),await xu(Buffer.concat([r,n]),{level:6}),{mode:384,flag:"wx"})}return o}};st=t=>`${t.dev}:${t.ino}:${t.mode}:${t.size}:${t.mtimeMs}:${t.ctimeMs}`;os=t=>t.split("/").some(e=>e.toLowerCase()===".git"),is=(t,e)=>!e.has(t.path)&&!os(t.path)});import{randomUUID as Eu}from"node:crypto";import{readFileSync as Au,renameSync as Tu,rmSync as fs,writeFileSync as Nu}from"node:fs";async function Pt(t,e,n={}){try{await v("/api/v1/cli/events",{method:"POST",token:e.token,baseUrl:e.apiUrl,body:{outcome:t,...n.runId?{runId:n.runId}:{}},signal:AbortSignal.timeout(n.timeoutMs??1500)})}catch{}}function ps(t,e){return!e||t.decision!=="allow"||!Pu.has(t.cause)?Promise.resolve():Pt(`gate_allow:${t.cause}`,e,{timeoutMs:500})}function gs(t,e){try{let n=le(t,hs),r=`${n}.${Eu()}.tmp`;try{Nu(r,JSON.stringify({version:1,at:new Date().toISOString(),treeHash:e})+`
70
- `,{flag:"wx",mode:384}),Tu(r,n)}catch(o){throw fs(r,{force:!0}),o}}catch{}}function vn(t,e=Date.now()){try{let n=le(t,hs),r=Date.parse(JSON.parse(Au(n,"utf8")).at??"");return fs(n,{force:!0}),Number.isFinite(r)&&e-r>=0&&e-r<Lu}catch{return!1}}var Pu,hs,Lu,Cn=J(()=>{"use strict";B();X();Pu=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);hs="last-denial.json",Lu=1440*60*1e3});import{randomUUID as Mu}from"node:crypto";import{readdirSync as ju,readFileSync as Hu,renameSync as Fu,rmSync as ms,statSync as ws,writeFileSync as Du}from"node:fs";import{dirname as ys,join as Uu}from"node:path";import{gunzipSync as Gu,gzipSync as Ju}from"node:zlib";function Ss(t,e,n){try{let r=le(t,ks(e)),o=`${r}.${Mu()}.tmp`,i=Ju(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:e,entries:n.map(s=>[s.path,s.mode,s.oid])})));try{Du(o,i,{flag:"wx",mode:384}),Fu(o,r)}catch(s){throw ms(o,{force:!0}),s}for(let s of ju(ys(r))){if(!s.startsWith("tree-")||!s.endsWith(".json.gz"))continue;let a=Uu(ys(r),s);try{Date.now()-ws(a).mtimeMs>bs&&ms(a,{force:!0})}catch{}}}catch{}}function Bu(t,e){try{let n=le(t,ks(e));if(Date.now()-ws(n).mtimeMs>bs)return null;let r=JSON.parse(Gu(Hu(n)).toString("utf8"));if(r.version!==1||r.treeHash!==e||!Array.isArray(r.entries))return null;let o=new Map;for(let i of r.entries)Array.isArray(i)&&i.length===3&&i.every(s=>typeof s=="string")&&o.set(i[0],`${i[1]}:${i[2]}`);return o}catch{return null}}function xs(t,e,n){let r=Bu(t,e);if(!r)return null;let o=new Map;for(let a of n){let l=r.get(a.path);l!==`${a.mode}:${a.oid}`&&o.set(a.path,l===void 0?`${a.path} (new)`:a.path)}let i=new Set(n.map(a=>a.path));for(let a of r.keys())i.has(a)||o.set(a,`${a} (removed)`);let s=[...o.keys()].sort().map(a=>o.get(a));return{files:s.slice(0,Wu),total:s.length}}var Wu,bs,ks,qr=J(()=>{"use strict";X();Wu=8,bs=720*60*60*1e3,ks=t=>`tree-${t}.json.gz`});import{createHash as Vu}from"node:crypto";import{constants as _s}from"node:fs";import{open as qu}from"node:fs/promises";import{Readable as Yu}from"node:stream";function Rn(t){if(!Yr(t,Os))return!1;let e=t.provenance;return t.kind==="local_snapshot"&&t.version===2&&typeof t.sha256=="string"&&/^[a-f0-9]{64}$/.test(t.sha256)&&typeof t.bytes=="number"&&Number.isSafeInteger(t.bytes)&&t.bytes>0&&t.bytes<=Et.maxBundleBytes&&[t.baseTreeHash,t.treeHash,t.baseSha,t.headSha].every(n=>typeof n=="string"&&vs.test(n))&&Yr(e,Es)&&[e.headSha,e.baseSha].every(n=>n===null||typeof n=="string"&&vs.test(n))&&[e.branch,e.baseRef].every(n=>n===null||typeof n=="string"&&n.length>0&&n.length<=1024&&!/[\x00-\x1f\x7f]/.test(n))&&["explicit","merge-base","whole-project"].includes(e.baselineMode)}function Ku(t,e){return Os.filter(n=>n!=="provenance").every(n=>t[n]===e[n])&&Es.every(n=>t.provenance[n]===e.provenance[n])}function Lt(t,e){if(!Yr(t,["uploadId","expiresAt","status","source"])||typeof t.uploadId!="string"||!In.test(t.uploadId)||typeof t.expiresAt!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t.expiresAt)||!Number.isFinite(Date.parse(t.expiresAt))||!["pending","uploading","completed","cancelled"].includes(t.status)||!Rn(t.source)||e?.uploadId!==void 0&&e.uploadId!==t.uploadId||e?.manifest!==void 0&&!Ku(e.manifest,t.source))throw new F(502,"invalid_upload_response","Canary's answer does not match the upload in progress.","Run the command again to continue the upload.",e?.uploadId);return t}function As(t){if(!In.test(t))throw new F(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${Rs}/${t}`}function zu(t,e){return t instanceof F?new F(t.status,t.code,t.message,t.fix,e):t instanceof $?new F(t.status,"source_upload_failed",t.message,t.fix,e):new F(0,"source_upload_failed",t instanceof Error?t.message:"The source upload failed.","Run the command again to continue the upload.",e)}function $n(t){if(t.status==="completed")return t;throw t.status==="cancelled"?new F(410,"source_upload_cancelled","This upload was cancelled.",void 0,t.uploadId):new F(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",t.uploadId)}async function Cs(t,e,n={}){let r=await(n.request??v)(As(t),{...e});return Lt(r,{uploadId:t})}async function*Ts(t,e,n){let r=0;for(;r<e;){n?.throwIfAborted();let o=Buffer.allocUnsafe(Math.min(64*1024,e-r)),i=await t.read(o,0,o.length,r);if(!i.bytesRead)throw new F(0,"source_changed","The source changed while it was being uploaded. Run the command again.");r+=i.bytesRead,yield o.subarray(0,i.bytesRead)}}async function $s(t,e,n){let r=await t.stat();if(!r.isFile()||r.size!==e.bytes)throw new F(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let o=Vu("sha256");for await(let s of Ts(t,e.bytes,n))o.update(s);let i=await t.stat();if(o.digest("hex")!==e.sha256||i.size!==r.size||i.mtimeMs!==r.mtimeMs||i.ctimeMs!==r.ctimeMs)throw new F(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function Is(t,e,n,r){let o=Yu.from(Ts(t,e.manifest.bytes,e.signal));try{let i=await(r.fetch??fetch)(`${e.baseUrl.replace(/\/+$/,"")}${As(n)}/content`,{method:"PUT",headers:{...(r.headers??$e)(),authorization:`Bearer ${e.token}`,"content-type":"application/octet-stream","content-length":String(e.manifest.bytes)},body:o,duplex:"half",signal:e.signal,redirect:"error"});if(!i.ok){let s={};try{s=await i.json()}catch{}throw new F(i.status,typeof s.code=="string"?s.code:"source_upload_failed",typeof s.error=="string"?s.error:i.statusText,typeof s.fix=="string"?s.fix:void 0,n)}return $n(Lt(await i.json(),{uploadId:n,manifest:e.manifest}))}catch(i){throw i instanceof F?i:new F(0,"source_upload_uncertain","The connection dropped before Canary confirmed the upload.","An earlier upload is still in progress. Run the command again to continue it.",n)}finally{o.destroy()}}async function Ns(t,e={}){if(!Rn(t.manifest)||!In.test(t.workspaceId)||!In.test(t.repositoryId))throw new F(0,"invalid_source_receipt","A captured source, a workspace, and a repository are required before uploading.");let n={token:t.token,baseUrl:t.baseUrl,signal:t.signal},r;if(t.uploadId&&(r=Lt(await Cs(t.uploadId,n,e),{uploadId:t.uploadId,manifest:t.manifest}),r.status!=="pending"))return $n(r);let o=await qu(t.bundlePath,_s.O_RDONLY|_s.O_NOFOLLOW);try{if(await $s(o,t.manifest,t.signal),r||(r=Lt(await(e.request??v)(Rs,{...n,method:"POST",body:{workspaceId:t.workspaceId,repositoryId:t.repositoryId,source:t.manifest}}),{manifest:t.manifest})),t.onReceipt?.(r),r.status!=="pending")return $n(r);try{return await Is(o,t,r.uploadId,e)}catch(i){if(t.signal?.aborted||!(ie(i)||i instanceof $&&i.status===409))throw i;let s=Lt(await Cs(r.uploadId,n,e),{uploadId:r.uploadId,manifest:t.manifest});return s.status!=="pending"?$n(s):(await $s(o,t.manifest,t.signal),await Is(o,t,r.uploadId,e))}}catch(i){throw r?zu(i,r.uploadId):i}finally{await o.close()}}var F,Rs,In,vs,Os,Es,Yr,Kr=J(()=>{"use strict";B();Ie();ct();F=class extends ${constructor(n,r,o,i,s){super(n,o,i);this.code=r;this.uploadId=s;this.name="SourceUploadError"}},Rs="/api/v1/cli/source-uploads",In=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,vs=/^[a-f0-9]{40}$/,Os=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],Es=["headSha","branch","baseRef","baseSha","baselineMode"],Yr=(t,e)=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===e.length&&e.every(n=>Object.hasOwn(t,n))});import{createHash as Xu,randomUUID as Qu}from"node:crypto";import{readFileSync as Zu,renameSync as ed,rmSync as Ps,writeFileSync as td}from"node:fs";function Ls(t,e,n,r="verify"){let o=Xu("sha256").update(JSON.stringify([n,t,r])).digest("hex");return le(e,`source-upload-${o}.json`)}function Ms(t){try{let e=JSON.parse(Zu(t,"utf8"));if(typeof e.uploadId!="string"||!/^[a-f0-9-]{36}$/i.test(e.uploadId)||typeof e.expiresAt!="string"||!Number.isFinite(Date.parse(e.expiresAt)))throw new Error("invalid upload record");return{uploadId:e.uploadId,expiresAt:e.expiresAt}}catch(e){if(e.code!=="ENOENT")throw new F(0,"invalid_upload_receipt","Canary's record of an earlier upload under CANARY_HOME/local-repositories is unreadable.","Fix or remove that file, then run the command again.")}}function zr(t,e,n,r){let o=Ls(t,e,n,r.requestKey),i=Ms(o);i&&(!r.uploadId||i.uploadId===r.uploadId)&&Ps(o,{force:!0})}async function On(t,e,n,r,o={}){let i=Ls(t.manifest,e,n,o.requestKey),s=o.fresh?void 0:Ms(i),a=s&&Date.parse(s.expiresAt)>Date.now()?s.uploadId:void 0,l=await Ns({bundlePath:t.bundlePath,manifest:t.manifest,workspaceId:e.workspaceId,repositoryId:n,token:r,baseUrl:e.apiUrl,...a?{uploadId:a}:{},onReceipt:({uploadId:c,expiresAt:u})=>{let d=`${i}.${Qu()}.tmp`;try{td(d,JSON.stringify({uploadId:c,expiresAt:u})+`
71
- `,{flag:"wx",mode:384}),ed(d,i)}finally{Ps(d,{force:!0})}}});return{...l.source,uploadId:l.uploadId}}var Xr=J(()=>{"use strict";X();Kr()});import{readFileSync as js}from"node:fs";function id(t){if(t===void 0)return;let e=t;try{t==="-"?e=js(0,"utf8"):t.startsWith("@")&&(e=js(t.slice(1),"utf8"))}catch(n){throw new ge("brief_unreadable",`could not read the brief from ${t==="-"?"stdin":t.slice(1)}: ${n instanceof Error?n.message:String(n)}`,"pass the brief as text, @<file>, or - (stdin)")}return e.trim()===""?void 0:e}function me(t){return t==="P3"?null:t==="P0"||t==="P1"?t:"P2"}function sd(t,e){if(me(t.materiality)===null)return null;let r=e??null;return t.result==="fail"?{checkRunId:t.checkRunId,kind:"fail",proof:r?.isStatic===!1?"runtime":"source",headline:b(r?.finding?.headline)||b(t.title),summary:b(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:Us(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:b(r?.finding?.reproduce)||null}:t.result==="blocked"?{checkRunId:t.checkRunId,kind:"blocked",proof:"none",headline:b(t.title),summary:b(r?.verdict?.reasonOneLiner)||(jt[t.blockedReason??""]??""),location:Us(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}function eo(t,e,n){let r=H();v("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...n?{baseUrl:n}:{},body:{outcome:t,...e?{runId:e}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function Js(t){if(t.status!=="completed"||t.stageB.status==="failed")return 2;let e=t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns;return e>0&&t.stageC.checks.length===e?2:0}async function to(t,e,n={}){let r=d=>v(d,{token:e,...n.baseUrl?{baseUrl:n.baseUrl}:{}}),o=new Map,i="",s=new Set,a=!1,l=!1,c=null,u=Date.now();for(;;){let d;try{d=(await r(`/api/v1/red-team/runs/${t}`)).run,c=null}catch(f){if(ie(f)&&(c??=Date.now(),Date.now()-c<nd)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await Mt(Qr);continue}throw f}for(let f of d.stageC.checks)if(!(!(f.status==="completed"&&(f.result==="fail"||f.result==="blocked"))||o.has(f.checkRunId))){if(!We.test(f.checkRunId)){o.set(f.checkRunId,null);continue}try{o.set(f.checkRunId,await r(`/api/v1/red-team/runs/${t}/checks/${f.checkRunId}/finding`))}catch(g){ie(g)||o.set(f.checkRunId,null)}}for(let f of d.stageC.checks){if(s.has(f.checkRunId)||!(f.status==="completed"||f.status==="failed"||f.status==="cancelled")||me(f.materiality)===null)continue;s.add(f.checkRunId);let g=o.get(f.checkRunId),w=f.status!=="completed"?"!":f.result==="pass"?"\u2713":f.result==="fail"?"\u2717":"\u23F8",x=f.status!=="completed"?"errored":f.result==="pass"?"passed":f.result==="fail"?g?.isStatic===!1?"verified failure":"finding from the code":"could not verify";n.onProgress?.(`${w} ${x}: ${b(f.title)}`)}d.stageB.status!=="completed"&&(l=!0);let h=d.stageC.checks.length>0||d.stageB.finalChecksCount===0||Zr.has(d.status);!a&&d.stageB.status==="completed"&&h&&(a=!0,n.onProgress?.(cd(d,l?Date.now()-u:null,o)));let p=ad(d);if(p!==i&&(n.onProgress?.(p),i=p),Zr.has(d.status)){for(let m=0;m<3;m++){let g=d.stageC.checks.filter(w=>w.status==="completed"&&(w.result==="fail"||w.result==="blocked")&&!o.has(w.checkRunId));if(g.length===0)break;await Mt(Math.min(Qr,1e3));for(let w of g)try{o.set(w.checkRunId,await r(`/api/v1/red-team/runs/${t}/checks/${w.checkRunId}/finding`))}catch(x){(!ie(x)||m===2)&&o.set(w.checkRunId,null)}}let f=d.stageC.checks.filter(m=>m.status==="completed"&&(m.result==="fail"||m.result==="blocked")).sort((m,g)=>Gs[me(m.materiality)??"P2"]-Gs[me(g.materiality)??"P2"]).map(m=>sd(m,o.get(m.checkRunId)??null)).filter(m=>m!==null);return{run:d,findings:f}}if(Date.now()-u>Hs)throw new ge("still_running",`run ${t} is still ${d.status} after ${Math.round(Hs/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await Mt(Qr)}}function ad(t){if(t.status==="queued")return"\u2026 queued";if(t.phase==="stage_b"||t.stageC.checks.length===0){let n=t.stageB.risksFound??0;return`\u2026 analyzing the change${n?` \xB7 ${n} risk${n===1?"":"s"} found`:""}`}return`\u2026 ${t.stageC.completedCheckRuns+t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns}/${t.stageC.checks.length} checks done \xB7 ${t.stageC.results.fail} failed`}function cd(t,e,n=new Map){let r=t.stageC.checks.filter(d=>me(d.materiality)!==null),o=d=>d.result==="fail"&&n.get(d.checkRunId)?.isStatic!==!1,i=r.filter(o).length,s=t.stageC.checks.filter(d=>d.status==="failed"||d.status==="cancelled").length,a=r.filter(d=>!o(d)&&d.status!=="failed"&&d.status!=="cancelled").length,l=t.stageC.results.pass+t.stageC.results.blocked+r.filter(d=>d.result==="fail"&&n.get(d.checkRunId)?.isStatic===!1).length,c=Zr.has(t.status)?l>0?"verified in sandboxes":"not run":"verifying in sandboxes";return`${e===null?"analysis done":`analysis done in ${Math.max(1,Math.round(e/6e4))} min`} \xB7 ${se(i,"finding")} from the code \xB7 ${a} runtime check${a===1?"":"s"}${s?` \xB7 ${s} errored`:""} \xB7 ${c}`}function ld(t,e,n){let r=t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns;if(Js(t)===2)return`Verification did not complete (${t.status})${r?`: ${se(r,"check")} errored`:""}; nothing was verified.`;let o=e.filter(u=>u.kind==="fail"&&u.proof==="runtime").length,i=e.filter(u=>u.kind==="fail"&&u.proof==="source").length,s=e.filter(u=>u.kind==="blocked").length,a=t.stageC.results.pass,l=[`${se(o,"verified failure")}`,`${se(a,"check")} passed`,`${se(i,"finding")} from the code (source-reasoned, not run)`,...s?[`${s} could not be verified`]:[],`${se(r,"check")} errored`],c=a===0&&o===0&&s===0&&r===0;return`${l.join("; ")}.${c?" Nothing in this change was executed.":""}${ud(n)}`}function ud(t){let e=t?t.reverifiable-t.carried:0;return!t||e<=0?"":` ${e} of run ${t.sourceRunId.slice(0,8)}'s ${se(t.reverifiable,"failed check")} ${e===1?"was":"were"} not re-run (reported disputed or skipped).`}function dd(t,e){let n=t.slice(0,8);if(!e)return`re-checking the failed set of run ${n} \u2014`;let r=`of run ${n}'s ${se(e.reverifiable,"failed check")}`;return e.excludedReported>0?`re-checking ${e.carried} ${r} (${e.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${e.reverifiable} failed checks of run ${n} \u2014`}function no(t,e,n,r){return{ok:!0,runId:t.runId,treeHash:e,status:t.status,findings:n,summary:ld(t,n,r),failed:n.filter(o=>o.kind==="fail").length,passed:t.stageC.results.pass,blocked:n.filter(o=>o.kind==="blocked").length,errored:t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns,exitCode:Js(t),failureMessage:t.failure?.publicMessage??null,...r?{reverify:r}:{}}}function ro(t){let e=[];if(e.push(`Receipt ${an(t.treeHash)} \xB7 run ${b(t.runId)}`),t.exitCode===2)return e.push(`\u2717 Verification did not complete (${b(t.status)})${t.failureMessage?`: ${b(t.failureMessage)}`:""}`),t.errored>0&&e.push(` ${se(t.errored,"check")} errored \u2014 nothing was verified; this is not a clean result.`),e.push(` Run \`canary verify\` again; if it repeats, report run ${b(t.runId)}.`),e.join(`
72
- `);let n=[t.failed?`\u2717 ${se(t.failed,"finding")}`:"",t.passed?`\u2713 ${t.passed} passed`:"",t.blocked?`\u23F8 ${t.blocked} could not be verified`:""].filter(Boolean);t.findings.length===0&&t.errored===0?e.push(`\u2713 Clean \u2014 no findings in this change${t.passed?` \xB7 ${t.passed} passed`:""}.`):e.push(`${t.failed?"":"\u2713 No verified findings"}${t.failed||n.length===0?"":" \xB7 "}${n.join(" \xB7 ")}`);for(let r of t.findings)e.push(""),e.push(`${fd[r.kind]} ${b(r.headline)}${pd[r.kind]}`),r.summary&&e.push(` ${b(r.summary)}`),r.location&&e.push(` \u2192 ${b(r.location)}`),r.fix&&e.push(` reproduce: ${b(r.fix)}`);return t.errored>0&&e.push(`
73
- (${se(t.errored,"check")} errored and could not be verified.)`),e.push(`
74
- ${t.summary}`),e.join(`
75
- `)}function hd(t){let e=t;return!e||!["EPERM","EACCES","EROFS"].includes(e.code??"")||typeof e.path!="string"||!e.path.startsWith(ee())?null:{message:`Canary keeps its records under ${ee()} and cannot write there from here (${e.code})`,fix:"run the command outside the sandbox, or let it write under that folder"}}function I(t,e,n,r,o,i={}){if(t)console.log(JSON.stringify({ok:!1,error:e,message:n,...r?{fix:r}:{},exitCode:o,...i}));else{let s=typeof i.runId=="string"?i.runId:null;console.error(`\u2717 ${b(n)}${r?`
76
- fix: ${b(r)}`:""}${s?`
77
- run: ${b(s)}`:""}`)}process.exitCode=o}async function gd(t,e,n,r,o={}){let i={baseUrl:o.baseUrl??W()};je({cwd:t,agent:n,mode:r!==void 0?"reverify_failed":"full"});let s=(y,k,_,E=3,C={})=>{I(n,y,k,_,E,C),eo(`exit${E}:${y}`,C.runId,i.baseUrl)},a=H();if(!a)return s("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!We.test(r))return s("bad_run_id",`"${r}" is not a run id`,"pass the run id from your last `canary verify` (see the receipt line), e.g. `canary verify --failed <run-id>`");let l,c;try{l=id(e),c=await Nt(t,{baseRef:o.baseRef})}catch(y){if(y instanceof re||y instanceof ge)return s(y.code,y.message,y.fix);throw y}if(c.manifest.treeHash===c.manifest.baseTreeHash&&r===void 0)return await c.dispose(),s("nothing_to_verify","The current source matches the selected baseline","make a change, or choose a different baseline with --base <ref>");let u,d,h;try{u=await Rt(t,a,i.baseUrl),d=await It({...u,token:a});let y=AbortSignal.timeout(3e3);if((await mn(u,a,y).catch(_=>{throw y.aborted?new $(0,"Checking this repository's setup timed out","run `canary verify` again"):_}))?.state!=="ready")throw new ge("setup_required",`This repository isn't set up for you in ${b(d.workspace.name)} yet`,"run `canary setup`");h=await On(c,u,d.repositoryId,a,{fresh:!0}),Ss(u,c.manifest.treeHash,c.entries)}catch(y){if(y instanceof N||y instanceof ge)return s(y.code,y.message,"fix"in y?y.fix:void 0);if(y instanceof $)return s("api_error",y.message,y.fix,y.status>=400&&y.status<500?3:2);throw y}finally{await c.dispose()}l===void 0&&r===void 0&&console.error("! No --brief given \u2014 Canary will attack the change using the submitted source and baseline. A brief with acceptance criteria and must-not-break finds more."),ze();let p=y=>{n?console.error(` ${y}`):console.log(` ${y}`)};c.manifest.provenance.baselineMode==="whole-project"?p("No comparison branch found: reviewing the whole eligible project against an empty baseline."):p(`Baseline: ${b(c.manifest.provenance.baseRef)} \xB7 source ${an(c.manifest.treeHash)}`);let f,m,g;{let y,k=at(c.manifest.provenance.branch),_=()=>v("/api/v1/cli/runs",{method:"POST",token:a,...i,body:{repositoryId:d.repositoryId,workspaceId:u.workspaceId,source:h,...l!==void 0?{brief:l}:{},...k?{branch:k}:{},...r!==void 0?{reverifySourceRunId:r}:{}}});try{for(let C=1;;C+=1)try{y=await _();break}catch(U){if(C>=Fs||!ie(U)||U instanceof $&&U.runId&&We.test(U.runId))throw U;p(`${U.message} \u2014 retrying (${C}/${Fs-1})`),await Mt(Ds*C)}}catch(C){if(C instanceof $){let U=!ie(C)&&C.status>=400&&C.status<500,_e=C.fix??(C.status===401||C.status===403?"run `canary login`":U?void 0:"run `canary verify` again in a minute"),O={httpStatus:C.status,...C.runId?{runId:C.runId}:{}};return U?I(n,"api_error",C.message,_e,3,O):s("api_error",C.message,_e,2,O)}throw C}if(y.treeHash!==c.manifest.treeHash||y.headSha!==c.manifest.headSha)return I(n,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!We.test(y.runId))return I(n,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);f=y.runId;let E=r?dd(r,y.reverify):y.created?"submitted":"same verification inputs as an existing run \u2014 following it:";p(`${E} ${an(c.manifest.treeHash)} \xB7 run ${f} \xB7 ${se(c.files.length,"file")}`),m=y.reverify,g=y.created,g&&Pt(`started_by:${vn(u)?"hook":n||xr().harness!=="unknown"?"skill":"manual"}`,{token:a,apiUrl:i.baseUrl},{runId:f})}if(o.noWait){let y=!1;if(r!==void 0&&!m&&!g)for(let _=0;_<3&&!m;_++)try{m=(await v(`/api/v1/red-team/runs/${f}`,{token:a,...i})).run.reverify;break}catch(E){if(!ie(E)||_===2){y=!0;break}await Mt(Ds*(_+1))}let k={ok:!0,runId:f,runUrl:rd(f),treeHash:c.manifest.treeHash,created:g,...m?{reverify:m}:{},next:`${od(f)}${y?" What this re-check carried could not be read just now; the document from `canary run wait` will say.":""}`};console.log(n?JSON.stringify(k):`Run ${f} is under way: ${k.runUrl}
78
- ${k.next}`);return}let w;try{w=await to(f,a,{...i,onProgress:p})}catch(y){if(y instanceof ge)return s(y.code,y.message,y.fix,2,{runId:f});if(y instanceof $){let k=y.status===401||y.status===403;return s("api_error",`${y.message} \u2014 run ${f} may still be running`,y.fix??(k?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:f,httpStatus:y.status})}throw y}let x={...no(w.run,c.manifest.treeHash,w.findings,m),source:c.manifest,repositoryId:d.repositoryId};console.log(n?JSON.stringify(x):ro(x)),process.exitCode=x.exitCode}function Ws(t){t.command("verify").description("Pressure-test your local change set with Canary (no commit or PR needed)").option("--brief <text>","what the change intends and must not break (text, @file, or - for stdin)").option("--failed <runId>","re-check only the failed checks of an earlier run, against your current (fixed) code").option("--json","output one JSON document").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","compare directly with a local commit (use HEAD for worktree changes only)").option("--no-wait","start the run and return its id at once; collect it later with `canary run wait <runId>`").action(async e=>{try{H()&&await(await Promise.resolve().then(()=>(Be(),Bs))).installByDefault({json:e.json===!0}),await gd(e.dir??process.cwd(),e.brief,e.json===!0,e.failed,{baseRef:e.base,noWait:e.wait===!1})}catch(n){let r=hd(n);if(r){I(e.json===!0,"home_not_writable",r.message,r.fix,2),eo("exit2:home_not_writable");return}I(e.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),eo("exit2:internal_error")}})}var Qr,nd,Hs,Zr,ge,b,We,rd,od,Mt,Fs,Ds,Us,Gs,jt,fd,pd,se,lt=J(()=>{"use strict";B();Ie();j();vi();yn();X();ct();Cn();qr();Xr();Xe();Qr=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,nd=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Hs=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,Zr=new Set(["completed","failed","cancelled"]),ge=class extends Error{constructor(n,r,o){super(r);this.code=n;this.fix=o;this.name="VerifyError"}},b=t=>(t??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g," ").trim(),We=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,rd=t=>`${ke().replace(/\/+$/,"")}/runs/${t}`,od=t=>`Collect the result with \`canary run wait ${t}\` (it returns when the run has finished; run it in the background where your shell allows).`,Mt=t=>new Promise(e=>setTimeout(e,t)),Fs=3,Ds=1e3;Us=t=>t?t.startLine?`${t.file}:${t.startLine}`:t.file:null;Gs={P0:0,P1:1,P2:2},jt={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"};fd={fail:"\u2717",blocked:"\u23F8"},pd={fail:"",blocked:" (could not be verified)"},se=(t,e)=>`${t} ${e}${t===1?"":"s"}`});var Bs={};mc(Bs,{hooksStatus:()=>Ht,installByDefault:()=>Ft,pendingPushCheck:()=>so,registerHooks:()=>ao,runHooksInstall:()=>Ys,runHooksUninstall:()=>Ks,statusLines:()=>En});function io(t,e=[]){try{z(n=>({...n,hooks:{state:t,at:new Date().toISOString(),...e.length?{refused:e}:{}}}))}catch{}}function md(t){return[oo,"It is a hook in the agent's own settings, which the agent runs. `canary hooks install` adds:","",...t.flatMap(e=>[` ${e.file}`,` ${e.summary}`,...e.snippet.split(`
79
- `).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${Vs}`].join(`
80
- `)}function qs(t){for(let e of t)e.result==="refused"?console.log(`\u2717 ${e.file} was left alone: ${e.detail}. To do it by hand:
81
- ${e.snippet}`):console.log(`${e.result==="unchanged"?"\xB7":"\u2713"} ${e.file}: ${e.result==="written"?"added":e.result==="removed"?"removed":"nothing to change"}${e.detail?`; ${e.detail}`:""}`)}function yd(t,e){for(let n of e)n.afterInstall&&t.some(r=>r.harness===n.id&&r.result==="written")&&console.log(`${n.label}: ${n.afterInstall}`);sn("canary")||console.log("Note: `canary` is not on PATH in this shell. The agent's harness must be able to find it, or the hook does nothing."),t.some(n=>n.result==="written")&&He()==="off"&&console.log("The check itself is switched off (`canary gate on` turns it on).")}function wd(t,e){return e?.length?{targets:t.filter(n=>e.includes(n.id)&&n.detected()),unknown:e.filter(n=>!t.some(r=>r.id===n&&r.detected()))}:{targets:t.filter(n=>n.byDefault&&n.detected()),unknown:[]}}async function Ys(t){let e=t.targets??_t(),{targets:n,unknown:r}=wd(e,t.harnesses),o=n.flatMap(s=>s.plan());if(r.length)return I(t.json,"harness_not_found",`not found on this machine: ${r.join(", ")}`,`known: ${e.map(s=>s.id).join(", ")}; one counts as found once its settings folder exists`,3);if(!n.length){let s=e.filter(a=>!a.byDefault&&a.detected()).map(a=>`\`canary hooks install --harness ${a.id}\` registers ${a.label}, which is not covered by default yet.`);t.json?console.log(JSON.stringify({ok:!0,installed:[],note:"no coding agent to register by default"})):console.log([`No coding agent to register was found on this machine (looked for ${e.filter(a=>a.byDefault).map(a=>a.label).join(", ")}).`,...s].join(`
82
- `));return}if(t.plan){console.log(t.json?JSON.stringify({ok:!0,plan:o}):md(o));return}let i=n.flatMap(s=>s.install());i.some(s=>s.result!=="refused")&&io("installed"),t.json?console.log(JSON.stringify({ok:!i.some(s=>s.result==="refused"),outcomes:i,canaryOnPath:sn("canary"),mode:He(),notes:n.filter(s=>s.afterInstall&&i.some(a=>a.harness===s.id&&a.result==="written")).map(s=>`${s.label}: ${s.afterInstall}`)})):(qs(i),yd(i,n)),i.some(s=>s.result==="refused")&&(process.exitCode=2)}function Ks(t){let e=(t.targets??_t()).flatMap(n=>n.uninstall());io("removed"),t.json?console.log(JSON.stringify({ok:!e.some(n=>n.result==="refused"),outcomes:e})):qs(e),e.some(n=>n.result==="refused")&&(process.exitCode=2)}function Ht(t=_t()){return{mode:He(),registration:T().hooks?.state??null,canaryOnPath:sn("canary"),harnesses:t.map(e=>({harness:e.id,label:e.label,detected:e.detected(),items:e.status()}))}}function so(t){try{return He()==="off"?[]:Ht(t).harnesses.flatMap(e=>e.items.filter(n=>n.state==="untrusted"&&n.pending).map(n=>({harness:e.harness,label:e.label,...n.pending})))}catch{return[]}}function En(t){let e=[];for(let n of t.harnesses){if(!n.detected&&n.items.every(r=>r.state==="missing")){e.push(`${n.label}: not found on this machine`);continue}for(let r of n.items)e.push(`${n.label}: ${r.state==="registered"?"registered":r.state==="untrusted"?"registered, not yet trusted":r.state==="missing"?"not registered":r.state} (${r.file})${r.detail?`: ${r.detail}`:""}`)}return t.harnesses.some(n=>n.items.some(r=>r.state!=="missing"))&&!t.canaryOnPath&&e.push("`canary` is not on PATH in this shell; a harness that cannot find it runs no check."),t.harnesses.some(n=>n.items.some(r=>r.state!=="missing"))&&e.push("Switch the check off: `canary gate off`. Take it out: `canary hooks uninstall` (before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)."),e}async function Ft(t){try{if(process.env.CI||!t.targets&&process.env.NODE_TEST_CONTEXT)return;let e=T();if(e.agentSkills===!1||e.hooks?.state==="removed")return;let n=new Set(e.hooks?.refused??[]);if(e.hooks?.state==="installed"&&!n.size)return;let r=(t.targets??_t()).filter(c=>c.byDefault&&c.detected());if(!r.length)return;let o=r.flatMap(c=>c.install()),i=o.filter(c=>c.result==="written"),s=o.filter(c=>c.result==="refused"&&!n.has(c.file)),a=o.filter(c=>c.result==="refused").map(c=>c.file);if(o.some(c=>c.result!=="refused")||e.hooks?.state==="installed")io("installed",a);else if(a.length)try{z(c=>({...c,hooks:{...c.hooks,refused:a}}))}catch{}let l=r.filter(c=>c.afterInstall&&i.some(u=>u.harness===c.id)).map(c=>`${c.label}: ${c.afterInstall}`);if(t.json){(i.length||s.length)&&console.error(JSON.stringify({notice:"push_check",added:i.map(c=>c.file),leftAlone:s.map(c=>({file:c.file,why:c.detail})),message:oo,off:"canary gate off",remove:"canary hooks uninstall",notes:l}));return}if(i.length){let c=r.filter(u=>i.some(d=>d.harness===u.id)).map(u=>u.label).join(" and ");console.error(`
83
- Canary added its push check to ${c} (${i.map(u=>u.file).join(", ")}).
84
- ${oo}
85
- ${Vs}`);for(let u of l)console.error(u)}for(let c of s)console.error(`Canary left ${c.file} alone (${c.detail}): not added there: ${c.summary}. \`canary hooks install --plan\` shows what to add by hand.`)}catch{}}function ao(t){let e=t.command("hooks").description("The push check in your coding agents' settings: install, uninstall, status. Login adds it; `canary hooks uninstall` takes it out, also as `npx -y @runcanary/cli hooks uninstall` once the CLI is gone");e.command("install").description("Add the push check to your coding agents' settings (login does this by default)").option("--plan","show exactly what would be added, and add nothing").option("--harness <id...>","register only these (claude, codex, cursor); default: every one found that is covered by default").option("--json","print one JSON document").action(async n=>{try{await Ys({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(r){I(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),e.command("uninstall").description("Remove exactly what `canary hooks install` added (do this before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)").option("--json","print one JSON document").action(n=>{try{Ks({json:n.json===!0})}catch(r){I(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}),e.command("status").description("Show where the check is registered, and anything that stops it from running").option("--json","print one JSON document").action(n=>{let r=Ht();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(`The push check is ${r.mode}.`);for(let o of En(r))console.log(o)}})}var oo,Vs,Be=J(()=>{"use strict";j();nn();_i();lt();oo="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.",Vs="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`."});var Ho=wc(jo(),1),{program:Op,createCommand:Ep,createArgument:Ap,createOption:Tp,CommanderError:Np,InvalidArgumentError:Pp,InvalidOptionArgumentError:Lp,Command:Fo,Argument:Mp,Option:jp,Help:Hp}=Ho.default;import{createHash as Rd,randomBytes as aa}from"node:crypto";import{spawn as Od}from"node:child_process";import{createServer as Ed}from"node:http";j();import{existsSync as kr,lstatSync as Zc,mkdirSync as el,readFileSync as ni,rmSync as tl,rmdirSync as nl,writeFileSync as rl}from"node:fs";import{homedir as br}from"node:os";import{join as Me}from"node:path";var Ke="Onboard this repository to Canary.",Zt="Verify my changes with Canary.";var wr=`---
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 ol="canary",il="canary-setup";function sl(t){let e=Me(t,"skills",il),n=Me(e,"SKILL.md");if(en(e)||en(n)||!kr(n))return;let r;try{r=ni(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{tl(n,{force:!1})}catch{return}try{nl(e)}catch{}}}function en(t){try{return Zc(t).isSymbolicLink()}catch{return!1}}function al(){return[Me(br(),".claude"),Me(br(),".agents"),Me(br(),".codex")].filter(t=>kr(t))}function tn(){let t={installed:[],refreshed:[],current:[],skipped:[]};if(T().agentSkills===!1)return t;for(let e of al()){sl(e);let n=Me(e,"skills",ol),r=Me(n,"SKILL.md");try{if(en(n)||en(r)){t.skipped.push(r);continue}let o=kr(r)?ni(r,"utf8"):null;if(o===wr){t.current.push(r);continue}el(n,{recursive:!0}),rl(r,wr),(o===null?t.installed:t.refreshed).push(r)}catch{}}return t}var ri=`Open your coding agent inside the repo you want to onboard and say: "${Ke}"`;B();Xe();j();Be();X();B();yn();function zs(t){try{return new URL(t).href.replace(/\/+$/,"")}catch{return}}var co=Ji;async function Xs(t,e,n,r){let o=await v("/api/v1/cli/workspaces",{token:t.token,baseUrl:r,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(o?.workspaces)||o.workspaces.some(d=>!d||typeof d.id!="string"||!d.id||typeof d.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let i=[...new Map(o.workspaces.map(({id:d,name:h})=>[d,{id:d,name:h}])).values()],a=e.user?.id===t.user.id&&zs(n)===zs(r)?i.find(d=>d.id===e.team?.id):void 0,l=i.length===1?i[0]:void 0,c=a??l??i.find(d=>d.id===t.team.id)??i[0]??{id:"",name:"No workspace selected"},u=co();return{workspace:c,workspaces:i,source:a?"saved in CLI":l?"only workspace":"active on platform",selectionRequired:!a&&!l,...u?{repository:u}:{},...i.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function An(t,e,n,r=AbortSignal.timeout(3e3)){try{let o=await mn({apiUrl:t.apiUrl,userId:t.userId,workspaceId:n},t.token,r);return o?{state:o.state}:void 0}catch{return}}function Tn(t,e){let n=/^\d+$/.test(e)?Number(e)-1:-1,r=n>=0?t.workspaces.filter((o,i)=>i===n):t.workspaces.filter(o=>o.id===e||o.name.toLowerCase()===e.toLowerCase());if(r.length!==1)throw new Error(r.length?"Workspace name is ambiguous. Use its ID.":"Workspace not found. Run canary workspace list.");return r[0]}import{stripVTControlCharacters as Qs}from"node:util";var D="\x1B[";function Ut(t,e,n){let r={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[e];return n?`${D}${r}m${t}${D}0m`:t}function P(t){return Qs(t).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var lo=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Zs(t){if(/^[\p{Mark}\u200d\ufe0f]+$/u.test(t))return 0;if(new RegExp("\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\u20e3","u").test(t))return 2;let e=t.codePointAt(0);return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072)?2:1}function Dt(t){return[...lo.segment(Qs(t))].reduce((e,n)=>e+Zs(n.segment),0)}function Nn(t,e){let n=0,r="";for(let o of t.split(/(\x1b\[[0-9;]*m)/)){if(o.startsWith(D)){r+=o;continue}for(let{segment:i}of lo.segment(o))n+=Zs(i),n<=e&&(r+=i)}return r}function Ee(t,e){let n=[],r="";for(let o of P(t).split(/\s+/)){r&&Dt(r+" "+o)>e&&(n.push(r),r="");for(let{segment:i}of lo.segment((r?" ":"")+o))Dt(r+i)>e&&r&&(n.push(r),r=""),r+=i}return r&&n.push(r),n}function ut(t){let e=[];return{render(n){if(n.join(`
125
- `)===e.join(`
126
- `))return;let r=Math.max(2,t.columns||80),o=Math.max(3,t.rows||24),i=Math.min(o-1,e.reduce((s,a)=>s+Math.max(1,Math.ceil(Dt(a)/r)),0));t.write((i?`\r${D}${i}A`:"")+`${D}0J`+(n.length?n.join(`\r
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
- `:"")),e=n}}}function ea(t,e,n){return t?[JSON.stringify({authorizeUrl:n})]:[e?"Opening your browser to authorize the Canary CLI...":"Open this URL in your browser to authorize the Canary CLI:",(e?`If it doesn't open, visit:
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 p=()=>h(130),f=()=>h(143),m=setInterval(c,80);return m.unref(),e.on("resize",c),process.once("SIGINT",p),process.once("SIGTERM",f),process.once("exit",u),e.write(`${Jt}?25l`),c(),{saving(){s("saving"),c()},celebrate(){return s("success"),c(),new Promise(g=>setTimeout(g,ra*1e3+100))},succeed(g,w){s("success"),c(),d(),process.stdout.write(` Account ${na(g)}
132
- Workspace ${na(w)}
133
-
134
- `)},fail(){s("failed"),c(),d()},clear(){a.render([]),d()},stop:d}}import{spawn as _d}from"node:child_process";import{createInterface as vd,emitKeypressEvents as Cd}from"node:readline";function uo(t){return t?t.installed.length+t.refreshed.length+t.current.length?`Installed \xB7 available to your coding agent${t.skipped.length?" (some locations skipped)":""}`:"Not installed \xB7 no writable agent location found":"Skipped \xB7 --no-agent-skills"}function fo(t){return t.workspaces.length>1}function Wt(t){return t.repositoryState==="ready"?Zt:Ke}async function ia(t){let e=process.stdin,n=process.stderr,r=e.readableFlowing===!0;n.write(`Choose a workspace:
135
- `),t.workspaces.forEach((s,a)=>{let l=t.workspaces.some(c=>c.id!==s.id&&c.name===s.name);n.write(` ${a+1}. ${P(s.name)}${l?` (${P(s.id)})`:""}
136
- `)});let o=vd({input:e,output:n,terminal:!1}),i=()=>o.close();process.once("SIGINT",i);try{n.write("Workspace (number or name): ");for await(let s of o)try{return Tn(t,s.trim())}catch(a){n.write(`${a instanceof Error?a.message:"Choose a listed workspace."}
137
- Workspace (number or name): `)}}finally{process.off("SIGINT",i),o.close(),r||e.pause()}}function $d(t,e,n,r){let{context:o}=t,i=Math.max(1,e-5),s=(h,p="text")=>Ut(P(h),p,r),a=(h="",p="text")=>` ${s(h,p)}`,l=[];if(e>=90&&n>=36&&!t.picker){let h={1:s("CANARY","gold"),3:s("You're connected."),5:s("Let's give your agent the next step.","muted")};l.push("",...dt[8].map((p,f)=>` ${s(p,"green")} ${h[f]??""}`),"")}else l.push(a("CANARY","gold"),a("You're connected."),"");if(l.push(a(`Account ${P(t.email)}`)),l.push(a(`Workspace ${o.selectionRequired?"Choose below":P(o.workspace.name)}`)),l.push(a(` ${o.source}${!t.done&&fo(o)?" \xB7 [w] Change":""}`,"muted")),t.picker){l.push("",a("Choose a workspace","gold"));let h=Math.max(1,Math.min(8,n-l.length-5)),p=Math.max(0,Math.min(t.highlighted-Math.floor(h/2),o.workspaces.length-h));for(let f=p;f<Math.min(p+h,o.workspaces.length);f++){let m=o.workspaces[f],w=o.workspaces.some(y=>y.id!==m.id&&y.name===m.name)?` \xB7 ${P(m.id)}`:"",x=!o.selectionRequired&&m.id===o.workspace.id?" \xB7 current":"";l.push(a(`${f===t.highlighted?"\u203A":" "} ${f+1}. ${P(m.name)}${w}${x}`,f===t.highlighted?"gold":"text"))}l.push(a(`${t.highlighted+1} of ${o.workspaces.length}`,"muted"),"",a("\u2191 \u2193 choose \xB7 number highlight \xB7 Enter select \xB7 Esc back","muted"))}else{let h=o.repositoryState==="ready",p=o.repository?P(o.repository):void 0;p?h?l.push(a(`Repository ${p} \xB7 your setup is ready`,"green")):o.repositoryState==="setup_required"?l.push(a(`Repository ${p} \xB7 not set up yet`)):l.push(a(`Repository ${p} \xB7 detected locally`)):l.push(a("Repository Open a local Git repository to continue")),l.push(a(`Agent skill ${uo(t.skill)}`,t.skill&&uo(t.skill).startsWith("Installed")?"green":"muted")),o.workspaceNotice&&l.push(...Ee(o.workspaceNotice,i).map(m=>a(m,"muted"))),l.push("",a("\u2500".repeat(Math.min(68,i)),"muted"),a(h?"NEXT \xB7 VERIFY A CHANGE":"NEXT \xB7 SET UP THIS REPOSITORY","gold"));let f=!!t.skill&&uo(t.skill).startsWith("Installed");l.push(a(f?"Open your coding agent in this repository and say:":"In your coding agent, run canary skills, then say:","muted")),l.push(...Ee(Wt(o),i-2).map(m=>a(`\u2502 ${m}`))),t.done||l.push("",a(`${fo(o)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),t.message&&l.push(...Ee(t.message,i).map(m=>a(m,"muted"))),l.push("",a(h?"Signed in \xB7 Ready to verify":o.repositoryState==="setup_required"?"Signed in \xB7 This repo isn't set up yet":"Signed in \xB7 Couldn't check this repo's setup",h?"green":"muted"))}let u=Math.max(1,n-2);return(u<=3?l.slice(0,u):l.length>u?[...l.slice(0,Math.max(0,u-3)),...l.slice(-3)]:l).map(h=>Nn(h,Math.max(1,e-1)))}async function Id(t,e){let n=process.platform==="darwin"?[["pbcopy"]]:process.platform==="win32"?[["clip.exe"]]:[["wl-copy"],["xclip","-selection","clipboard"],["xsel","--clipboard","--input"]];for(let[r,...o]of n){if(e.aborted)return!1;if(await new Promise(s=>{let a=_d(r,o,{stdio:["pipe","ignore","ignore"],signal:e}),l=setTimeout(()=>{a.kill(),s(!1)},1e3),c=u=>{clearTimeout(l),s(u)};a.on("error",()=>c(!1)),a.on("close",u=>c(u===0)),a.stdin.on("error",()=>{}),a.stdin.end(t)}))return!0}return!1}async function sa(t){let e=process.stdin,n=process.stderr,r={...t,picker:t.context.workspaces.length>1,highlighted:Math.max(0,t.context.workspaces.findIndex(p=>p.id===t.context.workspace.id))},o=!process.env.NO_COLOR,i=ut(n),s=()=>i.render($d(r,n.columns||80,n.rows||24,o));if(!e.isTTY||!n.isTTY||(n.rows||24)<16||(n.columns||80)<30){r.done=!0,s(),n.write(`
138
- ${Wt(r.context)}
139
- `);return}let a=e.isRaw,l=e.readableFlowing===!0,c=new AbortController,u=!1,d,h=0;await new Promise(p=>{function f(){if(u)return;u=!0,c.abort(),e.off("keypress",x),e.off("end",f),n.off("resize",w),process.off("SIGINT",f),process.off("SIGTERM",g),process.off("exit",m),r.picker=!1,r.done=!0,r.message=void 0;let y=t.sessionCurrent();y?s():i.render(["CLI session changed in another process. Run canary whoami to check the active account."]),m(),y&&!r.context.selectionRequired&&n.write(`
140
- ${Wt(r.context)}
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}),Ud(a,o)}catch(l){throw Gd(a,{force:!0}),l}return s})}ct();lt();var qd=500,jn={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 ya(t){return t==="on"?"The push check is on: an agent's push or pull request is held until its exact code has a Canary run with nothing open, or a recorded skip.":"The push check is off: agents push and open pull requests without Canary being asked."}function Yd(t,e){try{if(!di(t))return I(e,"config_unreadable","~/.canary/config.json exists but cannot be read, so the setting was not saved","repair or remove the file, then run the command again",2)}catch(n){if(n instanceof Le)return I(e,"config_busy",n.message,void 0,2);throw n}console.log(e?JSON.stringify({ok:!0,mode:t}):ya(t))}async function Kd(t,e,n){let r=(e??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,qd);if(!r)return I(n,"reason_required","a skip needs a reason",'canary skip --reason "<why this change needs no run>"',3);$t(t);let o=await Bt(t);if(!o.ok){let[c,u]=jn[o.cause]??jn.context_error;return I(n,o.cause,c,u,3)}let i;try{i=await _n(t)}catch(c){if(c instanceof re)return I(n,c.code,c.message,c.fix,3);throw c}let s=at(i.branch),a;try{a=ma(o.context.repository,i.treeHash,{reason:r,...s?{branch:s}:{}})}catch(c){if(c instanceof Le)return I(n,"config_busy",c.message,void 0,2);throw c}vn(o.context.repository);let l=await Ln(o.context,{treeHash:i.treeHash,branch:s},{timeoutMs:3e3});await Pt(l.ok?`gate_skip:${l.state}:${l.lineageHasRuns?"prior":"first"}`:"gate_skip:unknown:unknown",o.context),console.log(n?JSON.stringify({ok:!0,treeHash:i.treeHash,...s?{branch:s}:{},reason:a.reason,at:a.at}):`Skipped tree ${i.treeHash.slice(0,12)}${s?` on ${b(s)}`:""}: ${b(a.reason)}
144
- This covers exactly the code on disk now; any further edit is a new tree.`)}async function zd(t,e){$t(t);let n=await Bt(t);if(!n.ok){let[o,i]=jn[n.cause]??jn.context_error;return I(e,n.cause,o,i,3)}let r=Object.entries(Mn(n.context.repository).skips).map(([o,i])=>({treeHash:o,...i})).sort((o,i)=>i.at.localeCompare(o.at));if(e)return console.log(JSON.stringify({ok:!0,skips:r}));if(!r.length)return console.log("No skips recorded for this repository.");for(let o of r)console.log(`${o.treeHash.slice(0,12)} ${o.at.slice(0,16).replace("T"," ")} ${o.branch?b(o.branch):"(detached)"} ${b(o.reason)}`)}function wa(t){let e=t.command("gate").description("The check on an agent's push or pull request: on, off, status");for(let n of["on","off"])e.command(n).description(n==="on"?"Hold an agent's unverified push or pull request (the default)":"Never hold a push or pull request").option("--json","print one JSON document").action(r=>Yd(n,r.json===!0));e.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=Ht();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(ya(r.mode));for(let o of En(r))console.log(o)}}),t.command("skip").description("Let this exact code be pushed without a Canary run, with a reason").option("--reason <text>","why this change needs no run").option("--list","show the skips recorded for this repository").option("--dir <path>","repo directory (default: current directory)").option("--json","print one JSON document").action(async n=>{let r=n.json===!0;try{n.list?await zd(n.dir??process.cwd(),r):await Kd(n.dir??process.cwd(),n.reason,r)}catch(o){I(r,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}})}Be();Ie();var Xd={[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 ba(t){t.command("identity").description("Show what this CLI sends about where it runs (ids and hashes only; no request is made)").option("--json","print the headers as JSON").action(e=>{let n=$e();if(e.json===!0)return void console.log(JSON.stringify(n));for(let[r,o]of Object.entries(n)){let i=r===q.harness&&o==="unknown"?"(no running coding-agent session detected)":Xd[r]??"";console.log(`${r.padEnd(18)} ${o}${i?` ${i}`:""}`)}})}j();nn();Ie();ct();import{appendFileSync as bf,existsSync as kf}from"node:fs";import{join as Ta}from"node:path";var Ae=(t,e)=>({decision:"allow",cause:t,...e?{message:e}:{}}),po=t=>t.replace(/[\x00-\x1f\x7f]+/g,"?");function Hn(t){if(t.mode==="off")return Ae("mode_off");if(!t.trigger)return Ae("not_a_trigger");if(t.trigger.dir===null)return Ae("unknown_directory");if(!t.context)return null;if(!t.context.ok)return Ae(t.context.cause);if(t.trigger.editsFirst)return{decision:"deny",cause:"edits_first",message:ef(t.trigger)};if(!t.tree)return null;if(!t.tree.ok)return Ae("hash_failed",ka(`this checkout could not be read (${t.tree.detail})`));if(t.skip===void 0)return null;if(t.skip)return Ae("skipped",`Canary: this exact code goes out on a recorded skip, not a run (${po(t.skip.reason)}). Tell the user it was published without a Canary run, and why.`);if(!t.lookup)return null;if(!t.lookup.ok)return Ae(t.lookup.cause,ka(t.lookup.detail));let{state:e}=t.lookup;return e==="verified"?t.leftOut?Ae("verified",t.leftOut.length?Qd(t.leftOut):void 0):null:e==="none"&&t.lookup.newestRun?.treeHash&&t.since===void 0?null:{decision:"deny",cause:e,message:tf(t.trigger,t.tree,t.lookup,t.since)}}var ka=t=>`Canary did not check this: ${t}. Nothing was blocked.`;function Qd(t){let e=t.slice(0,8).map(po).join(", "),n=t.length;return`Canary: ${n} ${n===1?"file was":"files were"} present when this tree was verified but ${n===1?"is":"are"} not committed, so ${n===1?"it is":"they are"} not in what is being published: ${e}${n>8?`, and ${n-8} more`:""}.`}function Zd(t,e){let n=`Newest run on this branch: ${t.runId.slice(0,8)} (${t.state})`;if(e&&e.total>0){let r=e.total>e.files.length?` and ${e.total-e.files.length} more`:"";return`${n}. Changed since it: ${e.total} file${e.total===1?"":"s"}: ${e.files.map(po).join(", ")}${r}.`}return t.headSha?`${n}, taken from commit ${t.headSha.slice(0,7)}; \`git diff ${t.headSha.slice(0,7)}..HEAD --stat\` shows what was committed since.`:`${n}.`}function ef(t){let e=t.action==="push"?"push":"pull request",n=t.action==="push"?"`git push` as its own command (`git add \u2026 && git commit \u2026 && git push` is fine: a commit changes no file)":"`gh pr create` as its own command";return[`Canary held this ${e}: this command changes files before it publishes, so the code it would publish is not the code on disk now, which is what the check reads.`,`Make the edits first, then run ${n}. The check then reads the code being published.`].join(`
145
-
146
- `)}function tf(t,e,n,r){let o=t.action==="push"?"push":"pull request",i="Two ways forward. This is your decision, not a question for the user: choose by whether what changed since the last verified code can alter behaviour, and by what the user asked for.",s=`tree ${e.treeHash.slice(0,12)}${e.branch?` on ${e.branch}`:""}`,a=n.runId?`run ${n.runId}${n.runUrl?` (${n.runUrl})`:""}`:"",l=`Skip it: \`canary skip --reason "<why this change needs no run>"\`, then repeat the ${o}.`,c=[];if(n.state==="running")c.push(`Canary held this ${o}: ${a} is still checking this exact code (${s}).`,"",i,`1. Wait for it: \`canary run wait ${n.runId}\` (it returns when the run has finished; run it as a background shell command where you can), then repeat the ${o}.`,`2. ${l}`);else if(n.state==="open"){let u=n.open??0;c.push(`Canary held this ${o}: ${a} found ${u} finding${u===1?"":"s"} still open on this exact code (${s}).`,"",i,`1. Close them: fix the code and re-check with \`canary verify --failed ${n.runId}\`, or report a finding you will not fix with \`canary check ${n.runId} <checkRunId> --disputed "<why>"\` (or \`--skipped\`). Repeat the ${o} once none is open.`,`2. ${l}`)}else c.push(n.state==="failed"?`Canary held this ${o}: ${a} did not finish or could not check anything, so this exact code (${s}) is unverified.`:`Canary held this ${o}: this exact code (${s}) has no verification run of yours; ${n.lineageHasRuns?`an earlier tree ${e.branch?"on this branch":"here"} has one`:`nothing ${e.branch?"on this branch":"here"} has been verified yet`}.`,...n.newestRun?[Zd(n.newestRun,r)]:[],"",i,`1. Verify it: \`canary verify\`, wait for the run, close what it finds, then repeat the ${o}.`,`2. ${l}`);return c.push("","`canary skill gate` says when each one fits."),c.join(`
147
- `)}var Sa=["claude","codex","cursor"];function xa(t,e=0,n=[]){if(typeof t=="string")t&&n.push(t);else if(e<3&&t&&typeof t=="object")for(let r of Object.values(t))xa(r,e+1,n);return n}var Fn=t=>typeof t=="string"&&t?t:void 0,nf=new Set(["Bash","PowerShell","Monitor"]);function _a(t,e,n=process.env,r=process.platform){if(!e||typeof e!="object"||Array.isArray(e))return null;let o=e;if(t==="cursor"){let l=Array.isArray(o.workspace_roots)?o.workspace_roots:[],c=Fn(o.cwd)??Fn(l[0])??Fn(n.CURSOR_PROJECT_DIR)??process.cwd();return o.hook_event_name==="beforeShellExecution"&&typeof o.command=="string"?{kind:"shell",command:o.command,cwd:c,shell:r==="win32"?"powershell":"posix"}:o.hook_event_name==="beforeMCPExecution"&&typeof o.tool_name=="string"?{kind:"tool",toolName:o.tool_name,cwd:c}:null}if(o.hook_event_name!=="PreToolUse"||typeof o.tool_name!="string")return null;let i=Fn(o.cwd)??process.cwd(),s=o.tool_input&&typeof o.tool_input=="object"?o.tool_input:{};if(nf.has(o.tool_name)&&typeof s.command=="string")return{kind:"shell",command:s.command,cwd:i,shell:o.tool_name==="PowerShell"?"powershell":"posix"};let a=t==="codex"&&o.tool_name==="exec"?xa(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 va(t,e){if(t==="cursor"){if(e.decision!=="deny")return"";let n=e.message??"Canary held this call.";return JSON.stringify({permission:"deny",user_message:n,agent_message:n})}return e.decision==="deny"?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.message??"Canary held this call."}}):e.message?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e.message}}):""}Cn();import{execFile as rf}from"node:child_process";function Ca(t,e){let n={...Object.fromEntries(Object.entries(process.env).filter(([r])=>!r.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(r))),GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"};return new Promise(r=>{rf("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","status","--porcelain=v1","-z"],{cwd:t,env:n,signal:e,timeout:3e3,maxBuffer:16*1024*1024,encoding:"buffer"},(o,i)=>{if(o)return r([]);let s=i.toString("utf8").split("\0"),a=[];for(let l=0;l<s.length;l++){let c=s[l];c.length<4||(a.push(c.slice(3)),(c[0]==="R"||c[0]==="C")&&l++)}r(a)})})}qr();import{homedir as of}from"node:os";import{basename as sf,isAbsolute as af,resolve as cf}from"node:path";var lf=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),uf=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,$a=t=>t.replace(/\\(.)/g,(e,n)=>n==="n"?`
148
- `:n==="t"?" ":n);function Ea(t,e){for(let n of t)for(let r of n.matchAll(uf)){let o=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(s=>$a(s[1]??s[2]??"")).join(" "):$a(r[1]??r[2]??r[3]??""),i=mo(o,e);if(i)return i}return null}function Aa(t,e){let n=!t.includes("__");if(!n&&!t.startsWith("mcp__"))return null;let r=lf.get(n?t:t.slice(t.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:e}:null}function df(t){let e=[];for(let n=0;n<t.length;n++){if(t[n]==="\\"){n++;continue}let r=t[n]==="$"&&t[n+1]==="("?2:t[n]==="`"?1:0;if(!r)continue;let o=Un(t,n+r,r===2?")":"`");e.push(o.tokens),n=o.end-1}return e}var Dn=!1;function Un(t,e,n){let r=[],o=[],i="",s=!1,a=!1,l=!0,c=e,u=0,d=()=>{s&&r.push({word:i,quoted:a,bare:l}),i="",s=!1,a=!1,l=!0},h=f=>{d(),r.push({op:f})},p=(f,m)=>{let g=Un(t,f,m);return r.push({sub:g.tokens}),i+="$()",s=!0,g.end};for(;c<t.length;){let f=t[c],m=t[c+1];if(n==="`"&&f==="`")return d(),{tokens:r,end:c+1};if(n===")"&&f===")"&&u===0)return d(),{tokens:r,end:c+1};if(f==="\\"&&!Dn){m===`
149
- `||(i+=m??"",s=!0),c+=2;continue}if(f==="'"){s||(l=!1);let g=t.indexOf("'",c+1);i+=t.slice(c+1,g<0?void 0:g),s=!0,a=!0,c=g<0?t.length:g+1;continue}if(f==='"'){for(s||(l=!1),s=!0,a=!0,c++;c<t.length&&t[c]!=='"';)t[c]==="\\"&&!Dn&&c+1<t.length&&/[$`"\\\n]/.test(t[c+1])?(i+=t[c+1],c+=2):t[c]==="$"&&t[c+1]==="("?c=p(c+2,")"):t[c]==="`"?c=p(c+1,"`"):(i+=t[c],c++);c++;continue}if(f==="#"&&!s){for(;c<t.length&&t[c]!==`
150
- `;)c++;continue}if(f==="<"&&m==="<"&&t[c+2]!=="<"){let g=/^<<(-?)[ \t]*(?:'([^']*)'|"([^"]*)"|\\?([^\s;&|<>()]+))/.exec(t.slice(c));if(g){d(),o.push({end:g[2]??g[3]??g[4]??"",stripTabs:g[1]==="-",literal:g[4]===void 0||g[0].includes("\\")}),c+=g[0].length;continue}}if(f===`
151
- `){h(`
152
- `),c++;for(let g of o.splice(0))for(;;){let w=t.indexOf(`
153
- `,c),x=t.slice(c,w<0?void 0:w);if(c=w<0?t.length:w+1,(g.stripTabs?x.replace(/^\t+/,""):x)===g.end||w<0)break;if(!g.literal)for(let y of df(x))r.push({sub:y})}continue}if(f===" "||f===" "||f==="\r"){d(),c++;continue}if(f===">"||f==="<"){let g=f===">";d(),c++;let w=!1;for(;c<t.length&&(t[c]===">"||t[c]==="&"||t[c]==="|");)t[c]==="&"&&(w=!0),c++;for(;c<t.length&&(t[c]===" "||t[c]===" ");)c++;let x=c;for(;c<t.length&&!/[\s;&|()<>`]/.test(t[c]);)c++;if(g&&!w){let y=t.slice(x,c);y&&r.push({write:y})}continue}if(f==="&"&&m===">"){d(),c++;continue}if((f==="&"||f==="|")&&m===f){h(f+f),c+=2;continue}if(f==="$"&&m==="("){c=p(c+2,")");continue}if(f==="`"){c=p(c+1,"`");continue}if(f==="("){u++,h(f),c++;continue}if(f===")"){u=Math.max(0,u-1),h(f),c++;continue}if(f===";"||f==="&"||f==="|"){h(f),c++;continue}if(/[0-9]/.test(f)&&!s&&/^[0-9]+[<>]/.test(t.slice(c))){c++;continue}i+=f,s=!0,c++}return d(),{tokens:r,end:t.length}}var ff=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),pf=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),Ia=t=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(t),Te=!1,hf=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),Ra=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),gf=new Set(["sh","bash","zsh","dash","ksh"]),Oa=6,mf=new Set(["-c","--exec-path","--namespace","--super-prefix","--config-env","--attr-source"]);function ho(t,e){if(e===null||/[$`*?[]/.test(t.word))return null;let n=t.bare&&(t.word==="~"||t.word.startsWith("~/"))?of()+t.word.slice(1):t.word;return t.bare&&n.startsWith("~")?null:af(n)?n:cf(e,n)}function yf(t,e){let n=e,r=0;for(;r<t.length;r++){let i=t[r].word;if(i==="-C"){n=t[r+1]?ho(t[r+1],n):null,r++;continue}if(i.startsWith("-C")&&i.length>2){n=ho({...t[r],word:i.slice(2)},n);continue}if(/^--(git-dir|work-tree)(=|$)/.test(i)){n=null,i.includes("=")||r++;continue}if(mf.has(i)){r++;continue}if(!i.startsWith("-"))break}if(t[r]?.word!=="push")return null;let o=[];for(let{word:i}of t.slice(r+1)){if(i==="--")break;if(i==="--dry-run"||i==="--help"||i==="-h"||/^-[a-zA-Z]*n[a-zA-Z]*$/.test(i)||i==="--delete"||/^-[a-zA-Z]*d[a-zA-Z]*$/.test(i))return null;i.startsWith("-")||o.push(i)}return o.length>1&&o.slice(1).every(i=>i.startsWith(":"))?null:{dir:n}}function wf(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n].word;if(r==="--help"||r==="-h"||r==="--dry-run")return!1;if(r==="-R"||r==="--repo"){n++;continue}r.startsWith("-")||e.push(r)}return e[0]==="pr"&&(e[1]==="create"||e[1]==="new")}function go(t,e,n){let r=e,o=[],i=!1,s=()=>{let a=o;o=[];let l=i;i=!1;let c=g=>(!g&&l&&(Te=!0),g),u=0,d=(g,w)=>g.bare&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(g.word)||!g.quoted&&(hf.has(g.word)||Ra.has(g.word)||!!w&&Ra.has(w.word)&&g.word.startsWith("-"));for(;u<a.length&&d(a[u],a[u-1]);)u++;let h=a[u];if(!h)return c(null);let p=sf(h.word.replace(/\\/g,"/")).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase(),f=a.slice(u+1);if(p==="cd"||p==="pushd")return r=f[0]&&!f[0].word.startsWith("-")?ho(f[0],r):null,c(null);let m=(g,w)=>({action:g,via:"shell",dir:w,...Te?{editsFirst:!0}:{}});if(p==="git"){let g=yf(f,r);if(g)return m("push",g.dir);let w=f.find(y=>!y.word.startsWith("-"))?.word,x=(w==="checkout"||w==="switch")&&f.some(y=>/^-(b|B|c|C|-orphan)$/.test(y.word));return w&&pf.has(w)&&!x&&(Te=!0),c(null)}if(p==="gh")return wf(f)?m("pr_create",r):c(null);if(p==="tee"?f.some(g=>!g.word.startsWith("-")&&!Ia(g.word))&&(Te=!0):(ff.has(p)||(p==="sed"||p==="perl")&&f.some(g=>/^-[a-zA-Z]*i/.test(g.word)))&&(Te=!0),(p==="npm"||p==="pnpm"||p==="yarn")&&f[0]?.word==="version"&&(Te=!0),n<Oa&&(gf.has(p)||p==="eval")){let g=p==="eval"?0:f.findIndex(x=>/^-[a-zA-Z]*c[a-zA-Z]*$/.test(x.word))+1,w=p==="eval"?f.map(x=>x.word).join(" "):g>0?f[g]?.word:void 0;if(w)return c(go(Un(w,0,null).tokens,r,n+1))}return c(null)};for(let a of t){if("word"in a){o.push(a);continue}if("write"in a){i=i||!Ia(a.write);continue}if("sub"in a){let c=n<Oa?go(a.sub,r,n+1):null;if(c)return c;continue}let l=s();if(l)return l}return s()}function mo(t,e,n={}){if(!/\bpush\b/.test(t)&&!/\bpr\b/.test(t))return null;Dn=n.shell==="powershell",Te=!1;try{return go(Un(t,0,null).tokens,e,0)}finally{Dn=!1,Te=!1}}var Sf=8e3,xf=64*1024*1024;async function _f(t,e={}){let n=t.kind==="shell"?mo(t.command,t.cwd,{shell:t.shell}):t.kind==="script"?Ea(t.texts,t.cwd):Aa(t.toolName,t.cwd);if(!n)return Hn({mode:"on",trigger:null});let r={mode:He(),trigger:n},o,i="",s,a=[],l=()=>Math.max(250,Math.min(ft,e.deadline?e.deadline-Date.now()-500:ft)),c=[async()=>{je({cwd:n.dir,agent:!0});let d=await Bt(n.dir,{signal:e.signal,timeoutMs:l()});d.ok?(o=d.context,e.seen&&(e.seen.context=o),r.context={ok:!0}):r.context=d},async()=>{try{let d=await _n(n.dir,{signal:e.signal});i=d.root,a=d.files,s={treeHash:d.treeHash,branch:at(d.branch)},r.tree={ok:!0,...s}}catch(d){if(e.signal?.aborted)throw d;r.tree={ok:!1,detail:d instanceof re?d.message:"the working tree could not be read"}}},async()=>{r.skip=ga(o.repository,s.treeHash)},async()=>{r.lookup=await Ln(o,s,{timeoutMs:l(),signal:e.signal})},async()=>{let d=r.lookup?.ok?r.lookup.newestRun:void 0;r.since=d?.treeHash&&o?xs(o.repository,d.treeHash,a):null},async()=>{r.leftOut=await Ca(i,e.signal)}],u=null;for(let d of c){if(u=Hn(r),u)break;await d()}return u??=Hn(r)??{decision:"allow",cause:"crash"},u.decision==="deny"&&o&&s&&gs(o.repository,s.treeHash),u}async function vf(t){let e=[],n=0;for await(let r of t){let o=typeof r=="string"?Buffer.from(r):r;if(n+=o.length,n>xf)throw new Error("event too large");e.push(o)}return JSON.parse(Buffer.concat(e).toString("utf8").replace(/^\uFEFF/,""))}var Cf={claude:"claude-code",codex:"codex",cursor:"cursor"};async function $f(t,e){je({harness:Cf[t]});let n=e.ceilingMs??Sf;Ko(250);let r=new AbortController,o,i=new Promise(u=>{o=setTimeout(()=>{r.abort(),u({decision:"allow",cause:"ceiling"})},n)}),s={},a=(async()=>{let u=await vf(e.stdin);try{kf(Ta(ee(),"hook-debug"))&&bf(Ta(ee(),"hook-events.log"),`${new Date().toISOString()} ${t} ${JSON.stringify(u)}
154
- `)}catch{}let d=_a(t,u);return d?_f(d,{signal:r.signal,deadline:Date.now()+n,seen:s}):{decision:"allow",cause:"not_a_trigger"}})().catch(()=>({decision:"allow",cause:r.signal.aborted?"ceiling":"crash"})),l=await Promise.race([a,i]);clearTimeout(o);let c=va(t,l);return c&&await e.write(c),l.cause!=="not_a_trigger"&&e.note(`canary hook: ${l.decision} (${l.cause})`),await ps(l,s.context),l}function Na(t){t.command("hook <harness>",{hidden:!0}).description("check an agent's push or pull request before it happens (called by the agent harness, not by people)").action(async e=>{if(Sa.includes(e)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await $f(e,{stdin:process.stdin,ceilingMs:n,note:r=>process.stderr.write(r+`
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)})}B();j();function Pa(t){t.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async e=>{let n=e.json===!0,r=H();if(r)try{await v("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}ti();let o=!!process.env.CANARY_TOKEN;n?console.log(JSON.stringify({ok:!0,...o?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),o&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}B();j();lt();B();lt();var If={happy_path:"Core flow",boundary:"Edge case",failure:"Failure handling",security:"Security",parity:"Old-vs-new behavior",performance:"Performance",compatibility:"Compatibility",lifecycle:"Lifecycle",modality:"Interface"},Rf=15e3;function Of(t){return t&&If[t]||"Other"}var Ef=t=>{let e=t?.finding?.nextActionCodeRef??t?.codeRefs?.[0]??t?.checkReadback?.codeRefs?.[0]??null;return e?{file:e.file,line:e.startLine??null}:null},Af=t=>(Array.isArray(t?.evidence)?t.evidence:[]).filter(e=>e&&e.media&&typeof e.media.url=="string").map(e=>({kind:b(e.modality)||"evidence",caption:b(e.caption),url:e.media.url,expiresAt:e.media.expiresAt??null}));function Tf(t,e,n){if(t.status!=="completed"||me(t.materiality)===null)return null;let r=e??null,o=r?.isStatic===!0?"source":"runtime",i=t.result==="pass"?"passed":t.result==="fail"?"failed":"could_not_run",s=b(r?.assertion)||null;return{checkRunId:t.checkRunId,checkUrl:`${n}/checks/${t.checkRunId}`,scenarioId:t.stageBCheckId??t.checkRunId,category:Of(r?.lane),title:b(t.title),proof:o,status:i,whatWasTried:o==="source"?b(r?.finding?.whatWasTested)||null:b(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:s||b(r?.finding?.whatWasTested)||null,observed:b(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:s,location:Ef(r),evidence:Af(r),fix:o==="source"&&b(r?.finding?.reproduce)||null,reason:i==="could_not_run"&&(b(r?.verdict?.reasonOneLiner)||jt[t.blockedReason??""])||null}}async function La(t,e,n){let r=new Map,o=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;for(let i of e)if(!(i.status!=="completed"||r.has(i.checkRunId)||!o.test(i.checkRunId)))try{r.set(i.checkRunId,await v(`/api/v1/red-team/runs/${t}/checks/${i.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(Rf),...n.baseUrl?{baseUrl:n.baseUrl}:{}}))}catch{r.set(i.checkRunId,null)}return r}function Ma(t,e,n){let r=t.stageC.checks.map(o=>Tf(o,e.get(o.checkRunId)??null,n.runUrl)).filter(o=>o!==null);return{runId:t.runId,runUrl:n.runUrl,repo:n.repo,treeHash:t.target.treeHash??"",files:n.files,reverifySourceRunId:t.reverifySourceRunId??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null,checks:r,passed:r.filter(o=>o.status==="passed").length,failed:r.filter(o=>o.status==="failed").length,couldNotRun:r.filter(o=>o.status==="could_not_run").length,errored:t.stageC.failedCheckRuns+t.stageC.cancelledCheckRuns}}var Da=new Set(["completed","failed","cancelled"]);function ja(t){return Da.has(t.status)?null:t.status==="queued"?"queued":t.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function Ha(t){return t.status==="failed"||t.status==="cancelled"?"errored":t.status!=="completed"?t.status==="running"?"running":"pending":t.result==="pass"?"passed":t.result==="fail"?"failed":"could_not_run"}async function yo(t,e,n,r,o={}){let i=H();if(!i)return I(t,"not_logged_in","Not logged in","run `canary login` first",3),null;if(e.some(s=>!We.test(s)))return I(t,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await v(n,{token:i,...r?{baseUrl:r}:{},...o})}catch(s){if(s instanceof $){if(s.status===404)return I(t,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let a=!ie(s)&&s.status>=400&&s.status<500,l=s.fix??(s.status===401?"run `canary login`":a?void 0:"run the command again in a minute");return I(t,"api_error",s.message,l,a?3:2,{httpStatus:s.status}),null}throw s}}var Fa=t=>{if(!t?.file)return"";let e=t.startLine?`:${t.startLine}`:"",n=t.startLine&&t.endLine&&t.endLine>t.startLine?`-${t.endLine}`:"";return`${b(t.file)}${e}${n}`};async function Nf(t,e,n){let r=await yo(e,[t],`/api/v1/red-team/runs/${t}`,n);if(!r)return;let o=r.run,i=r.repository?.fullName??"";if(e){let c=o.stageC.checks.filter(p=>me(p.materiality)!==null).map(p=>({checkRunId:p.checkRunId,scenarioId:p.stageBCheckId??p.checkRunId,title:b(p.title),status:Ha(p)})),u={runId:o.runId,status:o.status,progress:ja(o),treeHash:o.target.treeHash??"",repo:i,reverifySourceRunId:o.reverifySourceRunId??null,startedAt:o.startedAt??null,completedAt:o.completedAt??null,failureMessage:o.failure?.publicMessage??null,checks:c,passed:c.filter(p=>p.status==="passed").length,failed:c.filter(p=>p.status==="failed").length,couldNotRun:c.filter(p=>p.status==="could_not_run").length,errored:o.stageC.failedCheckRuns+o.stageC.cancelledCheckRuns},d={},h=H();if(Da.has(o.status)&&h){let p=await La(t,o.stageC.checks,{token:h,...n?{baseUrl:n}:{}});d=Ma(o,p,{runUrl:`${ke().replace(/\/+$/,"")}/runs/${t}`,repo:i,files:null})}return void console.log(JSON.stringify({ok:!0,...u,...d}))}let s=ja(o),a=[`run ${b(o.runId)} \xB7 ${b(o.status)}${s?` \xB7 ${s}`:""}${o.target.treeHash?` \xB7 tree ${b(o.target.treeHash).slice(0,12)}`:""}`];o.failure?.publicMessage&&a.push(` ${b(o.failure.publicMessage)}`);let l=o.stageC;a.push(`checks ${l.checks.length} \xB7 ${l.results.pass} passed \xB7 ${l.results.fail} failed \xB7 ${l.results.blocked} could not verify \xB7 ${l.failedCheckRuns+l.cancelledCheckRuns} errored`);for(let c of l.checks){let u=Ha(c),d=u==="could_not_run"?"could not verify":u,h=c.result==="blocked"?jt[c.blockedReason??""]:void 0;a.push(` ${me(c.materiality)??"P3"} ${d.padEnd(16)} ${b(c.title)} ${b(c.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
157
- `))}async function Pf(t,e,n,r){let o=await yo(n,[t,e],`/api/v1/red-team/runs/${t}/checks/${e}/finding`,r);if(!o)return;if(n)return void console.log(JSON.stringify({ok:!0,runId:t,checkRunId:e,...o}));let i=[];i.push(b(o.finding?.headline)||"(no finding written for this check yet)"),o.verdict&&i.push(`verdict: ${b(o.verdict.result)}${o.verdict.reasonOneLiner?` \u2014 ${b(o.verdict.reasonOneLiner)}`:""}${o.isStatic?" (reasoned from the code, not run)":""}`),o.assertion&&i.push(`assertion: ${b(o.assertion)}`),o.observable&&i.push(`observable: ${b(o.observable)}`),o.checkReadback?.whyThisCheck&&i.push(`why this check: ${b(o.checkReadback.whyThisCheck)}`),o.finding?.whatWasTested&&i.push(`tested: ${b(o.finding.whatWasTested)}`),o.finding?.reproduce&&i.push(`reproduce: ${b(o.finding.reproduce)}`),o.finding?.nextActionCodeRef&&i.push(`\u2192 ${Fa(o.finding.nextActionCodeRef)}`);for(let s of o.codeRefs??[])i.push(` ref ${Fa(s)}${s.reason?` \u2014 ${b(s.reason)}`:""}`);for(let s of o.evidence??[])i.push(` evidence ${b(s.modality)}: ${b(s.caption)}${s.media?` ${b(s.media.url)}`:s.failureReason?` (${b(s.failureReason)})`:""}`);for(let s of o.verdict?.limitations??[])i.push(` limitation: ${b(s)}`);o.network?.failures?.length&&i.push(` network failures: ${o.network.failures.length}`),console.log(i.join(`
158
- `))}async function Lf(t,e,n,r,o,i){if(await yo(o,[t,e],`/api/v1/red-team/runs/${t}/checks/${e}/report`,i,{method:"POST",body:{reported:n,...r?{note:r}:{}}})){if(o)return void console.log(JSON.stringify({ok:!0,runId:t,checkRunId:e,reported:n}));console.log(`reported ${n}${r?`: ${b(r)}`:""}`)}}async function Mf(t,e,n){let r=H();if(!r)return I(e,"not_logged_in","Not logged in","run `canary login` first",3);if(!We.test(t))return I(e,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let o;try{o=await to(t,r,{...n?{baseUrl:n}:{},onProgress:s=>console.error(` ${s}`)})}catch(s){if(s instanceof ge)return I(e,s.code,s.message,`run \`canary run wait ${t}\` again to keep waiting`,2,{runId:t});if(s instanceof $){if(s.status===404)return I(e,"not_found","no such run in your workspace",void 0,3,{httpStatus:404});let a=!ie(s)&&s.status>=400&&s.status<500;return I(e,"api_error",s.message,s.fix??(s.status===401?"run `canary login`":a?void 0:`run \`canary run wait ${t}\` again`),a?3:2,{runId:t,httpStatus:s.status})}throw s}let i=no(o.run,o.run.target?.treeHash??"",o.findings,o.run.reverify);console.log(e?JSON.stringify(i):ro(i)),process.exitCode=i.exitCode}function Ua(t){t.command("run").argument("[runId]").description("Show a verify run: status and every check with its verdict").option("--json","print one JSON document: status, progress, every check with its verdict, and the report fields once the run has finished").action(async(n,r)=>{try{if(!n)return I(r.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await Nf(n,r.json===!0)}catch(o){I(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 Mf(n,i)}catch(s){I(i,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}}),t.command("check <runId> <checkRunId>").description("Show one check in full: verdict, what was tested, reproduce steps, code refs, evidence \u2014 or report what you did with it").option("--json","print the server's finding body, unchanged, under an ok:true envelope with runId and checkRunId").option("--fixed","report: you fixed the behaviour this finding describes").option("--disputed <why>","report: the finding is not a real problem, and why").option("--skipped <why>","report: you did not act on it, and why").action(async(n,r,o)=>{try{let i=[o.fixed?"fixed":null,o.disputed!==void 0?"disputed":null,o.skipped!==void 0?"skipped":null].filter(Boolean);if(i.length>1)return I(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?I(o.json===!0,"bad_report",`--${i[0]} needs a reason`,void 0,3):await Lf(n,r,i[0],s,o.json===!0)}await Pf(n,r,o.json===!0)}catch(i){I(o.json===!0,"internal_error",i instanceof Error?i.message:String(i),void 0,2)}})}import{readFileSync as Wf,unlinkSync as Bf,writeFileSync as Vf}from"node:fs";import{basename as qf,join as Yf}from"node:path";import{setTimeout as Kf}from"node:timers/promises";Be();B();Xe();j();Ie();import{emitKeypressEvents as jf}from"node:readline";var Hf=36,Ff=12,Ga=64*1024,wo=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Df={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},Uf={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function Gn(t){let e=Math.max(0,Math.floor(t));return e<60?`${e}s`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`}function Gf(t,e){let n="";for(let{segment:r}of[...wo.segment(P(t))].reverse()){if(Dt(r+n)>e)break;n=r+n}return n}function Ja(t,e,n){let r=t.question,o=Math.max(1,e-5),i=(l,c="text")=>` ${Ut(P(l),c,n)}`,s=0;if(r.secret){for(let l of wo.segment(t.input??""))if(++s===24)break}let a=r.secret?"\u2022".repeat(s):Gf(t.input??"",Math.max(1,o-2));return[i("CANARY \xB7 SETUP","gold"),i(`${t.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${Gn(t.seconds)}`),i(`CLI workspace ${t.workspace}`,"muted"),"",i(r.key,"gold"),...Ee(r.prompt,o).map(l=>i(l)),i(t.inputActive?`\u203A ${a||(r.secret?"(hidden)":"")}`:t.inputSubmitted?"Value captured locally.":"Input deferred","muted"),i(t.inputNotice??(r.secret?"Your value stays hidden.":""),"muted"),i(t.inputActive?"Enter submit \xB7 Esc/Ctrl+C later":t.inputSubmitted?"Waiting for verification to continue.":"Run canary setup to resume.","muted")]}function Jf(t,e,n,r){let o=Math.max(1,e-5),i=Math.max(1,n-2),s=t.outcome?Uf[t.outcome.status]:t.question?"Your input is needed":Df[t.status],a=t.outcome?.status==="green"?"green":"gold",l=(d,h="text")=>Ut(P(d),h,r),c;if(i<=3)c=[l(s,a),l(`Elapsed ${Gn(t.seconds)}`,"muted")].slice(0,i);else if(t.question&&!t.outcome)c=Ja(t,e,r);else{let d=t.seconds%1.6,h=!t.outcome&&["pending","running"].includes(t.status)&&d<1.4?Math.sin(d/1.4*Math.PI*2)*Math.sin(d/1.4*Math.PI):0,p=dt[Math.max(0,Math.min(16,Math.round(h*10)+8))];if(e>=76&&n>=23){let f={1:l("CANARY \xB7 SETUP","gold"),3:l(s,a),5:l(`Elapsed ${Gn(t.seconds)}`,"muted")};c=["",...p.map((m,g)=>` ${l(m,a)} ${f[g]??""}`)]}else c=[` ${l("CANARY \xB7 SETUP","gold")}`,` ${l(s,a)}`,` ${l(`Elapsed ${Gn(t.seconds)}`,"muted")}`];c.push("",` ${l(`Repository ${t.repository}`)}`,` ${l(`CLI workspace ${t.workspace}`)}`),t.detail&&!t.outcome&&c.push(...Ee(t.detail,o).map(f=>` ${l(f,"muted")}`)),t.outcome||c.push("",` ${l("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(c.length>i?[...c.slice(0,Math.max(0,i-2)),...c.slice(-2)]:c).map(d=>Nn(d,Math.max(1,e-1)))}function Wa(t){if(t.json||!t.animation||!process.stdin.isTTY||!process.stdout.isTTY||!process.stderr.isTTY||process.env.CI||process.env.TERM==="dumb"||process.env.CANARY_NO_ANIMATION)return;let e=process.stderr,n=process.stdin,r=!process.env.NO_COLOR,o=ut(e),i=performance.now(),s={...t,status:"submitting",seconds:0},a=!1,l=!1,c,u=!1,d,h,p=()=>({columns:e.columns||80,rows:e.rows||24}),f=O=>{try{e.write(O)}catch{}},m=()=>f(`${D}0m${D}?25h`);function g(){if(a||u)return;s.seconds=(performance.now()-i)/1e3;let{columns:O,rows:M}=p();try{o.render(Jf(s,O,M,r))}catch{_()}}function w(){let{columns:O,rows:M}=p();return n.isTTY&&O>=Hf&&M>=Ff&&Ja(s,O,!1).length<=M-2}function x(){let O=s.question;if(!O)return;u=!0;try{o.render([])}catch{}let M=Math.max(1,p().columns-3);f(`
159
- Input needed: ${P(O.key)}
160
- ${Ee(O.prompt,M).join(`
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 y(){h&&!w()?h.settle(null,!0):g()}function k(){!a||h||l||(l=!0,process.off("SIGINT",C),process.off("SIGTERM",U),process.off("exit",_),m(),c!==void 0&&(f(`
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(c)))}function _(){a||(a=!0,clearInterval(d),e.off("resize",y),h?.settle(null),k())}function E(O){c=O,_(),k()}function C(){h?h.settle(null):E(130)}function U(){E(143)}async function _e(O,M){return a||h||M?.aborted?null:(s.question={...O},s.input="",s.inputActive=!0,s.inputSubmitted=!1,s.inputNotice=void 0,u=!1,w()?new Promise(ye=>{let yt=n.isRaw,Kt=n.readableFlowing===!0,Z="",we="",de=!1,fe=!1,Y="",pe=!1,Ne=!1,R=!1,ae=!1,K;function zt(G,A=!1){ae||(K={answer:K&&G!==null?K.answer:G,showStatic:A||K?.showStatic||!1},Ne||=!!Y&&!fe,Z=we="",s.input="",(de||fe||Y||Ne)&&(s.inputNotice="Finishing clipboard input.",g()),qn())}function qn(){if(ae||!K||pe||de||fe||Y||Ne)return;let{answer:G,showStatic:A}=K;ae=!0,n.off("keypress",Co),n.off("data",xo),n.off("data",_o),n.off("end",qe),n.off("error",qe),n.off("close",qe),M?.removeEventListener("abort",Ve);try{n.setRawMode(yt)}catch{}Kt||n.pause(),f(`${D}?2004l`),Z="",we="",s.input="",s.inputActive=!1,s.inputSubmitted=G!==null,s.inputNotice=G===null?"You can provide this value later.":"Input received locally.",h=void 0,A&&!a?x():g(),m(),k(),ye(G)}function Ve(){zt(null)}function qe(){de=fe=pe=Ne=!1,Y="",zt(null)}function xo(G){pe=!0;for(let A of typeof G=="string"?G:G.toString("utf8")){let Ye=fe?`${D}201~`:`${D}200~`;Y=A===Ye[Y.length]?Y+A:A==="\x1B"?A:"",Y===Ye&&(fe=!fe,Y="")}}function _o(){pe=!1,qn()}function vo(G){Z.length+G.length>Ga?(R=!0,s.inputNotice="Too long. Ctrl+U clears input."):(Z+=G,R||(s.inputNotice=void 0))}function Co(G,A){if(!(ae||!A))try{if(!pe&&A.name==="escape"&&(Y=""),!Y&&A.sequence?.startsWith("\x1B")&&(Ne=!1),K){A.name==="paste-start"?de=!0:A.name==="paste-end"&&(de=!1),qn();return}if(A.name==="paste-start"){de=!0,we="";return}if(A.name==="escape"||A.ctrl&&["c","d"].includes(A.name??"")){Ve();return}if(A.name==="paste-end")de=!1,vo(we.replace(/\r\n?/g,`
167
- `)),we="";else if(de){let Ye=(G||A.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(A.sequence??"").includes("\x1B")||(we.length+Ye.length<=Ga?we+=Ye:(R=!0,s.inputNotice="Too long. Ctrl+U clears input."));return}else if(A.ctrl&&A.name==="u")Z="",R=!1,s.inputNotice=void 0;else if(A.name==="backspace")Z=[...wo.segment(Z)].slice(0,-1).map(uc=>uc.segment).join("");else if(A.name==="return"||A.name==="enter"){if(!Z.trim())s.inputNotice="Enter a value, or Esc to answer later.";else if(!R){zt(Z);return}}else!A.ctrl&&!A.meta&&G&&vo(G.replace(/[\x00-\x1f\x7f-\x9f]/g,""));s.input=Z,g()}catch{Ve()}}h={settle:zt};try{if(n.prependListener("data",xo),jf(n),n.on("keypress",Co),n.on("data",_o),n.once("end",qe),n.once("error",qe),n.once("close",qe),M?.addEventListener("abort",Ve,{once:!0}),M?.aborted){Ve();return}n.setRawMode(!0),n.resume(),f(`${D}?2004h${D}?25l`),g()}catch{Ve()}}):(s.inputActive=!1,x(),null))}return e.on("resize",y),process.on("SIGINT",C),process.on("SIGTERM",U),process.once("exit",_),d=setInterval(g,80),d.unref(),f(`${D}?25l`),g(),{update(O,M){a||(s.status=O,s.detail=M,h||(s.question=void 0,s.input=void 0,u=!1),f(`${D}?25l`),g())},warn(O){if(!a)try{o.render([])}catch{_()}f(`
168
- Warning: ${O.split(/\r?\n/).map(P).join(`
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:_e,finish(O){if(a)return;h?.settle(null),s.question=void 0,s.outcome=O,u=!1,g(),_();let M=[O.message,...O.updatedFiles?.length?[`Updated locally: ${O.updatedFiles.join(", ")}`]:[],...O.warning?[`Warning: ${O.warning}`]:[],...O.next?[`Next: ${O.next}`]:[]].filter(ye=>!!ye);M.length&&f(`
172
- ${M.flatMap(ye=>ye.split(/\r?\n/).map(P)).join(`
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:_}}Tr();yn();X();ct();Xr();Kr();var pt=3e3,Jn=2,zf=9e4,Ba=new Set(["pending","running","needs_input","green","red","error","interrupted"]);function V(t,e){for(let n of[...t.secrets].sort((r,o)=>o.length-r.length))n&&(e=e.split(n).join("[redacted]"));return e}var bo=t=>Yf(t,".canary","verify-job.json");function Vt(t){try{let e=JSON.parse(Wf(bo(t),"utf8"));if(!e||typeof e.jobId!="string"||!e.jobId)throw new Error("invalid job ID");if(e.sourceUploadId!==void 0&&(typeof e.sourceUploadId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.sourceUploadId)))throw new Error("invalid source upload ID");if(e.scope&&(!e.source||!Rn(e.source)||typeof e.recipeHash!="string"||typeof e.scope.apiUrl!="string"||![e.scope.userId,e.scope.workspaceId,e.scope.repositoryId].every(r=>typeof r=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(r))))throw new Error("invalid scope");let n=e.workspace&&typeof e.workspace.id=="string"&&typeof e.workspace.name=="string"?{id:e.workspace.id,name:e.workspace.name}:void 0;return{jobId:e.jobId,...typeof e.recipeHash=="string"?{recipeHash:e.recipeHash}:{},...n?{workspace:n}:{},...e.scope?{scope:e.scope}:{},...e.source?{source:e.source}:{},...e.sourceUploadId?{sourceUploadId:e.sourceUploadId}:{}}}catch(e){if(e.code==="ENOENT")return null;throw new te("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 Xf(t){return Vt(t)?.jobId??null}var Va=(t,e)=>Vf(bo(t),JSON.stringify(e)+`
175
- `);function Wn(t){try{Bf(bo(t))}catch{}}var ht=(t,e)=>Kf(t,void 0,{signal:e});function Qf(t){let e=t?.setup?.services;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"?n.name:void 0).filter(n=>typeof n=="string"):[]}function Zf(t,e){let n,r;try{n=Oe(t),vt(t),r=rt(t).name}catch(d){if(d instanceof te||d instanceof N){e?console.log(JSON.stringify({ok:!1,error:d.code,message:d.message,..."fix"in d&&d.fix?{fix:d.fix}:{}})):console.error(`\u2717 ${d.message}${"fix"in d&&d.fix?`
176
- Fix: ${d.fix}`:""}`),process.exitCode=1;return}throw d}let o=r??null,i=n.setupSh.trim().split(`
177
- `).length,s=Qf(n.runJson),a=[...new Set([...n.envManifest.map(d=>d.name),...Object.keys(n.envValues)])],l=n.envManifest.filter(d=>d.neededAt==="boot").map(d=>d.name),{missing:c}=Er(n.envManifest,n.envValues),u=c.length===0;e?console.log(JSON.stringify({ok:u,repo:o,recipe:{setupShLines:i,services:s,envKeys:a,bootRequired:l,missing:c}})):(console.log(`Repo ${o??"(local repository)"}`),console.log(`Recipe .canary/ \xB7 setup.sh (${i} lines) \xB7 run.json (${s.length} service${s.length===1?"":"s"}${s.length?": "+s.join(", "):""})`),console.log(`Env ${a.length} key${a.length===1?"":"s"} \xB7 ${l.length} boot-required \xB7 ${c.length?`MISSING: ${c.join(", ")}`:"all present"}`),u?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${c.join(", ")} (boot-required) ${c.length===1?"has":"have"} no value.`)),u||(process.exitCode=1)}async function qa(t,e,n,r,o={}){if(e.status==="green"){let i=Vt(t),s=i?.workspace,a=o.recipeChanged??!1;if(i?.recipeHash)try{a||=De(Oe(t))!==i.recipeHash}catch{a=!0}let l=!1;if(i?.source){let d=(p,f)=>p.sha256===f.sha256&&p.treeHash===f.treeHash&&p.baseTreeHash===f.baseTreeHash&&p.baseSha===f.baseSha&&p.provenance.baselineMode===f.provenance.baselineMode&&(p.provenance.baseRef??null)===(f.provenance.baseRef??null);if(e.approved?.source&&!d(e.approved.source,i.source))throw new Error("The approved source does not match the source this job was submitted with. Run canary setup again to verify the current files.");let h;try{h=await Nt(t,{baseRef:i.source.provenance.baseRef??void 0}),l=h.manifest.treeHash!==i.source.treeHash||h.manifest.baseTreeHash!==i.source.baseTreeHash||h.manifest.provenance.baselineMode!==i.source.provenance.baselineMode||(h.manifest.provenance.baseRef??null)!==(i.source.provenance.baseRef??null)}catch{l=!0}finally{await h?.dispose()}}if(i?.recipeHash)try{a||=De(Oe(t))!==i.recipeHash}catch{a=!0}let c=o.writeBack!==!1&&!a&&!l;if(a||l){let d="This result is for the files as they were when submitted. They changed since, so the approved recipe was not written over your files. Run canary setup again to verify the current files.";r.warnings.push(d),!n&&!r.display&&console.error(`! ${d}`)}Wn(t);let u=[];if(e.approved?.healed&&c)try{u=Ai(t,e.approved)}catch(d){let h=V(r,`Could not update .canary/ with the approved changes: ${d instanceof Error?d.message:String(d)}`);r.warnings.push(h),r.display||console.error(`! ${h}`)}return n?console.log(JSON.stringify({ok:!0,status:"green",jobId:e.jobId,...s?{workspace:s}:{},...a?{recipeChanged:!0}:{},...l?{sourceChanged:!0}:{},...i?.source?{source:i.source,repositoryId:i.scope?.repositoryId}:{},...e.approved?{approved:{healed:e.approved.healed,...e.approved.recipeId?{recipeId:e.approved.recipeId}:{},...e.approved.recipeVersionId?{recipeVersionId:e.approved.recipeVersionId}:{},...e.approved.version!==void 0?{version:e.approved.version}:{},...u.length?{updatedFiles:u}:{}}}:{}})):r.display?r.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${s?` Workspace: ${s.name}.`:""}`,updatedFiles:u,warning:r.warnings.join(`
178
- `)||void 0,next:`Open Canary: ${ke().replace(/\/+$/,"")}/repositories`}):(console.log("\u2713 Verified \u2014 the recipe boots from zero in a clean sandbox. This repo is set up on Canary."),s&&console.log(` Workspace: ${s.name}`),e.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),u.length?console.log(` Updated locally to match: ${u.join(", ")}`):c||console.log(" Its approved version was not written over your newer files."))),!0}if(e.status==="interrupted")return!1;if(e.status==="red"||e.status==="error"){Wn(t);let i={phase:e.failure?.phase?V(r,e.failure.phase):null,failingCommand:e.failure?.failingCommand?V(r,e.failure.failingCommand):null,log:e.failure?.log?V(r,e.failure.log):null};return n?console.log(JSON.stringify({ok:!1,status:e.status,jobId:e.jobId,failure:i})):r.display?r.display.finish({status:e.status,message:`Verification ${e.status==="error"?"errored":"failed"}${i.phase?` (${i.phase})`:""}${i.failingCommand?` at: ${i.failingCommand}`:""}${i.log?`
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 ${e.status==="error"?"errored":"failed"}${i.phase?` (${i.phase})`:""}${i.failingCommand?` at: ${i.failingCommand}`:""}`),i.log&&console.error(`
182
- ${i.log.slice(-2e3)}`),console.error("\nFix the recipe in .canary/ and run `canary setup` again.")),process.exitCode=1,!0}if(e.status==="needs_input"&&e.needsInput){let i={...e.needsInput,key:V(r,e.needsInput.key),prompt:V(r,e.needsInput.prompt)};return n?console.log(JSON.stringify({ok:!1,status:"needs_input",jobId:e.jobId,needsInput:i})):(console.log(`? The cloud verifier needs input${i.secret?" (a secret \u2014 pass the real value, don't echo it anywhere else)":""}:`),console.log(` ${i.key}: ${i.prompt}`),console.log(`
183
- Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function Ya(t,e){return t.status==="needs_input"&&t.needsInput?.questionId===e.questionId}async function ep(t,e,n){let r=new AbortController,o=new AbortController,i=t.display.ask({...e,key:V(t,e.key),prompt:V(t,e.prompt)},r.signal).then(a=>({kind:"answer",value:a})),s=(async()=>{for(;;){await ht(pt,o.signal);let a=await n(o.signal);if(!Ya(a,e))return{kind:"state",view:a}}})();try{return await Promise.race([i,s])}finally{o.abort(),r.abort(),await Promise.allSettled([i,s])}}async function tp(t,e,n,r,o,i){let s="",a=null;async function l(u){for(;;)try{let d=await v(`/api/v1/cli/verify/${e}`,{token:n,baseUrl:o.context?.apiUrl,signal:u});if(!d||!Ba.has(d.status))throw new Error("Verification returned an unrecognized state. Run canary setup again to retry.");return a=null,d}catch(d){if(u?.aborted)throw d;if(d instanceof $&&d.status===0&&(a===null&&(a=Date.now(),o.display?o.display.update("retrying","Cloud service unreachable. Retrying the same job."):r||console.log(" \u2026 cloud service unreachable \u2014 retrying")),Date.now()-a<zf)){await ht(pt,u);continue}throw d}}let c;for(;;){let u=c??await l();if(c=void 0,u.status==="interrupted")return"interrupted";if(u.status==="needs_input"&&i&&u.needsInput?.questionId===i.questionId&&Date.now()<i.until){await ht(pt);continue}if(u.status==="needs_input"&&u.needsInput&&o.display){let d=u.needsInput,h=await ep({...o,display:o.display},d,l);if(h.kind==="state"){c=h.view;continue}let p=h.value;if(p===null)return o.display.finish({status:"paused",message:"The verifier is waiting for your answer.",next:"Run canary setup to resume, or canary setup --answer '<value>' to answer directly."}),process.exitCode=3,"terminal";let f=await l();if(!Ya(f,d)){c=f;continue}o.display.update("answering","Sending your answer to the verifier.");try{await Xa(t,e,n,d,p,r,o)}catch(m){if(m instanceof $&&m.status===409)continue;throw m}i={questionId:d.questionId,until:Date.now()+3e4},o.display.update("answering","Answer received. Waiting for verification to continue."),await ht(pt);continue}if((u.status==="pending"||u.status==="running")&&(o.display?o.display.update(u.status):u.status!==s&&!r&&console.log(` \u2026 ${u.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),s=u.status,await qa(t,u,r,o))return"terminal";await ht(pt)}}async function Bn(t,e,n,r,o,i){ze();let s=e;for(let a=0;;){if(await tp(t,s,n,r,o,i)==="terminal")return;if(Wn(t),o.freshUpload=!0,a>=Jn){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:Jn})):o.display?o.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${Jn}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${Jn})`);let c=await za(t,n,r,o);if(c===null)return;s=c,i=void 0}}async function Ka(t,e,n,r){let o=r.context??=await Rt(t,e),i=n.scope;if(i.apiUrl.replace(/\/+$/,"")!==o.apiUrl.replace(/\/+$/,"")||i.userId!==o.userId||i.workspaceId!==o.workspaceId)throw new N("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json was started by a different account, workspace, or Canary server. Switch back to it to resume that job, or remove the file to start over.");if((await It({...o,token:e})).repositoryId!==i.repositoryId)throw new N("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json belongs to a different repository. Remove the file to start over.");r.baseRef??=n.source?.provenance.baseRef??void 0,zr(n.source,o,i.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function za(t,e,n,r){let o=Oe(t);vt(t);let{missing:i}=Er(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 Rt(t,e),a=await It({...s,token:e}),l=await Nt(t,{baseRef:r.baseRef});try{r.display?.update("submitting","Uploading your local source and the .canary/ recipe.");let c=De(o),u=await On(l,s,a.repositoryId,e,{requestKey:`setup:${c}`,fresh:r.freshUpload});r.freshUpload=!1;let d=await v("/api/v1/cli/verify",{method:"POST",token:e,baseUrl:s.apiUrl,body:{workspaceId:s.workspaceId,repositoryId:a.repositoryId,source:u,setupSh:o.setupSh,runJson:JSON.stringify(o.runJson??null),env:{manifest:o.envManifest,values:o.envValues}}});if(!d?.jobId||d.repositoryId!==a.repositoryId||d.workspace&&d.workspace.id!==s.workspaceId||d.source&&d.source.sha256!==l.manifest.sha256)throw new Error("Canary's answer does not match the repository and source that were uploaded. Run canary setup again.");return Va(t,{jobId:d.jobId,recipeHash:c,workspace:d.workspace??a.workspace,source:l.manifest,sourceUploadId:u.uploadId,scope:{apiUrl:s.apiUrl,userId:s.userId,workspaceId:s.workspaceId,repositoryId:a.repositoryId}}),zr(l.manifest,s,a.repositoryId,{requestKey:`setup:${c}`,uploadId:u.uploadId}),d.jobId}finally{await l.dispose()}}async function np(t,e,n){let r=H();if(!r){e?console.log(JSON.stringify({ok:!1,error:"not_logged_in",fix:"canary login"})):n.display?n.display.finish({status:"error",message:"You're not signed in.",next:"Run canary login first."}):console.error("\u2717 Not logged in \u2014 run `canary login` first."),process.exitCode=1;return}tn();let o=Vt(t);o?.scope&&await Ka(t,r,o,n);let i=o?.jobId??null;if(i){n.display?.update("submitting","Checking your saved verification job.");let a=null,l=!1,c=Date.now()+3e4;for(;;)try{if(a=await v(`/api/v1/cli/verify/${i}`,{token:r,baseUrl:n.context?.apiUrl}),!a||!Ba.has(a.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(u){if(u instanceof $&&u.status===0){if(Date.now()<c){n.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await ht(pt);continue}l=!0}else if(!(u instanceof $&&u.status===404))throw u;break}if(l){e?console.log(JSON.stringify({ok:!1,error:"unreachable",jobId:i})):n.display?n.display.finish({status:"error",message:"Could not reach the cloud service to check your saved job.",next:"Run canary setup again shortly. Your job is saved."}):console.error("\u2717 Could not reach the cloud service to check your saved verify job \u2014 try again shortly."),process.exitCode=1;return}if(a){if(a.status==="pending"||a.status==="running"||a.status==="needs_input"){n.display?n.display.update(a.status==="needs_input"?"answering":a.status,"Resuming your saved verification job."):e||console.log(`Resuming verify job ${i} \u2026`),await Bn(t,i,r,e,n);return}if(a.status==="green"||a.status==="red"||a.status==="error"){let u=!1;if(o?.recipeHash)try{u=De(Oe(t))!==o.recipeHash}catch{u=!0}e?console.error(JSON.stringify({event:"previous_job_result",jobId:i,...u?{recipeChanged:!0}:{}})):n.display?n.warnings.push(u?"This is your earlier verification result, and .canary/ changed since it was submitted: its approved version was not written over your files. Run canary setup again to verify the current files.":"This is your earlier verification result. If you changed .canary/ since then, run canary setup again to verify the current files."):console.log(`Your earlier verify job ${i} finished after the previous run stopped \u2014 applying its result now.
184
- `+(u?" .canary/ changed since it was submitted, so its approved version was NOT written over your files. Run `canary setup` again to verify the current files.":" If you changed .canary/ since then, run `canary setup` again to verify the current files.")),await qa(t,a,e,n,{writeBack:!u,recipeChanged:u});return}}Wn(t),n.freshUpload=!0}let s=await za(t,r,e,n);s!==null&&(n.display?n.display.update("pending","Recipe sent. Waiting for the cloud verifier."):e||console.log(`Shipped the recipe \u2014 verify job ${s}`),await Bn(t,s,r,e,n))}async function Xa(t,e,n,r,o,i,s){if(r.secret&&o&&s.secrets.add(o),await v(`/api/v1/cli/verify/${e}/answer`,{method:"POST",token:n,baseUrl:s.context?.apiUrl,body:{questionId:r.questionId,value:o}}),r.secret){let a=Vt(t),l=!1;try{l=!!a?.recipeHash&&De(Oe(t))===a.recipeHash}catch{}try{if(a?.recipeHash&&!l)throw new Error("Local recipe changed since submission; the answered value was not written over it.");Ar(t,[{name:r.key,value:o,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),l&&a&&Va(t,{...a,recipeHash:De(Oe(t))}),!i&&!s.display&&console.log(`Saved ${V(s,r.key)} to .canary/env.json for future runs.`)}catch(c){let u=V(s,`Could not save ${r.key} to .canary/env.json: ${c instanceof Error?c.message:String(c)}`);s.display?s.display.warn(u):console.error(`! ${u}`)}}}async function rp(t,e,n,r){let o=H(),i=Xf(t);if(!o||!i){n?console.log(JSON.stringify({ok:!1,error:i?"not_logged_in":"no_active_job",fix:i?"canary login":"canary setup"})):r.display?r.display.finish({status:"error",message:i?"You're not signed in.":"No active verification job.",next:i?"Run canary login first.":"Run canary setup first."}):console.error(i?"\u2717 Not logged in \u2014 run `canary login`.":"\u2717 No active verify job \u2014 run `canary setup` first."),process.exitCode=1;return}let s=Vt(t);s?.scope&&await Ka(t,o,s,r);let a=await v(`/api/v1/cli/verify/${i}`,{token:o,baseUrl:r.context?.apiUrl});if(a.status!=="needs_input"||!a.needsInput){r.display?r.display.update("submitting","Nothing is waiting for input. Checking the saved job."):n||console.log("Nothing is waiting for input \u2014 following the job instead."),await Bn(t,i,o,n,r);return}let l=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await Xa(t,i,o,l,e,n,r),r.display?r.display.update("answering","Answer received. Waiting for verification to continue."):n||console.log(`Answered ${V(r,l.key)} \u2014 resuming \u2026`),await Bn(t,i,o,n,r,{questionId:l.questionId,until:Date.now()+3e4})}function Qa(t){t.command("setup").description("Set up this repo on Canary: ship the .canary/ recipe for a cloud verify (boot + heal)").option("--check","validate the .canary/ recipe locally (no cloud)").option("--answer <value>","answer the question the cloud verifier is waiting on").option("--json","output machine-readable JSON").option("--no-animation","use plain progress output and answer questions with --answer").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","locally resolvable baseline for the submitted source snapshot").action(async e=>{let n=e.dir??process.cwd();je({cwd:n});let r=e.json===!0;if(e.check){Zf(n,r);return}let o={secrets:new Set(e.answer?[e.answer]:[]),warnings:[],baseRef:e.base};try{let i=T().team;o.display=Wa({json:r,animation:e.animation!==!1,repository:qf(n),workspace:i?.name||(i?.id?"Saved workspace":"Select a workspace")}),e.answer!==void 0?await rp(n,e.answer,r,o):await np(n,r,o)}catch(i){if(i instanceof te||i instanceof re||i instanceof N){let s=V(o,i.message),a="fix"in i&&i.fix?V(o,i.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:i.code,message:s,...a?{fix:a}:{}})):o.display?o.display.finish({status:"error",message:s,next:a}):console.error(`\u2717 ${s}${a?`
185
- Fix: ${a}`:""}`)}else if(i instanceof $){let s=V(o,i.message),a="fix"in i&&i.fix?V(o,i.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:"api_error",status:i.status,message:s,...a?{fix:a}:{}})):o.display?o.display.finish({status:"error",message:s,next:a||"Run canary setup in this repository to resume."}):console.error(`\u2717 ${s}${a?`
186
- Fix: ${a}`:""}`)}else{let s=V(o,i instanceof Error?i.message:String(i));r?console.log(JSON.stringify({ok:!1,error:"setup_error",message:s})):o.display?o.display.finish({status:"error",message:s,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${s}`)}process.exitCode=1}finally{o.display?.stop()}process.exitCode||await Ft({json:r})})}lt();j();Ie();import{lstatSync as op,mkdirSync as ip,readFileSync as Za,writeFileSync as ec}from"node:fs";import{join as ko}from"node:path";var sp=5e3,ap=/^[a-z0-9][a-z0-9-]{0,39}$/,cp=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,lp="npm i -g @runcanary/cli@latest";function nc(t){let e=ko(ee(),"skills");return{dir:e,body:ko(e,`${t}.md`),meta:ko(e,`${t}.json`)}}function up(t){let e=nc(t);try{let n=JSON.parse(Za(e.meta,"utf8"));return{body:Za(e.body,"utf8"),meta:n}}catch{return null}}function qt(t){try{return op(t).isSymbolicLink()}catch{return!1}}function dp(t,e){let n=nc(t);try{if(qt(ee())||qt(n.dir)||qt(n.body)||qt(n.meta)||(ip(n.dir,{recursive:!0,mode:448}),qt(n.dir)))return;ec(n.body,e.body,{flag:"w",mode:384}),ec(n.meta,JSON.stringify(e.meta,null,2)+`
187
- `,{flag:"w",mode:384})}catch{}}function tc(t){return t instanceof Error?t.message:String(t)}async function fp(t,e){let n;try{n=await fetch(t,{headers:{...$e(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${e}`},signal:AbortSignal.timeout(sp)})}catch(r){return{kind:"failed",reason:tc(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: ${tc(r)}`}}}async function So(t){let e=await fp(t.url,t.cliVersion);switch(e.kind){case"ok":{let n={url:t.url,fetchedAt:new Date().toISOString(),cliVersion:t.cliVersion,contentVersion:e.contentVersion};return dp(t.key,{body:e.body,meta:n}),{ok:!0,body:e.body,url:t.url,contentVersion:e.contentVersion,offline:!1}}case"missing":return{ok:!1,error:t.notFound};case"failed":{let n=up(t.key);if(n&&n.meta.url===t.url)return{ok:!0,body:n.body,url:t.url,contentVersion:n.meta.contentVersion,offline:!0,reason:e.reason,fetchedAt:n.meta.fetchedAt,savedByCli:n.meta.cliVersion};let r=n?`the saved copy is from ${n.meta.url}, not this server`:"there is no saved copy";return{ok:!1,error:`live fetch of ${t.url} failed (${e.reason}) and ${r} \u2014 retry when the server is reachable`}}}}function pp(t,e){let n=i=>i.replace(/^v/,"").split("-")[0].split(".").map(s=>Number.parseInt(s,10)||0),r=n(t),o=n(e);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s<0?-1:1}return 0}function hp(t){let e=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t);if(e)return/^minCli:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m.exec(e[1])?.[1]}function rc(t){return t.offline?`OFFLINE COPY \u2014 live fetch of ${t.url} failed (${t.reason}). Showing the copy fetched ${t.fetchedAt} by CLI ${t.savedByCli}; it may be outdated.`:`Source: ${t.url}${t.contentVersion?` (content version ${t.contentVersion})`:""}`}function gt(t,e,n={}){if(!t.ok)return e?{stream:"stdout",text:JSON.stringify({ok:!1,error:t.error,...n})+`
188
- `,exit:1}:{stream:"stderr",text:`\u2717 ${t.error}
189
- `,exit:1};if(e){let r={ok:!0,source:t.url,contentVersion:t.contentVersion??null,offline:t.offline,...t.offline?{reason:t.reason,fetchedAt:t.fetchedAt}:{},...n,body:t.body};return{stream:"stdout",text:JSON.stringify(r)+`
190
- `,exit:0}}return{stream:"stdout",text:`${rc(t)}
191
-
192
- ${t.body}${t.body.endsWith(`
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 Yt(t){(t.stream==="stdout"?process.stdout:process.stderr).write(t.text),process.exit(t.exit)}function gp(t,e,n={}){if(!t.ok||e){let r=gt(t,e,n);return r.stream==="stdout"?{stdout:r.text,stderr:"",exit:r.exit}:{stdout:"",stderr:r.text,exit:r.exit}}return{stdout:t.body,stderr:`${rc(t)}
195
- `,exit:0}}function Vn(){return W().replace(/\/+$/,"")}function oc(t){t.command("skills").description("List the operations a coding agent can perform with Canary (hosted index)").option("--json","output machine-readable JSON").action(async e=>{let n=await So({key:"index",url:`${Vn()}/llms.txt`,cliVersion:t.version()??"0.0.0",notFound:`this Canary server (${Vn()}) does not publish skills yet`});Yt(gt(n,!!e.json))}),t.command("skill <name>").description("Print the hosted instructions for one Canary operation").option("--json","output machine-readable JSON").option("--asset <file>","print a file published beside the operation (a template, a schema) instead of its instructions").action(async(e,n)=>{let r=!!n.json;ap.test(e)||Yt(gt({ok:!1,error:`invalid operation name "${e.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},r));let o=t.version()??"0.0.0";if(n.asset!==void 0){cp.test(n.asset)||Yt(gt({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 So({key:`${e}--${n.asset}`,url:`${Vn()}/skills/${e}/${n.asset}`,cliVersion:o,notFound:`no such asset "${n.asset}" for "${e}" \u2014 run \`canary skill ${e}\` to see which files it publishes`}),a=gp(s,r,{name:e,asset:n.asset});a.stderr&&process.stderr.write(a.stderr);let l=()=>process.exit(a.exit);a.stdout?process.stdout.write(a.stdout,l):l()}let i=await So({key:e,url:`${Vn()}/skills/${e}.md`,cliVersion:o,notFound:`no such operation "${e}" \u2014 run \`canary skills\` to list the operations`});if(i.ok){let s=hp(i.body);if(s&&o!=="0.0.0-dev"&&pp(o,s)<0){let a=`"${e}" needs Canary CLI ${s} or newer (you have ${o}). Update: ${lp}`,l=gt({ok:!1,error:a},r,{needsCli:s,cliVersion:o});Yt({...l,exit:2})}}Yt(gt(i,r,{name:e}))})}B();j();Be();var mp=3e3;function yp(t){let e=t.periodEnd?` \xB7 resets ${new Date(t.periodEnd).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`:"";return t.limit===null?`Runs this month: ${t.used} \xB7 no limit`:`Runs this month: ${t.used} of ${t.limit}${e}`}function ic(t){t.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async e=>{let n=e.json===!0,r=H();if(!r){n?console.log(JSON.stringify({ok:!1,error:"not_logged_in"})):console.error("Not logged in. Run `canary login`."),process.exitCode=1;return}try{let o=T().team,i=o?.id&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o.id)?o:void 0,s=await v(`/api/v1/cli/auth/whoami${i?`?workspaceId=${encodeURIComponent(i.id)}`:""}`,{token:r}),a=i?{id:i.id,name:i.name??s.team.name}:void 0,l=co(),c=l&&a?await An({token:r,apiUrl:W().replace(/\/+$/,""),userId:s.user.id},l,a.id,AbortSignal.timeout(mp)):void 0,u=so();if(n)console.log(JSON.stringify({ok:!0,user:s.user,team:s.team,workspace:a,...s.usage?{usage:s.usage}:{},...l?{repository:{name:l,...c?.state?{state:c.state}:{}}}:{},...u.length?{pushCheck:{pending:u}}:{}}));else{console.log(`${s.user.email} (${a?.name??"No workspace selected"})`),s.usage&&console.log(yp(s.usage)),l&&(console.log(Pn(l,c?.state)),console.log(Gt(c?.state)));for(let d of u)console.log(`Push check on ${d.label}: ${d.why} Run \`${d.command}\` in a terminal. ${d.after}`)}}catch(o){let i=o instanceof $&&o.status===401,s=i?"invalid_token":o instanceof Error?o.message:String(o);n?console.log(JSON.stringify({ok:!1,error:s})):console.error(i?"Your CLI session is no longer valid. Run `canary login`.":`Error: ${s}`),process.exitCode=1}})}B();j();X();async function cc(){let t=H();if(!t)throw new $(401,"not logged in");let{workspaces:e}=await v("/api/v1/cli/workspaces",{token:t});return e}function mt(t,e,n,r={}){t?console.log(JSON.stringify({ok:!1,error:e,message:n,...r})):console.error(n),process.exitCode=1}function sc(t,e){if(e instanceof $&&e.status===401){mt(t,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}mt(t,"workspace_error",e instanceof Error?e.message:String(e))}async function wp(t){let e=await cc(),n=T().team?.id;if(t){console.log(JSON.stringify({workspaces:e,active:n??null}));return}if(e.length===0){console.error("You're not a member of any workspace yet. Set one up at www.runcanary.ai first.");return}let r=String(e.length).length;e.forEach((o,i)=>{let s=o.id===n?"*":" ",a=String(i+1).padStart(r," ");console.log(`${s} ${a} ${o.name}`)})}function ac(t,e){if(!z(n=>({...n,team:{id:t.id,name:t.name}}))){mt(e,"config_unreadable","The CLI's config file exists but cannot be read, so the workspace was not saved. Repair or remove it, or run: canary login",{fix:"canary login"});return}gn(),console.log(e?JSON.stringify({ok:!0,workspace:{id:t.id,name:t.name}}):`Switched to ${t.name}.`)}async function bp(t,e){let n=await cc(),r=t.trim();if(/^\d+$/.test(r)){let i=Number(r);if(i<1||i>n.length){mt(e,"workspace_not_found",`No workspace #${i} \u2014 you have ${n.length}. Run: canary workspace list`,{available:n.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}ac(n[i-1],e);return}let o=n.filter(i=>i.id===r||i.name.toLowerCase()===r.toLowerCase());if(o.length===0){mt(e,"workspace_not_found",`No workspace matching "${t}".`,{available:n.map(i=>({id:i.id,name:i.name})),fix:"canary workspace list"});return}if(o.length>1){mt(e,"workspace_ambiguous",`"${t}" matches multiple workspaces \u2014 use the id.`,{matches:o.map(i=>({id:i.id,name:i.name})),fix:`canary workspace use ${o[0].id}`});return}ac(o[0],e)}function kp(t){let e=T().team;if(!e){t?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(t?JSON.stringify({workspace:e}):e.name)}function lc(t){let e=t.command("workspace").description("List and switch Canary workspaces");e.command("list").description("List the workspaces you belong to (the active one is marked with *)").option("--json","output machine-readable JSON").action(async n=>{let r=n.json===!0;try{await wp(r)}catch(o){sc(r,o)}}),e.command("use <workspace>").description("Set the active workspace (by number from `list`, name, or id)").option("--json","output machine-readable JSON").action(async(n,r)=>{let o=r.json===!0;try{await bp(n,o)}catch(i){sc(o,i)}}),e.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>kp(n.json===!0))}X();Xe();var Q=new Fo;Q.name("canary").description("Canary \u2014 break the code your AI writes.").version(ve);process.argv[2]!=="hook"&&ai();process.argv[2]!=="hook"&&$t();da(Q);ic(Q);Pa(Q);oc(Q);lc(Q);Qa(Q);Ws(Q);Ua(Q);ba(Q);wa(Q);ao(Q);Na(Q);Q.parseAsync(process.argv).catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
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
+ */