@automagik/genie 4.260331.16 → 4.260331.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/genie.js +5 -5
- package/openclaw.plugin.json +1 -1
- package/package.json +2 -1
- package/plugins/genie/.claude-plugin/plugin.json +1 -1
- package/plugins/genie/package.json +1 -1
- package/scripts/postinstall-tmux.js +123 -0
- package/scripts/smart-install.js +85 -17
- package/src/lib/agent-sync.ts +31 -1
- package/src/lib/db.ts +5 -2
- package/src/lib/ensure-tmux.ts +2 -4
- package/src/lib/test-db.ts +28 -12
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"plugins": [
|
|
11
11
|
{
|
|
12
12
|
"name": "genie",
|
|
13
|
-
"version": "4.260331.
|
|
13
|
+
"version": "4.260331.18",
|
|
14
14
|
"source": "./plugins/genie",
|
|
15
15
|
"description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project."
|
|
16
16
|
}
|
package/dist/genie.js
CHANGED
|
@@ -21,9 +21,9 @@ Expecting one of '${allowedValues.join("', '")}'`);if(this._lifeCycleHooks[event
|
|
|
21
21
|
`),this.outputHelp({error:!0});let config=errorOptions||{},exitCode=config.exitCode||1,code=config.code||"commander.error";this._exit(exitCode,code,message)}_parseOptionsEnv(){this.options.forEach((option)=>{if(option.envVar&&option.envVar in process2.env){let optionKey=option.attributeName();if(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))if(option.required||option.optional)this.emit(`optionEnv:${option.name()}`,process2.env[option.envVar]);else this.emit(`optionEnv:${option.name()}`)}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=(optionKey)=>{return this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey))};this.options.filter((option)=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach((option)=>{Object.keys(option.implied).filter((impliedKey)=>!hasCustomOptionValue(impliedKey)).forEach((impliedKey)=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=(option2)=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find((target)=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find((target)=>!target.negate&&optionKey===target.attributeName());if(negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg))return negativeOption;return positiveOption||option2},getErrorMessage=(option2)=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();if(this.getOptionValueSource(optionKey)==="env")return`environment variable '${bestOption.envVar}'`;return`option '${bestOption.flags}'`},message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag){if(this._allowUnknownOption)return;let suggestion="";if(flag.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter((option)=>option.long).map((option)=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag,candidateFlags)}let message=`error: unknown option '${flag}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach((command)=>{if(candidateNames.push(command.name()),command.alias())candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
|
|
22
22
|
`),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){if(str===void 0&&argsDescription===void 0)return this._description;if(this._description=str,argsDescription)this._argsDescription=argsDescription;return this}summary(str){if(str===void 0)return this._summary;return this._summary=str,this}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)command=this.commands[this.commands.length-1];if(alias===command._name)throw Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases){if(aliases===void 0)return this._aliases;return aliases.forEach((alias)=>this.alias(alias)),this}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map((arg)=>{return humanReadableArgName(arg)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){if(str===void 0)return this._name;return this._name=str,this}nameFromFilename(filename){return this._name=path.basename(filename,path.extname(filename)),this}executableDir(path2){if(path2===void 0)return this._executableDir;return this._executableDir=path2,this}helpInformation(contextOptions){let helper=this.createHelp();if(helper.helpWidth===void 0)helper.helpWidth=contextOptions&&contextOptions.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return helper.formatHelp(this,helper)}_getHelpContext(contextOptions){contextOptions=contextOptions||{};let context={error:!!contextOptions.error},write;if(context.error)write=(arg)=>this._outputConfiguration.writeErr(arg);else write=(arg)=>this._outputConfiguration.writeOut(arg);return context.write=contextOptions.write||write,context.command=this,context}outputHelp(contextOptions){let deprecatedCallback;if(typeof contextOptions==="function")deprecatedCallback=contextOptions,contextOptions=void 0;let context=this._getHelpContext(contextOptions);this._getCommandAndAncestors().reverse().forEach((command)=>command.emit("beforeAllHelp",context)),this.emit("beforeHelp",context);let helpInformation=this.helpInformation(context);if(deprecatedCallback){if(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!=="string"&&!Buffer.isBuffer(helpInformation))throw Error("outputHelp callback must return a string or a Buffer")}if(context.write(helpInformation),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",context),this._getCommandAndAncestors().forEach((command)=>command.emit("afterAllHelp",context))}helpOption(flags,description){if(typeof flags==="boolean"){if(flags)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=process2.exitCode||0;if(exitCode===0&&contextOptions&&typeof contextOptions!=="function"&&contextOptions.error)exitCode=1;this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw Error(`Unexpected value for position to addHelpText.
|
|
23
23
|
Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,(context)=>{let helpStr;if(typeof text==="function")helpStr=text({error:context.error,command:context.command});else helpStr=text;if(helpStr)context.write(`${helpStr}
|
|
24
|
-
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();if(helpOption&&args.find((arg)=>helpOption.is(arg)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function incrementNodeInspectorPort(args){return args.map((arg)=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;if((match=arg.match(/^(--inspect(-brk)?)$/))!==null)debugOption=match[1];else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(debugOption=match[1],/^\d+$/.test(match[3]))debugPort=match[3];else debugHost=match[3];else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)debugOption=match[1],debugHost=match[3],debugPort=match[4];if(debugOption&&debugPort!=="0")return`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`;return arg})}exports.Command=Command});var require_commander=__commonJS((exports)=>{var{Argument}=require_argument(),{Command}=require_command(),{CommanderError,InvalidArgumentError}=require_error(),{Help}=require_help(),{Option}=require_option();exports.program=new Command;exports.createCommand=(name)=>new Command(name);exports.createOption=(flags,description)=>new Option(flags,description);exports.createArgument=(name,description)=>new Argument(name,description);exports.Command=Command;exports.Option=Option;exports.Argument=Argument;exports.Help=Help;exports.CommanderError=CommanderError;exports.InvalidArgumentError=InvalidArgumentError;exports.InvalidOptionArgumentError=InvalidArgumentError});var exports_ensure_tmux={};__export(exports_ensure_tmux,{tmuxBin:()=>tmuxBin,ensureTmux:()=>ensureTmux});import{execSync}from"child_process";import{chmodSync,existsSync as existsSync2,mkdirSync,rmSync,unlinkSync as unlinkSync2,writeFileSync}from"fs";import{arch,homedir as homedir2,platform,tmpdir}from"os";import{join as join2}from"path";function getPlatformAsset(){let os=platform(),cpu=arch(),key=`${os}-${cpu}`,asset={"linux-x64":`tmux-${TMUX_VERSION}-linux-x86_64.tar.gz`,"linux-arm64":`tmux-${TMUX_VERSION}-linux-arm64.tar.gz`,"darwin-arm64":`tmux-${TMUX_VERSION}-macos-arm64.tar.gz`,"darwin-x64":`tmux-${TMUX_VERSION}-macos-x86_64.tar.gz`}[key];if(!asset)throw Error(`Unsupported platform: ${key}
|
|
24
|
+
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();if(helpOption&&args.find((arg)=>helpOption.is(arg)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function incrementNodeInspectorPort(args){return args.map((arg)=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;if((match=arg.match(/^(--inspect(-brk)?)$/))!==null)debugOption=match[1];else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(debugOption=match[1],/^\d+$/.test(match[3]))debugPort=match[3];else debugHost=match[3];else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)debugOption=match[1],debugHost=match[3],debugPort=match[4];if(debugOption&&debugPort!=="0")return`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`;return arg})}exports.Command=Command});var require_commander=__commonJS((exports)=>{var{Argument}=require_argument(),{Command}=require_command(),{CommanderError,InvalidArgumentError}=require_error(),{Help}=require_help(),{Option}=require_option();exports.program=new Command;exports.createCommand=(name)=>new Command(name);exports.createOption=(flags,description)=>new Option(flags,description);exports.createArgument=(name,description)=>new Argument(name,description);exports.Command=Command;exports.Option=Option;exports.Argument=Argument;exports.Help=Help;exports.CommanderError=CommanderError;exports.InvalidArgumentError=InvalidArgumentError;exports.InvalidOptionArgumentError=InvalidArgumentError});var exports_ensure_tmux={};__export(exports_ensure_tmux,{tmuxBin:()=>tmuxBin,ensureTmux:()=>ensureTmux});import{execSync}from"child_process";import{chmodSync,copyFileSync,existsSync as existsSync2,mkdirSync,rmSync,unlinkSync as unlinkSync2,writeFileSync}from"fs";import{arch,homedir as homedir2,platform,tmpdir}from"os";import{join as join2}from"path";function getPlatformAsset(){let os=platform(),cpu=arch(),key=`${os}-${cpu}`,asset={"linux-x64":`tmux-${TMUX_VERSION}-linux-x86_64.tar.gz`,"linux-arm64":`tmux-${TMUX_VERSION}-linux-arm64.tar.gz`,"darwin-arm64":`tmux-${TMUX_VERSION}-macos-arm64.tar.gz`,"darwin-x64":`tmux-${TMUX_VERSION}-macos-x86_64.tar.gz`}[key];if(!asset)throw Error(`Unsupported platform: ${key}
|
|
25
25
|
tmux auto-download supports: linux-x64, linux-arm64, macos-arm64, macos-x64.
|
|
26
|
-
Install tmux manually: https://github.com/tmux/tmux/wiki/Installing`);return asset}function genieHome(){return process.env.GENIE_HOME??join2(homedir2(),".genie")}function genieBinDir(){return join2(genieHome(),"bin")}function cachedTmuxPath(){return join2(genieBinDir(),"tmux")}function tmuxBin(){if(_resolved)return _resolved;try{let p=execSync("which tmux",{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim();if(p)return _resolved=p,p}catch{}let cached=cachedTmuxPath();if(existsSync2(cached))return _resolved=cached,cached;return"tmux"}async function ensureTmux(){let bin=tmuxBin();if(bin!=="tmux")return bin;return downloadTmux()}async function downloadTmux(){let asset=getPlatformAsset(),url=process.env.GENIE_TMUX_URL??`https://github.com/tmux/tmux-builds/releases/download/v${TMUX_VERSION}/${asset}`,dest=cachedTmuxPath(),tempDir=join2(tmpdir(),`genie-tmux-download-${Date.now()}`);console.log(" tmux not found \u2014 downloading static binary..."),console.log(` ${url}`);try{let response=await fetch(url);if(!response.ok)throw Error(`HTTP ${response.status} ${response.statusText}`);let buffer=Buffer.from(await response.arrayBuffer()),sizeMB=(buffer.byteLength/1024/1024).toFixed(1);console.log(` Downloaded ${sizeMB} MB`),mkdirSync(tempDir,{recursive:!0});let tarballPath=join2(tempDir,asset);writeFileSync(tarballPath,buffer),execSync(`tar -xzf '${tarballPath}' -C '${tempDir}'`,{stdio:"ignore"});let extractedBin=join2(tempDir,"tmux");if(!existsSync2(extractedBin))throw Error("Tarball did not contain a tmux binary");mkdirSync(genieBinDir(),{recursive:!0})
|
|
26
|
+
Install tmux manually: https://github.com/tmux/tmux/wiki/Installing`);return asset}function genieHome(){return process.env.GENIE_HOME??join2(homedir2(),".genie")}function genieBinDir(){return join2(genieHome(),"bin")}function cachedTmuxPath(){return join2(genieBinDir(),"tmux")}function tmuxBin(){if(_resolved)return _resolved;try{let p=execSync("which tmux",{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim();if(p)return _resolved=p,p}catch{}let cached=cachedTmuxPath();if(existsSync2(cached))return _resolved=cached,cached;return"tmux"}async function ensureTmux(){let bin=tmuxBin();if(bin!=="tmux")return bin;return downloadTmux()}async function downloadTmux(){let asset=getPlatformAsset(),url=process.env.GENIE_TMUX_URL??`https://github.com/tmux/tmux-builds/releases/download/v${TMUX_VERSION}/${asset}`,dest=cachedTmuxPath(),tempDir=join2(tmpdir(),`genie-tmux-download-${Date.now()}`);console.log(" tmux not found \u2014 downloading static binary..."),console.log(` ${url}`);try{let response=await fetch(url);if(!response.ok)throw Error(`HTTP ${response.status} ${response.statusText}`);let buffer=Buffer.from(await response.arrayBuffer()),sizeMB=(buffer.byteLength/1024/1024).toFixed(1);console.log(` Downloaded ${sizeMB} MB`),mkdirSync(tempDir,{recursive:!0});let tarballPath=join2(tempDir,asset);writeFileSync(tarballPath,buffer),execSync(`tar -xzf '${tarballPath}' -C '${tempDir}'`,{stdio:"ignore"});let extractedBin=join2(tempDir,"tmux");if(!existsSync2(extractedBin))throw Error("Tarball did not contain a tmux binary");mkdirSync(genieBinDir(),{recursive:!0}),copyFileSync(extractedBin,dest),chmodSync(dest,493);let version=execSync(`'${dest}' -V`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim();return _resolved=dest,console.log(` ${version} installed to ${dest}`),dest}catch(err){try{if(existsSync2(dest))unlinkSync2(dest)}catch{}let msg=err instanceof Error?err.message:String(err);throw Error(`Failed to download tmux: ${msg}
|
|
27
27
|
Install manually:
|
|
28
28
|
Linux: sudo apt install tmux
|
|
29
29
|
macOS: brew install tmux`)}finally{try{rmSync(tempDir,{recursive:!0,force:!0})}catch{}}}var TMUX_VERSION="3.6a",_resolved=null;var init_ensure_tmux=()=>{};var util,objectUtil,ZodParsedType,getParsedType=(data)=>{switch(typeof data){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(data)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":if(Array.isArray(data))return ZodParsedType.array;if(data===null)return ZodParsedType.null;if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return ZodParsedType.promise;if(typeof Map<"u"&&data instanceof Map)return ZodParsedType.map;if(typeof Set<"u"&&data instanceof Set)return ZodParsedType.set;if(typeof Date<"u"&&data instanceof Date)return ZodParsedType.date;return ZodParsedType.object;default:return ZodParsedType.unknown}};var init_util=__esm(()=>{(function(util2){util2.assertEqual=(_)=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever(_x){throw Error()}util2.assertNever=assertNever,util2.arrayToEnum=(items)=>{let obj={};for(let item of items)obj[item]=item;return obj},util2.getValidEnumValues=(obj)=>{let validKeys=util2.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number"),filtered={};for(let k of validKeys)filtered[k]=obj[k];return util2.objectValues(filtered)},util2.objectValues=(obj)=>{return util2.objectKeys(obj).map(function(e){return obj[e]})},util2.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object)=>{let keys=[];for(let key in object)if(Object.prototype.hasOwnProperty.call(object,key))keys.push(key);return keys},util2.find=(arr,checker)=>{for(let item of arr)if(checker(item))return item;return},util2.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues,util2.jsonStringifyReplacer=(_,value)=>{if(typeof value==="bigint")return value.toString();return value}})(util||(util={}));(function(objectUtil2){objectUtil2.mergeShapes=(first,second)=>{return{...first,...second}}})(objectUtil||(objectUtil={}));ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var ZodIssueCode,quotelessJson=(obj)=>{return JSON.stringify(obj,null,2).replace(/"([^"]+)":/g,"$1:")},ZodError;var init_ZodError=__esm(()=>{init_util();ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);ZodError=class ZodError extends Error{get errors(){return this.issues}constructor(issues){super();this.issues=[],this.addIssue=(sub)=>{this.issues=[...this.issues,sub]},this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};let actualProto=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,actualProto);else this.__proto__=actualProto;this.name="ZodError",this.issues=issues}format(_mapper){let mapper=_mapper||function(issue){return issue.message},fieldErrors={_errors:[]},processError=(error)=>{for(let issue of error.issues)if(issue.code==="invalid_union")issue.unionErrors.map(processError);else if(issue.code==="invalid_return_type")processError(issue.returnTypeError);else if(issue.code==="invalid_arguments")processError(issue.argumentsError);else if(issue.path.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;while(i<issue.path.length){let el=issue.path[i];if(i!==issue.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue));curr=curr[el],i++}}};return processError(this),fieldErrors}static assert(value){if(!(value instanceof ZodError))throw Error(`Not a ZodError: ${value}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=(issue)=>issue.message){let fieldErrors={},formErrors=[];for(let sub of this.issues)if(sub.path.length>0){let firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[],fieldErrors[firstEl].push(mapper(sub))}else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}};ZodError.create=(issues)=>{return new ZodError(issues)}});var errorMap=(issue,_ctx)=>{let message;switch(issue.code){case ZodIssueCode.invalid_type:if(issue.received===ZodParsedType.undefined)message="Required";else message=`Expected ${issue.expected}, received ${issue.received}`;break;case ZodIssueCode.invalid_literal:message=`Invalid literal value, expected ${JSON.stringify(issue.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:message=`Unrecognized key(s) in object: ${util.joinValues(issue.keys,", ")}`;break;case ZodIssueCode.invalid_union:message="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:message=`Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;break;case ZodIssueCode.invalid_enum_value:message=`Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;break;case ZodIssueCode.invalid_arguments:message="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:message="Invalid function return type";break;case ZodIssueCode.invalid_date:message="Invalid date";break;case ZodIssueCode.invalid_string:if(typeof issue.validation==="object")if("includes"in issue.validation){if(message=`Invalid input: must include "${issue.validation.includes}"`,typeof issue.validation.position==="number")message=`${message} at one or more positions greater than or equal to ${issue.validation.position}`}else if("startsWith"in issue.validation)message=`Invalid input: must start with "${issue.validation.startsWith}"`;else if("endsWith"in issue.validation)message=`Invalid input: must end with "${issue.validation.endsWith}"`;else util.assertNever(issue.validation);else if(issue.validation!=="regex")message=`Invalid ${issue.validation}`;else message="Invalid";break;case ZodIssueCode.too_small:if(issue.type==="array")message=`Array must contain ${issue.exact?"exactly":issue.inclusive?"at least":"more than"} ${issue.minimum} element(s)`;else if(issue.type==="string")message=`String must contain ${issue.exact?"exactly":issue.inclusive?"at least":"over"} ${issue.minimum} character(s)`;else if(issue.type==="number")message=`Number must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${issue.minimum}`;else if(issue.type==="bigint")message=`Number must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${issue.minimum}`;else if(issue.type==="date")message=`Date must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(issue.minimum))}`;else message="Invalid input";break;case ZodIssueCode.too_big:if(issue.type==="array")message=`Array must contain ${issue.exact?"exactly":issue.inclusive?"at most":"less than"} ${issue.maximum} element(s)`;else if(issue.type==="string")message=`String must contain ${issue.exact?"exactly":issue.inclusive?"at most":"under"} ${issue.maximum} character(s)`;else if(issue.type==="number")message=`Number must be ${issue.exact?"exactly":issue.inclusive?"less than or equal to":"less than"} ${issue.maximum}`;else if(issue.type==="bigint")message=`BigInt must be ${issue.exact?"exactly":issue.inclusive?"less than or equal to":"less than"} ${issue.maximum}`;else if(issue.type==="date")message=`Date must be ${issue.exact?"exactly":issue.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(issue.maximum))}`;else message="Invalid input";break;case ZodIssueCode.custom:message="Invalid input";break;case ZodIssueCode.invalid_intersection_types:message="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:message=`Number must be a multiple of ${issue.multipleOf}`;break;case ZodIssueCode.not_finite:message="Number must be finite";break;default:message=_ctx.defaultError,util.assertNever(issue)}return{message}},en_default;var init_en=__esm(()=>{init_ZodError();init_util();en_default=errorMap});function setErrorMap(map){overrideErrorMap=map}function getErrorMap(){return overrideErrorMap}var overrideErrorMap;var init_errors=__esm(()=>{init_en();overrideErrorMap=en_default});function addIssueToContext(ctx,issueData){let overrideMap=getErrorMap(),issue=makeIssue({issueData,data:ctx.data,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,overrideMap,overrideMap===en_default?void 0:en_default].filter((x)=>!!x)});ctx.common.issues.push(issue)}class ParseStatus{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(status,results){let arrayValue=[];for(let s of results){if(s.status==="aborted")return INVALID;if(s.status==="dirty")status.dirty();arrayValue.push(s.value)}return{status:status.value,value:arrayValue}}static async mergeObjectAsync(status,pairs){let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value})}return ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){let finalObject={};for(let pair of pairs){let{key,value}=pair;if(key.status==="aborted")return INVALID;if(value.status==="aborted")return INVALID;if(key.status==="dirty")status.dirty();if(value.status==="dirty")status.dirty();if(key.value!=="__proto__"&&(typeof value.value<"u"||pair.alwaysSet))finalObject[key.value]=value.value}return{status:status.value,value:finalObject}}}var makeIssue=(params)=>{let{data,path,errorMaps,issueData}=params,fullPath=[...path,...issueData.path||[]],fullIssue={...issueData,path:fullPath};if(issueData.message!==void 0)return{...issueData,path:fullPath,message:issueData.message};let errorMessage="",maps=errorMaps.filter((m)=>!!m).slice().reverse();for(let map of maps)errorMessage=map(fullIssue,{data,defaultError:errorMessage}).message;return{...issueData,path:fullPath,message:errorMessage}},EMPTY_PATH,INVALID,DIRTY=(value)=>({status:"dirty",value}),OK=(value)=>({status:"valid",value}),isAborted=(x)=>x.status==="aborted",isDirty=(x)=>x.status==="dirty",isValid=(x)=>x.status==="valid",isAsync=(x)=>typeof Promise<"u"&&x instanceof Promise;var init_parseUtil=__esm(()=>{init_errors();init_en();EMPTY_PATH=[];INVALID=Object.freeze({status:"aborted"})});var init_typeAliases=()=>{};var errorUtil;var init_errorUtil=__esm(()=>{(function(errorUtil2){errorUtil2.errToObj=(message)=>typeof message==="string"?{message}:message||{},errorUtil2.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}))});class ParseInputLazyPath{constructor(parent,value,path,key){this._cachedPath=[],this.parent=parent,this.data=value,this._path=path,this._key=key}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function processCreateParams(params){if(!params)return{};let{errorMap:errorMap2,invalid_type_error,required_error,description}=params;if(errorMap2&&(invalid_type_error||required_error))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(errorMap2)return{errorMap:errorMap2,description};return{errorMap:(iss,ctx)=>{let{message}=params;if(iss.code==="invalid_enum_value")return{message:message??ctx.defaultError};if(typeof ctx.data>"u")return{message:message??required_error??ctx.defaultError};if(iss.code!=="invalid_type")return{message:ctx.defaultError};return{message:message??invalid_type_error??ctx.defaultError}},description}}class ZodType{get description(){return this._def.description}_getType(input){return getParsedType(input.data)}_getOrReturnCtx(input,ctx){return ctx||{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}_processInputParams(input){return{status:new ParseStatus,ctx:{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}}_parseSync(input){let result=this._parse(input);if(isAsync(result))throw Error("Synchronous parse encountered promise.");return result}_parseAsync(input){let result=this._parse(input);return Promise.resolve(result)}parse(data,params){let result=this.safeParse(data,params);if(result.success)return result.data;throw result.error}safeParse(data,params){let ctx={common:{issues:[],async:params?.async??!1,contextualErrorMap:params?.errorMap},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)},result=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result)}"~validate"(data){let ctx={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};if(!this["~standard"].async)try{let result=this._parseSync({data,path:[],parent:ctx});return isValid(result)?{value:result.value}:{issues:ctx.common.issues}}catch(err){if(err?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;ctx.common={issues:[],async:!0}}return this._parseAsync({data,path:[],parent:ctx}).then((result)=>isValid(result)?{value:result.value}:{issues:ctx.common.issues})}async parseAsync(data,params){let result=await this.safeParseAsync(data,params);if(result.success)return result.data;throw result.error}async safeParseAsync(data,params){let ctx={common:{issues:[],contextualErrorMap:params?.errorMap,async:!0},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)},maybeAsyncResult=this._parse({data,path:ctx.path,parent:ctx}),result=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result)}refine(check,message){let getIssueProperties=(val)=>{if(typeof message==="string"||typeof message>"u")return{message};else if(typeof message==="function")return message(val);else return message};return this._refinement((val,ctx)=>{let result=check(val),setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});if(typeof Promise<"u"&&result instanceof Promise)return result.then((data)=>{if(!data)return setError(),!1;else return!0});if(!result)return setError(),!1;else return!0})}refinement(check,refinementData){return this._refinement((val,ctx)=>{if(!check(val))return ctx.addIssue(typeof refinementData==="function"?refinementData(val,ctx):refinementData),!1;else return!0})}_refinement(refinement){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement}})}superRefine(refinement){return this._refinement(refinement)}constructor(def){this.spa=this.safeParseAsync,this._def=def,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(data)=>this["~validate"](data)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(option){return ZodUnion.create([this,option],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform}})}default(def){let defaultValueFunc=typeof def==="function"?def:()=>def;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:defaultValueFunc,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(def){let catchValueFunc=typeof def==="function"?def:()=>def;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:catchValueFunc,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(description){return new this.constructor({...this._def,description})}pipe(target){return ZodPipeline.create(this,target)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function timeRegexSource(args){let secondsRegexSource="[0-5]\\d";if(args.precision)secondsRegexSource=`${secondsRegexSource}\\.\\d{${args.precision}}`;else if(args.precision==null)secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`;let secondsQuantifier=args.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args){return new RegExp(`^${timeRegexSource(args)}$`)}function datetimeRegex(args){let regex=`${dateRegexSource}T${timeRegexSource(args)}`,opts=[];if(opts.push(args.local?"Z?":"Z"),args.offset)opts.push("([+-]\\d{2}:?\\d{2})");return regex=`${regex}(${opts.join("|")})`,new RegExp(`^${regex}$`)}function isValidIP(ip,version){if((version==="v4"||!version)&&ipv4Regex.test(ip))return!0;if((version==="v6"||!version)&&ipv6Regex.test(ip))return!0;return!1}function isValidJWT(jwt,alg){if(!jwtRegex.test(jwt))return!1;try{let[header]=jwt.split(".");if(!header)return!1;let base64=header.replace(/-/g,"+").replace(/_/g,"/").padEnd(header.length+(4-header.length%4)%4,"="),decoded=JSON.parse(atob(base64));if(typeof decoded!=="object"||decoded===null)return!1;if("typ"in decoded&&decoded?.typ!=="JWT")return!1;if(!decoded.alg)return!1;if(alg&&decoded.alg!==alg)return!1;return!0}catch{return!1}}function isValidCidr(ip,version){if((version==="v4"||!version)&&ipv4CidrRegex.test(ip))return!0;if((version==="v6"||!version)&&ipv6CidrRegex.test(ip))return!0;return!1}function floatSafeRemainder(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepDecCount=(step.toString().split(".")[1]||"").length,decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}function deepPartialify(schema){if(schema instanceof ZodObject){let newShape={};for(let key in schema.shape){let fieldSchema=schema.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema._def,shape:()=>newShape})}else if(schema instanceof ZodArray)return new ZodArray({...schema._def,type:deepPartialify(schema.element)});else if(schema instanceof ZodOptional)return ZodOptional.create(deepPartialify(schema.unwrap()));else if(schema instanceof ZodNullable)return ZodNullable.create(deepPartialify(schema.unwrap()));else if(schema instanceof ZodTuple)return ZodTuple.create(schema.items.map((item)=>deepPartialify(item)));else return schema}function mergeValues(a,b){let aType=getParsedType(a),bType=getParsedType(b);if(a===b)return{valid:!0,data:a};else if(aType===ZodParsedType.object&&bType===ZodParsedType.object){let bKeys=util.objectKeys(b),sharedKeys=util.objectKeys(a).filter((key)=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}else if(aType===ZodParsedType.array&&bType===ZodParsedType.array){if(a.length!==b.length)return{valid:!1};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}else if(aType===ZodParsedType.date&&bType===ZodParsedType.date&&+a===+b)return{valid:!0,data:a};else return{valid:!1}}function createZodEnum(values,params){return new ZodEnum({values,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(params)})}function cleanParams(params,data){let p=typeof params==="function"?params(data):typeof params==="string"?{message:params}:params;return typeof p==="string"?{message:p}:p}function custom(check,_params={},fatal){if(check)return ZodAny.create().superRefine((data,ctx)=>{let r=check(data);if(r instanceof Promise)return r.then((r2)=>{if(!r2){let params=cleanParams(_params,data),_fatal=params.fatal??fatal??!0;ctx.addIssue({code:"custom",...params,fatal:_fatal})}});if(!r){let params=cleanParams(_params,data),_fatal=params.fatal??fatal??!0;ctx.addIssue({code:"custom",...params,fatal:_fatal})}return});return ZodAny.create()}var handleResult=(ctx,result)=>{if(isValid(result))return{success:!0,data:result.value};else{if(!ctx.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let error=new ZodError(ctx.common.issues);return this._error=error,this._error}}}},cuidRegex,cuid2Regex,ulidRegex,uuidRegex,nanoidRegex,jwtRegex,durationRegex,emailRegex,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",emojiRegex,ipv4Regex,ipv4CidrRegex,ipv6Regex,ipv6CidrRegex,base64Regex,base64urlRegex,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex,ZodString,ZodNumber,ZodBigInt,ZodBoolean,ZodDate,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodArray,ZodObject,ZodUnion,getDiscriminator=(type)=>{if(type instanceof ZodLazy)return getDiscriminator(type.schema);else if(type instanceof ZodEffects)return getDiscriminator(type.innerType());else if(type instanceof ZodLiteral)return[type.value];else if(type instanceof ZodEnum)return type.options;else if(type instanceof ZodNativeEnum)return util.objectValues(type.enum);else if(type instanceof ZodDefault)return getDiscriminator(type._def.innerType);else if(type instanceof ZodUndefined)return[void 0];else if(type instanceof ZodNull)return[null];else if(type instanceof ZodOptional)return[void 0,...getDiscriminator(type.unwrap())];else if(type instanceof ZodNullable)return[null,...getDiscriminator(type.unwrap())];else if(type instanceof ZodBranded)return getDiscriminator(type.unwrap());else if(type instanceof ZodReadonly)return getDiscriminator(type.unwrap());else if(type instanceof ZodCatch)return getDiscriminator(type._def.innerType);else return[]},ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodFunction,ZodLazy,ZodLiteral,ZodEnum,ZodNativeEnum,ZodPromise,ZodEffects,ZodOptional,ZodNullable,ZodDefault,ZodCatch,ZodNaN,BRAND,ZodBranded,ZodPipeline,ZodReadonly,late,ZodFirstPartyTypeKind,instanceOfType=(cls,params={message:`Input not instance of ${cls.name}`})=>custom((data)=>data instanceof cls,params),stringType,numberType,nanType,bigIntType,booleanType,dateType,symbolType,undefinedType,nullType,anyType,unknownType,neverType,voidType,arrayType,objectType,strictObjectType,unionType,discriminatedUnionType,intersectionType,tupleType,recordType,mapType,setType,functionType,lazyType,literalType,enumType,nativeEnumType,promiseType,effectsType,optionalType,nullableType,preprocessType,pipelineType,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce,NEVER;var init_types=__esm(()=>{init_ZodError();init_errors();init_errorUtil();init_parseUtil();init_util();cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegex=new RegExp(`^${dateRegexSource}$`);ZodString=class ZodString extends ZodType{_parse(input){if(this._def.coerce)input.data=String(input.data);if(this._getType(input)!==ZodParsedType.string){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType}),INVALID}let status=new ParseStatus,ctx=void 0;for(let check of this._def.checks)if(check.kind==="min"){if(input.data.length<check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="max"){if(input.data.length>check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="length"){let tooBig=input.data.length>check.value,tooSmall=input.data.length<check.value;if(tooBig||tooSmall){if(ctx=this._getOrReturnCtx(input,ctx),tooBig)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message});else if(tooSmall)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message});status.dirty()}}else if(check.kind==="email"){if(!emailRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="emoji"){if(!emojiRegex)emojiRegex=new RegExp(_emojiRegex,"u");if(!emojiRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="uuid"){if(!uuidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="nanoid"){if(!nanoidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cuid"){if(!cuidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cuid2"){if(!cuid2Regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="ulid"){if(!ulidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="url")try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="regex"){if(check.regex.lastIndex=0,!check.regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="trim")input.data=input.data.trim();else if(check.kind==="includes"){if(!input.data.includes(check.value,check.position))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message}),status.dirty()}else if(check.kind==="toLowerCase")input.data=input.data.toLowerCase();else if(check.kind==="toUpperCase")input.data=input.data.toUpperCase();else if(check.kind==="startsWith"){if(!input.data.startsWith(check.value))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message}),status.dirty()}else if(check.kind==="endsWith"){if(!input.data.endsWith(check.value))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message}),status.dirty()}else if(check.kind==="datetime"){if(!datetimeRegex(check).test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message}),status.dirty()}else if(check.kind==="date"){if(!dateRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message}),status.dirty()}else if(check.kind==="time"){if(!timeRegex(check).test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message}),status.dirty()}else if(check.kind==="duration"){if(!durationRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="ip"){if(!isValidIP(input.data,check.version))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="jwt"){if(!isValidJWT(input.data,check.alg))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cidr"){if(!isValidCidr(input.data,check.version))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="base64"){if(!base64Regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="base64url"){if(!base64urlRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement((data)=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new ZodString({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options)})}ip(options){return this._addCheck({kind:"ip",...errorUtil.errToObj(options)})}cidr(options){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options)})}datetime(options){if(typeof options==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:options});return this._addCheck({kind:"datetime",precision:typeof options?.precision>"u"?null:options?.precision,offset:options?.offset??!1,local:options?.local??!1,...errorUtil.errToObj(options?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options){if(typeof options==="string")return this._addCheck({kind:"time",precision:null,message:options});return this._addCheck({kind:"time",precision:typeof options?.precision>"u"?null:options?.precision,...errorUtil.errToObj(options?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options){return this._addCheck({kind:"includes",value,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((ch)=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find((ch)=>ch.kind==="date")}get isTime(){return!!this._def.checks.find((ch)=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find((ch)=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find((ch)=>ch.kind==="email")}get isURL(){return!!this._def.checks.find((ch)=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find((ch)=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find((ch)=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((ch)=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((ch)=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((ch)=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find((ch)=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find((ch)=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find((ch)=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find((ch)=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find((ch)=>ch.kind==="base64url")}get minLength(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxLength(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}};ZodString.create=(params)=>{return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??!1,...processCreateParams(params)})};ZodNumber=class ZodNumber extends ZodType{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(input){if(this._def.coerce)input.data=Number(input.data);if(this._getType(input)!==ZodParsedType.number){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType}),INVALID}let ctx=void 0,status=new ParseStatus;for(let check of this._def.checks)if(check.kind==="int"){if(!util.isInteger(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message}),status.dirty()}else if(check.kind==="min"){if(check.inclusive?input.data<check.value:input.data<=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="max"){if(check.inclusive?input.data>check.value:input.data>=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="multipleOf"){if(floatSafeRemainder(input.data,check.value)!==0)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()}else if(check.kind==="finite"){if(!Number.isFinite(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodNumber({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxValue(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}get isInt(){return!!this._def.checks.find((ch)=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null,min=null;for(let ch of this._def.checks)if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf")return!0;else if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}else if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return Number.isFinite(min)&&Number.isFinite(max)}};ZodNumber.create=(params)=>{return new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||!1,...processCreateParams(params)})};ZodBigInt=class ZodBigInt extends ZodType{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(input){if(this._def.coerce)try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}if(this._getType(input)!==ZodParsedType.bigint)return this._getInvalidInput(input);let ctx=void 0,status=new ParseStatus;for(let check of this._def.checks)if(check.kind==="min"){if(check.inclusive?input.data<check.value:input.data<=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()}else if(check.kind==="max"){if(check.inclusive?input.data>check.value:input.data>=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()}else if(check.kind==="multipleOf"){if(input.data%check.value!==BigInt(0))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}_getInvalidInput(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType}),INVALID}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodBigInt({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxValue(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}};ZodBigInt.create=(params)=>{return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??!1,...processCreateParams(params)})};ZodBoolean=class ZodBoolean extends ZodType{_parse(input){if(this._def.coerce)input.data=Boolean(input.data);if(this._getType(input)!==ZodParsedType.boolean){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodBoolean.create=(params)=>{return new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||!1,...processCreateParams(params)})};ZodDate=class ZodDate extends ZodType{_parse(input){if(this._def.coerce)input.data=new Date(input.data);if(this._getType(input)!==ZodParsedType.date){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType}),INVALID}if(Number.isNaN(input.data.getTime())){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date}),INVALID}let status=new ParseStatus,ctx=void 0;for(let check of this._def.checks)if(check.kind==="min"){if(input.data.getTime()<check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:!0,exact:!1,minimum:check.value,type:"date"}),status.dirty()}else if(check.kind==="max"){if(input.data.getTime()>check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:!0,exact:!1,maximum:check.value,type:"date"}),status.dirty()}else util.assertNever(check);return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new ZodDate({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min!=null?new Date(min):null}get maxDate(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max!=null?new Date(max):null}};ZodDate.create=(params)=>{return new ZodDate({checks:[],coerce:params?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)})};ZodSymbol=class ZodSymbol extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.symbol){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodSymbol.create=(params)=>{return new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)})};ZodUndefined=class ZodUndefined extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodUndefined.create=(params)=>{return new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)})};ZodNull=class ZodNull extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.null){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodNull.create=(params)=>{return new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)})};ZodAny=class ZodAny extends ZodType{constructor(){super(...arguments);this._any=!0}_parse(input){return OK(input.data)}};ZodAny.create=(params)=>{return new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)})};ZodUnknown=class ZodUnknown extends ZodType{constructor(){super(...arguments);this._unknown=!0}_parse(input){return OK(input.data)}};ZodUnknown.create=(params)=>{return new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)})};ZodNever=class ZodNever extends ZodType{_parse(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType}),INVALID}};ZodNever.create=(params)=>{return new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)})};ZodVoid=class ZodVoid extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodVoid.create=(params)=>{return new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)})};ZodArray=class ZodArray extends ZodType{_parse(input){let{ctx,status}=this._processInputParams(input),def=this._def;if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(def.exactLength!==null){let tooBig=ctx.data.length>def.exactLength.value,tooSmall=ctx.data.length<def.exactLength.value;if(tooBig||tooSmall)addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:void 0,maximum:tooBig?def.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:def.exactLength.message}),status.dirty()}if(def.minLength!==null){if(ctx.data.length<def.minLength.value)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:!0,exact:!1,message:def.minLength.message}),status.dirty()}if(def.maxLength!==null){if(ctx.data.length>def.maxLength.value)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:!0,exact:!1,message:def.maxLength.message}),status.dirty()}if(ctx.common.async)return Promise.all([...ctx.data].map((item,i)=>{return def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i))})).then((result2)=>{return ParseStatus.mergeArray(status,result2)});let result=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new ZodArray({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new ZodArray({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new ZodArray({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}};ZodArray.create=(schema,params)=>{return new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})};ZodObject=class ZodObject extends ZodType{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let shape=this._def.shape(),keys=util.objectKeys(shape);return this._cached={shape,keys},this._cached}_parse(input){if(this._getType(input)!==ZodParsedType.object){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.parsedType}),INVALID}let{status,ctx}=this._processInputParams(input),{shape,keys:shapeKeys}=this._getCached(),extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip")){for(let key in ctx.data)if(!shapeKeys.includes(key))extraKeys.push(key)}let pairs=[];for(let key of shapeKeys){let keyValidator=shape[key],value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){let unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough")for(let key of extraKeys)pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}});else if(unknownKeys==="strict"){if(extraKeys.length>0)addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys}),status.dirty()}else if(unknownKeys==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let catchall=this._def.catchall;for(let key of extraKeys){let value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}if(ctx.common.async)return Promise.resolve().then(async()=>{let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then((syncPairs)=>{return ParseStatus.mergeObjectSync(status,syncPairs)});else return ParseStatus.mergeObjectSync(status,pairs)}get shape(){return this._def.shape()}strict(message){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...message!==void 0?{errorMap:(issue,ctx)=>{let defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;if(issue.code==="unrecognized_keys")return{message:errorUtil.errToObj(message).message??defaultError};return{message:defaultError}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){return new ZodObject({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new ZodObject({...this._def,catchall:index})}pick(mask){let shape={};for(let key of util.objectKeys(mask))if(mask[key]&&this.shape[key])shape[key]=this.shape[key];return new ZodObject({...this._def,shape:()=>shape})}omit(mask){let shape={};for(let key of util.objectKeys(this.shape))if(!mask[key])shape[key]=this.shape[key];return new ZodObject({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){let newShape={};for(let key of util.objectKeys(this.shape)){let fieldSchema=this.shape[key];if(mask&&!mask[key])newShape[key]=fieldSchema;else newShape[key]=fieldSchema.optional()}return new ZodObject({...this._def,shape:()=>newShape})}required(mask){let newShape={};for(let key of util.objectKeys(this.shape))if(mask&&!mask[key])newShape[key]=this.shape[key];else{let newField=this.shape[key];while(newField instanceof ZodOptional)newField=newField._def.innerType;newShape[key]=newField}return new ZodObject({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodObject.strictCreate=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodObject.lazycreate=(shape,params)=>{return new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodUnion=class ZodUnion extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),options=this._def.options;function handleResults(results){for(let result of results)if(result.result.status==="valid")return result.result;for(let result of results)if(result.result.status==="dirty")return ctx.common.issues.push(...result.ctx.common.issues),result.result;let unionErrors=results.map((result)=>new ZodError(result.ctx.common.issues));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}if(ctx.common.async)return Promise.all(options.map(async(option)=>{let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults);else{let dirty=void 0,issues=[];for(let option of options){let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null},result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid")return result;else if(result.status==="dirty"&&!dirty)dirty={result,ctx:childCtx};if(childCtx.common.issues.length)issues.push(childCtx.common.issues)}if(dirty)return ctx.common.issues.push(...dirty.ctx.common.issues),dirty.result;let unionErrors=issues.map((issues2)=>new ZodError(issues2));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(types,params)=>{return new ZodUnion({options:types,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)})};ZodDiscriminatedUnion=class ZodDiscriminatedUnion extends ZodType{_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let discriminator=this.discriminator,discriminatorValue=ctx.data[discriminator],option=this.optionsMap.get(discriminatorValue);if(!option)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]}),INVALID;if(ctx.common.async)return option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});else return option._parseSync({data:ctx.data,path:ctx.path,parent:ctx})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options,params){let optionsMap=new Map;for(let type of options){let discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length)throw Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);for(let value of discriminatorValues){if(optionsMap.has(value))throw Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);optionsMap.set(value,type)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options,optionsMap,...processCreateParams(params)})}};ZodIntersection=class ZodIntersection extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input),handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight))return INVALID;let merged=mergeValues(parsedLeft.value,parsedRight.value);if(!merged.valid)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types}),INVALID;if(isDirty(parsedLeft)||isDirty(parsedRight))status.dirty();return{status:status.value,value:merged.data}};if(ctx.common.async)return Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right));else return handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}};ZodIntersection.create=(left,right,params)=>{return new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)})};ZodTuple=class ZodTuple extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(ctx.data.length<this._def.items.length)return addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;if(!this._def.rest&&ctx.data.length>this._def.items.length)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),status.dirty();let items=[...ctx.data].map((item,itemIndex)=>{let schema=this._def.items[itemIndex]||this._def.rest;if(!schema)return null;return schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async)return Promise.all(items).then((results)=>{return ParseStatus.mergeArray(status,results)});else return ParseStatus.mergeArray(status,items)}get items(){return this._def.items}rest(rest){return new ZodTuple({...this._def,rest})}};ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})};ZodRecord=class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let pairs=[],keyType=this._def.keyType,valueType=this._def.valueType;for(let key in ctx.data)pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data});if(ctx.common.async)return ParseStatus.mergeObjectAsync(status,pairs);else return ParseStatus.mergeObjectSync(status,pairs)}get element(){return this._def.valueType}static create(first,second,third){if(second instanceof ZodType)return new ZodRecord({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)});return new ZodRecord({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}};ZodMap=class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType}),INVALID;let keyType=this._def.keyType,valueType=this._def.valueType,pairs=[...ctx.data.entries()].map(([key,value],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}});if(ctx.common.async){let finalMap=new Map;return Promise.resolve().then(async()=>{for(let pair of pairs){let key=await pair.key,value=await pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;if(key.status==="dirty"||value.status==="dirty")status.dirty();finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{let finalMap=new Map;for(let pair of pairs){let{key,value}=pair;if(key.status==="aborted"||value.status==="aborted")return INVALID;if(key.status==="dirty"||value.status==="dirty")status.dirty();finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}};ZodMap.create=(keyType,valueType,params)=>{return new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)})};ZodSet=class ZodSet extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType}),INVALID;let def=this._def;if(def.minSize!==null){if(ctx.data.size<def.minSize.value)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:!0,exact:!1,message:def.minSize.message}),status.dirty()}if(def.maxSize!==null){if(ctx.data.size>def.maxSize.value)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:!0,exact:!1,message:def.maxSize.message}),status.dirty()}let valueType=this._def.valueType;function finalizeSet(elements2){let parsedSet=new Set;for(let element of elements2){if(element.status==="aborted")return INVALID;if(element.status==="dirty")status.dirty();parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}let elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));if(ctx.common.async)return Promise.all(elements).then((elements2)=>finalizeSet(elements2));else return finalizeSet(elements)}min(minSize,message){return new ZodSet({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new ZodSet({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}};ZodSet.create=(valueType,params)=>{return new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)})};ZodFunction=class ZodFunction extends ZodType{constructor(){super(...arguments);this.validate=this.implement}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType}),INVALID;function makeArgsIssue(args,error){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error}})}function makeReturnsIssue(returns,error){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error}})}let params={errorMap:ctx.common.contextualErrorMap},fn=ctx.data;if(this._def.returns instanceof ZodPromise){let me=this;return OK(async function(...args){let error=new ZodError([]),parsedArgs=await me._def.args.parseAsync(args,params).catch((e)=>{throw error.addIssue(makeArgsIssue(args,e)),error}),result=await Reflect.apply(fn,this,parsedArgs);return await me._def.returns._def.type.parseAsync(result,params).catch((e)=>{throw error.addIssue(makeReturnsIssue(result,e)),error})})}else{let me=this;return OK(function(...args){let parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success)throw new ZodError([makeArgsIssue(args,parsedArgs.error)]);let result=Reflect.apply(fn,this,parsedArgs.data),parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success)throw new ZodError([makeReturnsIssue(result,parsedReturns.error)]);return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new ZodFunction({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new ZodFunction({...this._def,returns:returnType})}implement(func){return this.parse(func)}strictImplement(func){return this.parse(func)}static create(args,returns,params){return new ZodFunction({args:args?args:ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}};ZodLazy=class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(input){let{ctx}=this._processInputParams(input);return this._def.getter()._parse({data:ctx.data,path:ctx.path,parent:ctx})}};ZodLazy.create=(getter,params)=>{return new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)})};ZodLiteral=class ZodLiteral extends ZodType{_parse(input){if(input.data!==this._def.value){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}};ZodLiteral.create=(value,params)=>{return new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)})};ZodEnum=class ZodEnum extends ZodType{_parse(input){if(typeof input.data!=="string"){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(input.data)){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Values(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}extract(values,newDef=this._def){return ZodEnum.create(values,{...this._def,...newDef})}exclude(values,newDef=this._def){return ZodEnum.create(this.options.filter((opt)=>!values.includes(opt)),{...this._def,...newDef})}};ZodEnum.create=createZodEnum;ZodNativeEnum=class ZodNativeEnum extends ZodType{_parse(input){let nativeEnumValues=util.getValidEnumValues(this._def.values),ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(!this._cache)this._cache=new Set(util.getValidEnumValues(this._def.values));if(!this._cache.has(input.data)){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(values,params)=>{return new ZodNativeEnum({values,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)})};ZodPromise=class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===!1)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType}),INVALID;let promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then((data)=>{return this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})}))}};ZodPromise.create=(schema,params)=>{return new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)})};ZodEffects=class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){let{status,ctx}=this._processInputParams(input),effect=this._def.effect||null,checkCtx={addIssue:(arg)=>{if(addIssueToContext(ctx,arg),arg.fatal)status.abort();else status.dirty()},get path(){return ctx.path}};if(checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx),effect.type==="preprocess"){let processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async)return Promise.resolve(processed).then(async(processed2)=>{if(status.value==="aborted")return INVALID;let result=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result});else{if(status.value==="aborted")return INVALID;let result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result}}if(effect.type==="refinement"){let executeRefinement=(acc)=>{let result=effect.refinement(acc,checkCtx);if(ctx.common.async)return Promise.resolve(result);if(result instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return acc};if(ctx.common.async===!1){let inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value),{status:status.value,value:inner.value}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((inner)=>{if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value).then(()=>{return{status:status.value,value:inner.value}})})}if(effect.type==="transform")if(ctx.common.async===!1){let base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;let result=effect.transform(base.value,checkCtx);if(result instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:status.value,value:result}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base)=>{if(!isValid(base))return INVALID;return Promise.resolve(effect.transform(base.value,checkCtx)).then((result)=>({status:status.value,value:result}))});util.assertNever(effect)}};ZodEffects.create=(schema,effect,params)=>{return new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)})};ZodEffects.createWithPreprocess=(preprocess,schema,params)=>{return new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)})};ZodOptional=class ZodOptional extends ZodType{_parse(input){if(this._getType(input)===ZodParsedType.undefined)return OK(void 0);return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}};ZodOptional.create=(type,params)=>{return new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)})};ZodNullable=class ZodNullable extends ZodType{_parse(input){if(this._getType(input)===ZodParsedType.null)return OK(null);return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}};ZodNullable.create=(type,params)=>{return new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)})};ZodDefault=class ZodDefault extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;if(ctx.parsedType===ZodParsedType.undefined)data=this._def.defaultValue();return this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}};ZodDefault.create=(type,params)=>{return new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default==="function"?params.default:()=>params.default,...processCreateParams(params)})};ZodCatch=class ZodCatch extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),newCtx={...ctx,common:{...ctx.common,issues:[]}},result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result))return result.then((result2)=>{return{status:"valid",value:result2.status==="valid"?result2.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}});else return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(type,params)=>{return new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch==="function"?params.catch:()=>params.catch,...processCreateParams(params)})};ZodNaN=class ZodNaN extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.nan){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType}),INVALID}return{status:"valid",value:input.data}}};ZodNaN.create=(params)=>{return new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)})};BRAND=Symbol("zod_brand");ZodBranded=class ZodBranded extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}};ZodPipeline=class ZodPipeline extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.common.async)return(async()=>{let inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty")return status.dirty(),DIRTY(inResult.value);else return this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})})();else{let inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty")return status.dirty(),{status:"dirty",value:inResult.value};else return this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}static create(a,b){return new ZodPipeline({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}};ZodReadonly=class ZodReadonly extends ZodType{_parse(input){let result=this._def.innerType._parse(input),freeze=(data)=>{if(isValid(data))data.value=Object.freeze(data.value);return data};return isAsync(result)?result.then((data)=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}};ZodReadonly.create=(type,params)=>{return new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)})};late={object:ZodObject.lazycreate};(function(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,coerce={string:(arg)=>ZodString.create({...arg,coerce:!0}),number:(arg)=>ZodNumber.create({...arg,coerce:!0}),boolean:(arg)=>ZodBoolean.create({...arg,coerce:!0}),bigint:(arg)=>ZodBigInt.create({...arg,coerce:!0}),date:(arg)=>ZodDate.create({...arg,coerce:!0})},NEVER=INVALID});var exports_external={};__export(exports_external,{void:()=>voidType,util:()=>util,unknown:()=>unknownType,union:()=>unionType,undefined:()=>undefinedType,tuple:()=>tupleType,transformer:()=>effectsType,symbol:()=>symbolType,string:()=>stringType,strictObject:()=>strictObjectType,setErrorMap:()=>setErrorMap,set:()=>setType,record:()=>recordType,quotelessJson:()=>quotelessJson,promise:()=>promiseType,preprocess:()=>preprocessType,pipeline:()=>pipelineType,ostring:()=>ostring,optional:()=>optionalType,onumber:()=>onumber,oboolean:()=>oboolean,objectUtil:()=>objectUtil,object:()=>objectType,number:()=>numberType,nullable:()=>nullableType,null:()=>nullType,never:()=>neverType,nativeEnum:()=>nativeEnumType,nan:()=>nanType,map:()=>mapType,makeIssue:()=>makeIssue,literal:()=>literalType,lazy:()=>lazyType,late:()=>late,isValid:()=>isValid,isDirty:()=>isDirty,isAsync:()=>isAsync,isAborted:()=>isAborted,intersection:()=>intersectionType,instanceof:()=>instanceOfType,getParsedType:()=>getParsedType,getErrorMap:()=>getErrorMap,function:()=>functionType,enum:()=>enumType,effect:()=>effectsType,discriminatedUnion:()=>discriminatedUnionType,defaultErrorMap:()=>en_default,datetimeRegex:()=>datetimeRegex,date:()=>dateType,custom:()=>custom,coerce:()=>coerce,boolean:()=>booleanType,bigint:()=>bigIntType,array:()=>arrayType,any:()=>anyType,addIssueToContext:()=>addIssueToContext,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransformer:()=>ZodEffects,ZodSymbol:()=>ZodSymbol,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodSchema:()=>ZodType,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPipeline:()=>ZodPipeline,ZodParsedType:()=>ZodParsedType,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNever:()=>ZodNever,ZodNativeEnum:()=>ZodNativeEnum,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEffects:()=>ZodEffects,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCatch:()=>ZodCatch,ZodBranded:()=>ZodBranded,ZodBoolean:()=>ZodBoolean,ZodBigInt:()=>ZodBigInt,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,Schema:()=>ZodType,ParseStatus:()=>ParseStatus,OK:()=>OK,NEVER:()=>NEVER,INVALID:()=>INVALID,EMPTY_PATH:()=>EMPTY_PATH,DIRTY:()=>DIRTY,BRAND:()=>BRAND});var init_external=__esm(()=>{init_errors();init_parseUtil();init_typeAliases();init_util();init_types();init_ZodError()});var init_zod=__esm(()=>{init_external();init_external()});var SessionConfigSchema,TerminalConfigSchema,LoggingConfigSchema,ShellConfigSchema,ShortcutsConfigSchema,CodexConfigSchema,WorkerProfileSchema,OtelConfigSchema,OmniConfigSchema,CouncilPresetSchema,GenieConfigSchema;var init_genie_config=__esm(()=>{init_zod();SessionConfigSchema=exports_external.object({name:exports_external.string().default("genie"),defaultWindow:exports_external.string().default("shell"),autoCreate:exports_external.boolean().default(!0)}),TerminalConfigSchema=exports_external.object({execTimeout:exports_external.number().default(120000),readLines:exports_external.number().default(100),worktreeBase:exports_external.string().optional()}),LoggingConfigSchema=exports_external.object({tmuxDebug:exports_external.boolean().default(!1),verbose:exports_external.boolean().default(!1)}),ShellConfigSchema=exports_external.object({preference:exports_external.enum(["auto","zsh","bash","fish"]).default("auto")}),ShortcutsConfigSchema=exports_external.object({tmuxInstalled:exports_external.boolean().default(!1),shellInstalled:exports_external.boolean().default(!1)}),CodexConfigSchema=exports_external.object({configured:exports_external.boolean().default(!1)}),WorkerProfileSchema=exports_external.object({launcher:exports_external.preprocess((val)=>val==="claudio"?"claude":val,exports_external.literal("claude")),claudeArgs:exports_external.array(exports_external.string())}).passthrough(),OtelConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),port:exports_external.number().optional(),logPrompts:exports_external.boolean().default(!0)}),OmniConfigSchema=exports_external.object({apiUrl:exports_external.string(),apiKey:exports_external.string().optional(),defaultInstanceId:exports_external.string().optional()}),CouncilPresetSchema=exports_external.object({left:exports_external.string(),right:exports_external.string(),skill:exports_external.string().default("council")}),GenieConfigSchema=exports_external.object({version:exports_external.number().default(2),session:SessionConfigSchema.default({}),terminal:TerminalConfigSchema.default({}),logging:LoggingConfigSchema.default({}),shell:ShellConfigSchema.default({}),shortcuts:ShortcutsConfigSchema.default({}),codex:CodexConfigSchema.optional(),installMethod:exports_external.enum(["source","npm","bun"]).optional(),updateChannel:exports_external.enum(["latest","next"]).default("latest"),setupComplete:exports_external.boolean().default(!1),lastSetupAt:exports_external.string().optional(),sourcePath:exports_external.string().optional(),workerProfiles:exports_external.record(exports_external.string(),WorkerProfileSchema).optional(),defaultWorkerProfile:exports_external.string().optional(),councilPresets:exports_external.record(exports_external.string(),CouncilPresetSchema).optional(),defaultCouncilPreset:exports_external.string().optional(),promptMode:exports_external.enum(["append","system"]).default("append"),autoMergeDev:exports_external.boolean().default(!1),defaultProject:exports_external.string().optional(),otel:OtelConfigSchema.optional(),omni:OmniConfigSchema.optional()})});var exports_genie_config={};__export(exports_genie_config,{updateShortcutsConfig:()=>updateShortcutsConfig,saveGenieConfig:()=>saveGenieConfig,resetConfig:()=>resetConfig,markSetupComplete:()=>markSetupComplete,loadGenieConfigSync:()=>loadGenieConfigSync,loadGenieConfig:()=>loadGenieConfig,isSetupComplete:()=>isSetupComplete,getTerminalConfig:()=>getTerminalConfig,getGenieDir:()=>getGenieDir,getGenieConfigPath:()=>getGenieConfigPath,genieConfigExists:()=>genieConfigExists,contractPath:()=>contractPath});import{existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir3}from"os";import{join as join3}from"path";function getGenieDir(){return GENIE_DIR}function getGenieConfigPath(){return GENIE_CONFIG_FILE}function genieConfigExists(){return existsSync3(GENIE_CONFIG_FILE)}function ensureGenieDir(){if(!existsSync3(GENIE_DIR))mkdirSync2(GENIE_DIR,{recursive:!0})}async function loadGenieConfig(){if(!existsSync3(GENIE_CONFIG_FILE))return GenieConfigSchema.parse({});try{let content=readFileSync(GENIE_CONFIG_FILE,"utf-8"),data=JSON.parse(content);return GenieConfigSchema.parse(data)}catch(error){let message=error instanceof Error?error.message:String(error);return console.warn(`Warning: Invalid genie config, using defaults: ${message}`),GenieConfigSchema.parse({})}}async function saveGenieConfig(config){ensureGenieDir();try{let validated=GenieConfigSchema.parse(config),content=JSON.stringify(validated,null,2);writeFileSync2(GENIE_CONFIG_FILE,content,"utf-8")}catch(error){let message=error instanceof Error?error.message:String(error);throw Error(`Failed to save genie config: ${message}`)}}function getDefaultGenieConfig(){return GenieConfigSchema.parse({})}function loadGenieConfigSync(){if(!existsSync3(GENIE_CONFIG_FILE))return GenieConfigSchema.parse({});try{let content=readFileSync(GENIE_CONFIG_FILE,"utf-8"),data=JSON.parse(content);return GenieConfigSchema.parse(data)}catch{return GenieConfigSchema.parse({})}}function contractPath(path){let home=homedir3();if(path.startsWith(`${home}/`))return`~${path.slice(home.length)}`;if(path===home)return"~";return path}function getTerminalConfig(){return loadGenieConfigSync().terminal}function isSetupComplete(){if(!genieConfigExists())return!1;return loadGenieConfigSync().setupComplete??!1}async function markSetupComplete(){let config=await loadGenieConfig();config.setupComplete=!0,config.lastSetupAt=new Date().toISOString(),await saveGenieConfig(config)}async function resetConfig(){let defaultConfig=getDefaultGenieConfig();await saveGenieConfig(defaultConfig)}async function updateShortcutsConfig(partial){let config=await loadGenieConfig();config.shortcuts={...config.shortcuts,...partial},await saveGenieConfig(config)}var GENIE_DIR,GENIE_CONFIG_FILE;var init_genie_config2=__esm(()=>{init_genie_config();GENIE_DIR=join3(homedir3(),".genie"),GENIE_CONFIG_FILE=join3(GENIE_DIR,"config.json")});var isUpKey=(key,keybindings=[])=>key.name==="up"||keybindings.includes("vim")&&key.name==="k"||keybindings.includes("emacs")&&key.ctrl&&key.name==="p",isDownKey=(key,keybindings=[])=>key.name==="down"||keybindings.includes("vim")&&key.name==="j"||keybindings.includes("emacs")&&key.ctrl&&key.name==="n",isBackspaceKey=(key)=>key.name==="backspace",isTabKey=(key)=>key.name==="tab",isNumberKey=(key)=>"1234567890".includes(key.name),isEnterKey=(key)=>key.name==="enter"||key.name==="return";var AbortPromptError,CancelPromptError,ExitPromptError,HookError,ValidationError;var init_errors2=__esm(()=>{AbortPromptError=class AbortPromptError extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(options){super();this.cause=options?.cause}};CancelPromptError=class CancelPromptError extends Error{name="CancelPromptError";message="Prompt was canceled"};ExitPromptError=class ExitPromptError extends Error{name="ExitPromptError"};HookError=class HookError extends Error{name="HookError"};ValidationError=class ValidationError extends Error{name="ValidationError"}});import{AsyncLocalStorage,AsyncResource}from"async_hooks";function createStore(rl){return{rl,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function withHooks(rl,cb){let store=createStore(rl);return hookStorage.run(store,()=>{function cycle(render){store.handleChange=()=>{store.index=0,render()},store.handleChange()}return cb(cycle)})}function getStore(){let store=hookStorage.getStore();if(!store)throw new HookError("[Inquirer] Hook functions can only be called from within a prompt");return store}function readline(){return getStore().rl}function withUpdates(fn){let wrapped=(...args)=>{let store=getStore(),shouldUpdate=!1,oldHandleChange=store.handleChange;store.handleChange=()=>{shouldUpdate=!0};let returnValue=fn(...args);if(shouldUpdate)oldHandleChange();return store.handleChange=oldHandleChange,returnValue};return AsyncResource.bind(wrapped)}function withPointer(cb){let store=getStore(),{index}=store,pointer={get(){return store.hooks[index]},set(value){store.hooks[index]=value},initialized:index in store.hooks},returnValue=cb(pointer);return store.index++,returnValue}function handleChange(){getStore().handleChange()}var hookStorage,effectScheduler;var init_hook_engine=__esm(()=>{init_errors2();hookStorage=new AsyncLocalStorage;effectScheduler={queue(cb){let store=getStore(),{index}=store;store.hooksEffect.push(()=>{store.hooksCleanup[index]?.();let cleanFn=cb(readline());if(cleanFn!=null&&typeof cleanFn!=="function")throw new ValidationError("useEffect return value must be a cleanup function or nothing.");store.hooksCleanup[index]=cleanFn})},run(){let store=getStore();withUpdates(()=>{store.hooksEffect.forEach((effect)=>{effect()}),store.hooksEffect.length=0})()},clearAll(){let store=getStore();store.hooksCleanup.forEach((cleanFn)=>{cleanFn?.()}),store.hooksEffect.length=0,store.hooksCleanup.length=0}}});import{AsyncResource as AsyncResource2}from"async_hooks";function useState(defaultValue){return withPointer((pointer)=>{let setState=AsyncResource2.bind(function(newValue){if(pointer.get()!==newValue)pointer.set(newValue),handleChange()});if(pointer.initialized)return[pointer.get(),setState];let value=typeof defaultValue==="function"?defaultValue():defaultValue;return pointer.set(value),[value,setState]})}var init_use_state=__esm(()=>{init_hook_engine()});function useEffect(cb,depArray){withPointer((pointer)=>{let oldDeps=pointer.get();if(!Array.isArray(oldDeps)||depArray.some((dep,i)=>!Object.is(dep,oldDeps[i])))effectScheduler.queue(cb);pointer.set(depArray)})}var init_use_effect=__esm(()=>{init_hook_engine()});var require_yoctocolors_cjs=__commonJS((exports,module)=>{var tty=__require("tty"),hasColors=tty?.WriteStream?.prototype?.hasColors?.()??!1,format=(open,close)=>{if(!hasColors)return(input)=>input;let openCode=`\x1B[${open}m`,closeCode=`\x1B[${close}m`;return(input)=>{let string=input+"",index=string.indexOf(closeCode);if(index===-1)return openCode+string+closeCode;let result=openCode,lastIndex=0,replaceCode=(close===22?closeCode:"")+openCode;while(index!==-1)result+=string.slice(lastIndex,index)+replaceCode,lastIndex=index+closeCode.length,index=string.indexOf(closeCode,lastIndex);return result+=string.slice(lastIndex)+closeCode,result}},colors={};colors.reset=format(0,0);colors.bold=format(1,22);colors.dim=format(2,22);colors.italic=format(3,23);colors.underline=format(4,24);colors.overline=format(53,55);colors.inverse=format(7,27);colors.hidden=format(8,28);colors.strikethrough=format(9,29);colors.black=format(30,39);colors.red=format(31,39);colors.green=format(32,39);colors.yellow=format(33,39);colors.blue=format(34,39);colors.magenta=format(35,39);colors.cyan=format(36,39);colors.white=format(37,39);colors.gray=format(90,39);colors.bgBlack=format(40,49);colors.bgRed=format(41,49);colors.bgGreen=format(42,49);colors.bgYellow=format(43,49);colors.bgBlue=format(44,49);colors.bgMagenta=format(45,49);colors.bgCyan=format(46,49);colors.bgWhite=format(47,49);colors.bgGray=format(100,49);colors.redBright=format(91,39);colors.greenBright=format(92,39);colors.yellowBright=format(93,39);colors.blueBright=format(94,39);colors.magentaBright=format(95,39);colors.cyanBright=format(96,39);colors.whiteBright=format(97,39);colors.bgRedBright=format(101,49);colors.bgGreenBright=format(102,49);colors.bgYellowBright=format(103,49);colors.bgBlueBright=format(104,49);colors.bgMagentaBright=format(105,49);colors.bgCyanBright=format(106,49);colors.bgWhiteBright=format(107,49);module.exports=colors});import process2 from"process";function isUnicodeSupported(){if(process2.platform!=="win32")return process2.env.TERM!=="linux";return Boolean(process2.env.WT_SESSION)||Boolean(process2.env.TERMINUS_SUBLIME)||process2.env.ConEmuTask==="{cmd::Cmder}"||process2.env.TERM_PROGRAM==="Terminus-Sublime"||process2.env.TERM_PROGRAM==="vscode"||process2.env.TERM==="xterm-256color"||process2.env.TERM==="alacritty"||process2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var common,specialMainSymbols,specialFallbackSymbols,mainSymbols,fallbackSymbols,shouldUseMain,figures,esm_default,replacements;var init_esm=__esm(()=>{common={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},specialMainSymbols={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},specialFallbackSymbols={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},mainSymbols={...common,...specialMainSymbols},fallbackSymbols={...common,...specialFallbackSymbols},shouldUseMain=isUnicodeSupported(),figures=shouldUseMain?mainSymbols:fallbackSymbols,esm_default=figures,replacements=Object.entries(specialMainSymbols)});var import_yoctocolors_cjs,defaultTheme;var init_theme=__esm(()=>{init_esm();import_yoctocolors_cjs=__toESM(require_yoctocolors_cjs(),1),defaultTheme={prefix:{idle:import_yoctocolors_cjs.default.blue("?"),done:import_yoctocolors_cjs.default.green(esm_default.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((frame)=>import_yoctocolors_cjs.default.yellow(frame))},style:{answer:import_yoctocolors_cjs.default.cyan,message:import_yoctocolors_cjs.default.bold,error:(text)=>import_yoctocolors_cjs.default.red(`> ${text}`),defaultAnswer:(text)=>import_yoctocolors_cjs.default.dim(`(${text})`),help:import_yoctocolors_cjs.default.dim,highlight:import_yoctocolors_cjs.default.cyan,key:(text)=>import_yoctocolors_cjs.default.cyan(import_yoctocolors_cjs.default.bold(`<${text}>`))}}});function isPlainObject(value){if(typeof value!=="object"||value===null)return!1;let proto=value;while(Object.getPrototypeOf(proto)!==null)proto=Object.getPrototypeOf(proto);return Object.getPrototypeOf(value)===proto}function deepMerge(...objects){let output={};for(let obj of objects)for(let[key,value]of Object.entries(obj)){let prevValue=output[key];output[key]=isPlainObject(prevValue)&&isPlainObject(value)?deepMerge(prevValue,value):value}return output}function makeTheme(...themes){let themesToMerge=[defaultTheme,...themes.filter((theme)=>theme!=null)];return deepMerge(...themesToMerge)}var init_make_theme=__esm(()=>{init_theme()});function usePrefix({status="idle",theme}){let[showLoader,setShowLoader]=useState(!1),[tick,setTick]=useState(0),{prefix,spinner}=makeTheme(theme);if(useEffect(()=>{if(status==="loading"){let tickInterval,inc=-1,delayTimeout=setTimeout(()=>{setShowLoader(!0),tickInterval=setInterval(()=>{inc=inc+1,setTick(inc%spinner.frames.length)},spinner.interval)},300);return()=>{clearTimeout(delayTimeout),clearInterval(tickInterval)}}else setShowLoader(!1)},[status]),showLoader)return spinner.frames[tick];return typeof prefix==="string"?prefix:prefix[status==="loading"?"idle":status]??prefix.idle}var init_use_prefix=__esm(()=>{init_use_state();init_use_effect();init_make_theme()});function useMemo(fn,dependencies){return withPointer((pointer)=>{let prev=pointer.get();if(!prev||prev.dependencies.length!==dependencies.length||prev.dependencies.some((dep,i)=>dep!==dependencies[i])){let value=fn();return pointer.set({value,dependencies}),value}return prev.value})}var init_use_memo=__esm(()=>{init_hook_engine()});function useRef(val){return useState({current:val})[0]}var init_use_ref=__esm(()=>{init_use_state()});function useKeypress(userHandler){let signal=useRef(userHandler);signal.current=userHandler,useEffect((rl)=>{let ignore=!1,handler=withUpdates((_input,event)=>{if(ignore)return;signal.current(event,rl)});return rl.input.on("keypress",handler),()=>{ignore=!0,rl.input.removeListener("keypress",handler)}},[])}var init_use_keypress=__esm(()=>{init_use_ref();init_use_effect();init_hook_engine()});var require_cli_width=__commonJS((exports,module)=>{module.exports=cliWidth;function normalizeOpts(options){let defaultOpts={defaultWidth:0,output:process.stdout,tty:__require("tty")};if(!options)return defaultOpts;return Object.keys(defaultOpts).forEach(function(key){if(!options[key])options[key]=defaultOpts[key]}),options}function cliWidth(options){let opts=normalizeOpts(options);if(opts.output.getWindowSize)return opts.output.getWindowSize()[0]||opts.defaultWidth;if(opts.tty.getWindowSize)return opts.tty.getWindowSize()[1]||opts.defaultWidth;if(opts.output.columns)return opts.output.columns;if(process.env.CLI_WIDTH){let width=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(width)&&width!==0)return width}return opts.defaultWidth}});var require_ansi_regex=__commonJS((exports,module)=>{module.exports=({onlyFirst=!1}={})=>{let pattern=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(pattern,onlyFirst?void 0:"g")}});var require_strip_ansi=__commonJS((exports,module)=>{var ansiRegex=require_ansi_regex();module.exports=(string)=>typeof string==="string"?string.replace(ansiRegex(),""):string});var require_is_fullwidth_code_point=__commonJS((exports,module)=>{var isFullwidthCodePoint=(codePoint)=>{if(Number.isNaN(codePoint))return!1;if(codePoint>=4352&&(codePoint<=4447||codePoint===9001||codePoint===9002||11904<=codePoint&&codePoint<=12871&&codePoint!==12351||12880<=codePoint&&codePoint<=19903||19968<=codePoint&&codePoint<=42182||43360<=codePoint&&codePoint<=43388||44032<=codePoint&&codePoint<=55203||63744<=codePoint&&codePoint<=64255||65040<=codePoint&&codePoint<=65049||65072<=codePoint&&codePoint<=65131||65281<=codePoint&&codePoint<=65376||65504<=codePoint&&codePoint<=65510||110592<=codePoint&&codePoint<=110593||127488<=codePoint&&codePoint<=127569||131072<=codePoint&&codePoint<=262141))return!0;return!1};module.exports=isFullwidthCodePoint;module.exports.default=isFullwidthCodePoint});var require_emoji_regex=__commonJS((exports,module)=>{module.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var require_string_width=__commonJS((exports,module)=>{var stripAnsi=require_strip_ansi(),isFullwidthCodePoint=require_is_fullwidth_code_point(),emojiRegex2=require_emoji_regex(),stringWidth=(string)=>{if(typeof string!=="string"||string.length===0)return 0;if(string=stripAnsi(string),string.length===0)return 0;string=string.replace(emojiRegex2()," ");let width=0;for(let i=0;i<string.length;i++){let code=string.codePointAt(i);if(code<=31||code>=127&&code<=159)continue;if(code>=768&&code<=879)continue;if(code>65535)i++;width+=isFullwidthCodePoint(code)?2:1}return width};module.exports=stringWidth;module.exports.default=stringWidth});var require_color_name=__commonJS((exports,module)=>{module.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var require_conversions=__commonJS((exports,module)=>{var cssKeywords=require_color_name(),reverseKeywords={};for(let key of Object.keys(cssKeywords))reverseKeywords[cssKeywords[key]]=key;var convert={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};module.exports=convert;for(let model of Object.keys(convert)){if(!("channels"in convert[model]))throw Error("missing channels property: "+model);if(!("labels"in convert[model]))throw Error("missing channel labels property: "+model);if(convert[model].labels.length!==convert[model].channels)throw Error("channel and label counts mismatch: "+model);let{channels,labels}=convert[model];delete convert[model].channels,delete convert[model].labels,Object.defineProperty(convert[model],"channels",{value:channels}),Object.defineProperty(convert[model],"labels",{value:labels})}convert.rgb.hsl=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255,min=Math.min(r,g,b),max=Math.max(r,g,b),delta=max-min,h,s;if(max===min)h=0;else if(r===max)h=(g-b)/delta;else if(g===max)h=2+(b-r)/delta;else if(b===max)h=4+(r-g)/delta;if(h=Math.min(h*60,360),h<0)h+=360;let l=(min+max)/2;if(max===min)s=0;else if(l<=0.5)s=delta/(max+min);else s=delta/(2-max-min);return[h,s*100,l*100]};convert.rgb.hsv=function(rgb){let rdif,gdif,bdif,h,s,r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255,v=Math.max(r,g,b),diff=v-Math.min(r,g,b),diffc=function(c){return(v-c)/6/diff+0.5};if(diff===0)h=0,s=0;else{if(s=diff/v,rdif=diffc(r),gdif=diffc(g),bdif=diffc(b),r===v)h=bdif-gdif;else if(g===v)h=0.3333333333333333+rdif-bdif;else if(b===v)h=0.6666666666666666+gdif-rdif;if(h<0)h+=1;else if(h>1)h-=1}return[h*360,s*100,v*100]};convert.rgb.hwb=function(rgb){let r=rgb[0],g=rgb[1],b=rgb[2],h=convert.rgb.hsl(rgb)[0],w=0.00392156862745098*Math.min(r,Math.min(g,b));return b=1-0.00392156862745098*Math.max(r,Math.max(g,b)),[h,w*100,b*100]};convert.rgb.cmyk=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255,k=Math.min(1-r,1-g,1-b),c=(1-r-k)/(1-k)||0,m=(1-g-k)/(1-k)||0,y=(1-b-k)/(1-k)||0;return[c*100,m*100,y*100,k*100]};function comparativeDistance(x,y){return(x[0]-y[0])**2+(x[1]-y[1])**2+(x[2]-y[2])**2}convert.rgb.keyword=function(rgb){let reversed=reverseKeywords[rgb];if(reversed)return reversed;let currentClosestDistance=1/0,currentClosestKeyword;for(let keyword of Object.keys(cssKeywords)){let value=cssKeywords[keyword],distance=comparativeDistance(rgb,value);if(distance<currentClosestDistance)currentClosestDistance=distance,currentClosestKeyword=keyword}return currentClosestKeyword};convert.keyword.rgb=function(keyword){return cssKeywords[keyword]};convert.rgb.xyz=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255;r=r>0.04045?((r+0.055)/1.055)**2.4:r/12.92,g=g>0.04045?((g+0.055)/1.055)**2.4:g/12.92,b=b>0.04045?((b+0.055)/1.055)**2.4:b/12.92;let x=r*0.4124+g*0.3576+b*0.1805,y=r*0.2126+g*0.7152+b*0.0722,z=r*0.0193+g*0.1192+b*0.9505;return[x*100,y*100,z*100]};convert.rgb.lab=function(rgb){let xyz=convert.rgb.xyz(rgb),x=xyz[0],y=xyz[1],z=xyz[2];x/=95.047,y/=100,z/=108.883,x=x>0.008856?x**0.3333333333333333:7.787*x+0.13793103448275862,y=y>0.008856?y**0.3333333333333333:7.787*y+0.13793103448275862,z=z>0.008856?z**0.3333333333333333:7.787*z+0.13793103448275862;let l=116*y-16,a=500*(x-y),b=200*(y-z);return[l,a,b]};convert.hsl.rgb=function(hsl){let h=hsl[0]/360,s=hsl[1]/100,l=hsl[2]/100,t2,t3,val;if(s===0)return val=l*255,[val,val,val];if(l<0.5)t2=l*(1+s);else t2=l+s-l*s;let t1=2*l-t2,rgb=[0,0,0];for(let i=0;i<3;i++){if(t3=h+0.3333333333333333*-(i-1),t3<0)t3++;if(t3>1)t3--;if(6*t3<1)val=t1+(t2-t1)*6*t3;else if(2*t3<1)val=t2;else if(3*t3<2)val=t1+(t2-t1)*(0.6666666666666666-t3)*6;else val=t1;rgb[i]=val*255}return rgb};convert.hsl.hsv=function(hsl){let h=hsl[0],s=hsl[1]/100,l=hsl[2]/100,smin=s,lmin=Math.max(l,0.01);l*=2,s*=l<=1?l:2-l,smin*=lmin<=1?lmin:2-lmin;let v=(l+s)/2,sv=l===0?2*smin/(lmin+smin):2*s/(l+s);return[h,sv*100,v*100]};convert.hsv.rgb=function(hsv){let h=hsv[0]/60,s=hsv[1]/100,v=hsv[2]/100,hi=Math.floor(h)%6,f=h-Math.floor(h),p=255*v*(1-s),q=255*v*(1-s*f),t=255*v*(1-s*(1-f));switch(v*=255,hi){case 0:return[v,t,p];case 1:return[q,v,p];case 2:return[p,v,t];case 3:return[p,q,v];case 4:return[t,p,v];case 5:return[v,p,q]}};convert.hsv.hsl=function(hsv){let h=hsv[0],s=hsv[1]/100,v=hsv[2]/100,vmin=Math.max(v,0.01),sl,l;l=(2-s)*v;let lmin=(2-s)*vmin;return sl=s*vmin,sl/=lmin<=1?lmin:2-lmin,sl=sl||0,l/=2,[h,sl*100,l*100]};convert.hwb.rgb=function(hwb){let h=hwb[0]/360,wh=hwb[1]/100,bl=hwb[2]/100,ratio=wh+bl,f;if(ratio>1)wh/=ratio,bl/=ratio;let i=Math.floor(6*h),v=1-bl;if(f=6*h-i,(i&1)!==0)f=1-f;let n=wh+f*(v-wh),r,g,b;switch(i){default:case 6:case 0:r=v,g=n,b=wh;break;case 1:r=n,g=v,b=wh;break;case 2:r=wh,g=v,b=n;break;case 3:r=wh,g=n,b=v;break;case 4:r=n,g=wh,b=v;break;case 5:r=v,g=wh,b=n;break}return[r*255,g*255,b*255]};convert.cmyk.rgb=function(cmyk){let c=cmyk[0]/100,m=cmyk[1]/100,y=cmyk[2]/100,k=cmyk[3]/100,r=1-Math.min(1,c*(1-k)+k),g=1-Math.min(1,m*(1-k)+k),b=1-Math.min(1,y*(1-k)+k);return[r*255,g*255,b*255]};convert.xyz.rgb=function(xyz){let x=xyz[0]/100,y=xyz[1]/100,z=xyz[2]/100,r,g,b;return r=x*3.2406+y*-1.5372+z*-0.4986,g=x*-0.9689+y*1.8758+z*0.0415,b=x*0.0557+y*-0.204+z*1.057,r=r>0.0031308?1.055*r**0.4166666666666667-0.055:r*12.92,g=g>0.0031308?1.055*g**0.4166666666666667-0.055:g*12.92,b=b>0.0031308?1.055*b**0.4166666666666667-0.055:b*12.92,r=Math.min(Math.max(0,r),1),g=Math.min(Math.max(0,g),1),b=Math.min(Math.max(0,b),1),[r*255,g*255,b*255]};convert.xyz.lab=function(xyz){let x=xyz[0],y=xyz[1],z=xyz[2];x/=95.047,y/=100,z/=108.883,x=x>0.008856?x**0.3333333333333333:7.787*x+0.13793103448275862,y=y>0.008856?y**0.3333333333333333:7.787*y+0.13793103448275862,z=z>0.008856?z**0.3333333333333333:7.787*z+0.13793103448275862;let l=116*y-16,a=500*(x-y),b=200*(y-z);return[l,a,b]};convert.lab.xyz=function(lab){let l=lab[0],a=lab[1],b=lab[2],x,y,z;y=(l+16)/116,x=a/500+y,z=y-b/200;let y2=y**3,x2=x**3,z2=z**3;return y=y2>0.008856?y2:(y-0.13793103448275862)/7.787,x=x2>0.008856?x2:(x-0.13793103448275862)/7.787,z=z2>0.008856?z2:(z-0.13793103448275862)/7.787,x*=95.047,y*=100,z*=108.883,[x,y,z]};convert.lab.lch=function(lab){let l=lab[0],a=lab[1],b=lab[2],h;if(h=Math.atan2(b,a)*360/2/Math.PI,h<0)h+=360;let c=Math.sqrt(a*a+b*b);return[l,c,h]};convert.lch.lab=function(lch){let l=lch[0],c=lch[1],hr=lch[2]/360*2*Math.PI,a=c*Math.cos(hr),b=c*Math.sin(hr);return[l,a,b]};convert.rgb.ansi16=function(args,saturation=null){let[r,g,b]=args,value=saturation===null?convert.rgb.hsv(args)[2]:saturation;if(value=Math.round(value/50),value===0)return 30;let ansi=30+(Math.round(b/255)<<2|Math.round(g/255)<<1|Math.round(r/255));if(value===2)ansi+=60;return ansi};convert.hsv.ansi16=function(args){return convert.rgb.ansi16(convert.hsv.rgb(args),args[2])};convert.rgb.ansi256=function(args){let r=args[0],g=args[1],b=args[2];if(r===g&&g===b){if(r<8)return 16;if(r>248)return 231;return Math.round((r-8)/247*24)+232}return 16+36*Math.round(r/255*5)+6*Math.round(g/255*5)+Math.round(b/255*5)};convert.ansi16.rgb=function(args){let color=args%10;if(color===0||color===7){if(args>50)color+=3.5;return color=color/10.5*255,[color,color,color]}let mult=(~~(args>50)+1)*0.5,r=(color&1)*mult*255,g=(color>>1&1)*mult*255,b=(color>>2&1)*mult*255;return[r,g,b]};convert.ansi256.rgb=function(args){if(args>=232){let c=(args-232)*10+8;return[c,c,c]}args-=16;let rem,r=Math.floor(args/36)/5*255,g=Math.floor((rem=args%36)/6)/5*255,b=rem%6/5*255;return[r,g,b]};convert.rgb.hex=function(args){let string=(((Math.round(args[0])&255)<<16)+((Math.round(args[1])&255)<<8)+(Math.round(args[2])&255)).toString(16).toUpperCase();return"000000".substring(string.length)+string};convert.hex.rgb=function(args){let match=args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!match)return[0,0,0];let colorString=match[0];if(match[0].length===3)colorString=colorString.split("").map((char)=>{return char+char}).join("");let integer=parseInt(colorString,16),r=integer>>16&255,g=integer>>8&255,b=integer&255;return[r,g,b]};convert.rgb.hcg=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255,max=Math.max(Math.max(r,g),b),min=Math.min(Math.min(r,g),b),chroma=max-min,grayscale,hue;if(chroma<1)grayscale=min/(1-chroma);else grayscale=0;if(chroma<=0)hue=0;else if(max===r)hue=(g-b)/chroma%6;else if(max===g)hue=2+(b-r)/chroma;else hue=4+(r-g)/chroma;return hue/=6,hue%=1,[hue*360,chroma*100,grayscale*100]};convert.hsl.hcg=function(hsl){let s=hsl[1]/100,l=hsl[2]/100,c=l<0.5?2*s*l:2*s*(1-l),f=0;if(c<1)f=(l-0.5*c)/(1-c);return[hsl[0],c*100,f*100]};convert.hsv.hcg=function(hsv){let s=hsv[1]/100,v=hsv[2]/100,c=s*v,f=0;if(c<1)f=(v-c)/(1-c);return[hsv[0],c*100,f*100]};convert.hcg.rgb=function(hcg){let h=hcg[0]/360,c=hcg[1]/100,g=hcg[2]/100;if(c===0)return[g*255,g*255,g*255];let pure=[0,0,0],hi=h%1*6,v=hi%1,w=1-v,mg=0;switch(Math.floor(hi)){case 0:pure[0]=1,pure[1]=v,pure[2]=0;break;case 1:pure[0]=w,pure[1]=1,pure[2]=0;break;case 2:pure[0]=0,pure[1]=1,pure[2]=v;break;case 3:pure[0]=0,pure[1]=w,pure[2]=1;break;case 4:pure[0]=v,pure[1]=0,pure[2]=1;break;default:pure[0]=1,pure[1]=0,pure[2]=w}return mg=(1-c)*g,[(c*pure[0]+mg)*255,(c*pure[1]+mg)*255,(c*pure[2]+mg)*255]};convert.hcg.hsv=function(hcg){let c=hcg[1]/100,g=hcg[2]/100,v=c+g*(1-c),f=0;if(v>0)f=c/v;return[hcg[0],f*100,v*100]};convert.hcg.hsl=function(hcg){let c=hcg[1]/100,l=hcg[2]/100*(1-c)+0.5*c,s=0;if(l>0&&l<0.5)s=c/(2*l);else if(l>=0.5&&l<1)s=c/(2*(1-l));return[hcg[0],s*100,l*100]};convert.hcg.hwb=function(hcg){let c=hcg[1]/100,g=hcg[2]/100,v=c+g*(1-c);return[hcg[0],(v-c)*100,(1-v)*100]};convert.hwb.hcg=function(hwb){let w=hwb[1]/100,v=1-hwb[2]/100,c=v-w,g=0;if(c<1)g=(v-c)/(1-c);return[hwb[0],c*100,g*100]};convert.apple.rgb=function(apple){return[apple[0]/65535*255,apple[1]/65535*255,apple[2]/65535*255]};convert.rgb.apple=function(rgb){return[rgb[0]/255*65535,rgb[1]/255*65535,rgb[2]/255*65535]};convert.gray.rgb=function(args){return[args[0]/100*255,args[0]/100*255,args[0]/100*255]};convert.gray.hsl=function(args){return[0,0,args[0]]};convert.gray.hsv=convert.gray.hsl;convert.gray.hwb=function(gray){return[0,100,gray[0]]};convert.gray.cmyk=function(gray){return[0,0,0,gray[0]]};convert.gray.lab=function(gray){return[gray[0],0,0]};convert.gray.hex=function(gray){let val=Math.round(gray[0]/100*255)&255,string=((val<<16)+(val<<8)+val).toString(16).toUpperCase();return"000000".substring(string.length)+string};convert.rgb.gray=function(rgb){return[(rgb[0]+rgb[1]+rgb[2])/3/255*100]}});var require_route=__commonJS((exports,module)=>{var conversions=require_conversions();function buildGraph(){let graph={},models=Object.keys(conversions);for(let len=models.length,i=0;i<len;i++)graph[models[i]]={distance:-1,parent:null};return graph}function deriveBFS(fromModel){let graph=buildGraph(),queue=[fromModel];graph[fromModel].distance=0;while(queue.length){let current=queue.pop(),adjacents=Object.keys(conversions[current]);for(let len=adjacents.length,i=0;i<len;i++){let adjacent=adjacents[i],node=graph[adjacent];if(node.distance===-1)node.distance=graph[current].distance+1,node.parent=current,queue.unshift(adjacent)}}return graph}function link(from,to){return function(args){return to(from(args))}}function wrapConversion(toModel,graph){let path=[graph[toModel].parent,toModel],fn=conversions[graph[toModel].parent][toModel],cur=graph[toModel].parent;while(graph[cur].parent)path.unshift(graph[cur].parent),fn=link(conversions[graph[cur].parent][cur],fn),cur=graph[cur].parent;return fn.conversion=path,fn}module.exports=function(fromModel){let graph=deriveBFS(fromModel),conversion={},models=Object.keys(graph);for(let len=models.length,i=0;i<len;i++){let toModel=models[i];if(graph[toModel].parent===null)continue;conversion[toModel]=wrapConversion(toModel,graph)}return conversion}});var require_color_convert=__commonJS((exports,module)=>{var conversions=require_conversions(),route=require_route(),convert={},models=Object.keys(conversions);function wrapRaw(fn){let wrappedFn=function(...args){let arg0=args[0];if(arg0===void 0||arg0===null)return arg0;if(arg0.length>1)args=arg0;return fn(args)};if("conversion"in fn)wrappedFn.conversion=fn.conversion;return wrappedFn}function wrapRounded(fn){let wrappedFn=function(...args){let arg0=args[0];if(arg0===void 0||arg0===null)return arg0;if(arg0.length>1)args=arg0;let result=fn(args);if(typeof result==="object")for(let len=result.length,i=0;i<len;i++)result[i]=Math.round(result[i]);return result};if("conversion"in fn)wrappedFn.conversion=fn.conversion;return wrappedFn}models.forEach((fromModel)=>{convert[fromModel]={},Object.defineProperty(convert[fromModel],"channels",{value:conversions[fromModel].channels}),Object.defineProperty(convert[fromModel],"labels",{value:conversions[fromModel].labels});let routes=route(fromModel);Object.keys(routes).forEach((toModel)=>{let fn=routes[toModel];convert[fromModel][toModel]=wrapRounded(fn),convert[fromModel][toModel].raw=wrapRaw(fn)})});module.exports=convert});var require_ansi_styles=__commonJS((exports,module)=>{var wrapAnsi16=(fn,offset)=>(...args)=>{return`\x1B[${fn(...args)+offset}m`},wrapAnsi256=(fn,offset)=>(...args)=>{let code=fn(...args);return`\x1B[${38+offset};5;${code}m`},wrapAnsi16m=(fn,offset)=>(...args)=>{let rgb=fn(...args);return`\x1B[${38+offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`},ansi2ansi=(n)=>n,rgb2rgb=(r,g,b)=>[r,g,b],setLazyProperty=(object,property,get)=>{Object.defineProperty(object,property,{get:()=>{let value=get();return Object.defineProperty(object,property,{value,enumerable:!0,configurable:!0}),value},enumerable:!0,configurable:!0})},colorConvert,makeDynamicStyles=(wrap,targetSpace,identity,isBackground)=>{if(colorConvert===void 0)colorConvert=require_color_convert();let offset=isBackground?10:0,styles={};for(let[sourceSpace,suite]of Object.entries(colorConvert)){let name=sourceSpace==="ansi16"?"ansi":sourceSpace;if(sourceSpace===targetSpace)styles[name]=wrap(identity,offset);else if(typeof suite==="object")styles[name]=wrap(suite[targetSpace],offset)}return styles};function assembleStyles(){let codes=new Map,styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};styles.color.gray=styles.color.blackBright,styles.bgColor.bgGray=styles.bgColor.bgBlackBright,styles.color.grey=styles.color.blackBright,styles.bgColor.bgGrey=styles.bgColor.bgBlackBright;for(let[groupName,group]of Object.entries(styles)){for(let[styleName,style]of Object.entries(group))styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:codes,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",setLazyProperty(styles.color,"ansi",()=>makeDynamicStyles(wrapAnsi16,"ansi16",ansi2ansi,!1)),setLazyProperty(styles.color,"ansi256",()=>makeDynamicStyles(wrapAnsi256,"ansi256",ansi2ansi,!1)),setLazyProperty(styles.color,"ansi16m",()=>makeDynamicStyles(wrapAnsi16m,"rgb",rgb2rgb,!1)),setLazyProperty(styles.bgColor,"ansi",()=>makeDynamicStyles(wrapAnsi16,"ansi16",ansi2ansi,!0)),setLazyProperty(styles.bgColor,"ansi256",()=>makeDynamicStyles(wrapAnsi256,"ansi256",ansi2ansi,!0)),setLazyProperty(styles.bgColor,"ansi16m",()=>makeDynamicStyles(wrapAnsi16m,"rgb",rgb2rgb,!0)),styles}Object.defineProperty(module,"exports",{enumerable:!0,get:assembleStyles})});var require_wrap_ansi=__commonJS((exports,module)=>{var stringWidth=require_string_width(),stripAnsi=require_strip_ansi(),ansiStyles=require_ansi_styles(),ESCAPES=new Set(["\x1B","\x9B"]),wrapAnsi=(code)=>`${ESCAPES.values().next().value}[${code}m`,wordLengths=(string)=>string.split(" ").map((character)=>stringWidth(character)),wrapWord=(rows,word,columns)=>{let characters=[...word],isInsideEscape=!1,visible=stringWidth(stripAnsi(rows[rows.length-1]));for(let[index,character]of characters.entries()){let characterLength=stringWidth(character);if(visible+characterLength<=columns)rows[rows.length-1]+=character;else rows.push(character),visible=0;if(ESCAPES.has(character))isInsideEscape=!0;else if(isInsideEscape&&character==="m"){isInsideEscape=!1;continue}if(isInsideEscape)continue;if(visible+=characterLength,visible===columns&&index<characters.length-1)rows.push(""),visible=0}if(!visible&&rows[rows.length-1].length>0&&rows.length>1)rows[rows.length-2]+=rows.pop()},stringVisibleTrimSpacesRight=(str)=>{let words=str.split(" "),last=words.length;while(last>0){if(stringWidth(words[last-1])>0)break;last--}if(last===words.length)return str;return words.slice(0,last).join(" ")+words.slice(last).join("")},exec=(string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let pre="",ret="",escapeCode,lengths=wordLengths(string),rows=[""];for(let[index,word]of string.split(" ").entries()){if(options.trim!==!1)rows[rows.length-1]=rows[rows.length-1].trimLeft();let rowLength=stringWidth(rows[rows.length-1]);if(index!==0){if(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1))rows.push(""),rowLength=0;if(rowLength>0||options.trim===!1)rows[rows.length-1]+=" ",rowLength++}if(options.hard&&lengths[index]>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((lengths[index]-remainingColumns-1)/columns);if(Math.floor((lengths[index]-1)/columns)<breaksStartingThisLine)rows.push("");wrapWord(rows,word,columns);continue}if(rowLength+lengths[index]>columns&&rowLength>0&&lengths[index]>0){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns);continue}rows.push("")}if(rowLength+lengths[index]>columns&&options.wordWrap===!1){wrapWord(rows,word,columns);continue}rows[rows.length-1]+=word}if(options.trim!==!1)rows=rows.map(stringVisibleTrimSpacesRight);pre=rows.join(`
|
|
@@ -166,7 +166,7 @@ disable_paste_burst = true
|
|
|
166
166
|
tell.location
|
|
167
167
|
from (select lo_tell64($1) as location) tell
|
|
168
168
|
) seek
|
|
169
|
-
`};return resolve2(lo),new Promise(async(r)=>finish=r);async function readable({highWaterMark=16384,start=0,end=1/0}={}){let max=end-start;return start&&await lo.seek(start),new Stream2.Readable({highWaterMark,async read(size){let l=size>max?size-max:size;max-=size;let[{data}]=await lo.read(l);if(this.push(data),data.length<size)this.push(null)}})}async function writable({highWaterMark=16384,start=0}={}){return start&&await lo.seek(start),new Stream2.Writable({highWaterMark,write(chunk,encoding,callback){lo.write(chunk).then(()=>callback(),callback)}})}}).catch(reject)})}var init_large=()=>{};var exports_src={};__export(exports_src,{default:()=>src_default});import os from"os";import fs from"fs";function Postgres(a,b2){let options=parseOptions(a,b2),subscribe=options.no_subscribe||Subscribe(Postgres,{...options}),ending=!1,queries=queue_default(),connecting=queue_default(),reserved=queue_default(),closed=queue_default(),ended=queue_default(),open=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open,busy,full},connections=[...Array(options.max)].map(()=>connection_default(options,queues,{onopen,onend,onclose})),sql=Sql(handler);return Object.assign(sql,{get parameters(){return options.parameters},largeObject:largeObject.bind(null,sql),subscribe,CLOSE,END:CLOSE,PostgresError,options,reserve,listen,begin,close,end}),sql;function Sql(handler2){return handler2.debug=options.debug,Object.entries(options.types).reduce((acc,[name,type])=>{return acc[name]=(x)=>new Parameter(x,type.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json,file}),sql2;function typed(value,type){return new Parameter(value,type)}function sql2(strings,...args){return strings&&Array.isArray(strings.raw)?new Query(strings,args,handler2,cancel):typeof strings==="string"&&!args.length?new Identifier(options.transform.column.to?options.transform.column.to(strings):strings):new Builder(strings,args)}function unsafe(string,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([string],args,handler2,cancel,{prepare:!1,...options2,simple:"simple"in options2?options2.simple:args.length===0})}function file(path,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([],args,(query2)=>{fs.readFile(path,"utf8",(err,string)=>{if(err)return query2.reject(err);query2.strings=[string],handler2(query2)})},cancel,{...options2,simple:"simple"in options2?options2.simple:args.length===0})}}async function listen(name,fn,onlisten){let listener={fn,onlisten},sql2=listen.sql||(listen.sql=Postgres({...options,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(listen.channels).forEach(([name2,{listeners}])=>{delete listen.channels[name2],Promise.all(listeners.map((l)=>listen(name2,l.fn,l.onlisten).catch(()=>{})))})},onnotify(c,x){c in listen.channels&&listen.channels[c].listeners.forEach((l)=>l.fn(x))}})),channels=listen.channels||(listen.channels={});if(name in channels){channels[name].listeners.push(listener);let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result.state,unlisten};async function unlisten(){if(name in channels===!1)return;if(channels[name].listeners=channels[name].listeners.filter((x)=>x!==listener),channels[name].listeners.length)return;return delete channels[name],sql2`unlisten ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`}}async function notify(channel,payload){return await sql`select pg_notify(${channel}, ${""+payload})`}async function reserve(){let queue=queue_default(),c=open.length?open.shift():await new Promise((resolve2,reject)=>{let query={reserve:resolve2,reject};queries.push(query),closed.length&&connect(closed.shift(),query)});move(c,reserved),c.reserved=()=>queue.length?c.execute(queue.shift()):move(c,reserved),c.reserved.release=!0;let sql2=Sql(handler2);return sql2.release=()=>{c.reserved=null,onopen(c)},sql2;function handler2(q){c.queue===full?queue.push(q):c.execute(q)||move(c,full)}}async function begin(options2,fn){!fn&&(fn=options2,options2="");let queries2=queue_default(),savepoints=0,connection2,prepare=null;try{return await sql.unsafe("begin "+options2.replace(/[^a-z ]/ig,""),[],{onexecute}).execute(),await Promise.race([scope(connection2,fn),new Promise((_,reject)=>connection2.onclose=reject)])}catch(error2){throw error2}async function scope(c,fn2,name){let sql2=Sql(handler2);sql2.savepoint=savepoint,sql2.prepare=(x)=>prepare=x.replace(/[^a-z0-9$-_. ]/gi);let uncaughtError,result;name&&await sql2`savepoint ${sql2(name)}`;try{if(result=await new Promise((resolve2,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve2,reject)}),uncaughtError)throw uncaughtError}catch(e){throw await(name?sql2`rollback to ${sql2(name)}`:sql2`rollback`),e instanceof PostgresError&&e.code==="25P02"&&uncaughtError||e}if(!name)prepare?await sql2`prepare transaction '${sql2.unsafe(prepare)}'`:await sql2`commit`;return result;function savepoint(name2,fn3){if(name2&&Array.isArray(name2.raw))return savepoint((sql3)=>sql3.apply(sql3,arguments));return arguments.length===1&&(fn3=name2,name2=null),scope(c,fn3,"s"+savepoints+++(name2?"_"+name2:""))}function handler2(q){q.catch((e)=>uncaughtError||(uncaughtError=e)),c.queue===full?queries2.push(q):c.execute(q)||move(c,full)}}function onexecute(c){connection2=c,move(c,reserved),c.reserved=()=>queries2.length?c.execute(queries2.shift()):move(c,reserved)}}function move(c,queue){return c.queue.remove(c),queue.push(c),c.queue=queue,queue===open?c.idleTimer.start():c.idleTimer.cancel(),c}function json(x){return new Parameter(x,3802)}function array(x,type){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type||(x.length?inferType(x)||25:0),options.shared.typeArrayMap)}function handler(query){if(ending)return query.reject(Errors.connection("CONNECTION_ENDED",options,options));if(open.length)return go(open.shift(),query);if(closed.length)return connect(closed.shift(),query);busy.length?go(busy.shift(),query):queries.push(query)}function go(c,query){return c.execute(query)?move(c,busy):move(c,full)}function cancel(query){return new Promise((resolve2,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve2,reject):query.cancelled={resolve:resolve2,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve2())})}async function end({timeout=null}={}){if(ending)return ending;await 1;let timer2;return ending=Promise.race([new Promise((r)=>timeout!==null&&(timer2=setTimeout(destroy,timeout*1000,r))),Promise.all(connections.map((c)=>c.end()).concat(listen.sql?listen.sql.end({timeout:0}):[],subscribe.sql?subscribe.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(timer2))}async function close(){await Promise.all(connections.map((c)=>c.end()))}async function destroy(resolve2){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve2()}function connect(c,query){return move(c,connecting),c.connect(query),c}function onend(c){move(c,ended)}function onopen(c){if(queries.length===0)return move(c,open);let max=Math.ceil(queries.length/(connecting.length+1)),ready=!0;while(ready&&queries.length&&max-- >0){let query=queries.shift();if(query.reserve)return query.reserve(c);ready=c.execute(query)}ready?move(c,busy):move(c,full)}function onclose(c,e){move(c,closed),c.reserved=null,c.onclose&&(c.onclose(e),c.onclose=null),options.onclose&&options.onclose(c.id),queries.length&&connect(c,queries.shift())}}function parseOptions(a,b2){if(a&&a.shared)return a;let env=process.env,o=(!a||typeof a==="string"?b2:a)||{},{url,multihost}=parseUrl(a),query=[...url.searchParams].reduce((a2,[b3,c])=>(a2[b3]=c,a2),{}),host=o.hostname||o.host||multihost||url.hostname||env.PGHOST||"localhost",port=o.port||url.port||env.PGPORT||5432,user=o.user||o.username||url.username||env.PGUSERNAME||env.PGUSER||osUsername();o.no_prepare&&(o.prepare=!1),query.sslmode&&(query.ssl=query.sslmode,delete query.sslmode),"timeout"in o&&(console.log("The timeout option is deprecated, use idle_timeout instead"),o.idle_timeout=o.timeout),query.sslrootcert==="system"&&(query.ssl="verify-full");let ints=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],defaults={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime,max_pipeline:100,backoff,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(host)?host:host.split(",").map((x)=>x.split(":")[0]),port:Array.isArray(port)?port:host.split(",").map((x)=>parseInt(x.split(":")[1]||port)),path:o.path||host.indexOf("/")>-1&&host+"/.s.PGSQL."+port,database:o.database||o.db||(url.pathname||"").slice(1)||env.PGDATABASE||user,user,pass:o.pass||o.password||url.password||env.PGPASSWORD||"",...Object.entries(defaults).reduce((acc,[k,d])=>{let value=k in o?o[k]:(k in query)?query[k]==="disable"||query[k]==="false"?!1:query[k]:env["PG"+k.toUpperCase()]||d;return acc[k]=typeof value==="string"&&ints.includes(k)?+value:value,acc},{}),connection:{application_name:env.PGAPPNAME||"postgres.js",...o.connection,...Object.entries(query).reduce((acc,[k,v])=>((k in defaults)||(acc[k]=v),acc),{})},types:o.types||{},target_session_attrs:tsa(o,url,env),onnotice:o.onnotice,onnotify:o.onnotify,onclose:o.onclose,onparameter:o.onparameter,socket:o.socket,transform:parseTransform(o.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...mergeUserTypes(o.types)}}function tsa(o,url,env){let x=o.target_session_attrs||url.searchParams.get("target_session_attrs")||env.PGTARGETSESSIONATTRS;if(!x||["read-write","read-only","primary","standby","prefer-standby"].includes(x))return x;throw Error("target_session_attrs "+x+" is not supported")}function backoff(retries){return(0.5+Math.random()/2)*Math.min(3**retries/100,20)}function max_lifetime(){return 60*(30+Math.random()*30)}function parseTransform(x){return{undefined:x.undefined,column:{from:typeof x.column==="function"?x.column:x.column&&x.column.from,to:x.column&&x.column.to},value:{from:typeof x.value==="function"?x.value:x.value&&x.value.from,to:x.value&&x.value.to},row:{from:typeof x.row==="function"?x.row:x.row&&x.row.from,to:x.row&&x.row.to}}}function parseUrl(url){if(!url||typeof url!=="string")return{url:{searchParams:new Map}};let host=url;host=host.slice(host.indexOf("://")+3).split(/[?/]/)[0],host=decodeURIComponent(host.slice(host.indexOf("@")+1));let urlObj=new URL(url.replace(host,host.split(",")[0]));return{url:{username:decodeURIComponent(urlObj.username),password:decodeURIComponent(urlObj.password),host:urlObj.host,hostname:urlObj.hostname,port:urlObj.port,pathname:urlObj.pathname,searchParams:urlObj.searchParams},multihost:host.indexOf(",")>-1&&host}}function osUsername(){try{return os.userInfo().username}catch(_){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}var src_default;var init_src=__esm(()=>{init_types2();init_connection();init_query();init_queue();init_errors3();init_large();Object.assign(Postgres,{PostgresError,toPascal,pascal,toCamel,camel,toKebab,kebab,fromPascal,fromCamel,fromKebab,BigInt:{to:20,from:[20],parse:(x)=>BigInt(x),serialize:(x)=>x.toString()}});src_default=Postgres});var exports_db={};__export(exports_db,{shutdown:()=>shutdown,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve});import{execSync as execSync3,spawn as spawn2}from"child_process";import{existsSync as existsSync12,mkdirSync as mkdirSync6,readFileSync as readFileSync6,renameSync,unlinkSync as unlinkSync5,writeFileSync as writeFileSync6}from"fs";import{homedir as homedir12}from"os";import{join as join13}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function selfHealPostgres(dataDir){try{execSync3(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync3(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join13(dataDir,"postmaster.pid");if(existsSync12(pidFile))try{unlinkSync5(pidFile)}catch{}try{execSync3("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000})}catch{}}function getPort(){let envPort=process.env.GENIE_PG_PORT;if(envPort){let parsed=Number.parseInt(envPort,10);if(!Number.isNaN(parsed)&&parsed>0&&parsed<65536)return parsed}return DEFAULT_PORT}async function isPostgresHealthy(port){try{return await Promise.race([(async()=>{let pg=(await Promise.resolve().then(() => (init_src(),exports_src))).default,probe=pg({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:1,connect_timeout:3,idle_timeout:1});try{return await probe`SELECT 1`,await probe.end({timeout:2}),!0}catch{try{await probe.end({timeout:1})}catch{}return!1}})(),new Promise((resolve2)=>{setTimeout(()=>resolve2(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync6(LOCKFILE_PATH,"utf-8").trim(),port=Number.parseInt(content,10);if(!Number.isNaN(port)&&port>0&&port<65536)return port}catch{}return null}function writeLockfile(port){try{mkdirSync6(GENIE_HOME2,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync6(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync5(LOCKFILE_PATH)}catch{}}async function ensurePgserve(){if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}async function autoStartDaemon(){let pidPath=join13(GENIE_HOME2,"scheduler.pid");try{let pidStr=readFileSync6(pidPath,"utf-8").trim(),pid=Number.parseInt(pidStr,10);if(!Number.isNaN(pid)&&pid>0)try{process.kill(pid,0);return}catch{}}catch{}let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn2(bunPath,[genieBin,"daemon","start"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()}async function _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),portFromFile=readLockfile();if(portFromFile!==null&&await isPostgresHealthy(portFromFile))return activePort=portFromFile,process.env.GENIE_PG_AVAILABLE="true",portFromFile;if(await isPostgresHealthy(port))return activePort=port,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(process.env.GENIE_IS_DAEMON==="1"||process.env.GENIE_APP==="1"){mkdirSync6(DATA_DIR,{recursive:!0}),selfHealPostgres(DATA_DIR);try{let startedPort=await startPgserveOnPort(port);return registerExitHandler(),startedPort}catch(err){process.env.GENIE_PG_AVAILABLE="false";let message=err instanceof Error?err.message:String(err);throw Error(`pgserve failed to start: ${maskCredentials(message)}`)}}await autoStartDaemon();let deadline=Date.now()+16000;while(Date.now()<deadline){let p=readLockfile();if(p!==null&&await isPostgresHealthy(p))return activePort=p,process.env.GENIE_PG_AVAILABLE="true",p;await new Promise((r)=>setTimeout(r,500))}throw process.env.GENIE_PG_AVAILABLE="false",Error("Timed out waiting for daemon to start pgserve (16s). Run: genie daemon start")}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync12(resolved))return resolved}catch{}let globalBin=join13(homedir12(),".bun","bin","pgserve");if(existsSync12(globalBin))return globalBin;try{return execSync3("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync6(DATA_DIR,{recursive:!0});let child=spawn2(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let deadline=Date.now()+15000;while(Date.now()<deadline){if(await isPostgresHealthy(port))return activePort=port,ownsLockfile=!0,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;await new Promise((r)=>setTimeout(r,500))}try{child.kill("SIGTERM")}catch{}throw Error(`pgserve failed to start on port ${port} (timeout after 15s)`)}function registerExitHandler(){if(exitHandlerRegistered)return;exitHandlerRegistered=!0;let cleanup=()=>{if(pgserveChild){try{pgserveChild.kill("SIGTERM")}catch{}pgserveChild=null}if(ownsLockfile)removeLockfile(),ownsLockfile=!1};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit(130)}),process.on("SIGTERM",()=>{cleanup(),process.exit(143)})}async function getConnection(){if(sqlClient)try{return await sqlClient`SELECT 1`,sqlClient}catch{try{await sqlClient.end({timeout:2})}catch{}sqlClient=null,activePort=null}let port=await ensurePgserve(),postgres2=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testSchema=process.env.GENIE_TEST_SCHEMA;sqlClient=postgres2({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning",...testSchema?{search_path:`${testSchema}, public`}:{}}});try{if(await runMigrations(sqlClient),!testSchema&&needsSeed())await runSeed(sqlClient)}catch(err){try{await sqlClient.end({timeout:2})}catch{}throw sqlClient=null,err}return sqlClient}function isConnected(){return sqlClient!==null}async function resetConnection(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null}async function isAvailable(){try{return await(await getConnection())`SELECT 1`,!0}catch{return!1}}async function shutdown(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1}function getDataDir(){return DATA_DIR}function getActivePort(){return activePort??getPort()}function getLockfilePath(){return LOCKFILE_PATH}var DEFAULT_PORT=19642,DEFAULT_HOST="127.0.0.1",GENIE_HOME2,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,ownsLockfile=!1,exitHandlerRegistered=!1;var init_db=__esm(()=>{init_db_migrations();init_pg_seed();GENIE_HOME2=process.env.GENIE_HOME??join13(homedir12(),".genie"),DATA_DIR=join13(GENIE_HOME2,"data","pgserve"),LOCKFILE_PATH=join13(GENIE_HOME2,"pgserve.port")});var exports_audit={};__export(exports_audit,{recordAuditEvent:()=>recordAuditEvent,queryToolUsage:()=>queryToolUsage,queryTimeline:()=>queryTimeline,querySummary:()=>querySummary,queryErrorPatterns:()=>queryErrorPatterns,queryCostBreakdown:()=>queryCostBreakdown,queryAuditEvents:()=>queryAuditEvents,getActor:()=>getActor,generateTraceId:()=>generateTraceId});async function recordAuditEvent(entityType,entityId,eventType,actor,details){try{if(!await isAvailable())return;let sql=await getConnection();await sql`
|
|
169
|
+
`};return resolve2(lo),new Promise(async(r)=>finish=r);async function readable({highWaterMark=16384,start=0,end=1/0}={}){let max=end-start;return start&&await lo.seek(start),new Stream2.Readable({highWaterMark,async read(size){let l=size>max?size-max:size;max-=size;let[{data}]=await lo.read(l);if(this.push(data),data.length<size)this.push(null)}})}async function writable({highWaterMark=16384,start=0}={}){return start&&await lo.seek(start),new Stream2.Writable({highWaterMark,write(chunk,encoding,callback){lo.write(chunk).then(()=>callback(),callback)}})}}).catch(reject)})}var init_large=()=>{};var exports_src={};__export(exports_src,{default:()=>src_default});import os from"os";import fs from"fs";function Postgres(a,b2){let options=parseOptions(a,b2),subscribe=options.no_subscribe||Subscribe(Postgres,{...options}),ending=!1,queries=queue_default(),connecting=queue_default(),reserved=queue_default(),closed=queue_default(),ended=queue_default(),open=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open,busy,full},connections=[...Array(options.max)].map(()=>connection_default(options,queues,{onopen,onend,onclose})),sql=Sql(handler);return Object.assign(sql,{get parameters(){return options.parameters},largeObject:largeObject.bind(null,sql),subscribe,CLOSE,END:CLOSE,PostgresError,options,reserve,listen,begin,close,end}),sql;function Sql(handler2){return handler2.debug=options.debug,Object.entries(options.types).reduce((acc,[name,type])=>{return acc[name]=(x)=>new Parameter(x,type.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json,file}),sql2;function typed(value,type){return new Parameter(value,type)}function sql2(strings,...args){return strings&&Array.isArray(strings.raw)?new Query(strings,args,handler2,cancel):typeof strings==="string"&&!args.length?new Identifier(options.transform.column.to?options.transform.column.to(strings):strings):new Builder(strings,args)}function unsafe(string,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([string],args,handler2,cancel,{prepare:!1,...options2,simple:"simple"in options2?options2.simple:args.length===0})}function file(path,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([],args,(query2)=>{fs.readFile(path,"utf8",(err,string)=>{if(err)return query2.reject(err);query2.strings=[string],handler2(query2)})},cancel,{...options2,simple:"simple"in options2?options2.simple:args.length===0})}}async function listen(name,fn,onlisten){let listener={fn,onlisten},sql2=listen.sql||(listen.sql=Postgres({...options,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(listen.channels).forEach(([name2,{listeners}])=>{delete listen.channels[name2],Promise.all(listeners.map((l)=>listen(name2,l.fn,l.onlisten).catch(()=>{})))})},onnotify(c,x){c in listen.channels&&listen.channels[c].listeners.forEach((l)=>l.fn(x))}})),channels=listen.channels||(listen.channels={});if(name in channels){channels[name].listeners.push(listener);let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result.state,unlisten};async function unlisten(){if(name in channels===!1)return;if(channels[name].listeners=channels[name].listeners.filter((x)=>x!==listener),channels[name].listeners.length)return;return delete channels[name],sql2`unlisten ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`}}async function notify(channel,payload){return await sql`select pg_notify(${channel}, ${""+payload})`}async function reserve(){let queue=queue_default(),c=open.length?open.shift():await new Promise((resolve2,reject)=>{let query={reserve:resolve2,reject};queries.push(query),closed.length&&connect(closed.shift(),query)});move(c,reserved),c.reserved=()=>queue.length?c.execute(queue.shift()):move(c,reserved),c.reserved.release=!0;let sql2=Sql(handler2);return sql2.release=()=>{c.reserved=null,onopen(c)},sql2;function handler2(q){c.queue===full?queue.push(q):c.execute(q)||move(c,full)}}async function begin(options2,fn){!fn&&(fn=options2,options2="");let queries2=queue_default(),savepoints=0,connection2,prepare=null;try{return await sql.unsafe("begin "+options2.replace(/[^a-z ]/ig,""),[],{onexecute}).execute(),await Promise.race([scope(connection2,fn),new Promise((_,reject)=>connection2.onclose=reject)])}catch(error2){throw error2}async function scope(c,fn2,name){let sql2=Sql(handler2);sql2.savepoint=savepoint,sql2.prepare=(x)=>prepare=x.replace(/[^a-z0-9$-_. ]/gi);let uncaughtError,result;name&&await sql2`savepoint ${sql2(name)}`;try{if(result=await new Promise((resolve2,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve2,reject)}),uncaughtError)throw uncaughtError}catch(e){throw await(name?sql2`rollback to ${sql2(name)}`:sql2`rollback`),e instanceof PostgresError&&e.code==="25P02"&&uncaughtError||e}if(!name)prepare?await sql2`prepare transaction '${sql2.unsafe(prepare)}'`:await sql2`commit`;return result;function savepoint(name2,fn3){if(name2&&Array.isArray(name2.raw))return savepoint((sql3)=>sql3.apply(sql3,arguments));return arguments.length===1&&(fn3=name2,name2=null),scope(c,fn3,"s"+savepoints+++(name2?"_"+name2:""))}function handler2(q){q.catch((e)=>uncaughtError||(uncaughtError=e)),c.queue===full?queries2.push(q):c.execute(q)||move(c,full)}}function onexecute(c){connection2=c,move(c,reserved),c.reserved=()=>queries2.length?c.execute(queries2.shift()):move(c,reserved)}}function move(c,queue){return c.queue.remove(c),queue.push(c),c.queue=queue,queue===open?c.idleTimer.start():c.idleTimer.cancel(),c}function json(x){return new Parameter(x,3802)}function array(x,type){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type||(x.length?inferType(x)||25:0),options.shared.typeArrayMap)}function handler(query){if(ending)return query.reject(Errors.connection("CONNECTION_ENDED",options,options));if(open.length)return go(open.shift(),query);if(closed.length)return connect(closed.shift(),query);busy.length?go(busy.shift(),query):queries.push(query)}function go(c,query){return c.execute(query)?move(c,busy):move(c,full)}function cancel(query){return new Promise((resolve2,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve2,reject):query.cancelled={resolve:resolve2,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve2())})}async function end({timeout=null}={}){if(ending)return ending;await 1;let timer2;return ending=Promise.race([new Promise((r)=>timeout!==null&&(timer2=setTimeout(destroy,timeout*1000,r))),Promise.all(connections.map((c)=>c.end()).concat(listen.sql?listen.sql.end({timeout:0}):[],subscribe.sql?subscribe.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(timer2))}async function close(){await Promise.all(connections.map((c)=>c.end()))}async function destroy(resolve2){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve2()}function connect(c,query){return move(c,connecting),c.connect(query),c}function onend(c){move(c,ended)}function onopen(c){if(queries.length===0)return move(c,open);let max=Math.ceil(queries.length/(connecting.length+1)),ready=!0;while(ready&&queries.length&&max-- >0){let query=queries.shift();if(query.reserve)return query.reserve(c);ready=c.execute(query)}ready?move(c,busy):move(c,full)}function onclose(c,e){move(c,closed),c.reserved=null,c.onclose&&(c.onclose(e),c.onclose=null),options.onclose&&options.onclose(c.id),queries.length&&connect(c,queries.shift())}}function parseOptions(a,b2){if(a&&a.shared)return a;let env=process.env,o=(!a||typeof a==="string"?b2:a)||{},{url,multihost}=parseUrl(a),query=[...url.searchParams].reduce((a2,[b3,c])=>(a2[b3]=c,a2),{}),host=o.hostname||o.host||multihost||url.hostname||env.PGHOST||"localhost",port=o.port||url.port||env.PGPORT||5432,user=o.user||o.username||url.username||env.PGUSERNAME||env.PGUSER||osUsername();o.no_prepare&&(o.prepare=!1),query.sslmode&&(query.ssl=query.sslmode,delete query.sslmode),"timeout"in o&&(console.log("The timeout option is deprecated, use idle_timeout instead"),o.idle_timeout=o.timeout),query.sslrootcert==="system"&&(query.ssl="verify-full");let ints=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],defaults={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime,max_pipeline:100,backoff,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(host)?host:host.split(",").map((x)=>x.split(":")[0]),port:Array.isArray(port)?port:host.split(",").map((x)=>parseInt(x.split(":")[1]||port)),path:o.path||host.indexOf("/")>-1&&host+"/.s.PGSQL."+port,database:o.database||o.db||(url.pathname||"").slice(1)||env.PGDATABASE||user,user,pass:o.pass||o.password||url.password||env.PGPASSWORD||"",...Object.entries(defaults).reduce((acc,[k,d])=>{let value=k in o?o[k]:(k in query)?query[k]==="disable"||query[k]==="false"?!1:query[k]:env["PG"+k.toUpperCase()]||d;return acc[k]=typeof value==="string"&&ints.includes(k)?+value:value,acc},{}),connection:{application_name:env.PGAPPNAME||"postgres.js",...o.connection,...Object.entries(query).reduce((acc,[k,v])=>((k in defaults)||(acc[k]=v),acc),{})},types:o.types||{},target_session_attrs:tsa(o,url,env),onnotice:o.onnotice,onnotify:o.onnotify,onclose:o.onclose,onparameter:o.onparameter,socket:o.socket,transform:parseTransform(o.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...mergeUserTypes(o.types)}}function tsa(o,url,env){let x=o.target_session_attrs||url.searchParams.get("target_session_attrs")||env.PGTARGETSESSIONATTRS;if(!x||["read-write","read-only","primary","standby","prefer-standby"].includes(x))return x;throw Error("target_session_attrs "+x+" is not supported")}function backoff(retries){return(0.5+Math.random()/2)*Math.min(3**retries/100,20)}function max_lifetime(){return 60*(30+Math.random()*30)}function parseTransform(x){return{undefined:x.undefined,column:{from:typeof x.column==="function"?x.column:x.column&&x.column.from,to:x.column&&x.column.to},value:{from:typeof x.value==="function"?x.value:x.value&&x.value.from,to:x.value&&x.value.to},row:{from:typeof x.row==="function"?x.row:x.row&&x.row.from,to:x.row&&x.row.to}}}function parseUrl(url){if(!url||typeof url!=="string")return{url:{searchParams:new Map}};let host=url;host=host.slice(host.indexOf("://")+3).split(/[?/]/)[0],host=decodeURIComponent(host.slice(host.indexOf("@")+1));let urlObj=new URL(url.replace(host,host.split(",")[0]));return{url:{username:decodeURIComponent(urlObj.username),password:decodeURIComponent(urlObj.password),host:urlObj.host,hostname:urlObj.hostname,port:urlObj.port,pathname:urlObj.pathname,searchParams:urlObj.searchParams},multihost:host.indexOf(",")>-1&&host}}function osUsername(){try{return os.userInfo().username}catch(_){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}var src_default;var init_src=__esm(()=>{init_types2();init_connection();init_query();init_queue();init_errors3();init_large();Object.assign(Postgres,{PostgresError,toPascal,pascal,toCamel,camel,toKebab,kebab,fromPascal,fromCamel,fromKebab,BigInt:{to:20,from:[20],parse:(x)=>BigInt(x),serialize:(x)=>x.toString()}});src_default=Postgres});var exports_db={};__export(exports_db,{shutdown:()=>shutdown,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve});import{execSync as execSync3,spawn as spawn2}from"child_process";import{existsSync as existsSync12,mkdirSync as mkdirSync6,readFileSync as readFileSync6,renameSync,unlinkSync as unlinkSync5,writeFileSync as writeFileSync6}from"fs";import{homedir as homedir12}from"os";import{join as join13}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function selfHealPostgres(dataDir){try{execSync3(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync3(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join13(dataDir,"postmaster.pid");if(existsSync12(pidFile))try{unlinkSync5(pidFile)}catch{}try{execSync3("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000})}catch{}}function getPort(){let envPort=process.env.GENIE_PG_PORT;if(envPort){let parsed=Number.parseInt(envPort,10);if(!Number.isNaN(parsed)&&parsed>0&&parsed<65536)return parsed}return DEFAULT_PORT}async function isPostgresHealthy(port){try{return await Promise.race([(async()=>{let pg=(await Promise.resolve().then(() => (init_src(),exports_src))).default,probe=pg({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:1,connect_timeout:3,idle_timeout:1});try{return await probe`SELECT 1`,await probe.end({timeout:2}),!0}catch{try{await probe.end({timeout:1})}catch{}return!1}})(),new Promise((resolve2)=>{setTimeout(()=>resolve2(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync6(LOCKFILE_PATH,"utf-8").trim(),port=Number.parseInt(content,10);if(!Number.isNaN(port)&&port>0&&port<65536)return port}catch{}return null}function writeLockfile(port){try{mkdirSync6(GENIE_HOME2,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync6(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync5(LOCKFILE_PATH)}catch{}}async function ensurePgserve(){if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}async function autoStartDaemon(){let pidPath=join13(GENIE_HOME2,"scheduler.pid");try{let pidStr=readFileSync6(pidPath,"utf-8").trim(),pid=Number.parseInt(pidStr,10);if(!Number.isNaN(pid)&&pid>0)try{process.kill(pid,0);return}catch{}}catch{}let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn2(bunPath,[genieBin,"daemon","start"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()}async function _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),portFromFile=readLockfile();if(portFromFile!==null&&await isPostgresHealthy(portFromFile))return activePort=portFromFile,process.env.GENIE_PG_AVAILABLE="true",portFromFile;if(await isPostgresHealthy(port))return activePort=port,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(process.env.GENIE_IS_DAEMON==="1"||process.env.GENIE_APP==="1"){mkdirSync6(DATA_DIR,{recursive:!0}),selfHealPostgres(DATA_DIR);try{let startedPort=await startPgserveOnPort(port);return registerExitHandler(),startedPort}catch(err){process.env.GENIE_PG_AVAILABLE="false";let message=err instanceof Error?err.message:String(err);throw Error(`pgserve failed to start: ${maskCredentials(message)}`)}}await autoStartDaemon();let deadline=Date.now()+16000;while(Date.now()<deadline){let p=readLockfile();if(p!==null&&await isPostgresHealthy(p))return activePort=p,process.env.GENIE_PG_AVAILABLE="true",p;await new Promise((r)=>setTimeout(r,500))}throw process.env.GENIE_PG_AVAILABLE="false",Error("Timed out waiting for daemon to start pgserve (16s). Run: genie daemon start")}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync12(resolved))return resolved}catch{}let globalBin=join13(homedir12(),".bun","bin","pgserve");if(existsSync12(globalBin))return globalBin;try{return execSync3("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync6(DATA_DIR,{recursive:!0});let child=spawn2(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let deadline=Date.now()+15000;while(Date.now()<deadline){if(await isPostgresHealthy(port))return activePort=port,ownsLockfile=!0,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;await new Promise((r)=>setTimeout(r,500))}try{child.kill("SIGTERM")}catch{}throw Error(`pgserve failed to start on port ${port} (timeout after 15s)`)}function registerExitHandler(){if(exitHandlerRegistered)return;exitHandlerRegistered=!0;let cleanup=()=>{if(pgserveChild){try{pgserveChild.kill("SIGTERM")}catch{}pgserveChild=null}if(ownsLockfile)removeLockfile(),ownsLockfile=!1};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit(130)}),process.on("SIGTERM",()=>{cleanup(),process.exit(143)})}async function getConnection(){if(sqlClient)try{return await sqlClient`SELECT 1`,sqlClient}catch{try{await sqlClient.end({timeout:2})}catch{}sqlClient=null,activePort=null}let port=await ensurePgserve(),postgres2=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testSchema=process.env.GENIE_TEST_SCHEMA;sqlClient=postgres2({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning",...testSchema?{search_path:`${testSchema}, public`}:{}}});try{if(!testSchema)await runMigrations(sqlClient);if(!testSchema&&needsSeed())await runSeed(sqlClient)}catch(err){try{await sqlClient.end({timeout:2})}catch{}throw sqlClient=null,err}return sqlClient}function isConnected(){return sqlClient!==null}async function resetConnection(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null}async function isAvailable(){try{return await(await getConnection())`SELECT 1`,!0}catch{return!1}}async function shutdown(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1}function getDataDir(){return DATA_DIR}function getActivePort(){return activePort??getPort()}function getLockfilePath(){return LOCKFILE_PATH}var DEFAULT_PORT=19642,DEFAULT_HOST="127.0.0.1",GENIE_HOME2,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,ownsLockfile=!1,exitHandlerRegistered=!1;var init_db=__esm(()=>{init_db_migrations();init_pg_seed();GENIE_HOME2=process.env.GENIE_HOME??join13(homedir12(),".genie"),DATA_DIR=join13(GENIE_HOME2,"data","pgserve"),LOCKFILE_PATH=join13(GENIE_HOME2,"pgserve.port")});var exports_audit={};__export(exports_audit,{recordAuditEvent:()=>recordAuditEvent,queryToolUsage:()=>queryToolUsage,queryTimeline:()=>queryTimeline,querySummary:()=>querySummary,queryErrorPatterns:()=>queryErrorPatterns,queryCostBreakdown:()=>queryCostBreakdown,queryAuditEvents:()=>queryAuditEvents,getActor:()=>getActor,generateTraceId:()=>generateTraceId});async function recordAuditEvent(entityType,entityId,eventType,actor,details){try{if(!await isAvailable())return;let sql=await getConnection();await sql`
|
|
170
170
|
INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
|
|
171
171
|
VALUES (${entityType}, ${entityId}, ${eventType}, ${actor??null}, ${sql.json(details??{})})
|
|
172
172
|
`}catch{}}function parseSince(since){let match=since.match(/^(\d+)([smhd])$/);if(!match)return since;let amount=Number.parseInt(match[1],10),unit=match[2],ms={s:1000,m:60000,h:3600000,d:86400000}[unit]??3600000;return new Date(Date.now()-amount*ms).toISOString()}async function queryAuditEvents(options={}){let sql=await getConnection(),conditions=[],values2=[],paramIdx=1;if(options.type)conditions.push(`event_type = $${paramIdx++}`),values2.push(options.type);if(options.entity)conditions.push(`(entity_type = $${paramIdx} OR entity_id = $${paramIdx})`),paramIdx++,values2.push(options.entity);if(options.since)conditions.push(`created_at >= $${paramIdx++}::timestamptz`),values2.push(parseSince(options.since));if(options.errorsOnly)conditions.push("event_type LIKE '%error%' OR (details::text LIKE '%error%')");let where=conditions.length>0?`WHERE ${conditions.join(" AND ")}`:"",limit=options.limit??50;return await sql.unsafe(`SELECT id, entity_type, entity_id, event_type, actor, details, created_at
|
|
@@ -587,7 +587,7 @@ Run 'genie agent list' to list agents.`)}async function resolveTarget(target,opt
|
|
|
587
587
|
ORDER BY m.created_at DESC
|
|
588
588
|
LIMIT 100
|
|
589
589
|
`).map((r)=>({id:r.id,requestType:r.request_type,senderId:r.sender_id,body:r.body,createdAt:r.created_at instanceof Date?r.created_at.toISOString():String(r.created_at)}))}async function generateBrief(options){let teamConfig=await getTeam(options.team);if(!teamConfig)throw Error(`Team not found: ${options.team}`);let since=await resolveSince(options),repoPath=options.repoPath??teamConfig.repo,agentName=options.agent??teamConfig.leader??null,agentIdentifiers=agentName?[agentName]:[],[unreadMessages,taskMessages,recentEvents,pendingRequests,teamRoster]=await Promise.all([agentIdentifiers.length>0?getUnread(repoPath,agentIdentifiers):Promise.resolve([]),getTaskMessages(options.team,since),listRuntimeEvents({team:options.team,since,limit:100}),getPendingRequestMessages(options.team),getTeamRoster(options.team)]);return{team:options.team,agent:agentName,since,unreadMessages,taskMessages,recentEvents,pendingRequests,teamRoster}}function truncate(text,max){return text.length>max?`${text.slice(0,max)}...`:text}function formatUnreadSection(messages2){if(messages2.length===0)return[];let lines=[`## Unread Messages (${messages2.length})`];for(let msg of messages2)lines.push(`- **${msg.from}**: ${truncate(msg.body,120)}`);return lines.push(""),lines}function formatTaskMessagesSection(messages2){if(messages2.length===0)return[];let lines=[`## Task Updates (${messages2.length})`],byTask=new Map;for(let msg of messages2){let existing=byTask.get(msg.taskId)??[];existing.push(msg),byTask.set(msg.taskId,existing)}for(let[taskId,msgs]of byTask){lines.push(`### ${taskId}: ${msgs[0].taskTitle}`);for(let msg of msgs)lines.push(`- [${msg.senderType}:${msg.senderId}] ${truncate(msg.body,100)}`)}return lines.push(""),lines}function formatRequestsSection(requests){if(requests.length===0)return[];let lines=[`## Pending Requests (${requests.length})`];for(let req of requests)lines.push(`- [${req.requestType}] ${req.senderId}: ${truncate(req.body,80)}`);return lines.push(""),lines}function formatRosterSection(roster){if(roster.length===0)return[];let lines=[`## Team Roster (${roster.length})`];for(let member of roster){let state=member.executorState??"offline",icon=STATE_ICONS[state]??"\u25CC";lines.push(`- ${icon} **${member.agentId}** (${member.role??"unassigned"}): ${state}`)}return lines.push(""),lines}function formatEventsSection(events){if(events.length===0)return[];let lines=[`## Recent Events (${events.length})`],tail=events.slice(-10);for(let evt of tail){let ts3=evt.timestamp.slice(11,16);lines.push(`- ${ts3} [${evt.kind}] ${evt.agent}: ${truncate(evt.text,80)}`)}if(events.length>10)lines.push(` _(${events.length-10} more events)_`);return lines.push(""),lines}function formatBrief(brief){let lines=[`# BRIEF \u2014 ${brief.team}${brief.agent?` ${brief.agent}`:""}`,`Since: ${brief.since}`,"",...formatUnreadSection(brief.unreadMessages),...formatTaskMessagesSection(brief.taskMessages),...formatRequestsSection(brief.pendingRequests),...formatRosterSection(brief.teamRoster),...formatEventsSection(brief.recentEvents)];if(!(brief.unreadMessages.length+brief.taskMessages.length+brief.pendingRequests.length+brief.recentEvents.length>0))lines.push("_No activity since last session._","");return lines.join(`
|
|
590
|
-
`)}var STATE_ICONS;var init_brief=__esm(()=>{init_db();init_mailbox();init_runtime_events();init_team_manager();STATE_ICONS={working:"\u25CF",idle:"\u25CB",error:"\u2718"}});var exports_agent_sync={};__export(exports_agent_sync,{watchAgentDirectory:()=>watchAgentDirectory,syncAgentDirectory:()=>syncAgentDirectory,printSyncResult:()=>printSyncResult});import{execSync as execSync5}from"child_process";import{existsSync as existsSync19,watch as fsWatch,readdirSync as readdirSync5,realpathSync as realpathSync2}from"fs";import{join as join20}from"path";function getGitRemoteUrl(dir){try{return execSync5(`git -C "${dir}" config --get remote.origin.url`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function extractOrgRepo(remoteUrl){let sshMatch=remoteUrl.match(/[^/:]+\/[^/]+?(?:\.git)?$/);if(sshMatch)return sshMatch[0].replace(/\.git$/,"");return null}function getRepoPathForAgent(agentDir){let reposLink=join20(agentDir,"repos");try{if(!existsSync19(reposLink))return null;let target=realpathSync2(reposLink);if(!existsSync19(target))return null;return target}catch{return null}}function discoverAgents(workspaceRoot){let agentsDir=join20(workspaceRoot,"agents");if(!existsSync19(agentsDir))return[];let agents=[];try{let entries=readdirSync5(agentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let agentDir=join20(agentsDir,entry.name);if(!existsSync19(join20(agentDir,"AGENTS.md")))continue;agents.push({name:entry.name,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)})}}catch{}return agents}function discoverSingleAgent(workspaceRoot,agentName){let agentDir=join20(workspaceRoot,"agents",agentName);if(!existsSync19(join20(agentDir,"AGENTS.md")))return null;return{name:agentName,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)}}async function syncAgentDirectory(workspaceRoot){let result={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],errors:[]},agents=discoverAgents(workspaceRoot),discoveredNames=new Set(agents.map((a)=>a.name));for(let agent of agents)try{await syncSingleAgent(agent,result)}catch(err){result.errors.push({name:agent.name,error:err instanceof Error?err.message:String(err)})}return await removeMissingAgents(discoveredNames,result),result}function printSyncResult(result){if(result.registered.length>0)console.log(` Registered: ${result.registered.join(", ")}`);if(result.updated.length>0)console.log(` Updated: ${result.updated.join(", ")}`);if(result.reactivated.length>0)console.log(` Reactivated: ${result.reactivated.join(", ")}`);if(result.archived.length>0)console.log(` Removed: ${result.archived.join(", ")}`);if(result.unchanged.length>0)console.log(` Unchanged: ${result.unchanged.join(", ")}`);for(let err of result.errors)console.error(` Error (${err.name}): ${err.error}`);let total=result.registered.length+result.updated.length+result.unchanged.length+result.reactivated.length;console.log(`
|
|
590
|
+
`)}var STATE_ICONS;var init_brief=__esm(()=>{init_db();init_mailbox();init_runtime_events();init_team_manager();STATE_ICONS={working:"\u25CF",idle:"\u25CB",error:"\u2718"}});var exports_agent_sync={};__export(exports_agent_sync,{watchAgentDirectory:()=>watchAgentDirectory,syncAgentDirectory:()=>syncAgentDirectory,printSyncResult:()=>printSyncResult});import{execSync as execSync5}from"child_process";import{existsSync as existsSync19,watch as fsWatch,readdirSync as readdirSync5,realpathSync as realpathSync2}from"fs";import{join as join20}from"path";function getGitRemoteUrl(dir){try{return execSync5(`git -C "${dir}" config --get remote.origin.url`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function extractOrgRepo(remoteUrl){let sshMatch=remoteUrl.match(/[^/:]+\/[^/]+?(?:\.git)?$/);if(sshMatch)return sshMatch[0].replace(/\.git$/,"");return null}function getRepoPathForAgent(agentDir){let reposLink=join20(agentDir,"repos");try{if(!existsSync19(reposLink))return null;let target=realpathSync2(reposLink);if(!existsSync19(target))return null;return target}catch{return null}}function discoverAgents(workspaceRoot){let agentsDir=join20(workspaceRoot,"agents");if(!existsSync19(agentsDir))return[];let agents=[];try{let entries=readdirSync5(agentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let agentDir=join20(agentsDir,entry.name);if(!existsSync19(join20(agentDir,"AGENTS.md")))continue;agents.push({name:entry.name,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)}),discoverSubAgents(agentDir,entry.name,agents)}}catch{}return agents}function discoverSubAgents(parentDir,parentName,agents){let subAgentsDir=join20(parentDir,".genie","agents");if(!existsSync19(subAgentsDir))return;try{let entries=readdirSync5(subAgentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let subDir=join20(subAgentsDir,entry.name);if(!existsSync19(join20(subDir,"AGENTS.md")))continue;agents.push({name:`${parentName}/${entry.name}`,dir:subDir,repoUrl:getGitRemoteUrl(parentDir),productRepo:getRepoPathForAgent(parentDir)})}}catch{}}function discoverSingleAgent(workspaceRoot,agentName){let agentDir=join20(workspaceRoot,"agents",agentName);if(!existsSync19(join20(agentDir,"AGENTS.md")))return null;return{name:agentName,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)}}async function syncAgentDirectory(workspaceRoot){let result={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],errors:[]},agents=discoverAgents(workspaceRoot),discoveredNames=new Set(agents.map((a)=>a.name));for(let agent of agents)try{await syncSingleAgent(agent,result)}catch(err){result.errors.push({name:agent.name,error:err instanceof Error?err.message:String(err)})}return await removeMissingAgents(discoveredNames,result),result}function printSyncResult(result){if(result.registered.length>0)console.log(` Registered: ${result.registered.join(", ")}`);if(result.updated.length>0)console.log(` Updated: ${result.updated.join(", ")}`);if(result.reactivated.length>0)console.log(` Reactivated: ${result.reactivated.join(", ")}`);if(result.archived.length>0)console.log(` Removed: ${result.archived.join(", ")}`);if(result.unchanged.length>0)console.log(` Unchanged: ${result.unchanged.join(", ")}`);for(let err of result.errors)console.error(` Error (${err.name}): ${err.error}`);let total=result.registered.length+result.updated.length+result.unchanged.length+result.reactivated.length;console.log(`
|
|
591
591
|
Sync complete: ${total} active agent(s), ${result.archived.length} removed.`)}async function removeMissingAgents(discoveredNames,result){try{let entries=await ls();for(let entry of entries){if(discoveredNames.has(entry.name))continue;if(entry.scope==="built-in")continue;if(!entry.dir||!entry.dir.includes("/agents/"))continue;if(await rm3(entry.name))result.archived.push(entry.name)}}catch{}}async function syncSingleAgent(agent,result){let repoPath=(agent.repoUrl?extractOrgRepo(agent.repoUrl):null)??agent.repoUrl??agent.dir,existing=await get2(agent.name);if(!existing){await add({name:agent.name,dir:agent.dir,repo:repoPath,promptMode:"append"}),result.registered.push(agent.name);return}if(existing.repo!==repoPath||existing.dir!==agent.dir)await edit(agent.name,{dir:agent.dir,repo:repoPath}),result.updated.push(agent.name);else result.unchanged.push(agent.name)}async function syncSingleAgentByName(workspaceRoot,agentName){let agent=discoverSingleAgent(workspaceRoot,agentName);if(!agent)return"not-found";let result={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],errors:[]};if(await syncSingleAgent(agent,result),result.registered.length>0)return"registered";if(result.updated.length>0)return"updated";return"unchanged"}function watchAgentDirectory(workspaceRoot,options){let agentsDir=join20(workspaceRoot,"agents");if(!existsSync19(agentsDir))return null;let debounceTimer=null,pendingChanges=new Set,processChanges=async()=>{let names=[...pendingChanges];pendingChanges.clear();for(let name of names)try{let action=await processWatchedAgent(workspaceRoot,agentsDir,name);if(action)options?.onSync?.(name,action)}catch{}},watcher=fsWatch(agentsDir,{persistent:!1},(_event,filename)=>{if(!filename)return;let name=filename.split("/")[0];if(!name||name.startsWith("."))return;if(pendingChanges.add(name),debounceTimer)clearTimeout(debounceTimer);debounceTimer=setTimeout(processChanges,2000)});return{close:()=>{if(debounceTimer)clearTimeout(debounceTimer);watcher.close()}}}async function processWatchedAgent(workspaceRoot,agentsDir,name){let agentDir=join20(agentsDir,name);if(existsSync19(agentDir)&&existsSync19(join20(agentDir,"AGENTS.md"))){let action=await syncSingleAgentByName(workspaceRoot,name);return action!=="unchanged"&&action!=="not-found"?action:null}if(!existsSync19(agentDir)){if(await rm3(name))return"removed"}return null}var init_agent_sync=__esm(()=>{init_agent_directory()});var exports_workspace={};__export(exports_workspace,{scanAgents:()=>scanAgents2,getWorkspaceConfig:()=>getWorkspaceConfig,findWorkspace:()=>findWorkspace});import{existsSync as existsSync20,readFileSync as readFileSync9,readdirSync as readdirSync6}from"fs";import{dirname as dirname5,join as join21,resolve as resolve4,sep}from"path";function findWorkspace(cwd){let startDir=resolve4(cwd??process.cwd()),current=startDir;while(!0){let candidate=join21(current,WORKSPACE_MARKER);if(existsSync20(candidate)){let agent=detectAgent(startDir,current);return{root:current,agent:agent??void 0}}let parent=dirname5(current);if(parent===current)break;current=parent}return null}function detectAgent(startDir,workspaceRoot){let agentsDir=join21(workspaceRoot,"agents"),relative=startDir.slice(agentsDir.length);if(!startDir.startsWith(agentsDir)||relative.length>0&&relative[0]!==sep)return null;let parts=relative.split(sep).filter(Boolean);if(parts.length===0)return null;let agentName=parts[0],agentsMd=join21(agentsDir,agentName,"AGENTS.md");if(existsSync20(agentsMd))return agentName;return null}function getWorkspaceConfig(root){let configPath2=join21(root,WORKSPACE_MARKER),raw=readFileSync9(configPath2,"utf-8");return JSON.parse(raw)}function scanAgents2(root){let agentsDir=join21(root,"agents");if(!existsSync20(agentsDir))return[];try{return readdirSync6(agentsDir,{withFileTypes:!0}).filter((d)=>d.isDirectory()&&existsSync20(join21(agentsDir,d.name,"AGENTS.md"))).map((d)=>d.name).sort()}catch{return[]}}var WORKSPACE_MARKER=".genie/workspace.json";var init_workspace=()=>{};function padRight(str2,len){return str2.length>=len?str2:str2+" ".repeat(len-str2.length)}function truncate2(str2,len){return str2.length<=len?str2:`${str2.slice(0,len-1)}\u2026`}function formatDate(iso){if(!iso)return"-";return new Date(iso).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function formatRelativeTimestamp(ts3){let d=new Date(ts3),diffMs=Date.now()-d.getTime();if(diffMs<60000)return`${Math.floor(diffMs/1000)}s ago`;if(diffMs<3600000)return`${Math.floor(diffMs/60000)}m ago`;if(diffMs<86400000)return`${Math.floor(diffMs/3600000)}h ago`;return d.toISOString().replace("T"," ").slice(0,19)}function formatTimestamp(iso,opts){if(!iso)return opts?.fallback??"-";let d=iso instanceof Date?iso:new Date(iso),fmt={month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1};if(opts?.seconds)fmt.second="2-digit";return d.toLocaleString("en-US",fmt)}function formatTime(iso,opts){try{let date=new Date(iso),fmt={hour:"2-digit",minute:"2-digit",hour12:!1};if(opts?.seconds)fmt.second="2-digit";return date.toLocaleTimeString("en-US",fmt)}catch{return opts?.fallback??"??:??"}}var exports_task_service={};__export(exports_task_service,{updateTask:()=>updateTask,updateMessage:()=>updateMessage,untagTask:()=>untagTask,unblockTask:()=>unblockTask,unarchiveTask:()=>unarchiveTask,unarchiveProject:()=>unarchiveProject,tagTask:()=>tagTask,setRelease:()=>setRelease,setPreference:()=>setPreference,sendMessage:()=>sendMessage,resolveTaskId:()=>resolveTaskId,resolveChannels:()=>resolveChannels,removeMember:()=>removeMember,removeDependency:()=>removeDependency,removeActor:()=>removeActor,releaseTask:()=>releaseTask,moveTask:()=>moveTask,markDone:()=>markDone,listTypes:()=>listTypes,listTasksForActor:()=>listTasksForActor,listTasks:()=>listTasks,listTags:()=>listTags,listReleases:()=>listReleases,listProjectsFiltered:()=>listProjectsFiltered,listProjects:()=>listProjects,listConversations:()=>listConversations,linkTask:()=>linkTask,getType:()=>getType,getTaskTags:()=>getTaskTags,getTaskActors:()=>getTaskActors,getTask:()=>getTask,getStageLog:()=>getStageLog,getProjectByRepoPath:()=>getProjectByRepoPath,getProjectByName:()=>getProjectByName,getPreferences:()=>getPreferences,getMessages:()=>getMessages,getMessage:()=>getMessage,getMembers:()=>getMembers,getDependents:()=>getDependents,getConversation:()=>getConversation,getCheckoutOwner:()=>getCheckoutOwner,getBlockingDependencies:()=>getBlockingDependencies,getBlockers:()=>getBlockers,forceUnlockTask:()=>forceUnlockTask,findOrCreateConversation:()=>findOrCreateConversation,expireStaleCheckouts:()=>expireStaleCheckouts,ensureProject:()=>ensureProject,deletePreference:()=>deletePreference,createType:()=>createType,createTask:()=>createTask,createTag:()=>createTag,createProject:()=>createProject,commentOnTask:()=>commentOnTask,checkoutTask:()=>checkoutTask,blockTask:()=>blockTask,assignTask:()=>assignTask,archiveTask:()=>archiveTask,archiveProject:()=>archiveProject,archiveBoard:()=>archiveBoard,addMember:()=>addMember,addDependency:()=>addDependency});import{execSync as execSync6}from"child_process";function str2(v){return v!=null?String(v):null}function strOrDefault(v,def){return v!=null?String(v):def}function mapTask(row){return{id:row.id,seq:row.seq,parentId:str2(row.parent_id),repoPath:row.repo_path,projectId:str2(row.project_id),genieOsFolderId:str2(row.genie_os_folder_id),wishFile:str2(row.wish_file),groupName:str2(row.group_name),title:row.title,description:str2(row.description),acceptanceCriteria:str2(row.acceptance_criteria),typeId:row.type_id,stage:row.stage,status:row.status,priority:row.priority,startDate:str2(row.start_date),dueDate:str2(row.due_date),estimatedEffort:str2(row.estimated_effort),startedAt:str2(row.started_at),endedAt:str2(row.ended_at),blockedReason:str2(row.blocked_reason),releaseId:str2(row.release_id),checkoutRunId:str2(row.checkout_run_id),executionLockedAt:str2(row.execution_locked_at),checkoutTimeoutMs:row.checkout_timeout_ms??600000,sessionId:str2(row.session_id),paneId:str2(row.pane_id),traceId:str2(row.trace_id),boardId:str2(row.board_id),columnId:str2(row.column_id),externalId:str2(row.external_id),externalUrl:str2(row.external_url),archivedAt:str2(row.archived_at),metadata:row.metadata??{},createdAt:strOrDefault(row.created_at,""),updatedAt:strOrDefault(row.updated_at,"")}}function mapConversation(row){return{id:row.id,parentMessageId:row.parent_message_id!=null?Number(row.parent_message_id):null,name:row.name??null,type:row.type,linkedEntity:row.linked_entity??null,linkedEntityId:row.linked_entity_id??null,createdByType:row.created_by_type??null,createdById:row.created_by_id??null,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapMessage(row){return{id:Number(row.id),conversationId:row.conversation_id,replyToId:row.reply_to_id!=null?Number(row.reply_to_id):null,senderType:row.sender_type,senderId:row.sender_id,body:row.body,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapTaskActor(row){return{taskId:row.task_id,actorType:row.actor_type,actorId:row.actor_id,role:row.role,permissions:row.permissions??{},createdAt:String(row.created_at)}}function mapDependency(row){return{taskId:row.task_id,dependsOnId:row.depends_on_id,depType:row.dep_type,createdAt:String(row.created_at)}}function mapTag(row){return{id:row.id,name:row.name,color:row.color??"#9ca3af",typeId:row.type_id??null,createdAt:String(row.created_at)}}function mapTaskType(row){return{id:row.id,name:row.name,description:row.description??null,icon:row.icon??null,stages:row.stages,isBuiltin:row.is_builtin,createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapNotificationPref(row){return{actorType:row.actor_type,actorId:row.actor_id,channel:row.channel,priorityThreshold:row.priority_threshold,isDefault:row.is_default,enabled:row.enabled,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapStageLog(row){return{id:Number(row.id),taskId:row.task_id,fromStage:row.from_stage??null,toStage:row.to_stage,actorType:row.actor_type??null,actorId:row.actor_id??null,runId:row.run_id??null,gateType:row.gate_type??null,createdAt:String(row.created_at)}}function mapConversationMember(row){return{conversationId:row.conversation_id,actorType:row.actor_type,actorId:row.actor_id,role:row.role,joinedAt:String(row.joined_at)}}function mapProject(row){return{id:row.id,name:row.name,repoPath:str2(row.repo_path),description:str2(row.description),leaderAgent:str2(row.leader_agent),tmuxSession:str2(row.tmux_session),status:strOrDefault(row.status,"active"),archivedAt:str2(row.archived_at),createdAt:String(row.created_at)}}function getRepoPath(){try{return execSync6("git rev-parse --show-toplevel",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return process.cwd()}}async function resolveTaskId(idOrSeq,repoPath){let sql=await getConnection(),repo=repoPath??getRepoPath(),projectSeqMatch=idOrSeq.match(/^([^#]+)#(\d+)$/);if(projectSeqMatch&&!idOrSeq.startsWith("#")){let[,projectName,seqStr]=projectSeqMatch,seq2=Number.parseInt(seqStr,10);if(Number.isNaN(seq2))return null;let rows2=await sql`
|
|
592
592
|
SELECT t.id FROM tasks t
|
|
593
593
|
JOIN projects p ON t.project_id = p.id
|
|
@@ -2174,7 +2174,7 @@ Next steps:`),console.log(" 1. Reload tmux: tmux source ~/.tmux.conf"),console.
|
|
|
2174
2174
|
`:"";return writeFileSync4(filePath,newContent),!0}async function promptUninstallFrom(filePath,marker,label){if(!existsSync6(filePath))return;if(!contentExists(filePath,marker)){console.log(`\u2713 ${label} has no genie shortcuts`);return}if(await prompt(`Remove shortcuts from ${filePath}? [Y/n] `)==="n"){console.log(`\u23ED\uFE0F Skipped ${label}`);return}if(removeMarkedContent(filePath,marker))console.log(`\u2705 Removed from ${filePath}`)}async function uninstallShortcuts(){let home=homedir6(),marker="generated by genie-cli";console.log(`Uninstalling Warp-like shortcuts...
|
|
2175
2175
|
`),await promptUninstallFrom(join6(home,".tmux.conf"),"generated by genie-cli","tmux.conf");for(let shellRc of[join6(home,".zshrc"),join6(home,".bashrc")])await promptUninstallFrom(shellRc,"generated by genie-cli",shellRc);let termuxDir=join6(home,".termux"),isTermux=existsSync6(termuxDir)||process.env.TERMUX_VERSION;if(isTermux){let termuxProps=join6(termuxDir,"termux.properties");if(await promptUninstallFrom(termuxProps,"generated by genie-cli","termux.properties"),!contentExists(termuxProps,"generated by genie-cli"))console.log(" Run: termux-reload-settings")}if(console.log(`
|
|
2176
2176
|
\u2705 Uninstallation complete!`),console.log(`
|
|
2177
|
-
Next steps:`),console.log(" 1. Reload tmux: tmux source ~/.tmux.conf"),console.log(" 2. Restart your shell or run: source ~/.bashrc"),isTermux)console.log(" 3. Reload Termux: termux-reload-settings")}var __dirname="/home/runner/_work/genie/genie/src/genie-commands";function printHeader(){console.log(),console.log(`\x1B[1m\x1B[36m${"=".repeat(64)}\x1B[0m`),console.log("\x1B[1m\x1B[36m Genie Setup Wizard\x1B[0m"),console.log(`\x1B[1m\x1B[36m${"=".repeat(64)}\x1B[0m`),console.log()}function printSection(title,description){if(console.log(),console.log(`\x1B[1m${title}\x1B[0m`),description)console.log(`\x1B[2m${description}\x1B[0m`);console.log()}async function configureSession(config,quick){if(printSection("2. Session Configuration","Configure tmux session settings"),quick)return console.log(` Using defaults: session="${config.session.name}", window="${config.session.defaultWindow}"`),config;let sessionName=await esm_default3({message:"Session name:",default:config.session.name}),defaultWindow=await esm_default3({message:"Default window name:",default:config.session.defaultWindow}),autoCreate=await esm_default2({message:"Auto-create session on connect?",default:config.session.autoCreate});return config.session={name:sessionName,defaultWindow,autoCreate},config}async function configureTerminal(config,quick){if(printSection("3. Terminal Defaults","Configure default values for term commands"),quick)return console.log(` Using defaults: timeout=${config.terminal.execTimeout}ms, lines=${config.terminal.readLines}`),config;let timeoutStr=await esm_default3({message:"Exec timeout (milliseconds):",default:String(config.terminal.execTimeout),validate:(v)=>{let n=Number.parseInt(v,10);return!Number.isNaN(n)&&n>0?!0:"Must be a positive number"}}),linesStr=await esm_default3({message:"Read lines (default for genie agent read):",default:String(config.terminal.readLines),validate:(v)=>{let n=Number.parseInt(v,10);return!Number.isNaN(n)&&n>0?!0:"Must be a positive number"}}),worktreeBase=await esm_default3({message:"Worktree base directory (leave empty for ~/.genie/worktrees/<project>/):",default:config.terminal.worktreeBase??""});return config.terminal={execTimeout:Number.parseInt(timeoutStr,10),readLines:Number.parseInt(linesStr,10),...worktreeBase?{worktreeBase}:{}},config}async function configureShortcuts(config,quick){printSection("4. Keyboard Shortcuts","Warp-like tmux shortcuts for quick navigation");let home=homedir7(),tmuxConf=join7(home,".tmux.conf");if(isShortcutsInstalled(tmuxConf))return console.log(" \x1B[32m\u2713\x1B[0m Tmux shortcuts already installed"),config.shortcuts.tmuxInstalled=!0,config;if(console.log(" Available shortcuts:"),console.log(" \x1B[36mCtrl+T\x1B[0m \u2192 New tab (window)"),console.log(" \x1B[36mCtrl+S\x1B[0m \u2192 Vertical split"),console.log(" \x1B[36mCtrl+H\x1B[0m \u2192 Horizontal split"),console.log(),quick)return console.log(" Skipped in quick mode. Run \x1B[36mgenie setup --shortcuts\x1B[0m to install."),config;if(await esm_default2({message:"Install tmux keyboard shortcuts?",default:!1}))console.log(),await installShortcuts(),config.shortcuts.tmuxInstalled=!0,await updateShortcutsConfig({tmuxInstalled:!0});else console.log(" Skipped. Run \x1B[36mgenie shortcuts install\x1B[0m later.");return config}function printCodexResult(result){if(result==="changed")console.log(" \x1B[32m\u2713\x1B[0m Codex config updated");else if(result==="unchanged")console.log(" \x1B[32m\u2713\x1B[0m Codex config already up to date");else console.log(" \x1B[31m\u2717\x1B[0m Failed to update codex config")}async function configureCodex(config,quick){printSection("5. Codex Integration","Configure OpenAI Codex for genie agents");let codexCheck=await checkCommand("codex");if(!codexCheck.exists)return console.log(" \x1B[33m!\x1B[0m Codex CLI not found. Skipping codex integration."),config;if(console.log(` \x1B[32m\u2713\x1B[0m Codex CLI found (${codexCheck.version??"unknown version"})`),isCodexConfigured())return console.log(" \x1B[32m\u2713\x1B[0m Codex config already configured"),config.codex={configured:!0},config;if(console.log(),console.log(" Genie needs to configure codex for agent communication:"),console.log(" \x1B[36mdisable_paste_burst\x1B[0m \u2192 Reliable tmux command injection"),console.log(" \x1B[36mOTel exporter\x1B[0m \u2192 Telemetry relay for state detection"),console.log(` Config: \x1B[2m${contractPath(getCodexConfigPath())}\x1B[0m`),console.log(),quick){let result=ensureCodexOtelConfig();return printCodexResult(result),config.codex={configured:result!=="error"},config}if(await esm_default2({message:"Configure Codex for genie agent integration?",default:!0})){let result=ensureCodexOtelConfig();printCodexResult(result),config.codex={configured:result!=="error"}}else console.log(" Skipped. Run \x1B[36mgenie setup --codex\x1B[0m later.");return config}async function configureDebug(config,quick){if(printSection("6. Debug Options","Logging and debugging settings"),quick)return console.log(" Using defaults: tmuxDebug=false, verbose=false"),config;let tmuxDebug=await esm_default2({message:"Enable tmux debug logging?",default:config.logging.tmuxDebug}),verbose=await esm_default2({message:"Enable verbose mode?",default:config.logging.verbose});return config.logging={tmuxDebug,verbose},config}async function configurePromptMode(config,quick){if(printSection("7. Prompt Mode","Controls how genie injects system prompts into Claude Code"),quick)return console.log(` Using default: promptMode="${config.promptMode}"`),config;console.log(" append \u2014 Uses --append-system-prompt-file (preserves Claude Code default system prompt)"),console.log(" system \u2014 Uses --system-prompt-file (replaces Claude Code default system prompt)"),console.log();let promptMode=await esm_default4({message:"Prompt mode:",choices:[{name:"append (recommended \u2014 preserves CC default)",value:"append"},{name:"system (replaces CC default)",value:"system"}],default:config.promptMode});return config.promptMode=promptMode,config}async function showSummaryAndSave(config){printSection("Summary",`Configuration will be saved to ${contractPath(getGenieConfigPath())}`),console.log(` Session: \x1B[36m${config.session.name}\x1B[0m (window: ${config.session.defaultWindow})`),console.log(` Terminal: timeout=${config.terminal.execTimeout}ms, lines=${config.terminal.readLines}`),console.log(` Shortcuts: ${config.shortcuts.tmuxInstalled?"\x1B[32minstalled\x1B[0m":"\x1B[2mnot installed\x1B[0m"}`),console.log(` Codex: ${config.codex?.configured?"\x1B[32mconfigured\x1B[0m":"\x1B[2mnot configured\x1B[0m"}`),console.log(` Debug: tmux=${config.logging.tmuxDebug}, verbose=${config.logging.verbose}`),console.log(` Prompt mode: \x1B[36m${config.promptMode}\x1B[0m`),console.log(),config.setupComplete=!0,config.lastSetupAt=new Date().toISOString(),await saveGenieConfig(config),console.log("\x1B[32m\u2713 Configuration saved!\x1B[0m")}async function showCurrentConfig(){let config=await loadGenieConfig();console.log(),console.log("\x1B[1mCurrent Genie Configuration\x1B[0m"),console.log(`\x1B[2m${contractPath(getGenieConfigPath())}\x1B[0m`),console.log(),console.log(JSON.stringify(config,null,2)),console.log()}function printNextSteps(){console.log(),console.log("\x1B[1mNext Steps:\x1B[0m"),console.log(),console.log(" Start a session: \x1B[36mgenie\x1B[0m"),console.log(" Watch AI work: \x1B[36mtmux attach -t genie\x1B[0m"),console.log(" Check health: \x1B[36mgenie doctor\x1B[0m"),console.log()}async function setupCommand(options={}){if(options.show){await showCurrentConfig();return}if(options.reset){await resetConfig(),console.log("\x1B[32m\u2713 Configuration reset to defaults.\x1B[0m"),console.log();return}let config=await loadGenieConfig();if(options.shortcuts){printHeader(),await configureShortcuts(config,!1),await markSetupComplete();return}if(options.terminal){printHeader(),config=await configureTerminal(config,!1),await saveGenieConfig(config),console.log("\x1B[32m\u2713 Terminal configuration saved.\x1B[0m");return}if(options.session){printHeader(),config=await configureSession(config,!1),await saveGenieConfig(config),console.log("\x1B[32m\u2713 Session configuration saved.\x1B[0m");return}if(options.codex){if(printHeader(),config=await configureCodex(config,!1),await saveGenieConfig(config),config.codex?.configured)console.log("\x1B[32m\u2713 Codex configuration saved.\x1B[0m");return}let quick=options.quick??!1;if(printHeader(),quick)console.log("\x1B[2mQuick mode: accepting all defaults\x1B[0m");config=await configureSession(config,quick),config=await configureTerminal(config,quick),config=await configureShortcuts(config,quick),config=await configureCodex(config,quick),config=await configureDebug(config,quick),config=await configurePromptMode(config,quick),await showSummaryAndSave(config),installGenieTmuxConf(),printNextSteps()}function installGenieTmuxConf(){let{existsSync:existsSync7,copyFileSync,mkdirSync:mkdirSync5}=__require("fs"),{resolve}=__require("path"),genieHome2=process.env.GENIE_HOME??join7(homedir7(),".genie"),dest=join7(genieHome2,"tmux.conf");if(existsSync7(dest))return;let src=[resolve(__dirname,"..","..","scripts","tmux","genie.tmux.conf"),resolve(__dirname,"..","scripts","tmux","genie.tmux.conf")].find((p)=>existsSync7(p));if(!src)return;try{mkdirSync5(genieHome2,{recursive:!0}),copyFileSync(src,dest),console.log(`\x1B[32m\u2713\x1B[0m Installed genie tmux config to ${dest}`)}catch{}}import{existsSync as existsSync7}from"fs";import{homedir as homedir8}from"os";import{join as join8}from"path";async function shortcutsShowCommand(){displayShortcuts();let home=homedir8(),tmuxConf=join8(home,".tmux.conf"),zshrc=join8(home,".zshrc"),bashrc=join8(home,".bashrc");if(console.log("Installation status:"),isShortcutsInstalled(tmuxConf))console.log(" \x1B[32m\u2713\x1B[0m tmux.conf");else console.log(" \x1B[33m-\x1B[0m tmux.conf");let shellRc=existsSync7(zshrc)?zshrc:bashrc;if(isShortcutsInstalled(shellRc))console.log(` \x1B[32m\u2713\x1B[0m ${shellRc.replace(home,"~")}`);else console.log(` \x1B[33m-\x1B[0m ${shellRc.replace(home,"~")}`);console.log(),console.log("Run \x1B[36mgenie shortcuts install\x1B[0m to install shortcuts."),console.log("Run \x1B[36mgenie shortcuts uninstall\x1B[0m to remove shortcuts."),console.log()}async function shortcutsInstallCommand(){await installShortcuts()}async function shortcutsUninstallCommand(){await uninstallShortcuts()}init_esm6();import{existsSync as existsSync8,lstatSync,rmSync as rmSync2,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir9}from"os";import{join as join9}from"path";init_genie_config2();var ORCHESTRATION_RULES_PATH=join9(homedir9(),".claude","rules","genie-orchestration.md"),LOCAL_BIN=join9(homedir9(),".local","bin"),SYMLINKS=["genie","term"];function isGenieSymlink(path){try{if(!existsSync8(path))return!1;if(!lstatSync(path).isSymbolicLink())return!1;return!0}catch{return!1}}function removeSymlinks(){let removed=[];for(let name of SYMLINKS){let symlinkPath=join9(LOCAL_BIN,name);if(isGenieSymlink(symlinkPath))try{unlinkSync4(symlinkPath),removed.push(name)}catch{}}return removed}function tryRemoveStep(label,successMsg,fn){console.log(`\x1B[2m${label}\x1B[0m`);try{fn(),console.log(` \x1B[32m+\x1B[0m ${successMsg}`)}catch(error){let message=error instanceof Error?error.message:String(error);console.log(` \x1B[33m!\x1B[0m ${label.replace("...","")} failed: ${message}`)}}function performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir){if(hasHookScript)tryRemoveStep("Removing hook script...","Hook script removed",()=>removeHookScript());if(existingSymlinks.length>0){console.log("\x1B[2mRemoving symlinks...\x1B[0m");let removed=removeSymlinks();if(removed.length>0)console.log(` \x1B[32m+\x1B[0m Removed: ${removed.join(", ")}`)}if(existsSync8(ORCHESTRATION_RULES_PATH))tryRemoveStep("Removing orchestration rules...","Orchestration rules removed (~/.claude/rules/genie-orchestration.md)",()=>unlinkSync4(ORCHESTRATION_RULES_PATH));if(hasGenieDir)tryRemoveStep("Removing genie directory...","Directory removed",()=>rmSync2(genieDir,{recursive:!0,force:!0}))}async function uninstallCommand(){console.log(),console.log("\x1B[1m\x1B[33m Uninstall Genie CLI\x1B[0m"),console.log();let genieDir=getGenieDir(),hasGenieDir=existsSync8(genieDir),hasHookScript=hookScriptExists(),hasOrchestrationRules=existsSync8(ORCHESTRATION_RULES_PATH),existingSymlinks=SYMLINKS.filter((name)=>isGenieSymlink(join9(LOCAL_BIN,name)));if(console.log("\x1B[2mThis will remove:\x1B[0m"),hasHookScript)console.log(" \x1B[31m-\x1B[0m Hook script (~/.claude/hooks/genie-bash-hook.sh)");if(hasOrchestrationRules)console.log(" \x1B[31m-\x1B[0m Orchestration rules (~/.claude/rules/genie-orchestration.md)");if(hasGenieDir)console.log(` \x1B[31m-\x1B[0m Genie directory (${contractPath(genieDir)})`);if(existingSymlinks.length>0)console.log(` \x1B[31m-\x1B[0m Symlinks from ~/.local/bin: ${existingSymlinks.join(", ")}`);if(console.log(),!hasGenieDir&&!hasHookScript&&!hasOrchestrationRules&&existingSymlinks.length===0){console.log("\x1B[33mNothing to uninstall.\x1B[0m"),console.log();return}if(!await esm_default2({message:"Are you sure you want to uninstall Genie CLI?",default:!1})){console.log(),console.log("\x1B[2mUninstall cancelled.\x1B[0m"),console.log();return}console.log(),performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir),console.log(),console.log("\x1B[32m+\x1B[0m Genie CLI uninstalled."),console.log(),console.log("\x1B[2mNote: If you installed via npm/bun, also run:\x1B[0m"),console.log(" \x1B[36mbun remove -g @automagik/genie\x1B[0m"),console.log(" \x1B[2mor\x1B[0m"),console.log(" \x1B[36mnpm uninstall -g @automagik/genie\x1B[0m"),console.log()}init_genie_config2();import{execSync as execSync2,spawn}from"child_process";import{chmodSync as chmodSync2,copyFileSync,existsSync as existsSync9,mkdirSync as mkdirSync5,readFileSync as readFileSync4,readdirSync,rmSync as rmSync3,writeFileSync as writeFileSync5}from"fs";import{chmod,copyFile,mkdir,unlink}from"fs/promises";import{homedir as homedir10}from"os";import{join as join10}from"path";var GENIE_HOME=process.env.GENIE_HOME||join10(homedir10(),".genie"),GENIE_SRC=join10(GENIE_HOME,"src"),GENIE_BIN=join10(GENIE_HOME,"bin"),LOCAL_BIN2=join10(homedir10(),".local","bin");function log(message){console.log(`\x1B[32m\u25B8\x1B[0m ${message}`)}function success(message){console.log(`\x1B[32m\u2714\x1B[0m ${message}`)}function error(message){console.log(`\x1B[31m\u2716\x1B[0m ${message}`)}async function runCommand(command,args,cwd){return new Promise((resolve)=>{let output=[],child=spawn(command,args,{cwd,stdio:["inherit","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}});child.stdout?.on("data",(data)=>{let str=data.toString();output.push(str),process.stdout.write(str)}),child.stderr?.on("data",(data)=>{let str=data.toString();output.push(str),process.stderr.write(str)}),child.on("close",(code)=>{resolve({success:code===0,output:output.join("")})}),child.on("error",(err)=>{error(err.message),resolve({success:!1,output:err.message})})})}async function getGitInfo(cwd){try{let branchResult=await runCommandSilent("git",["rev-parse","--abbrev-ref","HEAD"],cwd),commitResult=await runCommandSilent("git",["rev-parse","--short","HEAD"],cwd),dateResult=await runCommandSilent("git",["log","-1","--format=%ci"],cwd);if(branchResult.success&&commitResult.success&&dateResult.success)return{branch:branchResult.output.trim(),commit:commitResult.output.trim(),commitDate:dateResult.output.trim().split(" ")[0]}}catch{}return null}async function runCommandSilent(command,args,cwd,timeoutMs=4000){return new Promise((resolve)=>{let output=[],settled=!1,child=spawn(command,args,{cwd,stdio:["inherit","pipe","pipe"]}),timer=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGTERM"),resolve({success:!1,output:`Timed out after ${timeoutMs}ms`})},timeoutMs);child.stdout?.on("data",(data)=>{output.push(data.toString())}),child.stderr?.on("data",(data)=>{output.push(data.toString())}),child.on("close",(code)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({success:code===0,output:output.join("")})}),child.on("error",(err)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({success:!1,output:err.message})})})}function detectFromBinaryPath(path){if(path.includes(".bun"))return"bun";if(path.includes("node_modules"))return"npm";if(path===join10(LOCAL_BIN2,"genie")||path.startsWith(GENIE_BIN))return"source";return null}async function detectInstallationType(){if(genieConfigExists())try{let config=await loadGenieConfig();if(config.installMethod)return config.installMethod}catch{}if(existsSync9(join10(GENIE_SRC,".git")))return"source";let result=await runCommandSilent("which",["genie"]);if(!result.success)return"unknown";let detected=detectFromBinaryPath(result.output.trim());if(detected)return detected;return(await runCommandSilent("which",["bun"])).success?"bun":"npm"}async function updateViaBun(channel){try{__require("fs").unlinkSync(join10(homedir10(),".bun","install","global","bun.lock"))}catch{}if(log(`Updating via bun (channel: ${channel})...`),!(await runCommand("bun",["add","-g","--force","--no-cache",`@automagik/genie@${channel}`])).success)return error("Failed to update via bun"),!1;return console.log(),success(`Genie CLI updated via bun (${channel})!`),!0}async function updateViaNpm(channel){if(log(`Updating via npm (channel: ${channel})...`),!(await runCommand("npm",["install","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via npm"),!1;return console.log(),success(`Genie CLI updated via npm (${channel})!`),!0}async function detectGlobalInstalls(){let found=new Set,[npmResult,bunResult]=await Promise.all([runCommandSilent("npm",["list","-g","@automagik/genie"]),runCommandSilent("bun",["pm","ls","-g"])]);if(npmResult.success&&!npmResult.output.includes("(empty)"))found.add("npm");if(bunResult.success&&bunResult.output.includes("@automagik/genie"))found.add("bun");return found}async function updateSource(){let beforeInfo=await getGitInfo(GENIE_SRC);if(beforeInfo)console.log(`Current: \x1B[2m${beforeInfo.branch}@${beforeInfo.commit} (${beforeInfo.commitDate})\x1B[0m`),console.log();if(log("Fetching latest changes..."),!(await runCommand("git",["fetch","origin"],GENIE_SRC)).success)error("Failed to fetch from origin"),process.exit(1);if(log("Resetting to origin/main..."),!(await runCommand("git",["reset","--hard","origin/main"],GENIE_SRC)).success)error("Failed to reset to origin/main"),process.exit(1);console.log();let afterInfo=await getGitInfo(GENIE_SRC);if(beforeInfo&&afterInfo&&beforeInfo.commit===afterInfo.commit){success("Already up to date!"),console.log();return}if(log("Installing dependencies..."),!(await runCommand("bun",["install"],GENIE_SRC)).success)error("Failed to install dependencies"),process.exit(1);if(console.log(),log("Building..."),!(await runCommand("bun",["run","build"],GENIE_SRC)).success)error("Failed to build"),process.exit(1);console.log(),log("Installing binaries...");try{await mkdir(GENIE_BIN,{recursive:!0}),await mkdir(LOCAL_BIN2,{recursive:!0});let binaries=["genie.js","term.js"],names=["genie","term"];for(let i=0;i<binaries.length;i++){let src=join10(GENIE_SRC,"dist",binaries[i]),binDest=join10(GENIE_BIN,binaries[i]),linkDest=join10(LOCAL_BIN2,names[i]);await copyFile(src,binDest),await chmod(binDest,493),await symlinkOrCopy(binDest,linkDest)}for(let legacy of["claudio.js","claudio"]){let legacyBin=join10(GENIE_BIN,legacy),legacyLink=join10(LOCAL_BIN2,legacy);try{await unlink(legacyBin)}catch{}try{await unlink(legacyLink)}catch{}}success("Binaries installed")}catch(err){error(`Failed to install binaries: ${err}`),process.exit(1)}if(console.log(),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),success("Genie CLI updated successfully!"),console.log(),afterInfo)console.log(`Version: \x1B[36m${afterInfo.branch}@${afterInfo.commit}\x1B[0m (${afterInfo.commitDate})`),console.log()}async function symlinkOrCopy(src,dest){let{symlink,unlink:unlink2}=await import("fs/promises");try{if(existsSync9(dest))await unlink2(dest);await symlink(src,dest)}catch{await copyFile(src,dest)}}function copyDirSync(src,dest){mkdirSync5(dest,{recursive:!0});for(let entry of readdirSync(src,{withFileTypes:!0})){let srcPath=join10(src,entry.name),destPath=join10(dest,entry.name);if(entry.isDirectory())copyDirSync(srcPath,destPath);else copyFileSync(srcPath,destPath)}}async function resolveGlobalPkgDir(installType){if(installType==="bun"){let bunPath=join10(homedir10(),".bun","install","global","node_modules","@automagik","genie");if(existsSync9(bunPath))return bunPath}if(installType==="npm"){let npmRootResult=await runCommandSilent("npm",["root","-g"]);if(npmRootResult.success){let npmPath=join10(npmRootResult.output.trim(),"@automagik","genie");if(existsSync9(npmPath))return npmPath}}let bunFallback=join10(homedir10(),".bun","install","global","node_modules","@automagik","genie");if(existsSync9(bunFallback))return bunFallback;let npmRootFallback=await runCommandSilent("npm",["root","-g"]);if(npmRootFallback.success){let npmPath=join10(npmRootFallback.output.trim(),"@automagik","genie");if(existsSync9(npmPath))return npmPath}return null}function updatePluginRegistry(claudePlugins,cacheDir,version){let registryPath=join10(claudePlugins,"installed_plugins.json");try{if(!existsSync9(registryPath))return;let registry=JSON.parse(readFileSync4(registryPath,"utf-8")),entries=registry.plugins?.["genie@automagik"];if(!Array.isArray(entries))return;for(let entry of entries)if(entry.scope==="user")entry.installPath=cacheDir,entry.version=version,entry.lastUpdated=new Date().toISOString();writeFileSync5(registryPath,JSON.stringify(registry,null,2))}catch(err){log(`Registry update failed (non-fatal): ${err}`)}}function syncTmuxConf(tmuxScriptsSrc){mkdirSync5(GENIE_HOME,{recursive:!0});let tmuxConfSrc=join10(tmuxScriptsSrc,"genie.tmux.conf"),tmuxConfDest=join10(GENIE_HOME,"tmux.conf");if(existsSync9(tmuxConfSrc))try{copyFileSync(tmuxConfSrc,tmuxConfDest),success(`Installed tmux config to ${tmuxConfDest}`);try{let{tmuxBin:tmuxBin2}=(init_ensure_tmux(),__toCommonJS(exports_ensure_tmux));execSync2(`${tmuxBin2()} -L genie source-file '${tmuxConfDest}'`,{stdio:"ignore"}),success("Reloaded genie tmux server configuration")}catch{}}catch{}let tuiConfSrc=join10(tmuxScriptsSrc,"tui-tmux.conf"),tuiConfDest=join10(GENIE_HOME,"tui-tmux.conf");if(existsSync9(tuiConfSrc))try{copyFileSync(tuiConfSrc,tuiConfDest),success(`Installed TUI tmux config to ${tuiConfDest}`)}catch{}}function syncTmuxScripts(globalPkgDir){let tmuxScriptsSrc=join10(globalPkgDir,"scripts","tmux");if(!existsSync9(tmuxScriptsSrc))return;let scriptsDir=join10(GENIE_HOME,"scripts");mkdirSync5(scriptsDir,{recursive:!0});let scriptCount=0;for(let entry of readdirSync(tmuxScriptsSrc))if(entry.endsWith(".sh")||entry==="genie.tmux.conf"||entry==="tui-tmux.conf"){let src=join10(tmuxScriptsSrc,entry),dest=join10(scriptsDir,entry);copyFileSync(src,dest);try{chmodSync2(dest,entry.endsWith(".sh")?493:420)}catch{}scriptCount++}if(scriptCount>0)success(`Refreshed ${scriptCount} tmux scripts at ${scriptsDir}`);syncTmuxConf(tmuxScriptsSrc)}async function syncPlugin(installType){log("Syncing Claude Code plugin...");let globalPkgDir=await resolveGlobalPkgDir(installType);if(!globalPkgDir){log("Could not find installed package \u2014 skipping plugin sync");return}let pluginSrc=join10(globalPkgDir,"plugins","genie");if(!existsSync9(pluginSrc)){log("Plugin source not found in package \u2014 skipping plugin sync");return}let version;try{version=JSON.parse(readFileSync4(join10(globalPkgDir,"package.json"),"utf-8")).version}catch{log("Could not read package version \u2014 skipping plugin sync");return}let claudePlugins=join10(homedir10(),".claude","plugins"),cacheDir=join10(claudePlugins,"cache","automagik","genie",version);try{if(existsSync9(cacheDir))rmSync3(cacheDir,{recursive:!0,force:!0});copyDirSync(pluginSrc,cacheDir);let skillsSrc=join10(globalPkgDir,"skills");if(existsSync9(skillsSrc)&&!existsSync9(join10(cacheDir,"skills")))copyDirSync(skillsSrc,join10(cacheDir,"skills"))}catch(err){error(`Failed to copy plugin: ${err}`);return}updatePluginRegistry(claudePlugins,cacheDir,version),syncTmuxScripts(globalPkgDir),success(`Plugin synced to v${version}`)}async function resolveChannel(options){if(options.next)return"next";if(options.stable)return"latest";if(genieConfigExists())try{let config=await loadGenieConfig();if(config.updateChannel)return config.updateChannel}catch{}return"latest"}async function persistChannel(channel){try{let config=await loadGenieConfig();config.updateChannel=channel,await saveGenieConfig(config)}catch{}}async function updateCommand(options={}){console.log(),console.log("\x1B[1m\uD83E\uDDDE Genie CLI Update\x1B[0m"),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),console.log();let channel=await resolveChannel(options);if(options.next||options.stable)await persistChannel(channel);let installType=await detectInstallationType();if(log(`Detected installation: ${installType}`),log(`Channel: ${channel}${channel==="next"?" (dev builds)":" (stable)"}`),console.log(),installType==="unknown")error("No Genie CLI installation found"),console.log(),console.log("Install method not configured. Please reinstall genie:"),console.log("\x1B[36m curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash\x1B[0m"),console.log(),process.exit(1);if(installType==="source"){await updateSource();return}let globalInstalls=await detectGlobalInstalls(),primaryMethod=installType;if(!(primaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))process.exit(1);let secondaryMethod=primaryMethod==="bun"?"npm":"bun";if(globalInstalls.has(secondaryMethod)){if(console.log(),log(`Also updating ${secondaryMethod}-global install...`),!(secondaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))error(`Secondary update via ${secondaryMethod} failed (non-blocking)`)}await syncPlugin(installType)}init_version();function buildSearchNames(recipient,dirEntry){let names=new Set([recipient]);if(dirEntry){if(names.add(dirEntry.entry.name),dirEntry.entry.roles)for(let role of dirEntry.entry.roles)names.add(role)}return names}function buildSpawnArgs(template){let args=["spawn","--provider",template.provider,"--team",template.team];if(template.role)args.push("--role",template.role);if(template.skill)args.push("--skill",template.skill);if(template.cwd)args.push("--cwd",template.cwd);if(template.extraArgs)args.push(...template.extraArgs);return args}async function isRecipientLeader(recipient,teamName){try{let{getTeam:getTeam2}=await Promise.resolve().then(() => (init_team_manager(),exports_team_manager)),config=await getTeam2(teamName);return!!config?.leader&&recipient===config.leader}catch{return!1}}async function autoSpawn(payload){let input=payload.tool_input;if(!input||input.type!=="message")return;let recipient=input.recipient;if(!recipient||recipient==="team-lead")return;let teamName=process.env.GENIE_TEAM??payload.team_name;if(!teamName)return;if(await isRecipientLeader(recipient,teamName))return;try{let registryMod=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry)),tmuxMod=await Promise.resolve().then(() => (init_tmux(),exports_tmux)),directoryMod=await Promise.resolve().then(() => (init_agent_directory(),exports_agent_directory)),existing=(await registryMod.list()).find((a)=>(a.role===recipient||a.id===recipient)&&a.team===teamName);if(existing&&await tmuxMod.isPaneAlive(existing.paneId))return;let dirEntry=await directoryMod.resolve(recipient),templates=await registryMod.listTemplates(),searchNames=buildSearchNames(recipient,dirEntry),template=templates.find((t)=>{if(t.team!==teamName)return!1;return[...searchNames].some((q)=>t.id===q||t.role===q)});if(!template){if(dirEntry)console.error(`[genie-hook] Agent "${recipient}" is registered in directory but has no spawn template in team "${teamName}".`);return}let{spawnSync}=__require("child_process");spawnSync("genie",buildSpawnArgs(template),{timeout:1e4,stdio:"ignore",env:{...process.env,GENIE_TEAM:teamName}}),console.error(`[genie-hook] Auto-spawned "${recipient}" in team "${teamName}"`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(`[genie-hook] Auto-spawn failed for "${recipient}": ${msg}`)}}var DENY_PATTERNS=[{test:(cmd)=>/git\s+push\b/i.test(cmd)&&/(?:^|\s)(main|master)(?:\s|$)/.test(cmd),reason:"BLOCKED: Push to main/master is FORBIDDEN. Push to a feature branch and create a PR targeting dev."},{test:(cmd)=>/git\s+push\b/.test(cmd)&&/:(main|master)\b/.test(cmd),reason:"BLOCKED: Push refspec targeting main/master is FORBIDDEN."},{test:(cmd)=>/gh\s+pr\s+create\b/.test(cmd)&&/(--base|-B)\s+(main|master)\b/.test(cmd),reason:"BLOCKED: PRs must target dev, not main/master. Use: gh pr create --base dev"},{test:(cmd)=>/gh\s+pr\s+create\b/.test(cmd)&&!/(--base|-B)\s+\S/.test(cmd),reason:"BLOCKED: gh pr create requires explicit --base flag. Without it, GitHub defaults to main. Use: gh pr create --base dev"},{test:(cmd)=>/gh\s+pr\s+merge\b/.test(cmd),reason:"BLOCKED: Agents may NOT merge PRs. Only humans merge via GitHub UI."},{test:(cmd)=>/git\s+checkout\s+(main|master)\s*[;&|]+\s*git\s+(commit|merge|cherry-pick|rebase|push|add)\b/.test(cmd),reason:"BLOCKED: Committing or mutating on main/master is FORBIDDEN. Work on feature branches."}];async function branchGuard(payload){let input=payload.tool_input;if(!input)return;let command=input.command;if(!command)return;if(!/\b(git|gh)\b/.test(command))return;for(let pattern of DENY_PATTERNS)if(pattern.test(command))return{decision:"deny",reason:pattern.reason};return}async function identityInject(payload){let input=payload.tool_input;if(!input)return;let msgType=input.type;if(msgType&&msgType!=="message"&&msgType!=="broadcast")return;let agentName=process.env.GENIE_AGENT_NAME;if(!agentName)return;let contentField=input.content!==void 0?"content":"message",content=input[contentField];if(!content)return;if(content.startsWith(`[from:${agentName}]`))return;return{updatedInput:{...input,[contentField]:`[from:${agentName}] ${content}`}}}var NUDGE_PATTERNS=[{test:/tmux\s+capture-pane/,message:`If you're checking genie agent progress, use structured monitoring instead:
|
|
2177
|
+
Next steps:`),console.log(" 1. Reload tmux: tmux source ~/.tmux.conf"),console.log(" 2. Restart your shell or run: source ~/.bashrc"),isTermux)console.log(" 3. Reload Termux: termux-reload-settings")}var __dirname="/home/runner/_work/genie/genie/src/genie-commands";function printHeader(){console.log(),console.log(`\x1B[1m\x1B[36m${"=".repeat(64)}\x1B[0m`),console.log("\x1B[1m\x1B[36m Genie Setup Wizard\x1B[0m"),console.log(`\x1B[1m\x1B[36m${"=".repeat(64)}\x1B[0m`),console.log()}function printSection(title,description){if(console.log(),console.log(`\x1B[1m${title}\x1B[0m`),description)console.log(`\x1B[2m${description}\x1B[0m`);console.log()}async function configureSession(config,quick){if(printSection("2. Session Configuration","Configure tmux session settings"),quick)return console.log(` Using defaults: session="${config.session.name}", window="${config.session.defaultWindow}"`),config;let sessionName=await esm_default3({message:"Session name:",default:config.session.name}),defaultWindow=await esm_default3({message:"Default window name:",default:config.session.defaultWindow}),autoCreate=await esm_default2({message:"Auto-create session on connect?",default:config.session.autoCreate});return config.session={name:sessionName,defaultWindow,autoCreate},config}async function configureTerminal(config,quick){if(printSection("3. Terminal Defaults","Configure default values for term commands"),quick)return console.log(` Using defaults: timeout=${config.terminal.execTimeout}ms, lines=${config.terminal.readLines}`),config;let timeoutStr=await esm_default3({message:"Exec timeout (milliseconds):",default:String(config.terminal.execTimeout),validate:(v)=>{let n=Number.parseInt(v,10);return!Number.isNaN(n)&&n>0?!0:"Must be a positive number"}}),linesStr=await esm_default3({message:"Read lines (default for genie agent read):",default:String(config.terminal.readLines),validate:(v)=>{let n=Number.parseInt(v,10);return!Number.isNaN(n)&&n>0?!0:"Must be a positive number"}}),worktreeBase=await esm_default3({message:"Worktree base directory (leave empty for ~/.genie/worktrees/<project>/):",default:config.terminal.worktreeBase??""});return config.terminal={execTimeout:Number.parseInt(timeoutStr,10),readLines:Number.parseInt(linesStr,10),...worktreeBase?{worktreeBase}:{}},config}async function configureShortcuts(config,quick){printSection("4. Keyboard Shortcuts","Warp-like tmux shortcuts for quick navigation");let home=homedir7(),tmuxConf=join7(home,".tmux.conf");if(isShortcutsInstalled(tmuxConf))return console.log(" \x1B[32m\u2713\x1B[0m Tmux shortcuts already installed"),config.shortcuts.tmuxInstalled=!0,config;if(console.log(" Available shortcuts:"),console.log(" \x1B[36mCtrl+T\x1B[0m \u2192 New tab (window)"),console.log(" \x1B[36mCtrl+S\x1B[0m \u2192 Vertical split"),console.log(" \x1B[36mCtrl+H\x1B[0m \u2192 Horizontal split"),console.log(),quick)return console.log(" Skipped in quick mode. Run \x1B[36mgenie setup --shortcuts\x1B[0m to install."),config;if(await esm_default2({message:"Install tmux keyboard shortcuts?",default:!1}))console.log(),await installShortcuts(),config.shortcuts.tmuxInstalled=!0,await updateShortcutsConfig({tmuxInstalled:!0});else console.log(" Skipped. Run \x1B[36mgenie shortcuts install\x1B[0m later.");return config}function printCodexResult(result){if(result==="changed")console.log(" \x1B[32m\u2713\x1B[0m Codex config updated");else if(result==="unchanged")console.log(" \x1B[32m\u2713\x1B[0m Codex config already up to date");else console.log(" \x1B[31m\u2717\x1B[0m Failed to update codex config")}async function configureCodex(config,quick){printSection("5. Codex Integration","Configure OpenAI Codex for genie agents");let codexCheck=await checkCommand("codex");if(!codexCheck.exists)return console.log(" \x1B[33m!\x1B[0m Codex CLI not found. Skipping codex integration."),config;if(console.log(` \x1B[32m\u2713\x1B[0m Codex CLI found (${codexCheck.version??"unknown version"})`),isCodexConfigured())return console.log(" \x1B[32m\u2713\x1B[0m Codex config already configured"),config.codex={configured:!0},config;if(console.log(),console.log(" Genie needs to configure codex for agent communication:"),console.log(" \x1B[36mdisable_paste_burst\x1B[0m \u2192 Reliable tmux command injection"),console.log(" \x1B[36mOTel exporter\x1B[0m \u2192 Telemetry relay for state detection"),console.log(` Config: \x1B[2m${contractPath(getCodexConfigPath())}\x1B[0m`),console.log(),quick){let result=ensureCodexOtelConfig();return printCodexResult(result),config.codex={configured:result!=="error"},config}if(await esm_default2({message:"Configure Codex for genie agent integration?",default:!0})){let result=ensureCodexOtelConfig();printCodexResult(result),config.codex={configured:result!=="error"}}else console.log(" Skipped. Run \x1B[36mgenie setup --codex\x1B[0m later.");return config}async function configureDebug(config,quick){if(printSection("6. Debug Options","Logging and debugging settings"),quick)return console.log(" Using defaults: tmuxDebug=false, verbose=false"),config;let tmuxDebug=await esm_default2({message:"Enable tmux debug logging?",default:config.logging.tmuxDebug}),verbose=await esm_default2({message:"Enable verbose mode?",default:config.logging.verbose});return config.logging={tmuxDebug,verbose},config}async function configurePromptMode(config,quick){if(printSection("7. Prompt Mode","Controls how genie injects system prompts into Claude Code"),quick)return console.log(` Using default: promptMode="${config.promptMode}"`),config;console.log(" append \u2014 Uses --append-system-prompt-file (preserves Claude Code default system prompt)"),console.log(" system \u2014 Uses --system-prompt-file (replaces Claude Code default system prompt)"),console.log();let promptMode=await esm_default4({message:"Prompt mode:",choices:[{name:"append (recommended \u2014 preserves CC default)",value:"append"},{name:"system (replaces CC default)",value:"system"}],default:config.promptMode});return config.promptMode=promptMode,config}async function showSummaryAndSave(config){printSection("Summary",`Configuration will be saved to ${contractPath(getGenieConfigPath())}`),console.log(` Session: \x1B[36m${config.session.name}\x1B[0m (window: ${config.session.defaultWindow})`),console.log(` Terminal: timeout=${config.terminal.execTimeout}ms, lines=${config.terminal.readLines}`),console.log(` Shortcuts: ${config.shortcuts.tmuxInstalled?"\x1B[32minstalled\x1B[0m":"\x1B[2mnot installed\x1B[0m"}`),console.log(` Codex: ${config.codex?.configured?"\x1B[32mconfigured\x1B[0m":"\x1B[2mnot configured\x1B[0m"}`),console.log(` Debug: tmux=${config.logging.tmuxDebug}, verbose=${config.logging.verbose}`),console.log(` Prompt mode: \x1B[36m${config.promptMode}\x1B[0m`),console.log(),config.setupComplete=!0,config.lastSetupAt=new Date().toISOString(),await saveGenieConfig(config),console.log("\x1B[32m\u2713 Configuration saved!\x1B[0m")}async function showCurrentConfig(){let config=await loadGenieConfig();console.log(),console.log("\x1B[1mCurrent Genie Configuration\x1B[0m"),console.log(`\x1B[2m${contractPath(getGenieConfigPath())}\x1B[0m`),console.log(),console.log(JSON.stringify(config,null,2)),console.log()}function printNextSteps(){console.log(),console.log("\x1B[1mNext Steps:\x1B[0m"),console.log(),console.log(" Start a session: \x1B[36mgenie\x1B[0m"),console.log(" Watch AI work: \x1B[36mtmux attach -t genie\x1B[0m"),console.log(" Check health: \x1B[36mgenie doctor\x1B[0m"),console.log()}async function setupCommand(options={}){if(options.show){await showCurrentConfig();return}if(options.reset){await resetConfig(),console.log("\x1B[32m\u2713 Configuration reset to defaults.\x1B[0m"),console.log();return}let config=await loadGenieConfig();if(options.shortcuts){printHeader(),await configureShortcuts(config,!1),await markSetupComplete();return}if(options.terminal){printHeader(),config=await configureTerminal(config,!1),await saveGenieConfig(config),console.log("\x1B[32m\u2713 Terminal configuration saved.\x1B[0m");return}if(options.session){printHeader(),config=await configureSession(config,!1),await saveGenieConfig(config),console.log("\x1B[32m\u2713 Session configuration saved.\x1B[0m");return}if(options.codex){if(printHeader(),config=await configureCodex(config,!1),await saveGenieConfig(config),config.codex?.configured)console.log("\x1B[32m\u2713 Codex configuration saved.\x1B[0m");return}let quick=options.quick??!1;if(printHeader(),quick)console.log("\x1B[2mQuick mode: accepting all defaults\x1B[0m");config=await configureSession(config,quick),config=await configureTerminal(config,quick),config=await configureShortcuts(config,quick),config=await configureCodex(config,quick),config=await configureDebug(config,quick),config=await configurePromptMode(config,quick),await showSummaryAndSave(config),installGenieTmuxConf(),printNextSteps()}function installGenieTmuxConf(){let{existsSync:existsSync7,copyFileSync:copyFileSync2,mkdirSync:mkdirSync5}=__require("fs"),{resolve}=__require("path"),genieHome2=process.env.GENIE_HOME??join7(homedir7(),".genie"),dest=join7(genieHome2,"tmux.conf");if(existsSync7(dest))return;let src=[resolve(__dirname,"..","..","scripts","tmux","genie.tmux.conf"),resolve(__dirname,"..","scripts","tmux","genie.tmux.conf")].find((p)=>existsSync7(p));if(!src)return;try{mkdirSync5(genieHome2,{recursive:!0}),copyFileSync2(src,dest),console.log(`\x1B[32m\u2713\x1B[0m Installed genie tmux config to ${dest}`)}catch{}}import{existsSync as existsSync7}from"fs";import{homedir as homedir8}from"os";import{join as join8}from"path";async function shortcutsShowCommand(){displayShortcuts();let home=homedir8(),tmuxConf=join8(home,".tmux.conf"),zshrc=join8(home,".zshrc"),bashrc=join8(home,".bashrc");if(console.log("Installation status:"),isShortcutsInstalled(tmuxConf))console.log(" \x1B[32m\u2713\x1B[0m tmux.conf");else console.log(" \x1B[33m-\x1B[0m tmux.conf");let shellRc=existsSync7(zshrc)?zshrc:bashrc;if(isShortcutsInstalled(shellRc))console.log(` \x1B[32m\u2713\x1B[0m ${shellRc.replace(home,"~")}`);else console.log(` \x1B[33m-\x1B[0m ${shellRc.replace(home,"~")}`);console.log(),console.log("Run \x1B[36mgenie shortcuts install\x1B[0m to install shortcuts."),console.log("Run \x1B[36mgenie shortcuts uninstall\x1B[0m to remove shortcuts."),console.log()}async function shortcutsInstallCommand(){await installShortcuts()}async function shortcutsUninstallCommand(){await uninstallShortcuts()}init_esm6();import{existsSync as existsSync8,lstatSync,rmSync as rmSync2,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir9}from"os";import{join as join9}from"path";init_genie_config2();var ORCHESTRATION_RULES_PATH=join9(homedir9(),".claude","rules","genie-orchestration.md"),LOCAL_BIN=join9(homedir9(),".local","bin"),SYMLINKS=["genie","term"];function isGenieSymlink(path){try{if(!existsSync8(path))return!1;if(!lstatSync(path).isSymbolicLink())return!1;return!0}catch{return!1}}function removeSymlinks(){let removed=[];for(let name of SYMLINKS){let symlinkPath=join9(LOCAL_BIN,name);if(isGenieSymlink(symlinkPath))try{unlinkSync4(symlinkPath),removed.push(name)}catch{}}return removed}function tryRemoveStep(label,successMsg,fn){console.log(`\x1B[2m${label}\x1B[0m`);try{fn(),console.log(` \x1B[32m+\x1B[0m ${successMsg}`)}catch(error){let message=error instanceof Error?error.message:String(error);console.log(` \x1B[33m!\x1B[0m ${label.replace("...","")} failed: ${message}`)}}function performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir){if(hasHookScript)tryRemoveStep("Removing hook script...","Hook script removed",()=>removeHookScript());if(existingSymlinks.length>0){console.log("\x1B[2mRemoving symlinks...\x1B[0m");let removed=removeSymlinks();if(removed.length>0)console.log(` \x1B[32m+\x1B[0m Removed: ${removed.join(", ")}`)}if(existsSync8(ORCHESTRATION_RULES_PATH))tryRemoveStep("Removing orchestration rules...","Orchestration rules removed (~/.claude/rules/genie-orchestration.md)",()=>unlinkSync4(ORCHESTRATION_RULES_PATH));if(hasGenieDir)tryRemoveStep("Removing genie directory...","Directory removed",()=>rmSync2(genieDir,{recursive:!0,force:!0}))}async function uninstallCommand(){console.log(),console.log("\x1B[1m\x1B[33m Uninstall Genie CLI\x1B[0m"),console.log();let genieDir=getGenieDir(),hasGenieDir=existsSync8(genieDir),hasHookScript=hookScriptExists(),hasOrchestrationRules=existsSync8(ORCHESTRATION_RULES_PATH),existingSymlinks=SYMLINKS.filter((name)=>isGenieSymlink(join9(LOCAL_BIN,name)));if(console.log("\x1B[2mThis will remove:\x1B[0m"),hasHookScript)console.log(" \x1B[31m-\x1B[0m Hook script (~/.claude/hooks/genie-bash-hook.sh)");if(hasOrchestrationRules)console.log(" \x1B[31m-\x1B[0m Orchestration rules (~/.claude/rules/genie-orchestration.md)");if(hasGenieDir)console.log(` \x1B[31m-\x1B[0m Genie directory (${contractPath(genieDir)})`);if(existingSymlinks.length>0)console.log(` \x1B[31m-\x1B[0m Symlinks from ~/.local/bin: ${existingSymlinks.join(", ")}`);if(console.log(),!hasGenieDir&&!hasHookScript&&!hasOrchestrationRules&&existingSymlinks.length===0){console.log("\x1B[33mNothing to uninstall.\x1B[0m"),console.log();return}if(!await esm_default2({message:"Are you sure you want to uninstall Genie CLI?",default:!1})){console.log(),console.log("\x1B[2mUninstall cancelled.\x1B[0m"),console.log();return}console.log(),performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir),console.log(),console.log("\x1B[32m+\x1B[0m Genie CLI uninstalled."),console.log(),console.log("\x1B[2mNote: If you installed via npm/bun, also run:\x1B[0m"),console.log(" \x1B[36mbun remove -g @automagik/genie\x1B[0m"),console.log(" \x1B[2mor\x1B[0m"),console.log(" \x1B[36mnpm uninstall -g @automagik/genie\x1B[0m"),console.log()}init_genie_config2();import{execSync as execSync2,spawn}from"child_process";import{chmodSync as chmodSync2,copyFileSync as copyFileSync2,existsSync as existsSync9,mkdirSync as mkdirSync5,readFileSync as readFileSync4,readdirSync,rmSync as rmSync3,writeFileSync as writeFileSync5}from"fs";import{chmod,copyFile,mkdir,unlink}from"fs/promises";import{homedir as homedir10}from"os";import{join as join10}from"path";var GENIE_HOME=process.env.GENIE_HOME||join10(homedir10(),".genie"),GENIE_SRC=join10(GENIE_HOME,"src"),GENIE_BIN=join10(GENIE_HOME,"bin"),LOCAL_BIN2=join10(homedir10(),".local","bin");function log(message){console.log(`\x1B[32m\u25B8\x1B[0m ${message}`)}function success(message){console.log(`\x1B[32m\u2714\x1B[0m ${message}`)}function error(message){console.log(`\x1B[31m\u2716\x1B[0m ${message}`)}async function runCommand(command,args,cwd){return new Promise((resolve)=>{let output=[],child=spawn(command,args,{cwd,stdio:["inherit","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}});child.stdout?.on("data",(data)=>{let str=data.toString();output.push(str),process.stdout.write(str)}),child.stderr?.on("data",(data)=>{let str=data.toString();output.push(str),process.stderr.write(str)}),child.on("close",(code)=>{resolve({success:code===0,output:output.join("")})}),child.on("error",(err)=>{error(err.message),resolve({success:!1,output:err.message})})})}async function getGitInfo(cwd){try{let branchResult=await runCommandSilent("git",["rev-parse","--abbrev-ref","HEAD"],cwd),commitResult=await runCommandSilent("git",["rev-parse","--short","HEAD"],cwd),dateResult=await runCommandSilent("git",["log","-1","--format=%ci"],cwd);if(branchResult.success&&commitResult.success&&dateResult.success)return{branch:branchResult.output.trim(),commit:commitResult.output.trim(),commitDate:dateResult.output.trim().split(" ")[0]}}catch{}return null}async function runCommandSilent(command,args,cwd,timeoutMs=4000){return new Promise((resolve)=>{let output=[],settled=!1,child=spawn(command,args,{cwd,stdio:["inherit","pipe","pipe"]}),timer=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGTERM"),resolve({success:!1,output:`Timed out after ${timeoutMs}ms`})},timeoutMs);child.stdout?.on("data",(data)=>{output.push(data.toString())}),child.stderr?.on("data",(data)=>{output.push(data.toString())}),child.on("close",(code)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({success:code===0,output:output.join("")})}),child.on("error",(err)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({success:!1,output:err.message})})})}function detectFromBinaryPath(path){if(path.includes(".bun"))return"bun";if(path.includes("node_modules"))return"npm";if(path===join10(LOCAL_BIN2,"genie")||path.startsWith(GENIE_BIN))return"source";return null}async function detectInstallationType(){if(genieConfigExists())try{let config=await loadGenieConfig();if(config.installMethod)return config.installMethod}catch{}if(existsSync9(join10(GENIE_SRC,".git")))return"source";let result=await runCommandSilent("which",["genie"]);if(!result.success)return"unknown";let detected=detectFromBinaryPath(result.output.trim());if(detected)return detected;return(await runCommandSilent("which",["bun"])).success?"bun":"npm"}async function updateViaBun(channel){try{__require("fs").unlinkSync(join10(homedir10(),".bun","install","global","bun.lock"))}catch{}if(log(`Updating via bun (channel: ${channel})...`),!(await runCommand("bun",["add","-g","--force","--no-cache",`@automagik/genie@${channel}`])).success)return error("Failed to update via bun"),!1;return console.log(),success(`Genie CLI updated via bun (${channel})!`),!0}async function updateViaNpm(channel){if(log(`Updating via npm (channel: ${channel})...`),!(await runCommand("npm",["install","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via npm"),!1;return console.log(),success(`Genie CLI updated via npm (${channel})!`),!0}async function detectGlobalInstalls(){let found=new Set,[npmResult,bunResult]=await Promise.all([runCommandSilent("npm",["list","-g","@automagik/genie"]),runCommandSilent("bun",["pm","ls","-g"])]);if(npmResult.success&&!npmResult.output.includes("(empty)"))found.add("npm");if(bunResult.success&&bunResult.output.includes("@automagik/genie"))found.add("bun");return found}async function updateSource(){let beforeInfo=await getGitInfo(GENIE_SRC);if(beforeInfo)console.log(`Current: \x1B[2m${beforeInfo.branch}@${beforeInfo.commit} (${beforeInfo.commitDate})\x1B[0m`),console.log();if(log("Fetching latest changes..."),!(await runCommand("git",["fetch","origin"],GENIE_SRC)).success)error("Failed to fetch from origin"),process.exit(1);if(log("Resetting to origin/main..."),!(await runCommand("git",["reset","--hard","origin/main"],GENIE_SRC)).success)error("Failed to reset to origin/main"),process.exit(1);console.log();let afterInfo=await getGitInfo(GENIE_SRC);if(beforeInfo&&afterInfo&&beforeInfo.commit===afterInfo.commit){success("Already up to date!"),console.log();return}if(log("Installing dependencies..."),!(await runCommand("bun",["install"],GENIE_SRC)).success)error("Failed to install dependencies"),process.exit(1);if(console.log(),log("Building..."),!(await runCommand("bun",["run","build"],GENIE_SRC)).success)error("Failed to build"),process.exit(1);console.log(),log("Installing binaries...");try{await mkdir(GENIE_BIN,{recursive:!0}),await mkdir(LOCAL_BIN2,{recursive:!0});let binaries=["genie.js","term.js"],names=["genie","term"];for(let i=0;i<binaries.length;i++){let src=join10(GENIE_SRC,"dist",binaries[i]),binDest=join10(GENIE_BIN,binaries[i]),linkDest=join10(LOCAL_BIN2,names[i]);await copyFile(src,binDest),await chmod(binDest,493),await symlinkOrCopy(binDest,linkDest)}for(let legacy of["claudio.js","claudio"]){let legacyBin=join10(GENIE_BIN,legacy),legacyLink=join10(LOCAL_BIN2,legacy);try{await unlink(legacyBin)}catch{}try{await unlink(legacyLink)}catch{}}success("Binaries installed")}catch(err){error(`Failed to install binaries: ${err}`),process.exit(1)}if(console.log(),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),success("Genie CLI updated successfully!"),console.log(),afterInfo)console.log(`Version: \x1B[36m${afterInfo.branch}@${afterInfo.commit}\x1B[0m (${afterInfo.commitDate})`),console.log()}async function symlinkOrCopy(src,dest){let{symlink,unlink:unlink2}=await import("fs/promises");try{if(existsSync9(dest))await unlink2(dest);await symlink(src,dest)}catch{await copyFile(src,dest)}}function copyDirSync(src,dest){mkdirSync5(dest,{recursive:!0});for(let entry of readdirSync(src,{withFileTypes:!0})){let srcPath=join10(src,entry.name),destPath=join10(dest,entry.name);if(entry.isDirectory())copyDirSync(srcPath,destPath);else copyFileSync2(srcPath,destPath)}}async function resolveGlobalPkgDir(installType){if(installType==="bun"){let bunPath=join10(homedir10(),".bun","install","global","node_modules","@automagik","genie");if(existsSync9(bunPath))return bunPath}if(installType==="npm"){let npmRootResult=await runCommandSilent("npm",["root","-g"]);if(npmRootResult.success){let npmPath=join10(npmRootResult.output.trim(),"@automagik","genie");if(existsSync9(npmPath))return npmPath}}let bunFallback=join10(homedir10(),".bun","install","global","node_modules","@automagik","genie");if(existsSync9(bunFallback))return bunFallback;let npmRootFallback=await runCommandSilent("npm",["root","-g"]);if(npmRootFallback.success){let npmPath=join10(npmRootFallback.output.trim(),"@automagik","genie");if(existsSync9(npmPath))return npmPath}return null}function updatePluginRegistry(claudePlugins,cacheDir,version){let registryPath=join10(claudePlugins,"installed_plugins.json");try{if(!existsSync9(registryPath))return;let registry=JSON.parse(readFileSync4(registryPath,"utf-8")),entries=registry.plugins?.["genie@automagik"];if(!Array.isArray(entries))return;for(let entry of entries)if(entry.scope==="user")entry.installPath=cacheDir,entry.version=version,entry.lastUpdated=new Date().toISOString();writeFileSync5(registryPath,JSON.stringify(registry,null,2))}catch(err){log(`Registry update failed (non-fatal): ${err}`)}}function syncTmuxConf(tmuxScriptsSrc){mkdirSync5(GENIE_HOME,{recursive:!0});let tmuxConfSrc=join10(tmuxScriptsSrc,"genie.tmux.conf"),tmuxConfDest=join10(GENIE_HOME,"tmux.conf");if(existsSync9(tmuxConfSrc))try{copyFileSync2(tmuxConfSrc,tmuxConfDest),success(`Installed tmux config to ${tmuxConfDest}`);try{let{tmuxBin:tmuxBin2}=(init_ensure_tmux(),__toCommonJS(exports_ensure_tmux));execSync2(`${tmuxBin2()} -L genie source-file '${tmuxConfDest}'`,{stdio:"ignore"}),success("Reloaded genie tmux server configuration")}catch{}}catch{}let tuiConfSrc=join10(tmuxScriptsSrc,"tui-tmux.conf"),tuiConfDest=join10(GENIE_HOME,"tui-tmux.conf");if(existsSync9(tuiConfSrc))try{copyFileSync2(tuiConfSrc,tuiConfDest),success(`Installed TUI tmux config to ${tuiConfDest}`)}catch{}}function syncTmuxScripts(globalPkgDir){let tmuxScriptsSrc=join10(globalPkgDir,"scripts","tmux");if(!existsSync9(tmuxScriptsSrc))return;let scriptsDir=join10(GENIE_HOME,"scripts");mkdirSync5(scriptsDir,{recursive:!0});let scriptCount=0;for(let entry of readdirSync(tmuxScriptsSrc))if(entry.endsWith(".sh")||entry==="genie.tmux.conf"||entry==="tui-tmux.conf"){let src=join10(tmuxScriptsSrc,entry),dest=join10(scriptsDir,entry);copyFileSync2(src,dest);try{chmodSync2(dest,entry.endsWith(".sh")?493:420)}catch{}scriptCount++}if(scriptCount>0)success(`Refreshed ${scriptCount} tmux scripts at ${scriptsDir}`);syncTmuxConf(tmuxScriptsSrc)}async function syncPlugin(installType){log("Syncing Claude Code plugin...");let globalPkgDir=await resolveGlobalPkgDir(installType);if(!globalPkgDir){log("Could not find installed package \u2014 skipping plugin sync");return}let pluginSrc=join10(globalPkgDir,"plugins","genie");if(!existsSync9(pluginSrc)){log("Plugin source not found in package \u2014 skipping plugin sync");return}let version;try{version=JSON.parse(readFileSync4(join10(globalPkgDir,"package.json"),"utf-8")).version}catch{log("Could not read package version \u2014 skipping plugin sync");return}let claudePlugins=join10(homedir10(),".claude","plugins"),cacheDir=join10(claudePlugins,"cache","automagik","genie",version);try{if(existsSync9(cacheDir))rmSync3(cacheDir,{recursive:!0,force:!0});copyDirSync(pluginSrc,cacheDir);let skillsSrc=join10(globalPkgDir,"skills");if(existsSync9(skillsSrc)&&!existsSync9(join10(cacheDir,"skills")))copyDirSync(skillsSrc,join10(cacheDir,"skills"))}catch(err){error(`Failed to copy plugin: ${err}`);return}updatePluginRegistry(claudePlugins,cacheDir,version),syncTmuxScripts(globalPkgDir),success(`Plugin synced to v${version}`)}async function resolveChannel(options){if(options.next)return"next";if(options.stable)return"latest";if(genieConfigExists())try{let config=await loadGenieConfig();if(config.updateChannel)return config.updateChannel}catch{}return"latest"}async function persistChannel(channel){try{let config=await loadGenieConfig();config.updateChannel=channel,await saveGenieConfig(config)}catch{}}async function updateCommand(options={}){console.log(),console.log("\x1B[1m\uD83E\uDDDE Genie CLI Update\x1B[0m"),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),console.log();let channel=await resolveChannel(options);if(options.next||options.stable)await persistChannel(channel);let installType=await detectInstallationType();if(log(`Detected installation: ${installType}`),log(`Channel: ${channel}${channel==="next"?" (dev builds)":" (stable)"}`),console.log(),installType==="unknown")error("No Genie CLI installation found"),console.log(),console.log("Install method not configured. Please reinstall genie:"),console.log("\x1B[36m curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash\x1B[0m"),console.log(),process.exit(1);if(installType==="source"){await updateSource();return}let globalInstalls=await detectGlobalInstalls(),primaryMethod=installType;if(!(primaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))process.exit(1);let secondaryMethod=primaryMethod==="bun"?"npm":"bun";if(globalInstalls.has(secondaryMethod)){if(console.log(),log(`Also updating ${secondaryMethod}-global install...`),!(secondaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))error(`Secondary update via ${secondaryMethod} failed (non-blocking)`)}await syncPlugin(installType)}init_version();function buildSearchNames(recipient,dirEntry){let names=new Set([recipient]);if(dirEntry){if(names.add(dirEntry.entry.name),dirEntry.entry.roles)for(let role of dirEntry.entry.roles)names.add(role)}return names}function buildSpawnArgs(template){let args=["spawn","--provider",template.provider,"--team",template.team];if(template.role)args.push("--role",template.role);if(template.skill)args.push("--skill",template.skill);if(template.cwd)args.push("--cwd",template.cwd);if(template.extraArgs)args.push(...template.extraArgs);return args}async function isRecipientLeader(recipient,teamName){try{let{getTeam:getTeam2}=await Promise.resolve().then(() => (init_team_manager(),exports_team_manager)),config=await getTeam2(teamName);return!!config?.leader&&recipient===config.leader}catch{return!1}}async function autoSpawn(payload){let input=payload.tool_input;if(!input||input.type!=="message")return;let recipient=input.recipient;if(!recipient||recipient==="team-lead")return;let teamName=process.env.GENIE_TEAM??payload.team_name;if(!teamName)return;if(await isRecipientLeader(recipient,teamName))return;try{let registryMod=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry)),tmuxMod=await Promise.resolve().then(() => (init_tmux(),exports_tmux)),directoryMod=await Promise.resolve().then(() => (init_agent_directory(),exports_agent_directory)),existing=(await registryMod.list()).find((a)=>(a.role===recipient||a.id===recipient)&&a.team===teamName);if(existing&&await tmuxMod.isPaneAlive(existing.paneId))return;let dirEntry=await directoryMod.resolve(recipient),templates=await registryMod.listTemplates(),searchNames=buildSearchNames(recipient,dirEntry),template=templates.find((t)=>{if(t.team!==teamName)return!1;return[...searchNames].some((q)=>t.id===q||t.role===q)});if(!template){if(dirEntry)console.error(`[genie-hook] Agent "${recipient}" is registered in directory but has no spawn template in team "${teamName}".`);return}let{spawnSync}=__require("child_process");spawnSync("genie",buildSpawnArgs(template),{timeout:1e4,stdio:"ignore",env:{...process.env,GENIE_TEAM:teamName}}),console.error(`[genie-hook] Auto-spawned "${recipient}" in team "${teamName}"`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(`[genie-hook] Auto-spawn failed for "${recipient}": ${msg}`)}}var DENY_PATTERNS=[{test:(cmd)=>/git\s+push\b/i.test(cmd)&&/(?:^|\s)(main|master)(?:\s|$)/.test(cmd),reason:"BLOCKED: Push to main/master is FORBIDDEN. Push to a feature branch and create a PR targeting dev."},{test:(cmd)=>/git\s+push\b/.test(cmd)&&/:(main|master)\b/.test(cmd),reason:"BLOCKED: Push refspec targeting main/master is FORBIDDEN."},{test:(cmd)=>/gh\s+pr\s+create\b/.test(cmd)&&/(--base|-B)\s+(main|master)\b/.test(cmd),reason:"BLOCKED: PRs must target dev, not main/master. Use: gh pr create --base dev"},{test:(cmd)=>/gh\s+pr\s+create\b/.test(cmd)&&!/(--base|-B)\s+\S/.test(cmd),reason:"BLOCKED: gh pr create requires explicit --base flag. Without it, GitHub defaults to main. Use: gh pr create --base dev"},{test:(cmd)=>/gh\s+pr\s+merge\b/.test(cmd),reason:"BLOCKED: Agents may NOT merge PRs. Only humans merge via GitHub UI."},{test:(cmd)=>/git\s+checkout\s+(main|master)\s*[;&|]+\s*git\s+(commit|merge|cherry-pick|rebase|push|add)\b/.test(cmd),reason:"BLOCKED: Committing or mutating on main/master is FORBIDDEN. Work on feature branches."}];async function branchGuard(payload){let input=payload.tool_input;if(!input)return;let command=input.command;if(!command)return;if(!/\b(git|gh)\b/.test(command))return;for(let pattern of DENY_PATTERNS)if(pattern.test(command))return{decision:"deny",reason:pattern.reason};return}async function identityInject(payload){let input=payload.tool_input;if(!input)return;let msgType=input.type;if(msgType&&msgType!=="message"&&msgType!=="broadcast")return;let agentName=process.env.GENIE_AGENT_NAME;if(!agentName)return;let contentField=input.content!==void 0?"content":"message",content=input[contentField];if(!content)return;if(content.startsWith(`[from:${agentName}]`))return;return{updatedInput:{...input,[contentField]:`[from:${agentName}] ${content}`}}}var NUDGE_PATTERNS=[{test:/tmux\s+capture-pane/,message:`If you're checking genie agent progress, use structured monitoring instead:
|
|
2178
2178
|
`+` genie task status <slug> \u2014 wish progress from PG
|
|
2179
2179
|
`+` genie agent list --json \u2014 executor state machine
|
|
2180
2180
|
`+` genie events timeline <id> \u2014 structured event log
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@automagik/genie",
|
|
3
|
-
"version": "4.260331.
|
|
3
|
+
"version": "4.260331.18",
|
|
4
4
|
"description": "Collaborative terminal toolkit for human + AI workflows",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"build:plugin": "node scripts/build.js",
|
|
15
15
|
"sync": "node scripts/sync.js",
|
|
16
16
|
"build-and-sync": "npm run build:plugin && npm run sync",
|
|
17
|
+
"postinstall": "node scripts/postinstall-tmux.js",
|
|
17
18
|
"prepack": "bun run build",
|
|
18
19
|
"lint": "biome check .",
|
|
19
20
|
"lint:fix": "biome check --write .",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "genie",
|
|
3
|
-
"version": "4.260331.
|
|
3
|
+
"version": "4.260331.18",
|
|
4
4
|
"description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Namastex Labs"
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* postinstall-tmux.js — Download tmux static binary if not on PATH.
|
|
4
|
+
*
|
|
5
|
+
* Runs during `bun add -g @automagik/genie` and callable from smart-install.js.
|
|
6
|
+
* Downloads from the official tmux-builds repository:
|
|
7
|
+
* https://github.com/tmux/tmux-builds
|
|
8
|
+
*
|
|
9
|
+
* Standalone — no imports outside node builtins.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { arch, homedir, platform, tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
|
|
17
|
+
const TMUX_VERSION = '3.6a';
|
|
18
|
+
const GENIE_HOME = process.env.GENIE_HOME || join(homedir(), '.genie');
|
|
19
|
+
const BIN_DIR = join(GENIE_HOME, 'bin');
|
|
20
|
+
const TMUX_PATH = join(BIN_DIR, 'tmux');
|
|
21
|
+
|
|
22
|
+
function getPlatformAsset() {
|
|
23
|
+
const os = platform();
|
|
24
|
+
const cpu = arch();
|
|
25
|
+
const map = {
|
|
26
|
+
'linux-x64': `tmux-${TMUX_VERSION}-linux-x86_64.tar.gz`,
|
|
27
|
+
'linux-arm64': `tmux-${TMUX_VERSION}-linux-arm64.tar.gz`,
|
|
28
|
+
'darwin-arm64': `tmux-${TMUX_VERSION}-macos-arm64.tar.gz`,
|
|
29
|
+
'darwin-x64': `tmux-${TMUX_VERSION}-macos-x86_64.tar.gz`,
|
|
30
|
+
};
|
|
31
|
+
return map[`${os}-${cpu}`] || null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isTmuxOnPath() {
|
|
35
|
+
try {
|
|
36
|
+
const r = spawnSync('tmux', ['-V'], { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
37
|
+
return r.status === 0;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isTmuxCached() {
|
|
44
|
+
if (!existsSync(TMUX_PATH)) return false;
|
|
45
|
+
try {
|
|
46
|
+
const r = spawnSync(TMUX_PATH, ['-V'], { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
47
|
+
return r.status === 0;
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function downloadTmux() {
|
|
54
|
+
const asset = getPlatformAsset();
|
|
55
|
+
if (!asset) {
|
|
56
|
+
const key = `${platform()}-${arch()}`;
|
|
57
|
+
console.error(`[genie] tmux: no prebuilt binary for ${key}. Install tmux manually.`);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const url =
|
|
62
|
+
process.env.GENIE_TMUX_URL || `https://github.com/tmux/tmux-builds/releases/download/v${TMUX_VERSION}/${asset}`;
|
|
63
|
+
|
|
64
|
+
const tempDir = join(tmpdir(), `genie-tmux-${Date.now()}`);
|
|
65
|
+
|
|
66
|
+
console.error(`[genie] tmux not found — downloading ${asset}...`);
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
const res = await fetch(url);
|
|
70
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
71
|
+
|
|
72
|
+
const buffer = Buffer.from(await res.arrayBuffer());
|
|
73
|
+
const sizeMB = (buffer.byteLength / 1024 / 1024).toFixed(1);
|
|
74
|
+
console.error(`[genie] Downloaded ${sizeMB} MB`);
|
|
75
|
+
|
|
76
|
+
mkdirSync(tempDir, { recursive: true });
|
|
77
|
+
const tarball = join(tempDir, asset);
|
|
78
|
+
writeFileSync(tarball, buffer);
|
|
79
|
+
|
|
80
|
+
// Use spawnSync with args array to avoid shell injection with special path chars
|
|
81
|
+
const tarResult = spawnSync('tar', ['-xzf', tarball, '-C', tempDir], { stdio: 'ignore' });
|
|
82
|
+
if (tarResult.status !== 0) throw new Error('Failed to extract tmux tarball');
|
|
83
|
+
|
|
84
|
+
const extracted = join(tempDir, 'tmux');
|
|
85
|
+
if (!existsSync(extracted)) throw new Error('Tarball did not contain tmux binary');
|
|
86
|
+
|
|
87
|
+
mkdirSync(BIN_DIR, { recursive: true });
|
|
88
|
+
copyFileSync(extracted, TMUX_PATH);
|
|
89
|
+
chmodSync(TMUX_PATH, 0o755);
|
|
90
|
+
|
|
91
|
+
// Verify
|
|
92
|
+
const r = spawnSync(TMUX_PATH, ['-V'], { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
93
|
+
if (r.status !== 0) throw new Error('Downloaded binary not executable on this system');
|
|
94
|
+
|
|
95
|
+
console.error(`[genie] ${r.stdout.trim()} installed to ${TMUX_PATH}`);
|
|
96
|
+
return true;
|
|
97
|
+
} catch (err) {
|
|
98
|
+
try {
|
|
99
|
+
if (existsSync(TMUX_PATH)) unlinkSync(TMUX_PATH);
|
|
100
|
+
} catch {}
|
|
101
|
+
console.error(`[genie] tmux download failed: ${err.message}`);
|
|
102
|
+
console.error('[genie] Install manually:');
|
|
103
|
+
if (platform() === 'darwin') console.error(' brew install tmux');
|
|
104
|
+
else console.error(' sudo apt install tmux');
|
|
105
|
+
return false;
|
|
106
|
+
} finally {
|
|
107
|
+
try {
|
|
108
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
109
|
+
} catch {}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Ensure tmux is available — download if missing.
|
|
115
|
+
* Exported for use by smart-install.js and other callers.
|
|
116
|
+
*/
|
|
117
|
+
export async function ensureTmux() {
|
|
118
|
+
if (isTmuxOnPath() || isTmuxCached()) return true;
|
|
119
|
+
return downloadTmux();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Run directly when invoked as a script (postinstall or CLI)
|
|
123
|
+
await ensureTmux();
|
package/scripts/smart-install.js
CHANGED
|
@@ -130,6 +130,69 @@ function getTmuxVersion() {
|
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
+
/**
|
|
134
|
+
* Download static tmux binary from official tmux-builds.
|
|
135
|
+
* Inlined here because the plugin build only copies smart-install.js.
|
|
136
|
+
*/
|
|
137
|
+
async function downloadTmuxBinary() {
|
|
138
|
+
const TMUX_VERSION = '3.6a';
|
|
139
|
+
const os = process.platform;
|
|
140
|
+
const cpu = process.arch;
|
|
141
|
+
const assetMap = {
|
|
142
|
+
'linux-x64': `tmux-${TMUX_VERSION}-linux-x86_64.tar.gz`,
|
|
143
|
+
'linux-arm64': `tmux-${TMUX_VERSION}-linux-arm64.tar.gz`,
|
|
144
|
+
'darwin-arm64': `tmux-${TMUX_VERSION}-macos-arm64.tar.gz`,
|
|
145
|
+
'darwin-x64': `tmux-${TMUX_VERSION}-macos-x86_64.tar.gz`,
|
|
146
|
+
};
|
|
147
|
+
const asset = assetMap[`${os}-${cpu}`];
|
|
148
|
+
if (!asset) {
|
|
149
|
+
console.error(`tmux: no prebuilt binary for ${os}-${cpu}.`);
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const url = `https://github.com/tmux/tmux-builds/releases/download/v${TMUX_VERSION}/${asset}`;
|
|
154
|
+
const { tmpdir } = await import('node:os');
|
|
155
|
+
const { copyFileSync, chmodSync, rmSync, writeFileSync } = await import('node:fs');
|
|
156
|
+
const tempDir = join(tmpdir(), `genie-tmux-${Date.now()}`);
|
|
157
|
+
const dest = join(GENIE_DIR, 'bin', 'tmux');
|
|
158
|
+
|
|
159
|
+
console.error(`Downloading tmux ${TMUX_VERSION} (${asset})...`);
|
|
160
|
+
try {
|
|
161
|
+
const res = await fetch(url);
|
|
162
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
163
|
+
const buffer = Buffer.from(await res.arrayBuffer());
|
|
164
|
+
console.error(`Downloaded ${(buffer.byteLength / 1024 / 1024).toFixed(1)} MB`);
|
|
165
|
+
|
|
166
|
+
mkdirSync(tempDir, { recursive: true });
|
|
167
|
+
writeFileSync(join(tempDir, asset), buffer);
|
|
168
|
+
const tarResult = spawnSync('tar', ['-xzf', join(tempDir, asset), '-C', tempDir], { stdio: 'ignore' });
|
|
169
|
+
if (tarResult.status !== 0) throw new Error('tar extraction failed');
|
|
170
|
+
|
|
171
|
+
const extracted = join(tempDir, 'tmux');
|
|
172
|
+
if (!existsSync(extracted)) throw new Error('tarball did not contain tmux binary');
|
|
173
|
+
|
|
174
|
+
mkdirSync(join(GENIE_DIR, 'bin'), { recursive: true });
|
|
175
|
+
copyFileSync(extracted, dest);
|
|
176
|
+
chmodSync(dest, 0o755);
|
|
177
|
+
|
|
178
|
+
const verify = spawnSync(dest, ['-V'], { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
179
|
+
if (verify.status !== 0) throw new Error('binary not executable');
|
|
180
|
+
|
|
181
|
+
console.error(`${verify.stdout.trim()} installed to ${dest}`);
|
|
182
|
+
return true;
|
|
183
|
+
} catch (e) {
|
|
184
|
+
try {
|
|
185
|
+
if (existsSync(dest)) (await import('node:fs')).unlinkSync(dest);
|
|
186
|
+
} catch {}
|
|
187
|
+
console.error(`tmux download failed: ${e.message}`);
|
|
188
|
+
return false;
|
|
189
|
+
} finally {
|
|
190
|
+
try {
|
|
191
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
192
|
+
} catch {}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
133
196
|
/**
|
|
134
197
|
* Check if beads (bd) is installed
|
|
135
198
|
*/
|
|
@@ -325,25 +388,30 @@ try {
|
|
|
325
388
|
installBun();
|
|
326
389
|
}
|
|
327
390
|
|
|
328
|
-
// 2. Check tmux -
|
|
391
|
+
// 2. Check tmux — auto-download static binary if missing
|
|
329
392
|
if (!isTmuxInstalled()) {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
393
|
+
const tmuxCached = join(GENIE_DIR, 'bin', 'tmux');
|
|
394
|
+
if (existsSync(tmuxCached)) {
|
|
395
|
+
console.error(`tmux found at ${tmuxCached}`);
|
|
396
|
+
} else {
|
|
397
|
+
const ok = await downloadTmuxBinary();
|
|
398
|
+
if (!ok) {
|
|
399
|
+
console.error('Please install tmux manually:');
|
|
400
|
+
if (process.platform === 'darwin') {
|
|
401
|
+
console.error(' brew install tmux');
|
|
402
|
+
} else if (process.platform === 'linux') {
|
|
403
|
+
console.error(' sudo apt install tmux # Debian/Ubuntu');
|
|
404
|
+
console.error(' sudo dnf install tmux # Fedora/RHEL');
|
|
405
|
+
console.error(' sudo pacman -S tmux # Arch');
|
|
406
|
+
} else if (IS_WINDOWS) {
|
|
407
|
+
console.error(' WSL is required for tmux on Windows');
|
|
408
|
+
console.error(' Inside WSL: sudo apt install tmux');
|
|
409
|
+
}
|
|
410
|
+
console.error('');
|
|
411
|
+
console.error('Then restart Claude Code.');
|
|
412
|
+
process.exit(2);
|
|
413
|
+
}
|
|
343
414
|
}
|
|
344
|
-
console.error('');
|
|
345
|
-
console.error('Then restart Claude Code.');
|
|
346
|
-
process.exit(2); // Exit code 2 = blocking error for Claude to process
|
|
347
415
|
}
|
|
348
416
|
|
|
349
417
|
// 3. Check/install beads
|
package/src/lib/agent-sync.ts
CHANGED
|
@@ -82,7 +82,8 @@ function getRepoPathForAgent(agentDir: string): string | null {
|
|
|
82
82
|
// Discovery
|
|
83
83
|
// ============================================================================
|
|
84
84
|
|
|
85
|
-
/** Discover all agents in {workspaceRoot}/agents/ that have AGENTS.md.
|
|
85
|
+
/** Discover all agents in {workspaceRoot}/agents/ that have AGENTS.md.
|
|
86
|
+
* Also recursively discovers sub-agents in {agent}/.genie/agents/. */
|
|
86
87
|
function discoverAgents(workspaceRoot: string): AgentInfo[] {
|
|
87
88
|
const agentsDir = join(workspaceRoot, 'agents');
|
|
88
89
|
if (!existsSync(agentsDir)) return [];
|
|
@@ -101,6 +102,9 @@ function discoverAgents(workspaceRoot: string): AgentInfo[] {
|
|
|
101
102
|
repoUrl: getGitRemoteUrl(agentDir),
|
|
102
103
|
productRepo: getRepoPathForAgent(agentDir),
|
|
103
104
|
});
|
|
105
|
+
|
|
106
|
+
// Discover sub-agents in .genie/agents/
|
|
107
|
+
discoverSubAgents(agentDir, entry.name, agents);
|
|
104
108
|
}
|
|
105
109
|
} catch {
|
|
106
110
|
// agents/ dir may not be readable
|
|
@@ -108,6 +112,32 @@ function discoverAgents(workspaceRoot: string): AgentInfo[] {
|
|
|
108
112
|
return agents;
|
|
109
113
|
}
|
|
110
114
|
|
|
115
|
+
/** Discover sub-agents inside {parentDir}/.genie/agents/.
|
|
116
|
+
* Names are scoped as {parentName}/{subName} to avoid collisions
|
|
117
|
+
* (e.g. genie/qa vs totvs/qa). */
|
|
118
|
+
function discoverSubAgents(parentDir: string, parentName: string, agents: AgentInfo[]): void {
|
|
119
|
+
const subAgentsDir = join(parentDir, '.genie', 'agents');
|
|
120
|
+
if (!existsSync(subAgentsDir)) return;
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
const entries = readdirSync(subAgentsDir, { withFileTypes: true });
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (!entry.isDirectory()) continue;
|
|
126
|
+
const subDir = join(subAgentsDir, entry.name);
|
|
127
|
+
if (!existsSync(join(subDir, 'AGENTS.md'))) continue;
|
|
128
|
+
|
|
129
|
+
agents.push({
|
|
130
|
+
name: `${parentName}/${entry.name}`,
|
|
131
|
+
dir: subDir,
|
|
132
|
+
repoUrl: getGitRemoteUrl(parentDir),
|
|
133
|
+
productRepo: getRepoPathForAgent(parentDir),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
// sub-agents dir may not be readable
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
111
141
|
/** Discover a single agent by name. */
|
|
112
142
|
function discoverSingleAgent(workspaceRoot: string, agentName: string): AgentInfo | null {
|
|
113
143
|
const agentDir = join(workspaceRoot, 'agents', agentName);
|
package/src/lib/db.ts
CHANGED
|
@@ -418,8 +418,11 @@ export async function getConnection() {
|
|
|
418
418
|
});
|
|
419
419
|
|
|
420
420
|
try {
|
|
421
|
-
//
|
|
422
|
-
|
|
421
|
+
// Skip migrations in test mode — setupTestSchema() already ran them in the isolated schema.
|
|
422
|
+
// Running them again here races with other test workers on public._genie_migrations.
|
|
423
|
+
if (!testSchema) {
|
|
424
|
+
await runMigrations(sqlClient);
|
|
425
|
+
}
|
|
423
426
|
|
|
424
427
|
// Run idempotent JSON → PG seed if source files exist
|
|
425
428
|
if (!testSchema && needsSeed()) {
|
package/src/lib/ensure-tmux.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { execSync } from 'node:child_process';
|
|
19
|
-
import { chmodSync, existsSync, mkdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
20
20
|
import { arch, homedir, platform, tmpdir } from 'node:os';
|
|
21
21
|
import { join } from 'node:path';
|
|
22
22
|
|
|
@@ -149,10 +149,8 @@ async function downloadTmux(): Promise<string> {
|
|
|
149
149
|
throw new Error('Tarball did not contain a tmux binary');
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
// 4. Move to cache
|
|
152
|
+
// 4. Move to cache (copy, not rename — may cross filesystem boundaries with /tmp)
|
|
153
153
|
mkdirSync(genieBinDir(), { recursive: true });
|
|
154
|
-
// Copy instead of rename (may cross filesystem boundaries with /tmp)
|
|
155
|
-
const { copyFileSync } = require('node:fs');
|
|
156
154
|
copyFileSync(extractedBin, dest);
|
|
157
155
|
chmodSync(dest, 0o755);
|
|
158
156
|
|
package/src/lib/test-db.ts
CHANGED
|
@@ -53,7 +53,13 @@ const STALE_SCHEMA_AGE_MS = 10 * 60 * 1000; // 10 minutes
|
|
|
53
53
|
export async function setupTestSchema(): Promise<() => Promise<void>> {
|
|
54
54
|
const schemaName = `test_${process.pid}_${Date.now()}`;
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
let port: number;
|
|
57
|
+
try {
|
|
58
|
+
port = await ensurePgserve();
|
|
59
|
+
} catch {
|
|
60
|
+
// PG unreachable under concurrent test load — return no-op cleanup
|
|
61
|
+
return async () => {};
|
|
62
|
+
}
|
|
57
63
|
const postgres = (await import('postgres')).default;
|
|
58
64
|
const adminSql = postgres({
|
|
59
65
|
host: '127.0.0.1',
|
|
@@ -68,18 +74,28 @@ export async function setupTestSchema(): Promise<() => Promise<void>> {
|
|
|
68
74
|
connection: { client_min_messages: 'warning' },
|
|
69
75
|
});
|
|
70
76
|
|
|
71
|
-
|
|
72
|
-
|
|
77
|
+
try {
|
|
78
|
+
// Defensively clean up stale test schemas from crashed runs
|
|
79
|
+
await cleanupStaleSchemas(adminSql);
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
// Create the test schema and run migrations inside it.
|
|
82
|
+
// search_path = test schema ONLY (no public) ensures _genie_migrations is
|
|
83
|
+
// created fresh in the test schema, so migration runner sees zero applied
|
|
84
|
+
// and creates all tables in the test schema.
|
|
85
|
+
// max: 1 ensures SET search_path applies to all subsequent queries on this connection.
|
|
86
|
+
await adminSql.unsafe(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`);
|
|
87
|
+
await adminSql.unsafe(`SET search_path TO "${schemaName}"`);
|
|
88
|
+
await runMigrations(adminSql);
|
|
89
|
+
await adminSql.end({ timeout: 5 });
|
|
90
|
+
} catch {
|
|
91
|
+
// Schema creation or migration race under concurrent test load — skip gracefully
|
|
92
|
+
try {
|
|
93
|
+
await adminSql.end({ timeout: 1 });
|
|
94
|
+
} catch {
|
|
95
|
+
/* Best-effort cleanup: connection may already be closed */
|
|
96
|
+
}
|
|
97
|
+
return async () => {};
|
|
98
|
+
}
|
|
83
99
|
|
|
84
100
|
// Reset the singleton and set the env var so getConnection() picks up the schema
|
|
85
101
|
await resetConnection();
|