@automagik/genie 4.260409.11 → 4.260409.13
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 +114 -114
- package/package.json +1 -1
- package/plugins/genie/.claude-plugin/plugin.json +1 -1
- package/plugins/genie/package.json +1 -1
- package/src/lib/provider-adapters.ts +15 -8
- package/src/services/executors/claude-code.ts +2 -1
- package/src/services/omni-bridge.ts +34 -86
package/dist/genie.js
CHANGED
|
@@ -59,13 +59,88 @@ ${errCtx.stack}`;sub.unsubscribe(),d.reject(err)}else if(err=(0,msg_1.isRequestE
|
|
|
59
59
|
|
|
60
60
|
${errCtx.stack}`;d.reject(err)}else d.resolve(msg)}});return sub.requestSubject=subject,this.protocol.publish(subject,data,{reply:inbox,headers:opts.headers}),d}else{let r=new request_1.RequestOne(this.protocol.muxSubscriptions,subject,opts,asyncTraces);this.protocol.request(r);try{this.publish(subject,data,{reply:`${this.protocol.muxSubscriptions.baseInbox}${r.token}`,headers:opts.headers})}catch(err){r.cancel(err)}let p=Promise.race([r.timer,r.deferred]);return p.catch(()=>{r.cancel()}),p}}flush(){if(this.isClosed())return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));return this.protocol.flush()}drain(){if(this.isClosed())return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));if(this.isDraining())return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionDraining));return this.draining=!0,this.protocol.drain()}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){let srv=this.protocol.getServer();return srv?srv.listen:""}status(){let iter=new queued_iterator_1.QueuedIteratorImpl;return iter.iterClosed.then(()=>{let idx=this.listeners.indexOf(iter);this.listeners.splice(idx,1)}),this.listeners.push(iter),iter}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}context(){return __awaiter(this,void 0,void 0,function*(){return(yield this.request("$SYS.REQ.USER.INFO")).json((key,value)=>{if(key==="time")return new Date(Date.parse(value));return value})})}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}jetstreamManager(){return __awaiter(this,arguments,void 0,function*(opts={}){let adm=new jsm_1.JetStreamManagerImpl(this,opts);if(opts.checkAPI!==!1)try{yield adm.getAccountInfo()}catch(err){let ne=err;if(ne.code===core_1.ErrorCode.NoResponders)ne.code=core_1.ErrorCode.JetStreamNotEnabled;throw ne}return adm})}jetstream(opts={}){return new jsclient_1.JetStreamClientImpl(this,opts)}getServerVersion(){let info=this.info;return info?(0,semver_1.parseSemVer)(info.version):void 0}rtt(){return __awaiter(this,void 0,void 0,function*(){if(!this.protocol._closed&&!this.protocol.connected)throw types_1.NatsError.errorForCode(core_1.ErrorCode.Disconnect);let start=Date.now();return yield this.flush(),Date.now()-start})}get features(){return this.protocol.features}get services(){if(!this._services)this._services=new ServicesFactory(this);return this._services}reconnect(){if(this.isClosed())return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));if(this.isDraining())return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionDraining));return this.protocol.reconnect()}}exports.NatsConnectionImpl=NatsConnectionImpl;class ServicesFactory{constructor(nc){this.nc=nc}add(config){try{return new service_1.ServiceImpl(this.nc,config).start()}catch(err){return Promise.reject(err)}}client(opts,prefix){return new serviceclient_1.ServiceClientImpl(this.nc,opts,prefix)}}exports.ServicesFactory=ServicesFactory});var require_bench=__commonJS((exports)=>{var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result2){result2.done?resolve(result2.value):adopt(result2.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__asyncValues=exports&&exports.__asyncValues||function(o){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values==="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}};Object.defineProperty(exports,"__esModule",{value:!0});exports.Bench=exports.Metric=void 0;exports.throughput=throughput;exports.msgThroughput=msgThroughput;exports.humanizeBytes=humanizeBytes;var types_1=require_types(),nuid_1=require_nuid(),util_1=require_util(),core_1=require_core();class Metric{constructor(name,duration){this.name=name,this.duration=duration,this.date=Date.now(),this.payload=0,this.msgs=0,this.bytes=0}toString(){let sec=this.duration/1000,mps=Math.round(this.msgs/sec),label=this.asyncRequests?"asyncRequests":"",minmax="";if(this.max)minmax=`${this.min}/${this.max}`;return`${this.name}${label?" [asyncRequests]":""} ${humanizeNumber(mps)} msgs/sec - [${sec.toFixed(2)} secs] ~ ${throughput(this.bytes,sec)} ${minmax}`}toCsv(){return`"${this.name}",${new Date(this.date).toISOString()},${this.lang},${this.version},${this.msgs},${this.payload},${this.bytes},${this.duration},${this.asyncRequests?this.asyncRequests:!1}
|
|
61
61
|
`}static header(){return`Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
|
|
62
|
-
`}}exports.Metric=Metric;class Bench{constructor(nc,opts={msgs:1e5,size:128,subject:"",asyncRequests:!1,pub:!1,sub:!1,req:!1,rep:!1}){if(this.nc=nc,this.callbacks=opts.callbacks||!1,this.msgs=opts.msgs||0,this.size=opts.size||0,this.subject=opts.subject||nuid_1.nuid.next(),this.asyncRequests=opts.asyncRequests||!1,this.pub=opts.pub||!1,this.sub=opts.sub||!1,this.req=opts.req||!1,this.rep=opts.rep||!1,this.perf=new util_1.Perf,this.payload=this.size?new Uint8Array(this.size):types_1.Empty,!this.pub&&!this.sub&&!this.req&&!this.rep)throw Error("no bench option selected")}run(){return __awaiter(this,void 0,void 0,function*(){if(this.nc.closed().then((err)=>{if(err)throw new core_1.NatsError(`bench closed with an error: ${err.message}`,core_1.ErrorCode.Unknown,err)}),this.callbacks)yield this.runCallbacks();else yield this.runAsync();return this.processMetrics()})}processMetrics(){let nc=this.nc,{lang,version}=nc.protocol.transport;if(this.pub&&this.sub)this.perf.measure("pubsub","pubStart","subStop");if(this.req&&this.rep)this.perf.measure("reqrep","reqStart","reqStop");let measures=this.perf.getEntries(),pubsub=measures.find((m)=>m.name==="pubsub"),reqrep=measures.find((m)=>m.name==="reqrep"),req=measures.find((m)=>m.name==="req"),rep=measures.find((m)=>m.name==="rep"),pub=measures.find((m)=>m.name==="pub"),sub=measures.find((m)=>m.name==="sub"),stats=this.nc.stats(),metrics=[];if(pubsub){let{name,duration}=pubsub,m=new Metric(name,duration);m.msgs=this.msgs*2,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(reqrep){let{name,duration}=reqrep,m=new Metric(name,duration);m.msgs=this.msgs*2,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(pub){let{name,duration}=pub,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(sub){let{name,duration}=sub,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.inBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(rep){let{name,duration}=rep,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(req){let{name,duration}=req,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}return metrics}runCallbacks(){return __awaiter(this,void 0,void 0,function*(){let jobs=[];if(this.sub){let d=(0,util_1.deferred)();jobs.push(d);let i=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{if(i++,i===1)this.perf.mark("subStart");if(i===this.msgs)this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),d.resolve()}})}if(this.rep){let d=(0,util_1.deferred)();jobs.push(d);let i=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(_,m)=>{if(m.respond(this.payload),i++,i===1)this.perf.mark("repStart");if(i===this.msgs)this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop"),d.resolve()}})}if(this.pub){let job=(()=>__awaiter(this,void 0,void 0,function*(){this.perf.mark("pubStart");for(let i=0;i<this.msgs;i++)this.nc.publish(this.subject,this.payload);yield this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")}))();jobs.push(job)}if(this.req){let job=(()=>__awaiter(this,void 0,void 0,function*(){if(this.asyncRequests){this.perf.mark("reqStart");let a=[];for(let i=0;i<this.msgs;i++)a.push(this.nc.request(this.subject,this.payload,{timeout:20000}));yield Promise.all(a),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let i=0;i<this.msgs;i++)yield this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}}))();jobs.push(job)}yield Promise.all(jobs)})}runAsync(){return __awaiter(this,void 0,void 0,function*(){let jobs=[];if(this.rep){let first=!1,sub=this.nc.subscribe(this.subject,{max:this.msgs}),job=(()=>__awaiter(this,void 0,void 0,function*(){var _a,e_1,_b,_c;try{for(var _d=!0,sub_1=__asyncValues(sub),sub_1_1;sub_1_1=yield sub_1.next(),_a=sub_1_1.done,!_a;_d=!0){_c=sub_1_1.value,_d=!1;let m=_c;if(!first)this.perf.mark("repStart"),first=!0;m.respond(this.payload)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{if(!_d&&!_a&&(_b=sub_1.return))yield _b.call(sub_1)}finally{if(e_1)throw e_1.error}}yield this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")}))();jobs.push(job)}if(this.sub){let first=!1,sub=this.nc.subscribe(this.subject,{max:this.msgs}),job=(()=>__awaiter(this,void 0,void 0,function*(){var _a,e_2,_b,_c;try{for(var _d=!0,sub_2=__asyncValues(sub),sub_2_1;sub_2_1=yield sub_2.next(),_a=sub_2_1.done,!_a;_d=!0){_c=sub_2_1.value,_d=!1;let _m=_c;if(!first)this.perf.mark("subStart"),first=!0}}catch(e_2_1){e_2={error:e_2_1}}finally{try{if(!_d&&!_a&&(_b=sub_2.return))yield _b.call(sub_2)}finally{if(e_2)throw e_2.error}}this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")}))();jobs.push(job)}if(this.pub){let job=(()=>__awaiter(this,void 0,void 0,function*(){this.perf.mark("pubStart");for(let i=0;i<this.msgs;i++)this.nc.publish(this.subject,this.payload);yield this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")}))();jobs.push(job)}if(this.req){let job=(()=>__awaiter(this,void 0,void 0,function*(){if(this.asyncRequests){this.perf.mark("reqStart");let a=[];for(let i=0;i<this.msgs;i++)a.push(this.nc.request(this.subject,this.payload,{timeout:20000}));yield Promise.all(a),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let i=0;i<this.msgs;i++)yield this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}}))();jobs.push(job)}yield Promise.all(jobs)})}}exports.Bench=Bench;function throughput(bytes,seconds){return`${humanizeBytes(bytes/seconds)}/sec`}function msgThroughput(msgs,seconds){return`${Math.floor(msgs/seconds)} msgs/sec`}function humanizeBytes(bytes,si=!1){let base=si?1000:1024,pre=si?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],post=si?"iB":"B";if(bytes<base)return`${bytes.toFixed(2)} ${post}`;let exp=parseInt(Math.log(bytes)/Math.log(base)+""),index=parseInt(exp-1+"");return`${(bytes/Math.pow(base,exp)).toFixed(2)} ${pre[index]}${post}`}function humanizeNumber(n){return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var require_internal_mod=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m[k]}};Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.parseIP=exports.isIP=exports.TE=exports.TD=exports.Metric=exports.Bench=exports.writeAll=exports.readAll=exports.MAX_SIZE=exports.DenoBuffer=exports.State=exports.Parser=exports.Kind=exports.QueuedIteratorImpl=exports.StringCodec=exports.JSONCodec=exports.usernamePasswordAuthenticator=exports.tokenAuthenticator=exports.nkeyAuthenticator=exports.jwtAuthenticator=exports.credsAuthenticator=exports.RequestOne=exports.checkUnsupportedOption=exports.checkOptions=exports.buildAuthenticator=exports.DataBuffer=exports.MuxSubscription=exports.Heartbeat=exports.MsgHdrsImpl=exports.headers=exports.canonicalMIMEHeaderKey=exports.timeout=exports.render=exports.nanos=exports.millis=exports.extend=exports.delay=exports.deferred=exports.deadline=exports.collect=exports.backoff=exports.ProtocolHandler=exports.INFO=exports.Connect=exports.setTransportFactory=exports.getResolveFn=exports.MsgImpl=exports.nuid=exports.Nuid=exports.NatsConnectionImpl=void 0;exports.Subscriptions=exports.SubscriptionImpl=exports.syncIterator=exports.ServiceVerb=exports.ServiceResponseType=exports.ServiceErrorHeader=exports.ServiceErrorCodeHeader=exports.ServiceError=exports.RequestStrategy=exports.NatsError=exports.Match=exports.isNatsError=exports.Events=exports.ErrorCode=exports.DebugEvents=exports.createInbox=exports.extractProtocolMessage=exports.Empty=exports.parseSemVer=exports.compare=exports.NoopKvCodecs=exports.defaultBucketOpts=exports.Bucket=exports.Base64KeyCodec=exports.TypedSubscription=void 0;var nats_1=require_nats();Object.defineProperty(exports,"NatsConnectionImpl",{enumerable:!0,get:function(){return nats_1.NatsConnectionImpl}});var nuid_1=require_nuid();Object.defineProperty(exports,"Nuid",{enumerable:!0,get:function(){return nuid_1.Nuid}});Object.defineProperty(exports,"nuid",{enumerable:!0,get:function(){return nuid_1.nuid}});var msg_1=require_msg();Object.defineProperty(exports,"MsgImpl",{enumerable:!0,get:function(){return msg_1.MsgImpl}});var transport_1=require_transport();Object.defineProperty(exports,"getResolveFn",{enumerable:!0,get:function(){return transport_1.getResolveFn}});Object.defineProperty(exports,"setTransportFactory",{enumerable:!0,get:function(){return transport_1.setTransportFactory}});var protocol_1=require_protocol();Object.defineProperty(exports,"Connect",{enumerable:!0,get:function(){return protocol_1.Connect}});Object.defineProperty(exports,"INFO",{enumerable:!0,get:function(){return protocol_1.INFO}});Object.defineProperty(exports,"ProtocolHandler",{enumerable:!0,get:function(){return protocol_1.ProtocolHandler}});var util_1=require_util();Object.defineProperty(exports,"backoff",{enumerable:!0,get:function(){return util_1.backoff}});Object.defineProperty(exports,"collect",{enumerable:!0,get:function(){return util_1.collect}});Object.defineProperty(exports,"deadline",{enumerable:!0,get:function(){return util_1.deadline}});Object.defineProperty(exports,"deferred",{enumerable:!0,get:function(){return util_1.deferred}});Object.defineProperty(exports,"delay",{enumerable:!0,get:function(){return util_1.delay}});Object.defineProperty(exports,"extend",{enumerable:!0,get:function(){return util_1.extend}});Object.defineProperty(exports,"millis",{enumerable:!0,get:function(){return util_1.millis}});Object.defineProperty(exports,"nanos",{enumerable:!0,get:function(){return util_1.nanos}});Object.defineProperty(exports,"render",{enumerable:!0,get:function(){return util_1.render}});Object.defineProperty(exports,"timeout",{enumerable:!0,get:function(){return util_1.timeout}});var headers_1=require_headers();Object.defineProperty(exports,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return headers_1.canonicalMIMEHeaderKey}});Object.defineProperty(exports,"headers",{enumerable:!0,get:function(){return headers_1.headers}});Object.defineProperty(exports,"MsgHdrsImpl",{enumerable:!0,get:function(){return headers_1.MsgHdrsImpl}});var heartbeats_1=require_heartbeats();Object.defineProperty(exports,"Heartbeat",{enumerable:!0,get:function(){return heartbeats_1.Heartbeat}});var muxsubscription_1=require_muxsubscription();Object.defineProperty(exports,"MuxSubscription",{enumerable:!0,get:function(){return muxsubscription_1.MuxSubscription}});var databuffer_1=require_databuffer();Object.defineProperty(exports,"DataBuffer",{enumerable:!0,get:function(){return databuffer_1.DataBuffer}});var options_1=require_options();Object.defineProperty(exports,"buildAuthenticator",{enumerable:!0,get:function(){return options_1.buildAuthenticator}});Object.defineProperty(exports,"checkOptions",{enumerable:!0,get:function(){return options_1.checkOptions}});Object.defineProperty(exports,"checkUnsupportedOption",{enumerable:!0,get:function(){return options_1.checkUnsupportedOption}});var request_1=require_request();Object.defineProperty(exports,"RequestOne",{enumerable:!0,get:function(){return request_1.RequestOne}});var authenticator_1=require_authenticator();Object.defineProperty(exports,"credsAuthenticator",{enumerable:!0,get:function(){return authenticator_1.credsAuthenticator}});Object.defineProperty(exports,"jwtAuthenticator",{enumerable:!0,get:function(){return authenticator_1.jwtAuthenticator}});Object.defineProperty(exports,"nkeyAuthenticator",{enumerable:!0,get:function(){return authenticator_1.nkeyAuthenticator}});Object.defineProperty(exports,"tokenAuthenticator",{enumerable:!0,get:function(){return authenticator_1.tokenAuthenticator}});Object.defineProperty(exports,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return authenticator_1.usernamePasswordAuthenticator}});var codec_1=require_codec();Object.defineProperty(exports,"JSONCodec",{enumerable:!0,get:function(){return codec_1.JSONCodec}});Object.defineProperty(exports,"StringCodec",{enumerable:!0,get:function(){return codec_1.StringCodec}});__exportStar(require_nkeys2(),exports);var queued_iterator_1=require_queued_iterator();Object.defineProperty(exports,"QueuedIteratorImpl",{enumerable:!0,get:function(){return queued_iterator_1.QueuedIteratorImpl}});var parser_1=require_parser();Object.defineProperty(exports,"Kind",{enumerable:!0,get:function(){return parser_1.Kind}});Object.defineProperty(exports,"Parser",{enumerable:!0,get:function(){return parser_1.Parser}});Object.defineProperty(exports,"State",{enumerable:!0,get:function(){return parser_1.State}});var denobuffer_1=require_denobuffer();Object.defineProperty(exports,"DenoBuffer",{enumerable:!0,get:function(){return denobuffer_1.DenoBuffer}});Object.defineProperty(exports,"MAX_SIZE",{enumerable:!0,get:function(){return denobuffer_1.MAX_SIZE}});Object.defineProperty(exports,"readAll",{enumerable:!0,get:function(){return denobuffer_1.readAll}});Object.defineProperty(exports,"writeAll",{enumerable:!0,get:function(){return denobuffer_1.writeAll}});var bench_1=require_bench();Object.defineProperty(exports,"Bench",{enumerable:!0,get:function(){return bench_1.Bench}});Object.defineProperty(exports,"Metric",{enumerable:!0,get:function(){return bench_1.Metric}});var encoders_1=require_encoders();Object.defineProperty(exports,"TD",{enumerable:!0,get:function(){return encoders_1.TD}});Object.defineProperty(exports,"TE",{enumerable:!0,get:function(){return encoders_1.TE}});var ipparser_1=require_ipparser();Object.defineProperty(exports,"isIP",{enumerable:!0,get:function(){return ipparser_1.isIP}});Object.defineProperty(exports,"parseIP",{enumerable:!0,get:function(){return ipparser_1.parseIP}});var typedsub_1=require_typedsub();Object.defineProperty(exports,"TypedSubscription",{enumerable:!0,get:function(){return typedsub_1.TypedSubscription}});var kv_1=require_kv();Object.defineProperty(exports,"Base64KeyCodec",{enumerable:!0,get:function(){return kv_1.Base64KeyCodec}});Object.defineProperty(exports,"Bucket",{enumerable:!0,get:function(){return kv_1.Bucket}});Object.defineProperty(exports,"defaultBucketOpts",{enumerable:!0,get:function(){return kv_1.defaultBucketOpts}});Object.defineProperty(exports,"NoopKvCodecs",{enumerable:!0,get:function(){return kv_1.NoopKvCodecs}});var semver_1=require_semver();Object.defineProperty(exports,"compare",{enumerable:!0,get:function(){return semver_1.compare}});Object.defineProperty(exports,"parseSemVer",{enumerable:!0,get:function(){return semver_1.parseSemVer}});var types_1=require_types();Object.defineProperty(exports,"Empty",{enumerable:!0,get:function(){return types_1.Empty}});var transport_2=require_transport();Object.defineProperty(exports,"extractProtocolMessage",{enumerable:!0,get:function(){return transport_2.extractProtocolMessage}});var core_1=require_core();Object.defineProperty(exports,"createInbox",{enumerable:!0,get:function(){return core_1.createInbox}});Object.defineProperty(exports,"DebugEvents",{enumerable:!0,get:function(){return core_1.DebugEvents}});Object.defineProperty(exports,"ErrorCode",{enumerable:!0,get:function(){return core_1.ErrorCode}});Object.defineProperty(exports,"Events",{enumerable:!0,get:function(){return core_1.Events}});Object.defineProperty(exports,"isNatsError",{enumerable:!0,get:function(){return core_1.isNatsError}});Object.defineProperty(exports,"Match",{enumerable:!0,get:function(){return core_1.Match}});Object.defineProperty(exports,"NatsError",{enumerable:!0,get:function(){return core_1.NatsError}});Object.defineProperty(exports,"RequestStrategy",{enumerable:!0,get:function(){return core_1.RequestStrategy}});Object.defineProperty(exports,"ServiceError",{enumerable:!0,get:function(){return core_1.ServiceError}});Object.defineProperty(exports,"ServiceErrorCodeHeader",{enumerable:!0,get:function(){return core_1.ServiceErrorCodeHeader}});Object.defineProperty(exports,"ServiceErrorHeader",{enumerable:!0,get:function(){return core_1.ServiceErrorHeader}});Object.defineProperty(exports,"ServiceResponseType",{enumerable:!0,get:function(){return core_1.ServiceResponseType}});Object.defineProperty(exports,"ServiceVerb",{enumerable:!0,get:function(){return core_1.ServiceVerb}});Object.defineProperty(exports,"syncIterator",{enumerable:!0,get:function(){return core_1.syncIterator}});var protocol_2=require_protocol();Object.defineProperty(exports,"SubscriptionImpl",{enumerable:!0,get:function(){return protocol_2.SubscriptionImpl}});Object.defineProperty(exports,"Subscriptions",{enumerable:!0,get:function(){return protocol_2.Subscriptions}})});var require_internal_mod2=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.ConsumerEvents=exports.ConsumerDebugEvents=exports.StoreCompression=exports.StorageType=exports.RetentionPolicy=exports.ReplayPolicy=exports.DiscardPolicy=exports.DeliverPolicy=exports.AckPolicy=exports.RepublishHeaders=exports.KvWatchInclude=exports.JsHeaders=exports.isConsumerOptsBuilder=exports.DirectMsgHeaders=exports.consumerOpts=exports.AdvisoryKind=exports.isHeartbeatMsg=exports.isFlowControlMsg=exports.checkJsError=void 0;var jsutil_1=require_jsutil();Object.defineProperty(exports,"checkJsError",{enumerable:!0,get:function(){return jsutil_1.checkJsError}});Object.defineProperty(exports,"isFlowControlMsg",{enumerable:!0,get:function(){return jsutil_1.isFlowControlMsg}});Object.defineProperty(exports,"isHeartbeatMsg",{enumerable:!0,get:function(){return jsutil_1.isHeartbeatMsg}});var types_1=require_types2();Object.defineProperty(exports,"AdvisoryKind",{enumerable:!0,get:function(){return types_1.AdvisoryKind}});Object.defineProperty(exports,"consumerOpts",{enumerable:!0,get:function(){return types_1.consumerOpts}});Object.defineProperty(exports,"DirectMsgHeaders",{enumerable:!0,get:function(){return types_1.DirectMsgHeaders}});Object.defineProperty(exports,"isConsumerOptsBuilder",{enumerable:!0,get:function(){return types_1.isConsumerOptsBuilder}});Object.defineProperty(exports,"JsHeaders",{enumerable:!0,get:function(){return types_1.JsHeaders}});Object.defineProperty(exports,"KvWatchInclude",{enumerable:!0,get:function(){return types_1.KvWatchInclude}});Object.defineProperty(exports,"RepublishHeaders",{enumerable:!0,get:function(){return types_1.RepublishHeaders}});var jsapi_types_1=require_jsapi_types();Object.defineProperty(exports,"AckPolicy",{enumerable:!0,get:function(){return jsapi_types_1.AckPolicy}});Object.defineProperty(exports,"DeliverPolicy",{enumerable:!0,get:function(){return jsapi_types_1.DeliverPolicy}});Object.defineProperty(exports,"DiscardPolicy",{enumerable:!0,get:function(){return jsapi_types_1.DiscardPolicy}});Object.defineProperty(exports,"ReplayPolicy",{enumerable:!0,get:function(){return jsapi_types_1.ReplayPolicy}});Object.defineProperty(exports,"RetentionPolicy",{enumerable:!0,get:function(){return jsapi_types_1.RetentionPolicy}});Object.defineProperty(exports,"StorageType",{enumerable:!0,get:function(){return jsapi_types_1.StorageType}});Object.defineProperty(exports,"StoreCompression",{enumerable:!0,get:function(){return jsapi_types_1.StoreCompression}});var consumer_1=require_consumer();Object.defineProperty(exports,"ConsumerDebugEvents",{enumerable:!0,get:function(){return consumer_1.ConsumerDebugEvents}});Object.defineProperty(exports,"ConsumerEvents",{enumerable:!0,get:function(){return consumer_1.ConsumerEvents}})});var require_nats_base_client=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m[k]}};Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});__exportStar(require_internal_mod(),exports);__exportStar(require_internal_mod2(),exports)});var require_node_transport=__commonJS((exports)=>{var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve2){resolve2(value)})}return new(P||(P=Promise))(function(resolve2,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result2){result2.done?resolve2(result2.value):adopt(result2.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__await=exports&&exports.__await||function(v){return this instanceof __await?(this.v=v,this):new __await(v)},__asyncGenerator=exports&&exports.__asyncGenerator||function(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(f){return function(v){return Promise.resolve(v).then(f,reject)}}function verb(n,f){if(g[n]){if(i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f)i[n]=f(i[n])}}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){if(f(v),q.shift(),q.length)resume(q[0][0],q[0][1])}};Object.defineProperty(exports,"__esModule",{value:!0});exports.NodeTransport=void 0;exports.nodeResolveHost=nodeResolveHost;var nats_base_client_1=require_nats_base_client(),net_1=__require("net"),util_1=require_util(),tls_1=__require("tls"),{resolve}=__require("path"),{readFile,existsSync:existsSync4}=__require("fs"),dns=__require("dns"),VERSION="2.29.3",LANG="nats.js";class NodeTransport{constructor(){this.yields=[],this.signal=(0,nats_base_client_1.deferred)(),this.closedNotification=(0,nats_base_client_1.deferred)(),this.connected=!1,this.tlsName="",this.done=!1,this.lang=LANG,this.version=VERSION}connect(hp,options){return __awaiter(this,void 0,void 0,function*(){this.tlsName=hp.tlsName,this.options=options;let{tls}=this.options,{handshakeFirst}=tls||{};try{if(handshakeFirst===!0)this.socket=yield this.tlsFirst(hp);else this.socket=yield this.dial(hp);let info=yield this.peekInfo();(0,nats_base_client_1.checkOptions)(info,options);let{tls_required:tlsRequired,tls_available:tlsAvailable}=info,desired=tlsAvailable===!0&&options.tls!==null;if(!handshakeFirst&&(tlsRequired||desired))this.socket=yield this.startTLS();if(tlsRequired&&this.socket.encrypted!==!0)throw new nats_base_client_1.NatsError("tls",nats_base_client_1.ErrorCode.ServerOptionNotAvailable);return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(err){if(!err)err=nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.ConnectionRefused,Error("node provided an undefined error!"));let{code}=err,perr=code==="ECONNREFUSED"?nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.ConnectionRefused,err):err;if(this.socket)this.socket.destroy();throw perr}})}dial(hp){let d=(0,nats_base_client_1.deferred)(),dialError,socket=(0,net_1.createConnection)(hp.port,hp.hostname,()=>{d.resolve(socket),socket.removeAllListeners()});return socket.on("error",(err)=>{dialError=err}),socket.on("close",()=>{socket.removeAllListeners(),d.reject(dialError)}),socket.setNoDelay(!0),d}get isClosed(){return this.done}close(err){return this._closed(err,!1)}peekInfo(){let d=(0,nats_base_client_1.deferred)(),peekError;return this.socket.on("data",(frame)=>{this.yields.push(frame);let t=nats_base_client_1.DataBuffer.concat(...this.yields),pm=(0,nats_base_client_1.extractProtocolMessage)(t);if(pm!=="")try{let m=nats_base_client_1.INFO.exec(pm);if(!m)throw Error("unexpected response from server");let info=JSON.parse(m[1]);d.resolve(info)}catch(err){d.reject(err)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(err)=>{peekError=err}),this.socket.on("close",()=>{this.socket.removeAllListeners(),d.reject(peekError)}),d}loadFile(fn){if(!fn)return Promise.resolve();let d=(0,nats_base_client_1.deferred)();try{if(fn=resolve(fn),!existsSync4(fn))d.reject(Error(`${fn} doesn't exist`));readFile(fn,(err,data)=>{if(err)return d.reject(err);d.resolve(data)})}catch(err){d.reject(err)}return d}loadClientCerts(){return __awaiter(this,void 0,void 0,function*(){let tlsOpts={},{certFile,cert,caFile,ca,keyFile,key}=this.options.tls;try{if(certFile){let data=yield this.loadFile(certFile);if(data)tlsOpts.cert=data}else if(cert)tlsOpts.cert=cert;if(keyFile){let data=yield this.loadFile(keyFile);if(data)tlsOpts.key=data}else if(key)tlsOpts.key=key;if(caFile){let data=yield this.loadFile(caFile);if(data)tlsOpts.ca=[data]}else if(ca)tlsOpts.ca=ca;return Promise.resolve(tlsOpts)}catch(err){return Promise.reject(err)}})}tlsFirst(hp){return __awaiter(this,void 0,void 0,function*(){let tlsError,tlsOpts={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)tlsOpts.socket=this.socket;if(typeof this.options.tls==="object")try{let certOpts=(yield this.loadClientCerts())||{};tlsOpts=(0,util_1.extend)(tlsOpts,this.options.tls,certOpts)}catch(err){return Promise.reject(new nats_base_client_1.NatsError(err.message,nats_base_client_1.ErrorCode.Tls,err))}let d=(0,nats_base_client_1.deferred)();try{let tlsSocket=(0,tls_1.connect)(hp.port,hp.hostname,tlsOpts,()=>{tlsSocket.removeAllListeners(),d.resolve(tlsSocket)});tlsSocket.on("error",(err)=>{tlsError=err}),tlsSocket.on("secureConnect",()=>{if(tlsOpts.rejectUnauthorized===!1)return;if(!tlsSocket.authorized)throw tlsSocket.authorizationError}),tlsSocket.on("close",()=>{d.reject(tlsError),tlsSocket.removeAllListeners()}),tlsSocket.setNoDelay(!0)}catch(err){d.reject(nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.Tls,err))}return d})}startTLS(){return __awaiter(this,void 0,void 0,function*(){let tlsError,tlsOpts={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let certOpts=(yield this.loadClientCerts())||{};tlsOpts=(0,util_1.extend)(tlsOpts,this.options.tls,certOpts)}catch(err){return Promise.reject(new nats_base_client_1.NatsError(err.message,nats_base_client_1.ErrorCode.Tls,err))}let d=(0,nats_base_client_1.deferred)();try{let tlsSocket=(0,tls_1.connect)(tlsOpts,()=>{tlsSocket.removeAllListeners(),d.resolve(tlsSocket)});tlsSocket.on("error",(err)=>{tlsError=err}),tlsSocket.on("secureConnect",()=>{if(tlsOpts.rejectUnauthorized===!1)return;if(!tlsSocket.authorized)throw tlsSocket.authorizationError}),tlsSocket.on("close",()=>{d.reject(tlsError),tlsSocket.removeAllListeners()})}catch(err){d.reject(nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.Tls,err))}return d})}setupHandlers(){let connError;this.socket.on("data",(frame)=>{return this.yields.push(frame),this.signal.resolve()}),this.socket.on("error",(err)=>{connError=err}),this.socket.on("end",()=>{var _a,_b;if((_a=this.socket)===null||_a===void 0?void 0:_a.destroyed)return;(_b=this.socket)===null||_b===void 0||_b.write(new Uint8Array(0),()=>{var _a2;(_a2=this.socket)===null||_a2===void 0||_a2.end()})}),this.socket.on("close",()=>{this._closed(connError,!1)})}[Symbol.asyncIterator](){return this.iterate()}iterate(){return __asyncGenerator(this,arguments,function*(){let debug=this.options.debug;while(!0){if(this.yields.length===0)yield __await(this.signal);let yields=this.yields;this.yields=[];for(let i=0;i<yields.length;i++){if(debug)console.info(`> ${(0,nats_base_client_1.render)(yields[i])}`);yield yield __await(yields[i])}if(this.done)break;else if(this.yields.length===0)yields.length=0,this.yields=yields,this.signal=(0,nats_base_client_1.deferred)()}})}discard(){}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof tls_1.TLSSocket}_send(frame){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,nats_base_client_1.render)(frame)}`);let d=(0,nats_base_client_1.deferred)();try{this.socket.write(frame,(err)=>{if(err){if(this.options.debug)console.error(`!!! ${(0,nats_base_client_1.render)(frame)}: ${err}`);return d.reject(err)}return d.resolve()})}catch(err){if(this.options.debug)console.error(`!!! ${(0,nats_base_client_1.render)(frame)}: ${err}`);d.reject(err)}return d}send(frame){this._send(frame).catch((_err)=>{})}_closed(err_1){return __awaiter(this,arguments,void 0,function*(err,internal=!0){if(!this.connected)return;if(this.done)return;if(this.closeError=err,!err&&this.socket&&internal)try{yield this._send(new TextEncoder().encode(""))}catch(err2){if(this.options.debug)console.log("transport close terminated with an error",err2)}try{if(this.socket)this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0}catch(err2){console.log(err2)}this.done=!0,this.closedNotification.resolve(this.closeError)})}closed(){return this.closedNotification}}exports.NodeTransport=NodeTransport;function nodeResolveHost(s){return __awaiter(this,void 0,void 0,function*(){let a=(0,nats_base_client_1.deferred)(),aaaa=(0,nats_base_client_1.deferred)();dns.resolve4(s,(err,records)=>{if(err)a.resolve(err);else a.resolve(records)}),dns.resolve6(s,(err,records)=>{if(err)aaaa.resolve(err);else aaaa.resolve(records)});let ips=[],da=yield a;if(Array.isArray(da))ips.push(...da);let daaaa=yield aaaa;if(Array.isArray(daaaa))ips.push(...daaaa);if(ips.length===0)ips.push(s);return ips})}});var require_connect=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.connect=connect;var node_transport_1=require_node_transport(),nats_base_client_1=require_nats_base_client();function connect(opts={}){return(0,nats_base_client_1.setTransportFactory)({factory:()=>{return new node_transport_1.NodeTransport},dnsResolveFn:node_transport_1.nodeResolveHost}),nats_base_client_1.NatsConnectionImpl.connect(opts)}});var require_mod3=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.consumerOpts=exports.StoreCompression=exports.StorageType=exports.RetentionPolicy=exports.RepublishHeaders=exports.ReplayPolicy=exports.KvWatchInclude=exports.JsHeaders=exports.DiscardPolicy=exports.DirectMsgHeaders=exports.DeliverPolicy=exports.ConsumerEvents=exports.ConsumerDebugEvents=exports.AdvisoryKind=exports.AckPolicy=exports.isHeartbeatMsg=exports.isFlowControlMsg=exports.checkJsError=void 0;var internal_mod_1=require_internal_mod2();Object.defineProperty(exports,"checkJsError",{enumerable:!0,get:function(){return internal_mod_1.checkJsError}});Object.defineProperty(exports,"isFlowControlMsg",{enumerable:!0,get:function(){return internal_mod_1.isFlowControlMsg}});Object.defineProperty(exports,"isHeartbeatMsg",{enumerable:!0,get:function(){return internal_mod_1.isHeartbeatMsg}});var internal_mod_2=require_internal_mod2();Object.defineProperty(exports,"AckPolicy",{enumerable:!0,get:function(){return internal_mod_2.AckPolicy}});Object.defineProperty(exports,"AdvisoryKind",{enumerable:!0,get:function(){return internal_mod_2.AdvisoryKind}});Object.defineProperty(exports,"ConsumerDebugEvents",{enumerable:!0,get:function(){return internal_mod_2.ConsumerDebugEvents}});Object.defineProperty(exports,"ConsumerEvents",{enumerable:!0,get:function(){return internal_mod_2.ConsumerEvents}});Object.defineProperty(exports,"DeliverPolicy",{enumerable:!0,get:function(){return internal_mod_2.DeliverPolicy}});Object.defineProperty(exports,"DirectMsgHeaders",{enumerable:!0,get:function(){return internal_mod_2.DirectMsgHeaders}});Object.defineProperty(exports,"DiscardPolicy",{enumerable:!0,get:function(){return internal_mod_2.DiscardPolicy}});Object.defineProperty(exports,"JsHeaders",{enumerable:!0,get:function(){return internal_mod_2.JsHeaders}});Object.defineProperty(exports,"KvWatchInclude",{enumerable:!0,get:function(){return internal_mod_2.KvWatchInclude}});Object.defineProperty(exports,"ReplayPolicy",{enumerable:!0,get:function(){return internal_mod_2.ReplayPolicy}});Object.defineProperty(exports,"RepublishHeaders",{enumerable:!0,get:function(){return internal_mod_2.RepublishHeaders}});Object.defineProperty(exports,"RetentionPolicy",{enumerable:!0,get:function(){return internal_mod_2.RetentionPolicy}});Object.defineProperty(exports,"StorageType",{enumerable:!0,get:function(){return internal_mod_2.StorageType}});Object.defineProperty(exports,"StoreCompression",{enumerable:!0,get:function(){return internal_mod_2.StoreCompression}});var types_1=require_types2();Object.defineProperty(exports,"consumerOpts",{enumerable:!0,get:function(){return types_1.consumerOpts}})});var require_mod4=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m[k]}};Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.connect=void 0;if(typeof TextEncoder>"u"){let{TextEncoder:TextEncoder2,TextDecoder:TextDecoder2}=__require("util");global.TextEncoder=TextEncoder2,global.TextDecoder=TextDecoder2}if(typeof globalThis.crypto>"u"){let c=__require("crypto");global.crypto=c.webcrypto}if(typeof globalThis.ReadableStream>"u"){let chunks=process.versions.node.split(".");if(parseInt(chunks[0])>=16){let streams=__require("stream/web");global.ReadableStream=streams.ReadableStream}}var connect_1=require_connect();Object.defineProperty(exports,"connect",{enumerable:!0,get:function(){return connect_1.connect}});__exportStar(require_mod2(),exports);__exportStar(require_mod3(),exports)});function isValid2(value){return typeof value==="string"&&VALID.has(value)}function resolveExecutorType(override){if(isValid2(override))return override;let env=process.env.GENIE_EXECUTOR;if(isValid2(env))return env;try{let persisted=loadGenieConfigSync().omni?.executor;if(isValid2(persisted))return persisted}catch{}return"tmux"}var VALID;var init_executor_config=__esm(()=>{init_genie_config2();VALID=new Set(["tmux","sdk"])});function isBlockingEvent(event){return BLOCKING_EVENTS.has(event)}var DISPATCHED_EVENTS,BLOCKING_EVENTS;var init_types2=__esm(()=>{DISPATCHED_EVENTS=["PreToolUse","PostToolUse","SessionStart","SessionEnd","TeammateIdle","TaskCompleted"],BLOCKING_EVENTS=new Set(["PreToolUse","UserPromptSubmit","TeammateIdle","TaskCompleted","PermissionRequest"])});var exports_inject={};__export(exports_inject,{isTeamHooked:()=>isTeamHooked,injectTeamHooks:()=>injectTeamHooks,buildDispatchCommand:()=>buildDispatchCommand});import{existsSync as existsSync4}from"fs";import{mkdir,readFile,writeFile}from"fs/promises";import{homedir as homedir4}from"os";import{join as join4}from"path";import{fileURLToPath}from"url";function escapeShellArg(arg){return`'${arg.replace(/'/g,"'\\''")}'`}function buildDispatchCommand(){let entrypoint=fileURLToPath(new URL("../genie.ts",import.meta.url));if(!existsSync4(entrypoint))return"genie hook dispatch";let bun=process.execPath||"bun";return`${escapeShellArg(bun)} run ${escapeShellArg(entrypoint)} hook dispatch`}function isGenieDispatchCommand(command){return typeof command==="string"&&/(?:^|\s)hook\s+dispatch(?:\s|$)/.test(command)}function claudeConfigDir(){return process.env.CLAUDE_CONFIG_DIR??join4(homedir4(),".claude")}function teamSettingsPath(teamName){let sanitized=teamName.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase();return join4(claudeConfigDir(),"teams",sanitized,"settings.json")}function buildHooksConfig(){let hooks={},dispatchCommand=buildDispatchCommand();for(let event of DISPATCHED_EVENTS)hooks[event]=[{matcher:"*",hooks:[{type:"command",command:dispatchCommand,timeout:DISPATCH_TIMEOUT}]}];return hooks}async function injectIntoFile(settingsPath){let settings={};if(existsSync4(settingsPath))try{let content=await readFile(settingsPath,"utf-8");settings=JSON.parse(content)}catch{}let hooksConfig=buildHooksConfig(),existingHooks=settings.hooks;if(existingHooks){if(DISPATCHED_EVENTS.every((event)=>{let existing=existingHooks[event],desiredCommand=hooksConfig[event][0].hooks[0].command;return existing?.some((m)=>m.hooks?.some((h)=>h.command===desiredCommand))}))return!1}let mergedHooks=existingHooks?{...existingHooks}:{};for(let event of DISPATCHED_EVENTS){let genieEntry=hooksConfig[event][0],existingEntries=(mergedHooks[event]??[]).map((matcher)=>({...matcher,hooks:matcher.hooks?.map((hook)=>isGenieDispatchCommand(hook.command)?{...hook,command:genieEntry.hooks[0].command,timeout:DISPATCH_TIMEOUT}:hook)}));if(!existingEntries.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command))))mergedHooks[event]=[...existingEntries,genieEntry];else mergedHooks[event]=existingEntries}settings.hooks=mergedHooks;let dir=join4(settingsPath,"..");return await mkdir(dir,{recursive:!0}),await writeFile(settingsPath,JSON.stringify(settings,null,2)),!0}async function injectTeamHooks(teamName){let path=teamSettingsPath(teamName);return injectIntoFile(path)}async function isTeamHooked(teamName){let path=teamSettingsPath(teamName);if(!existsSync4(path))return!1;try{let content=await readFile(path,"utf-8"),hooks=JSON.parse(content).hooks;if(!hooks)return!1;return DISPATCHED_EVENTS.every((event)=>{return hooks[event]?.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)))})}catch{return!1}}var DISPATCH_TIMEOUT=15;var init_inject=__esm(()=>{init_types2()});var exports_provider_adapters={};__export(exports_provider_adapters,{validateSpawnParams:()=>validateSpawnParams,buildLaunchCommand:()=>buildLaunchCommand,buildCodexCommand:()=>buildCodexCommand,buildClaudeCommand:()=>buildClaudeCommand,CLAUDE_TEAM_COLORS:()=>CLAUDE_TEAM_COLORS});function validateSpawnParams(params){return spawnParamsSchema.parse(params)}function escapeShellArg2(arg){return`'${arg.replace(/'/g,"'\\''")}'`}function hasBinary(name){try{let BunExt=Bun;if(typeof BunExt.which==="function")return Boolean(BunExt.which(name));let{execSync:execSync2}=__require("child_process");return execSync2(`which ${name}`,{stdio:"ignore"}),!0}catch{return!1}}function resolveShellBinary(name){try{let{execFileSync}=__require("child_process"),shell=process.env.SHELL||"/bin/sh";return execFileSync(shell,["-lc",`command -v ${name}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function preflightCheck(provider){if(!hasBinary(provider))throw Error(`Provider binary "${provider}" not found on PATH. Install ${provider} or check your environment.`)}function appendNativeTeamFlags(parts,env,nt,params){env.CLAUDECODE="1",env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1";let agentName=nt.agentName??params.role??"worker";if(env.GENIE_AGENT_NAME=agentName,parts.push("--agent-id",escapeShellArg2(`${agentName}@${params.team}`)),parts.push("--agent-name",escapeShellArg2(agentName)),parts.push("--team-name",escapeShellArg2(params.team)),nt.color)parts.push("--agent-color",escapeShellArg2(nt.color));if(nt.parentSessionId)parts.push("--parent-session-id",escapeShellArg2(nt.parentSessionId));if(nt.agentType)parts.push("--agent-type",escapeShellArg2(nt.agentType));if(nt.planModeRequired)parts.push("--plan-mode-required");let effectivePermMode=nt.permissionMode??"bypassPermissions";parts.push("--permission-mode",escapeShellArg2(effectivePermMode))}function appendSystemPromptFlags(parts,params){if(params.systemPrompt){let{mkdirSync:mkdirSync4,writeFileSync:writeFileSync4,readFileSync:readFileSync3}=__require("fs"),{join:join5}=__require("path"),dir="/tmp/genie-prompts";mkdirSync4("/tmp/genie-prompts",{recursive:!0});let ts=Date.now().toString(36),promptFile=join5("/tmp/genie-prompts",`${params.role||"agent"}-${ts}.md`),content=params.systemPrompt;if(params.systemPromptFile)content=`${readFileSync3(params.systemPromptFile,"utf-8")}
|
|
63
|
-
|
|
64
|
-
|
|
62
|
+
`}}exports.Metric=Metric;class Bench{constructor(nc,opts={msgs:1e5,size:128,subject:"",asyncRequests:!1,pub:!1,sub:!1,req:!1,rep:!1}){if(this.nc=nc,this.callbacks=opts.callbacks||!1,this.msgs=opts.msgs||0,this.size=opts.size||0,this.subject=opts.subject||nuid_1.nuid.next(),this.asyncRequests=opts.asyncRequests||!1,this.pub=opts.pub||!1,this.sub=opts.sub||!1,this.req=opts.req||!1,this.rep=opts.rep||!1,this.perf=new util_1.Perf,this.payload=this.size?new Uint8Array(this.size):types_1.Empty,!this.pub&&!this.sub&&!this.req&&!this.rep)throw Error("no bench option selected")}run(){return __awaiter(this,void 0,void 0,function*(){if(this.nc.closed().then((err)=>{if(err)throw new core_1.NatsError(`bench closed with an error: ${err.message}`,core_1.ErrorCode.Unknown,err)}),this.callbacks)yield this.runCallbacks();else yield this.runAsync();return this.processMetrics()})}processMetrics(){let nc=this.nc,{lang,version}=nc.protocol.transport;if(this.pub&&this.sub)this.perf.measure("pubsub","pubStart","subStop");if(this.req&&this.rep)this.perf.measure("reqrep","reqStart","reqStop");let measures=this.perf.getEntries(),pubsub=measures.find((m)=>m.name==="pubsub"),reqrep=measures.find((m)=>m.name==="reqrep"),req=measures.find((m)=>m.name==="req"),rep=measures.find((m)=>m.name==="rep"),pub=measures.find((m)=>m.name==="pub"),sub=measures.find((m)=>m.name==="sub"),stats=this.nc.stats(),metrics=[];if(pubsub){let{name,duration}=pubsub,m=new Metric(name,duration);m.msgs=this.msgs*2,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(reqrep){let{name,duration}=reqrep,m=new Metric(name,duration);m.msgs=this.msgs*2,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(pub){let{name,duration}=pub,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(sub){let{name,duration}=sub,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.inBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(rep){let{name,duration}=rep,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}if(req){let{name,duration}=req,m=new Metric(name,duration);m.msgs=this.msgs,m.bytes=stats.inBytes+stats.outBytes,m.lang=lang,m.version=version,m.payload=this.payload.length,metrics.push(m)}return metrics}runCallbacks(){return __awaiter(this,void 0,void 0,function*(){let jobs=[];if(this.sub){let d=(0,util_1.deferred)();jobs.push(d);let i=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{if(i++,i===1)this.perf.mark("subStart");if(i===this.msgs)this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),d.resolve()}})}if(this.rep){let d=(0,util_1.deferred)();jobs.push(d);let i=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(_,m)=>{if(m.respond(this.payload),i++,i===1)this.perf.mark("repStart");if(i===this.msgs)this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop"),d.resolve()}})}if(this.pub){let job=(()=>__awaiter(this,void 0,void 0,function*(){this.perf.mark("pubStart");for(let i=0;i<this.msgs;i++)this.nc.publish(this.subject,this.payload);yield this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")}))();jobs.push(job)}if(this.req){let job=(()=>__awaiter(this,void 0,void 0,function*(){if(this.asyncRequests){this.perf.mark("reqStart");let a=[];for(let i=0;i<this.msgs;i++)a.push(this.nc.request(this.subject,this.payload,{timeout:20000}));yield Promise.all(a),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let i=0;i<this.msgs;i++)yield this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}}))();jobs.push(job)}yield Promise.all(jobs)})}runAsync(){return __awaiter(this,void 0,void 0,function*(){let jobs=[];if(this.rep){let first=!1,sub=this.nc.subscribe(this.subject,{max:this.msgs}),job=(()=>__awaiter(this,void 0,void 0,function*(){var _a,e_1,_b,_c;try{for(var _d=!0,sub_1=__asyncValues(sub),sub_1_1;sub_1_1=yield sub_1.next(),_a=sub_1_1.done,!_a;_d=!0){_c=sub_1_1.value,_d=!1;let m=_c;if(!first)this.perf.mark("repStart"),first=!0;m.respond(this.payload)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{if(!_d&&!_a&&(_b=sub_1.return))yield _b.call(sub_1)}finally{if(e_1)throw e_1.error}}yield this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")}))();jobs.push(job)}if(this.sub){let first=!1,sub=this.nc.subscribe(this.subject,{max:this.msgs}),job=(()=>__awaiter(this,void 0,void 0,function*(){var _a,e_2,_b,_c;try{for(var _d=!0,sub_2=__asyncValues(sub),sub_2_1;sub_2_1=yield sub_2.next(),_a=sub_2_1.done,!_a;_d=!0){_c=sub_2_1.value,_d=!1;let _m=_c;if(!first)this.perf.mark("subStart"),first=!0}}catch(e_2_1){e_2={error:e_2_1}}finally{try{if(!_d&&!_a&&(_b=sub_2.return))yield _b.call(sub_2)}finally{if(e_2)throw e_2.error}}this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")}))();jobs.push(job)}if(this.pub){let job=(()=>__awaiter(this,void 0,void 0,function*(){this.perf.mark("pubStart");for(let i=0;i<this.msgs;i++)this.nc.publish(this.subject,this.payload);yield this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")}))();jobs.push(job)}if(this.req){let job=(()=>__awaiter(this,void 0,void 0,function*(){if(this.asyncRequests){this.perf.mark("reqStart");let a=[];for(let i=0;i<this.msgs;i++)a.push(this.nc.request(this.subject,this.payload,{timeout:20000}));yield Promise.all(a),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let i=0;i<this.msgs;i++)yield this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}}))();jobs.push(job)}yield Promise.all(jobs)})}}exports.Bench=Bench;function throughput(bytes,seconds){return`${humanizeBytes(bytes/seconds)}/sec`}function msgThroughput(msgs,seconds){return`${Math.floor(msgs/seconds)} msgs/sec`}function humanizeBytes(bytes,si=!1){let base=si?1000:1024,pre=si?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],post=si?"iB":"B";if(bytes<base)return`${bytes.toFixed(2)} ${post}`;let exp=parseInt(Math.log(bytes)/Math.log(base)+""),index=parseInt(exp-1+"");return`${(bytes/Math.pow(base,exp)).toFixed(2)} ${pre[index]}${post}`}function humanizeNumber(n){return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var require_internal_mod=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m[k]}};Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.parseIP=exports.isIP=exports.TE=exports.TD=exports.Metric=exports.Bench=exports.writeAll=exports.readAll=exports.MAX_SIZE=exports.DenoBuffer=exports.State=exports.Parser=exports.Kind=exports.QueuedIteratorImpl=exports.StringCodec=exports.JSONCodec=exports.usernamePasswordAuthenticator=exports.tokenAuthenticator=exports.nkeyAuthenticator=exports.jwtAuthenticator=exports.credsAuthenticator=exports.RequestOne=exports.checkUnsupportedOption=exports.checkOptions=exports.buildAuthenticator=exports.DataBuffer=exports.MuxSubscription=exports.Heartbeat=exports.MsgHdrsImpl=exports.headers=exports.canonicalMIMEHeaderKey=exports.timeout=exports.render=exports.nanos=exports.millis=exports.extend=exports.delay=exports.deferred=exports.deadline=exports.collect=exports.backoff=exports.ProtocolHandler=exports.INFO=exports.Connect=exports.setTransportFactory=exports.getResolveFn=exports.MsgImpl=exports.nuid=exports.Nuid=exports.NatsConnectionImpl=void 0;exports.Subscriptions=exports.SubscriptionImpl=exports.syncIterator=exports.ServiceVerb=exports.ServiceResponseType=exports.ServiceErrorHeader=exports.ServiceErrorCodeHeader=exports.ServiceError=exports.RequestStrategy=exports.NatsError=exports.Match=exports.isNatsError=exports.Events=exports.ErrorCode=exports.DebugEvents=exports.createInbox=exports.extractProtocolMessage=exports.Empty=exports.parseSemVer=exports.compare=exports.NoopKvCodecs=exports.defaultBucketOpts=exports.Bucket=exports.Base64KeyCodec=exports.TypedSubscription=void 0;var nats_1=require_nats();Object.defineProperty(exports,"NatsConnectionImpl",{enumerable:!0,get:function(){return nats_1.NatsConnectionImpl}});var nuid_1=require_nuid();Object.defineProperty(exports,"Nuid",{enumerable:!0,get:function(){return nuid_1.Nuid}});Object.defineProperty(exports,"nuid",{enumerable:!0,get:function(){return nuid_1.nuid}});var msg_1=require_msg();Object.defineProperty(exports,"MsgImpl",{enumerable:!0,get:function(){return msg_1.MsgImpl}});var transport_1=require_transport();Object.defineProperty(exports,"getResolveFn",{enumerable:!0,get:function(){return transport_1.getResolveFn}});Object.defineProperty(exports,"setTransportFactory",{enumerable:!0,get:function(){return transport_1.setTransportFactory}});var protocol_1=require_protocol();Object.defineProperty(exports,"Connect",{enumerable:!0,get:function(){return protocol_1.Connect}});Object.defineProperty(exports,"INFO",{enumerable:!0,get:function(){return protocol_1.INFO}});Object.defineProperty(exports,"ProtocolHandler",{enumerable:!0,get:function(){return protocol_1.ProtocolHandler}});var util_1=require_util();Object.defineProperty(exports,"backoff",{enumerable:!0,get:function(){return util_1.backoff}});Object.defineProperty(exports,"collect",{enumerable:!0,get:function(){return util_1.collect}});Object.defineProperty(exports,"deadline",{enumerable:!0,get:function(){return util_1.deadline}});Object.defineProperty(exports,"deferred",{enumerable:!0,get:function(){return util_1.deferred}});Object.defineProperty(exports,"delay",{enumerable:!0,get:function(){return util_1.delay}});Object.defineProperty(exports,"extend",{enumerable:!0,get:function(){return util_1.extend}});Object.defineProperty(exports,"millis",{enumerable:!0,get:function(){return util_1.millis}});Object.defineProperty(exports,"nanos",{enumerable:!0,get:function(){return util_1.nanos}});Object.defineProperty(exports,"render",{enumerable:!0,get:function(){return util_1.render}});Object.defineProperty(exports,"timeout",{enumerable:!0,get:function(){return util_1.timeout}});var headers_1=require_headers();Object.defineProperty(exports,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return headers_1.canonicalMIMEHeaderKey}});Object.defineProperty(exports,"headers",{enumerable:!0,get:function(){return headers_1.headers}});Object.defineProperty(exports,"MsgHdrsImpl",{enumerable:!0,get:function(){return headers_1.MsgHdrsImpl}});var heartbeats_1=require_heartbeats();Object.defineProperty(exports,"Heartbeat",{enumerable:!0,get:function(){return heartbeats_1.Heartbeat}});var muxsubscription_1=require_muxsubscription();Object.defineProperty(exports,"MuxSubscription",{enumerable:!0,get:function(){return muxsubscription_1.MuxSubscription}});var databuffer_1=require_databuffer();Object.defineProperty(exports,"DataBuffer",{enumerable:!0,get:function(){return databuffer_1.DataBuffer}});var options_1=require_options();Object.defineProperty(exports,"buildAuthenticator",{enumerable:!0,get:function(){return options_1.buildAuthenticator}});Object.defineProperty(exports,"checkOptions",{enumerable:!0,get:function(){return options_1.checkOptions}});Object.defineProperty(exports,"checkUnsupportedOption",{enumerable:!0,get:function(){return options_1.checkUnsupportedOption}});var request_1=require_request();Object.defineProperty(exports,"RequestOne",{enumerable:!0,get:function(){return request_1.RequestOne}});var authenticator_1=require_authenticator();Object.defineProperty(exports,"credsAuthenticator",{enumerable:!0,get:function(){return authenticator_1.credsAuthenticator}});Object.defineProperty(exports,"jwtAuthenticator",{enumerable:!0,get:function(){return authenticator_1.jwtAuthenticator}});Object.defineProperty(exports,"nkeyAuthenticator",{enumerable:!0,get:function(){return authenticator_1.nkeyAuthenticator}});Object.defineProperty(exports,"tokenAuthenticator",{enumerable:!0,get:function(){return authenticator_1.tokenAuthenticator}});Object.defineProperty(exports,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return authenticator_1.usernamePasswordAuthenticator}});var codec_1=require_codec();Object.defineProperty(exports,"JSONCodec",{enumerable:!0,get:function(){return codec_1.JSONCodec}});Object.defineProperty(exports,"StringCodec",{enumerable:!0,get:function(){return codec_1.StringCodec}});__exportStar(require_nkeys2(),exports);var queued_iterator_1=require_queued_iterator();Object.defineProperty(exports,"QueuedIteratorImpl",{enumerable:!0,get:function(){return queued_iterator_1.QueuedIteratorImpl}});var parser_1=require_parser();Object.defineProperty(exports,"Kind",{enumerable:!0,get:function(){return parser_1.Kind}});Object.defineProperty(exports,"Parser",{enumerable:!0,get:function(){return parser_1.Parser}});Object.defineProperty(exports,"State",{enumerable:!0,get:function(){return parser_1.State}});var denobuffer_1=require_denobuffer();Object.defineProperty(exports,"DenoBuffer",{enumerable:!0,get:function(){return denobuffer_1.DenoBuffer}});Object.defineProperty(exports,"MAX_SIZE",{enumerable:!0,get:function(){return denobuffer_1.MAX_SIZE}});Object.defineProperty(exports,"readAll",{enumerable:!0,get:function(){return denobuffer_1.readAll}});Object.defineProperty(exports,"writeAll",{enumerable:!0,get:function(){return denobuffer_1.writeAll}});var bench_1=require_bench();Object.defineProperty(exports,"Bench",{enumerable:!0,get:function(){return bench_1.Bench}});Object.defineProperty(exports,"Metric",{enumerable:!0,get:function(){return bench_1.Metric}});var encoders_1=require_encoders();Object.defineProperty(exports,"TD",{enumerable:!0,get:function(){return encoders_1.TD}});Object.defineProperty(exports,"TE",{enumerable:!0,get:function(){return encoders_1.TE}});var ipparser_1=require_ipparser();Object.defineProperty(exports,"isIP",{enumerable:!0,get:function(){return ipparser_1.isIP}});Object.defineProperty(exports,"parseIP",{enumerable:!0,get:function(){return ipparser_1.parseIP}});var typedsub_1=require_typedsub();Object.defineProperty(exports,"TypedSubscription",{enumerable:!0,get:function(){return typedsub_1.TypedSubscription}});var kv_1=require_kv();Object.defineProperty(exports,"Base64KeyCodec",{enumerable:!0,get:function(){return kv_1.Base64KeyCodec}});Object.defineProperty(exports,"Bucket",{enumerable:!0,get:function(){return kv_1.Bucket}});Object.defineProperty(exports,"defaultBucketOpts",{enumerable:!0,get:function(){return kv_1.defaultBucketOpts}});Object.defineProperty(exports,"NoopKvCodecs",{enumerable:!0,get:function(){return kv_1.NoopKvCodecs}});var semver_1=require_semver();Object.defineProperty(exports,"compare",{enumerable:!0,get:function(){return semver_1.compare}});Object.defineProperty(exports,"parseSemVer",{enumerable:!0,get:function(){return semver_1.parseSemVer}});var types_1=require_types();Object.defineProperty(exports,"Empty",{enumerable:!0,get:function(){return types_1.Empty}});var transport_2=require_transport();Object.defineProperty(exports,"extractProtocolMessage",{enumerable:!0,get:function(){return transport_2.extractProtocolMessage}});var core_1=require_core();Object.defineProperty(exports,"createInbox",{enumerable:!0,get:function(){return core_1.createInbox}});Object.defineProperty(exports,"DebugEvents",{enumerable:!0,get:function(){return core_1.DebugEvents}});Object.defineProperty(exports,"ErrorCode",{enumerable:!0,get:function(){return core_1.ErrorCode}});Object.defineProperty(exports,"Events",{enumerable:!0,get:function(){return core_1.Events}});Object.defineProperty(exports,"isNatsError",{enumerable:!0,get:function(){return core_1.isNatsError}});Object.defineProperty(exports,"Match",{enumerable:!0,get:function(){return core_1.Match}});Object.defineProperty(exports,"NatsError",{enumerable:!0,get:function(){return core_1.NatsError}});Object.defineProperty(exports,"RequestStrategy",{enumerable:!0,get:function(){return core_1.RequestStrategy}});Object.defineProperty(exports,"ServiceError",{enumerable:!0,get:function(){return core_1.ServiceError}});Object.defineProperty(exports,"ServiceErrorCodeHeader",{enumerable:!0,get:function(){return core_1.ServiceErrorCodeHeader}});Object.defineProperty(exports,"ServiceErrorHeader",{enumerable:!0,get:function(){return core_1.ServiceErrorHeader}});Object.defineProperty(exports,"ServiceResponseType",{enumerable:!0,get:function(){return core_1.ServiceResponseType}});Object.defineProperty(exports,"ServiceVerb",{enumerable:!0,get:function(){return core_1.ServiceVerb}});Object.defineProperty(exports,"syncIterator",{enumerable:!0,get:function(){return core_1.syncIterator}});var protocol_2=require_protocol();Object.defineProperty(exports,"SubscriptionImpl",{enumerable:!0,get:function(){return protocol_2.SubscriptionImpl}});Object.defineProperty(exports,"Subscriptions",{enumerable:!0,get:function(){return protocol_2.Subscriptions}})});var require_internal_mod2=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.ConsumerEvents=exports.ConsumerDebugEvents=exports.StoreCompression=exports.StorageType=exports.RetentionPolicy=exports.ReplayPolicy=exports.DiscardPolicy=exports.DeliverPolicy=exports.AckPolicy=exports.RepublishHeaders=exports.KvWatchInclude=exports.JsHeaders=exports.isConsumerOptsBuilder=exports.DirectMsgHeaders=exports.consumerOpts=exports.AdvisoryKind=exports.isHeartbeatMsg=exports.isFlowControlMsg=exports.checkJsError=void 0;var jsutil_1=require_jsutil();Object.defineProperty(exports,"checkJsError",{enumerable:!0,get:function(){return jsutil_1.checkJsError}});Object.defineProperty(exports,"isFlowControlMsg",{enumerable:!0,get:function(){return jsutil_1.isFlowControlMsg}});Object.defineProperty(exports,"isHeartbeatMsg",{enumerable:!0,get:function(){return jsutil_1.isHeartbeatMsg}});var types_1=require_types2();Object.defineProperty(exports,"AdvisoryKind",{enumerable:!0,get:function(){return types_1.AdvisoryKind}});Object.defineProperty(exports,"consumerOpts",{enumerable:!0,get:function(){return types_1.consumerOpts}});Object.defineProperty(exports,"DirectMsgHeaders",{enumerable:!0,get:function(){return types_1.DirectMsgHeaders}});Object.defineProperty(exports,"isConsumerOptsBuilder",{enumerable:!0,get:function(){return types_1.isConsumerOptsBuilder}});Object.defineProperty(exports,"JsHeaders",{enumerable:!0,get:function(){return types_1.JsHeaders}});Object.defineProperty(exports,"KvWatchInclude",{enumerable:!0,get:function(){return types_1.KvWatchInclude}});Object.defineProperty(exports,"RepublishHeaders",{enumerable:!0,get:function(){return types_1.RepublishHeaders}});var jsapi_types_1=require_jsapi_types();Object.defineProperty(exports,"AckPolicy",{enumerable:!0,get:function(){return jsapi_types_1.AckPolicy}});Object.defineProperty(exports,"DeliverPolicy",{enumerable:!0,get:function(){return jsapi_types_1.DeliverPolicy}});Object.defineProperty(exports,"DiscardPolicy",{enumerable:!0,get:function(){return jsapi_types_1.DiscardPolicy}});Object.defineProperty(exports,"ReplayPolicy",{enumerable:!0,get:function(){return jsapi_types_1.ReplayPolicy}});Object.defineProperty(exports,"RetentionPolicy",{enumerable:!0,get:function(){return jsapi_types_1.RetentionPolicy}});Object.defineProperty(exports,"StorageType",{enumerable:!0,get:function(){return jsapi_types_1.StorageType}});Object.defineProperty(exports,"StoreCompression",{enumerable:!0,get:function(){return jsapi_types_1.StoreCompression}});var consumer_1=require_consumer();Object.defineProperty(exports,"ConsumerDebugEvents",{enumerable:!0,get:function(){return consumer_1.ConsumerDebugEvents}});Object.defineProperty(exports,"ConsumerEvents",{enumerable:!0,get:function(){return consumer_1.ConsumerEvents}})});var require_nats_base_client=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m[k]}};Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});__exportStar(require_internal_mod(),exports);__exportStar(require_internal_mod2(),exports)});var require_node_transport=__commonJS((exports)=>{var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve2){resolve2(value)})}return new(P||(P=Promise))(function(resolve2,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result2){result2.done?resolve2(result2.value):adopt(result2.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__await=exports&&exports.__await||function(v){return this instanceof __await?(this.v=v,this):new __await(v)},__asyncGenerator=exports&&exports.__asyncGenerator||function(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(f){return function(v){return Promise.resolve(v).then(f,reject)}}function verb(n,f){if(g[n]){if(i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f)i[n]=f(i[n])}}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){if(f(v),q.shift(),q.length)resume(q[0][0],q[0][1])}};Object.defineProperty(exports,"__esModule",{value:!0});exports.NodeTransport=void 0;exports.nodeResolveHost=nodeResolveHost;var nats_base_client_1=require_nats_base_client(),net_1=__require("net"),util_1=require_util(),tls_1=__require("tls"),{resolve}=__require("path"),{readFile,existsSync:existsSync4}=__require("fs"),dns=__require("dns"),VERSION="2.29.3",LANG="nats.js";class NodeTransport{constructor(){this.yields=[],this.signal=(0,nats_base_client_1.deferred)(),this.closedNotification=(0,nats_base_client_1.deferred)(),this.connected=!1,this.tlsName="",this.done=!1,this.lang=LANG,this.version=VERSION}connect(hp,options){return __awaiter(this,void 0,void 0,function*(){this.tlsName=hp.tlsName,this.options=options;let{tls}=this.options,{handshakeFirst}=tls||{};try{if(handshakeFirst===!0)this.socket=yield this.tlsFirst(hp);else this.socket=yield this.dial(hp);let info=yield this.peekInfo();(0,nats_base_client_1.checkOptions)(info,options);let{tls_required:tlsRequired,tls_available:tlsAvailable}=info,desired=tlsAvailable===!0&&options.tls!==null;if(!handshakeFirst&&(tlsRequired||desired))this.socket=yield this.startTLS();if(tlsRequired&&this.socket.encrypted!==!0)throw new nats_base_client_1.NatsError("tls",nats_base_client_1.ErrorCode.ServerOptionNotAvailable);return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(err){if(!err)err=nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.ConnectionRefused,Error("node provided an undefined error!"));let{code}=err,perr=code==="ECONNREFUSED"?nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.ConnectionRefused,err):err;if(this.socket)this.socket.destroy();throw perr}})}dial(hp){let d=(0,nats_base_client_1.deferred)(),dialError,socket=(0,net_1.createConnection)(hp.port,hp.hostname,()=>{d.resolve(socket),socket.removeAllListeners()});return socket.on("error",(err)=>{dialError=err}),socket.on("close",()=>{socket.removeAllListeners(),d.reject(dialError)}),socket.setNoDelay(!0),d}get isClosed(){return this.done}close(err){return this._closed(err,!1)}peekInfo(){let d=(0,nats_base_client_1.deferred)(),peekError;return this.socket.on("data",(frame)=>{this.yields.push(frame);let t=nats_base_client_1.DataBuffer.concat(...this.yields),pm=(0,nats_base_client_1.extractProtocolMessage)(t);if(pm!=="")try{let m=nats_base_client_1.INFO.exec(pm);if(!m)throw Error("unexpected response from server");let info=JSON.parse(m[1]);d.resolve(info)}catch(err){d.reject(err)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(err)=>{peekError=err}),this.socket.on("close",()=>{this.socket.removeAllListeners(),d.reject(peekError)}),d}loadFile(fn){if(!fn)return Promise.resolve();let d=(0,nats_base_client_1.deferred)();try{if(fn=resolve(fn),!existsSync4(fn))d.reject(Error(`${fn} doesn't exist`));readFile(fn,(err,data)=>{if(err)return d.reject(err);d.resolve(data)})}catch(err){d.reject(err)}return d}loadClientCerts(){return __awaiter(this,void 0,void 0,function*(){let tlsOpts={},{certFile,cert,caFile,ca,keyFile,key}=this.options.tls;try{if(certFile){let data=yield this.loadFile(certFile);if(data)tlsOpts.cert=data}else if(cert)tlsOpts.cert=cert;if(keyFile){let data=yield this.loadFile(keyFile);if(data)tlsOpts.key=data}else if(key)tlsOpts.key=key;if(caFile){let data=yield this.loadFile(caFile);if(data)tlsOpts.ca=[data]}else if(ca)tlsOpts.ca=ca;return Promise.resolve(tlsOpts)}catch(err){return Promise.reject(err)}})}tlsFirst(hp){return __awaiter(this,void 0,void 0,function*(){let tlsError,tlsOpts={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)tlsOpts.socket=this.socket;if(typeof this.options.tls==="object")try{let certOpts=(yield this.loadClientCerts())||{};tlsOpts=(0,util_1.extend)(tlsOpts,this.options.tls,certOpts)}catch(err){return Promise.reject(new nats_base_client_1.NatsError(err.message,nats_base_client_1.ErrorCode.Tls,err))}let d=(0,nats_base_client_1.deferred)();try{let tlsSocket=(0,tls_1.connect)(hp.port,hp.hostname,tlsOpts,()=>{tlsSocket.removeAllListeners(),d.resolve(tlsSocket)});tlsSocket.on("error",(err)=>{tlsError=err}),tlsSocket.on("secureConnect",()=>{if(tlsOpts.rejectUnauthorized===!1)return;if(!tlsSocket.authorized)throw tlsSocket.authorizationError}),tlsSocket.on("close",()=>{d.reject(tlsError),tlsSocket.removeAllListeners()}),tlsSocket.setNoDelay(!0)}catch(err){d.reject(nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.Tls,err))}return d})}startTLS(){return __awaiter(this,void 0,void 0,function*(){let tlsError,tlsOpts={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let certOpts=(yield this.loadClientCerts())||{};tlsOpts=(0,util_1.extend)(tlsOpts,this.options.tls,certOpts)}catch(err){return Promise.reject(new nats_base_client_1.NatsError(err.message,nats_base_client_1.ErrorCode.Tls,err))}let d=(0,nats_base_client_1.deferred)();try{let tlsSocket=(0,tls_1.connect)(tlsOpts,()=>{tlsSocket.removeAllListeners(),d.resolve(tlsSocket)});tlsSocket.on("error",(err)=>{tlsError=err}),tlsSocket.on("secureConnect",()=>{if(tlsOpts.rejectUnauthorized===!1)return;if(!tlsSocket.authorized)throw tlsSocket.authorizationError}),tlsSocket.on("close",()=>{d.reject(tlsError),tlsSocket.removeAllListeners()})}catch(err){d.reject(nats_base_client_1.NatsError.errorForCode(nats_base_client_1.ErrorCode.Tls,err))}return d})}setupHandlers(){let connError;this.socket.on("data",(frame)=>{return this.yields.push(frame),this.signal.resolve()}),this.socket.on("error",(err)=>{connError=err}),this.socket.on("end",()=>{var _a,_b;if((_a=this.socket)===null||_a===void 0?void 0:_a.destroyed)return;(_b=this.socket)===null||_b===void 0||_b.write(new Uint8Array(0),()=>{var _a2;(_a2=this.socket)===null||_a2===void 0||_a2.end()})}),this.socket.on("close",()=>{this._closed(connError,!1)})}[Symbol.asyncIterator](){return this.iterate()}iterate(){return __asyncGenerator(this,arguments,function*(){let debug=this.options.debug;while(!0){if(this.yields.length===0)yield __await(this.signal);let yields=this.yields;this.yields=[];for(let i=0;i<yields.length;i++){if(debug)console.info(`> ${(0,nats_base_client_1.render)(yields[i])}`);yield yield __await(yields[i])}if(this.done)break;else if(this.yields.length===0)yields.length=0,this.yields=yields,this.signal=(0,nats_base_client_1.deferred)()}})}discard(){}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof tls_1.TLSSocket}_send(frame){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,nats_base_client_1.render)(frame)}`);let d=(0,nats_base_client_1.deferred)();try{this.socket.write(frame,(err)=>{if(err){if(this.options.debug)console.error(`!!! ${(0,nats_base_client_1.render)(frame)}: ${err}`);return d.reject(err)}return d.resolve()})}catch(err){if(this.options.debug)console.error(`!!! ${(0,nats_base_client_1.render)(frame)}: ${err}`);d.reject(err)}return d}send(frame){this._send(frame).catch((_err)=>{})}_closed(err_1){return __awaiter(this,arguments,void 0,function*(err,internal=!0){if(!this.connected)return;if(this.done)return;if(this.closeError=err,!err&&this.socket&&internal)try{yield this._send(new TextEncoder().encode(""))}catch(err2){if(this.options.debug)console.log("transport close terminated with an error",err2)}try{if(this.socket)this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0}catch(err2){console.log(err2)}this.done=!0,this.closedNotification.resolve(this.closeError)})}closed(){return this.closedNotification}}exports.NodeTransport=NodeTransport;function nodeResolveHost(s){return __awaiter(this,void 0,void 0,function*(){let a=(0,nats_base_client_1.deferred)(),aaaa=(0,nats_base_client_1.deferred)();dns.resolve4(s,(err,records)=>{if(err)a.resolve(err);else a.resolve(records)}),dns.resolve6(s,(err,records)=>{if(err)aaaa.resolve(err);else aaaa.resolve(records)});let ips=[],da=yield a;if(Array.isArray(da))ips.push(...da);let daaaa=yield aaaa;if(Array.isArray(daaaa))ips.push(...daaaa);if(ips.length===0)ips.push(s);return ips})}});var require_connect=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.connect=connect;var node_transport_1=require_node_transport(),nats_base_client_1=require_nats_base_client();function connect(opts={}){return(0,nats_base_client_1.setTransportFactory)({factory:()=>{return new node_transport_1.NodeTransport},dnsResolveFn:node_transport_1.nodeResolveHost}),nats_base_client_1.NatsConnectionImpl.connect(opts)}});var require_mod3=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.consumerOpts=exports.StoreCompression=exports.StorageType=exports.RetentionPolicy=exports.RepublishHeaders=exports.ReplayPolicy=exports.KvWatchInclude=exports.JsHeaders=exports.DiscardPolicy=exports.DirectMsgHeaders=exports.DeliverPolicy=exports.ConsumerEvents=exports.ConsumerDebugEvents=exports.AdvisoryKind=exports.AckPolicy=exports.isHeartbeatMsg=exports.isFlowControlMsg=exports.checkJsError=void 0;var internal_mod_1=require_internal_mod2();Object.defineProperty(exports,"checkJsError",{enumerable:!0,get:function(){return internal_mod_1.checkJsError}});Object.defineProperty(exports,"isFlowControlMsg",{enumerable:!0,get:function(){return internal_mod_1.isFlowControlMsg}});Object.defineProperty(exports,"isHeartbeatMsg",{enumerable:!0,get:function(){return internal_mod_1.isHeartbeatMsg}});var internal_mod_2=require_internal_mod2();Object.defineProperty(exports,"AckPolicy",{enumerable:!0,get:function(){return internal_mod_2.AckPolicy}});Object.defineProperty(exports,"AdvisoryKind",{enumerable:!0,get:function(){return internal_mod_2.AdvisoryKind}});Object.defineProperty(exports,"ConsumerDebugEvents",{enumerable:!0,get:function(){return internal_mod_2.ConsumerDebugEvents}});Object.defineProperty(exports,"ConsumerEvents",{enumerable:!0,get:function(){return internal_mod_2.ConsumerEvents}});Object.defineProperty(exports,"DeliverPolicy",{enumerable:!0,get:function(){return internal_mod_2.DeliverPolicy}});Object.defineProperty(exports,"DirectMsgHeaders",{enumerable:!0,get:function(){return internal_mod_2.DirectMsgHeaders}});Object.defineProperty(exports,"DiscardPolicy",{enumerable:!0,get:function(){return internal_mod_2.DiscardPolicy}});Object.defineProperty(exports,"JsHeaders",{enumerable:!0,get:function(){return internal_mod_2.JsHeaders}});Object.defineProperty(exports,"KvWatchInclude",{enumerable:!0,get:function(){return internal_mod_2.KvWatchInclude}});Object.defineProperty(exports,"ReplayPolicy",{enumerable:!0,get:function(){return internal_mod_2.ReplayPolicy}});Object.defineProperty(exports,"RepublishHeaders",{enumerable:!0,get:function(){return internal_mod_2.RepublishHeaders}});Object.defineProperty(exports,"RetentionPolicy",{enumerable:!0,get:function(){return internal_mod_2.RetentionPolicy}});Object.defineProperty(exports,"StorageType",{enumerable:!0,get:function(){return internal_mod_2.StorageType}});Object.defineProperty(exports,"StoreCompression",{enumerable:!0,get:function(){return internal_mod_2.StoreCompression}});var types_1=require_types2();Object.defineProperty(exports,"consumerOpts",{enumerable:!0,get:function(){return types_1.consumerOpts}})});var require_mod4=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m[k]}};Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.connect=void 0;if(typeof TextEncoder>"u"){let{TextEncoder:TextEncoder2,TextDecoder:TextDecoder2}=__require("util");global.TextEncoder=TextEncoder2,global.TextDecoder=TextDecoder2}if(typeof globalThis.crypto>"u"){let c=__require("crypto");global.crypto=c.webcrypto}if(typeof globalThis.ReadableStream>"u"){let chunks=process.versions.node.split(".");if(parseInt(chunks[0])>=16){let streams=__require("stream/web");global.ReadableStream=streams.ReadableStream}}var connect_1=require_connect();Object.defineProperty(exports,"connect",{enumerable:!0,get:function(){return connect_1.connect}});__exportStar(require_mod2(),exports);__exportStar(require_mod3(),exports)});function isValid2(value){return typeof value==="string"&&VALID.has(value)}function resolveExecutorType(override){if(isValid2(override))return override;let env=process.env.GENIE_EXECUTOR;if(isValid2(env))return env;try{let persisted=loadGenieConfigSync().omni?.executor;if(isValid2(persisted))return persisted}catch{}return"tmux"}var VALID;var init_executor_config=__esm(()=>{init_genie_config2();VALID=new Set(["tmux","sdk"])});class BridgeSessionStore{sql;constructor(sql){this.sql=sql}async create(opts){let[row]=await this.sql`
|
|
63
|
+
INSERT INTO genie_bridge_sessions (
|
|
64
|
+
instance_id, chat_id, agent_name, executor_id,
|
|
65
|
+
tmux_pane_id, claude_session_id, metadata
|
|
66
|
+
) VALUES (
|
|
67
|
+
${opts.instanceId}, ${opts.chatId}, ${opts.agentName},
|
|
68
|
+
${opts.executorId??null}, ${opts.tmuxPaneId??null},
|
|
69
|
+
${opts.claudeSessionId??null}, ${JSON.stringify(opts.metadata??{})}::jsonb
|
|
70
|
+
)
|
|
71
|
+
RETURNING id
|
|
72
|
+
`;return row.id}async recordActivity(sessionId){await this.sql`
|
|
73
|
+
UPDATE genie_bridge_sessions
|
|
74
|
+
SET last_activity_at = now()
|
|
75
|
+
WHERE id = ${sessionId} AND status = 'active'
|
|
76
|
+
`}async close(sessionId){await this.sql`
|
|
77
|
+
UPDATE genie_bridge_sessions
|
|
78
|
+
SET status = 'closed', closed_at = now()
|
|
79
|
+
WHERE id = ${sessionId} AND status = 'active'
|
|
80
|
+
`}async markOrphaned(sessionIds){if(sessionIds.length===0)return;await this.sql`
|
|
81
|
+
UPDATE genie_bridge_sessions
|
|
82
|
+
SET status = 'orphaned'
|
|
83
|
+
WHERE id = ANY(${sessionIds}) AND status = 'active'
|
|
84
|
+
`}async markAllOrphaned(){return(await this.sql`
|
|
85
|
+
UPDATE genie_bridge_sessions
|
|
86
|
+
SET status = 'orphaned'
|
|
87
|
+
WHERE status = 'active'
|
|
88
|
+
RETURNING id
|
|
89
|
+
`).length}async list(status){if(status)return this.sql`
|
|
90
|
+
SELECT * FROM genie_bridge_sessions
|
|
91
|
+
WHERE status = ${status}
|
|
92
|
+
ORDER BY started_at DESC
|
|
93
|
+
`;return this.sql`
|
|
94
|
+
SELECT * FROM genie_bridge_sessions
|
|
95
|
+
ORDER BY started_at DESC
|
|
96
|
+
LIMIT 500
|
|
97
|
+
`}async getActive(instanceId,chatId){let[row]=await this.sql`
|
|
98
|
+
SELECT * FROM genie_bridge_sessions
|
|
99
|
+
WHERE instance_id = ${instanceId}
|
|
100
|
+
AND chat_id = ${chatId}
|
|
101
|
+
AND status = 'active'
|
|
102
|
+
LIMIT 1
|
|
103
|
+
`;return row??null}async updateExecutorInfo(sessionId,info){let sets=[],values=[];if(info.executorId!==void 0)sets.push("executor_id"),values.push(info.executorId);if(info.tmuxPaneId!==void 0)sets.push("tmux_pane_id"),values.push(info.tmuxPaneId);if(info.claudeSessionId!==void 0)sets.push("claude_session_id"),values.push(info.claudeSessionId);if(sets.length===0)return;await this.sql`
|
|
104
|
+
UPDATE genie_bridge_sessions SET
|
|
105
|
+
executor_id = COALESCE(${info.executorId??null}, executor_id),
|
|
106
|
+
tmux_pane_id = COALESCE(${info.tmuxPaneId??null}, tmux_pane_id),
|
|
107
|
+
claude_session_id = COALESCE(${info.claudeSessionId??null}, claude_session_id),
|
|
108
|
+
last_activity_at = now()
|
|
109
|
+
WHERE id = ${sessionId}
|
|
110
|
+
`}}function normalizeValue(v){if(v===void 0||v===null)return;if(v==="")return;if(v==="inherit")return;return v}function resolveField(agent,field,ctx){return resolveFieldWithSource(agent,field,ctx).value}function resolveFieldWithSource(agent,field,ctx){let agentVal=normalizeValue(agent[field]);if(agentVal!==void 0)return{value:agentVal,source:"explicit"};if(ctx.parent){let parentVal=normalizeValue(ctx.parent.fields[field]);if(parentVal!==void 0)return{value:parentVal,source:`parent:${ctx.parent.name}`}}if(ctx.workspaceDefaults){let wsVal=normalizeValue(ctx.workspaceDefaults[field]);if(wsVal!==void 0)return{value:wsVal,source:"workspace"}}return{value:BUILTIN_DEFAULTS[field],source:"built-in"}}function computeEffectiveDefaults(workspaceDefaults){if(!workspaceDefaults)return{...BUILTIN_DEFAULTS};let result2={...BUILTIN_DEFAULTS};for(let key of Object.keys(BUILTIN_DEFAULTS)){let wsVal=normalizeValue(workspaceDefaults[key]);if(wsVal!==void 0)result2[key]=wsVal}return result2}var BUILTIN_DEFAULTS,RESOLVED_FIELDS;var init_defaults=__esm(()=>{BUILTIN_DEFAULTS={model:"opus",promptMode:"append",color:"blue",effort:"high",thinking:"enabled",permissionMode:"bypassPermissions"},RESOLVED_FIELDS=["model"]});var exports_js_yaml={};__export(exports_js_yaml,{types:()=>types2,safeLoadAll:()=>safeLoadAll,safeLoad:()=>safeLoad,safeDump:()=>safeDump,loadAll:()=>loadAll,load:()=>load,dump:()=>dump,default:()=>jsYaml,YAMLException:()=>YAMLException,Type:()=>Type,Schema:()=>Schema,JSON_SCHEMA:()=>JSON_SCHEMA,FAILSAFE_SCHEMA:()=>FAILSAFE_SCHEMA,DEFAULT_SCHEMA:()=>DEFAULT_SCHEMA,CORE_SCHEMA:()=>CORE_SCHEMA});function isNothing(subject){return typeof subject>"u"||subject===null}function isObject(subject){return typeof subject==="object"&&subject!==null}function toArray(sequence){if(Array.isArray(sequence))return sequence;else if(isNothing(sequence))return[];return[sequence]}function extend(target,source){var index,length,key,sourceKeys;if(source){sourceKeys=Object.keys(source);for(index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key]}return target}function repeat(string,count){var result2="",cycle;for(cycle=0;cycle<count;cycle+=1)result2+=string;return result2}function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}function formatError(exception,compact){var where="",message=exception.reason||"(unknown reason)";if(!exception.mark)return message;if(exception.mark.name)where+='in "'+exception.mark.name+'" ';if(where+="("+(exception.mark.line+1)+":"+(exception.mark.column+1)+")",!compact&&exception.mark.snippet)where+=`
|
|
65
111
|
|
|
66
|
-
${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync4(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function buildClaudeCommand(params){preflightCheck("claude");let parts=[resolveShellBinary("claude")??"claude","--dangerously-skip-permissions"],env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(appendOtelEnv(env,params),params.nativeTeam?.enabled)appendNativeTeamFlags(parts,env,params.nativeTeam,params);if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));if(params.role)parts.push("--agent",escapeShellArg2(params.role));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name));appendSystemPromptFlags(parts,params);let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15},settingsObj={hooks:{PreToolUse:[{matcher:"*",hooks:[hookEntry]}],PostToolUse:[{matcher:"*",hooks:[hookEntry]}],UserPromptSubmit:[{hooks:[hookEntry]}],Stop:[{hooks:[hookEntry]}]}};if(params.permissions){let perms={};if(params.permissions.allow?.length)perms.allow=params.permissions.allow;if(params.permissions.deny?.length)perms.deny=params.permissions.deny;if(Object.keys(perms).length>0)settingsObj.permissions=perms}if(parts.push("--settings",escapeShellArg2(JSON.stringify(settingsObj))),params.disallowedTools?.length)for(let tool of params.disallowedTools)parts.push("--disallowedTools",escapeShellArg2(tool));if(params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));if(params.initialPrompt)parts.push(escapeShellArg2(params.initialPrompt));return{command:parts.join(" "),provider:"claude",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildCodexCommand(params){preflightCheck("codex");let parts=["codex"];if(parts.push("--yolo"),parts.push("--no-alt-screen"),params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));let promptParts=[`Genie worker. Team: ${params.team}.`];if(params.role)promptParts.push(`Role: ${params.role}.`);if(params.skill)promptParts.push(`Execute the ${params.skill} skill instructions.`);let prompt=promptParts.join(" ");return parts.push(escapeShellArg2(prompt)),{command:parts.join(" "),provider:"codex",meta:{role:params.role,skill:params.skill}}}function buildLaunchCommand(params){let validated=validateSpawnParams(params);switch(validated.provider){case"claude":return buildClaudeCommand(validated);case"codex":return buildCodexCommand(validated);case"claude-sdk":return{command:"claude-sdk-in-process",provider:"claude-sdk",meta:{role:validated.role,skill:validated.skill}};default:throw Error(`Unknown provider "${validated.provider}". Valid providers: claude, codex, claude-sdk`)}}var CLAUDE_TEAM_COLORS,spawnParamsSchema;var init_provider_adapters=__esm(()=>{init_zod();init_inject();CLAUDE_TEAM_COLORS=["red","blue","green","yellow","purple","orange","pink","cyan"],spawnParamsSchema=exports_external.object({provider:exports_external.enum(["claude","codex","claude-sdk","app-pty"]),team:exports_external.string().min(1,"Team name is required"),role:exports_external.string().optional(),skill:exports_external.string().optional(),extraArgs:exports_external.array(exports_external.string()).optional(),nativeTeam:exports_external.object({enabled:exports_external.boolean(),parentSessionId:exports_external.string().optional(),color:exports_external.string().optional(),agentType:exports_external.string().optional(),planModeRequired:exports_external.boolean().optional(),permissionMode:exports_external.string().optional(),agentName:exports_external.string().optional()}).optional(),sessionId:exports_external.string().uuid().optional(),resume:exports_external.string().optional(),systemPromptFile:exports_external.string().optional(),systemPrompt:exports_external.string().optional(),promptMode:exports_external.enum(["system","append"]).optional(),model:exports_external.string().optional(),initialPrompt:exports_external.string().optional(),name:exports_external.string().optional(),otelPort:exports_external.number().optional(),otelLogPrompts:exports_external.boolean().optional(),otelWishSlug:exports_external.string().optional(),newWindow:exports_external.boolean().optional(),windowTarget:exports_external.string().optional()})});var exports_claude_native_teams={};__export(exports_claude_native_teams,{writeNativeInbox:()=>writeNativeInbox,unregisterNativeMember:()=>unregisterNativeMember,sanitizeTeamName:()=>sanitizeTeamName,resolveNativeMemberName:()=>resolveNativeMemberName,registerNativeMember:()=>registerNativeMember,registerAsTeamLead:()=>registerAsTeamLead,loadConfig:()=>loadConfig,listTeamsWithUnreadInbox:()=>listTeamsWithUnreadInbox,listTeams:()=>listTeams,isInsideClaudeCode:()=>isInsideClaudeCode,ensureNativeTeam:()=>ensureNativeTeam,discoverTeamName:()=>discoverTeamName,discoverClaudeParentSessionId:()=>discoverClaudeParentSessionId,deleteNativeTeam:()=>deleteNativeTeam,clearNativeInbox:()=>clearNativeInbox,assignColor:()=>assignColor});import{existsSync as existsSync5}from"fs";import{mkdir as mkdir2,open,readFile as readFile2,readdir,rm,stat,unlink,writeFile as writeFile2}from"fs/promises";import{homedir as homedir5}from"os";import{join as join5}from"path";function claudeConfigDir2(){return process.env.CLAUDE_CONFIG_DIR??join5(homedir5(),".claude")}function teamsBaseDir(){return join5(claudeConfigDir2(),"teams")}function sanitizeTeamName(name){return name.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}async function listTeams(){try{return(await readdir(teamsBaseDir())).filter((e)=>!e.startsWith("."))}catch{return[]}}function teamDir(teamName){return join5(teamsBaseDir(),sanitizeTeamName(teamName))}function configPath(teamName){return join5(teamDir(teamName),"config.json")}function inboxesDir(teamName){return join5(teamDir(teamName),"inboxes")}function inboxPath(teamName,agentName){return join5(inboxesDir(teamName),`${sanitizeTeamName(agentName)}.json`)}function lockPath(filePath){return`${filePath}.lock`}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function acquireLock(path){let lock=lockPath(path),deadline=Date.now()+LOCK_TIMEOUT_MS;while(Date.now()<deadline)try{await writeFile2(lock,String(process.pid),{flag:"wx"});return}catch{try{let content=await readFile2(lock,"utf-8"),holderPid=Number.parseInt(content.trim(),10);if(!Number.isNaN(holderPid)&&!isPidAlive(holderPid)){try{await unlink(lock)}catch{}continue}}catch{continue}let jitter=Math.floor(Math.random()*LOCK_POLL_MS);await new Promise((r)=>setTimeout(r,LOCK_POLL_MS+jitter))}console.warn(`[claude-native-teams] Force-acquiring stale lock: ${lock}`),await writeFile2(lock,String(process.pid))}async function releaseLock(path){try{await unlink(lockPath(path))}catch{}}async function loadConfig(teamName){try{let content=await readFile2(configPath(teamName),"utf-8");return JSON.parse(content)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return null;let message=err instanceof Error?err.message:String(err);return console.warn(`[claude-native-teams] Failed to load config for "${teamName}": ${message}`),null}}async function saveConfig(teamName,config){await writeFile2(configPath(teamName),JSON.stringify(config,null,2))}async function countLeadSessionRefs(){let counts=new Map,teams=await listTeams();for(let team of teams){let leadSessionId=(await loadConfig(team))?.leadSessionId;if(!leadSessionId)continue;counts.set(leadSessionId,(counts.get(leadSessionId)??0)+1)}return counts}async function ensureNativeTeam(teamName,description,leadSessionId,leaderName){let dir=teamDir(teamName),inboxDir=inboxesDir(teamName);await mkdir2(dir,{recursive:!0}),await mkdir2(inboxDir,{recursive:!0}),ensureTeammateBypassPermissions();let existing=await loadConfig(teamName);if(existing)return existing;let sanitized=sanitizeTeamName(teamName),resolvedLeader=sanitizeTeamName(leaderName??teamName),config={name:sanitized,description,createdAt:Date.now(),leadAgentId:`${resolvedLeader}@${sanitized}`,leadSessionId,members:[]};return await saveConfig(teamName,config),config}async function registerNativeMember(teamName,member){let config=await loadConfig(teamName);if(!config)throw Error(`Native team "${teamName}" not found`);let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(member.agentName)}@${sanitized}`;config.members=config.members.filter((m)=>m.agentId!==agentId),config.members.push({agentId,name:sanitizeTeamName(member.agentName),agentType:member.agentType??"general-purpose",joinedAt:Date.now(),tmuxPaneId:member.tmuxPaneId,cwd:member.cwd??process.cwd(),backendType:"tmux",color:member.color,planModeRequired:member.planModeRequired??!1,isActive:!0}),await saveConfig(teamName,config);let inbox=inboxPath(teamName,member.agentName);if(!existsSync5(inbox))await writeFile2(inbox,"[]")}async function unregisterNativeMember(teamName,agentName){let config=await loadConfig(teamName);if(!config)return;let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(agentName)}@${sanitized}`,member=config.members.find((m)=>m.agentId===agentId);if(member)member.isActive=!1;await saveConfig(teamName,config)}async function writeNativeInbox(teamName,agentName,message){let path=inboxPath(teamName,agentName);await mkdir2(inboxesDir(teamName),{recursive:!0}),await acquireLock(path);try{let messages=[];try{let content=await readFile2(path,"utf-8");messages=JSON.parse(content)}catch{}messages.push(message),await writeFile2(path,JSON.stringify(messages,null,2))}finally{await releaseLock(path)}}async function resolveNativeMemberName(teamName,genieWorkerId){let config=await loadConfig(teamName);if(!config||config.members.length===0)return null;let sanitizedId=sanitizeTeamName(genieWorkerId),sanitizedTeam=sanitizeTeamName(teamName),exactMatch=config.members.find((m)=>m.name===sanitizedId&&m.isActive);if(exactMatch)return exactMatch.name;let agentIdMatch=config.members.find((m)=>m.agentId===`${sanitizedId}@${sanitizedTeam}`&&m.isActive);if(agentIdMatch)return agentIdMatch.name;let teamPrefix=`${sanitizedTeam}-`;if(sanitizedId.startsWith(teamPrefix)){let stripped=sanitizedId.slice(teamPrefix.length),prefixMatch=config.members.find((m)=>m.name===stripped&&m.isActive);if(prefixMatch)return prefixMatch.name}let inactiveMatch=config.members.find((m)=>m.name===sanitizedId);if(inactiveMatch)return inactiveMatch.name;return null}async function assignColor(teamName){let config=await loadConfig(teamName);if(!config)return CLAUDE_TEAM_COLORS[0];let usedColors=new Set(config.members.map((m)=>m.color));for(let color of CLAUDE_TEAM_COLORS)if(!usedColors.has(color))return color;return CLAUDE_TEAM_COLORS[config.members.length%CLAUDE_TEAM_COLORS.length]}async function clearNativeInbox(teamName,agentName){let path=inboxPath(teamName,agentName);await acquireLock(path);try{await writeFile2(path,"[]")}finally{await releaseLock(path)}}async function deleteNativeTeam(teamName){let dir=teamDir(teamName);if(!existsSync5(dir))return!1;return await rm(dir,{recursive:!0,force:!0}),!0}function extractLeaderInboxName(config,teamName){if(!config?.leadAgentId)return teamName??"unknown";let atIdx=config.leadAgentId.indexOf("@");return atIdx>0?config.leadAgentId.slice(0,atIdx):teamName??"unknown"}async function scanTeamInbox(base,name){let config=null;try{let cfgContent=await readFile2(join5(base,name,"config.json"),"utf-8");config=JSON.parse(cfgContent)}catch{}let leaderInboxName=extractLeaderInboxName(config,name),inboxFile=join5(base,name,"inboxes",`${leaderInboxName}.json`),messages;try{let content=await readFile2(inboxFile,"utf-8");messages=JSON.parse(content)}catch{return null}if(!Array.isArray(messages))return null;let unread=messages.filter((m)=>m.read===!1);if(unread.length===0)return null;let workingDir=null;if(config){let leadMember=config.members.find((m)=>m.agentId===config?.leadAgentId||m.name===leaderInboxName);if(leadMember?.cwd)workingDir=leadMember.cwd}return{teamName:name,unreadCount:unread.length,workingDir,firstUnreadText:unread[0]?.text??null}}async function listTeamsWithUnreadInbox(){let base=teamsBaseDir(),teamDirs;try{teamDirs=await readdir(base)}catch{return[]}let results=[];for(let name of teamDirs){let entry=await scanTeamInbox(base,name);if(entry)results.push(entry)}return results}function sanitizePath(p){return p.replace(/[^a-zA-Z0-9]/g,"-")}async function discoverClaudeSessionId(cwd){let envSessionId=process.env.CLAUDE_CODE_SESSION_ID;if(envSessionId)return envSessionId;let projectDir=join5(claudeConfigDir2(),"projects",sanitizePath(cwd??process.cwd()));try{let jsonls=(await readdir(projectDir)).filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let newest=null;for(let name of jsonls){let s=await stat(join5(projectDir,name));if(!newest||s.mtimeMs>newest.mtime)newest={name,mtime:s.mtimeMs}}if(!newest)return null;return newest.name.replace(".jsonl","")}catch{return null}}async function readSessionMetadata(filePath){let handle=null;try{handle=await open(filePath,"r");let buffer=Buffer.alloc(8192),{bytesRead}=await handle.read(buffer,0,buffer.length,0),head=buffer.toString("utf-8",0,bytesRead);for(let line of head.split(`
|
|
67
|
-
|
|
68
|
-
|
|
112
|
+
`+exception.mark.snippet;return message+" "+where}function YAMLException$1(reason,mark){if(Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=formatError(this,!1),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else this.stack=Error().stack||""}function getLine(buffer,lineStart,lineEnd,position,maxLineLength){var head="",tail="",maxHalfLength=Math.floor(maxLineLength/2)-1;if(position-lineStart>maxHalfLength)head=" ... ",lineStart=position-maxHalfLength+head.length;if(lineEnd-position>maxHalfLength)tail=" ...",lineEnd=position+maxHalfLength-tail.length;return{str:head+buffer.slice(lineStart,lineEnd).replace(/\t/g,"\u2192")+tail,pos:position-lineStart+head.length}}function padStart(string,max){return common.repeat(" ",max-string.length)+string}function makeSnippet(mark,options){if(options=Object.create(options||null),!mark.buffer)return null;if(!options.maxLength)options.maxLength=79;if(typeof options.indent!=="number")options.indent=1;if(typeof options.linesBefore!=="number")options.linesBefore=3;if(typeof options.linesAfter!=="number")options.linesAfter=2;var re=/\r?\n|\r|\0/g,lineStarts=[0],lineEnds=[],match,foundLineNo=-1;while(match=re.exec(mark.buffer))if(lineEnds.push(match.index),lineStarts.push(match.index+match[0].length),mark.position<=match.index&&foundLineNo<0)foundLineNo=lineStarts.length-2;if(foundLineNo<0)foundLineNo=lineStarts.length-1;var result2="",i,line,lineNoLength=Math.min(mark.line+options.linesAfter,lineEnds.length).toString().length,maxLineLength=options.maxLength-(options.indent+lineNoLength+3);for(i=1;i<=options.linesBefore;i++){if(foundLineNo-i<0)break;line=getLine(mark.buffer,lineStarts[foundLineNo-i],lineEnds[foundLineNo-i],mark.position-(lineStarts[foundLineNo]-lineStarts[foundLineNo-i]),maxLineLength),result2=common.repeat(" ",options.indent)+padStart((mark.line-i+1).toString(),lineNoLength)+" | "+line.str+`
|
|
113
|
+
`+result2}line=getLine(mark.buffer,lineStarts[foundLineNo],lineEnds[foundLineNo],mark.position,maxLineLength),result2+=common.repeat(" ",options.indent)+padStart((mark.line+1).toString(),lineNoLength)+" | "+line.str+`
|
|
114
|
+
`,result2+=common.repeat("-",options.indent+lineNoLength+3+line.pos)+`^
|
|
115
|
+
`;for(i=1;i<=options.linesAfter;i++){if(foundLineNo+i>=lineEnds.length)break;line=getLine(mark.buffer,lineStarts[foundLineNo+i],lineEnds[foundLineNo+i],mark.position-(lineStarts[foundLineNo]-lineStarts[foundLineNo+i]),maxLineLength),result2+=common.repeat(" ",options.indent)+padStart((mark.line+i+1).toString(),lineNoLength)+" | "+line.str+`
|
|
116
|
+
`}return result2.replace(/\n$/,"")}function compileStyleAliases(map){var result2={};if(map!==null)Object.keys(map).forEach(function(style){map[style].forEach(function(alias){result2[String(alias)]=style})});return result2}function Type$1(tag,options){if(options=options||{},Object.keys(options).forEach(function(name){if(TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)===-1)throw new exception('Unknown option "'+name+'" is met in definition of "'+tag+'" YAML type.')}),this.options=options,this.tag=tag,this.kind=options.kind||null,this.resolve=options.resolve||function(){return!0},this.construct=options.construct||function(data){return data},this.instanceOf=options.instanceOf||null,this.predicate=options.predicate||null,this.represent=options.represent||null,this.representName=options.representName||null,this.defaultStyle=options.defaultStyle||null,this.multi=options.multi||!1,this.styleAliases=compileStyleAliases(options.styleAliases||null),YAML_NODE_KINDS.indexOf(this.kind)===-1)throw new exception('Unknown kind "'+this.kind+'" is specified for "'+tag+'" YAML type.')}function compileList(schema,name){var result2=[];return schema[name].forEach(function(currentType){var newIndex=result2.length;result2.forEach(function(previousType,previousIndex){if(previousType.tag===currentType.tag&&previousType.kind===currentType.kind&&previousType.multi===currentType.multi)newIndex=previousIndex}),result2[newIndex]=currentType}),result2}function compileMap(){var result2={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},index,length;function collectType(type2){if(type2.multi)result2.multi[type2.kind].push(type2),result2.multi.fallback.push(type2);else result2[type2.kind][type2.tag]=result2.fallback[type2.tag]=type2}for(index=0,length=arguments.length;index<length;index+=1)arguments[index].forEach(collectType);return result2}function Schema$1(definition){return this.extend(definition)}function resolveYamlNull(data){if(data===null)return!0;var max=data.length;return max===1&&data==="~"||max===4&&(data==="null"||data==="Null"||data==="NULL")}function constructYamlNull(){return null}function isNull(object){return object===null}function resolveYamlBoolean(data){if(data===null)return!1;var max=data.length;return max===4&&(data==="true"||data==="True"||data==="TRUE")||max===5&&(data==="false"||data==="False"||data==="FALSE")}function constructYamlBoolean(data){return data==="true"||data==="True"||data==="TRUE"}function isBoolean(object){return Object.prototype.toString.call(object)==="[object Boolean]"}function isHexCode(c){return 48<=c&&c<=57||65<=c&&c<=70||97<=c&&c<=102}function isOctCode(c){return 48<=c&&c<=55}function isDecCode(c){return 48<=c&&c<=57}function resolveYamlInteger(data){if(data===null)return!1;var max=data.length,index=0,hasDigits=!1,ch;if(!max)return!1;if(ch=data[index],ch==="-"||ch==="+")ch=data[++index];if(ch==="0"){if(index+1===max)return!0;if(ch=data[++index],ch==="b"){index++;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(ch!=="0"&&ch!=="1")return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="x"){index++;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(!isHexCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="o"){index++;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(!isOctCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}}if(ch==="_")return!1;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(!isDecCode(data.charCodeAt(index)))return!1;hasDigits=!0}if(!hasDigits||ch==="_")return!1;return!0}function constructYamlInteger(data){var value=data,sign=1,ch;if(value.indexOf("_")!==-1)value=value.replace(/_/g,"");if(ch=value[0],ch==="-"||ch==="+"){if(ch==="-")sign=-1;value=value.slice(1),ch=value[0]}if(value==="0")return 0;if(ch==="0"){if(value[1]==="b")return sign*parseInt(value.slice(2),2);if(value[1]==="x")return sign*parseInt(value.slice(2),16);if(value[1]==="o")return sign*parseInt(value.slice(2),8)}return sign*parseInt(value,10)}function isInteger(object){return Object.prototype.toString.call(object)==="[object Number]"&&(object%1===0&&!common.isNegativeZero(object))}function resolveYamlFloat(data){if(data===null)return!1;if(!YAML_FLOAT_PATTERN.test(data)||data[data.length-1]==="_")return!1;return!0}function constructYamlFloat(data){var value,sign;if(value=data.replace(/_/g,"").toLowerCase(),sign=value[0]==="-"?-1:1,"+-".indexOf(value[0])>=0)value=value.slice(1);if(value===".inf")return sign===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;else if(value===".nan")return NaN;return sign*parseFloat(value,10)}function representYamlFloat(object,style){var res;if(isNaN(object))switch(style){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===object)switch(style){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===object)switch(style){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(common.isNegativeZero(object))return"-0.0";return res=object.toString(10),SCIENTIFIC_WITHOUT_DOT.test(res)?res.replace("e",".e"):res}function isFloat(object){return Object.prototype.toString.call(object)==="[object Number]"&&(object%1!==0||common.isNegativeZero(object))}function resolveYamlTimestamp(data){if(data===null)return!1;if(YAML_DATE_REGEXP.exec(data)!==null)return!0;if(YAML_TIMESTAMP_REGEXP.exec(data)!==null)return!0;return!1}function constructYamlTimestamp(data){var match,year,month,day,hour,minute,second,fraction=0,delta=null,tz_hour,tz_minute,date;if(match=YAML_DATE_REGEXP.exec(data),match===null)match=YAML_TIMESTAMP_REGEXP.exec(data);if(match===null)throw Error("Date resolve error");if(year=+match[1],month=+match[2]-1,day=+match[3],!match[4])return new Date(Date.UTC(year,month,day));if(hour=+match[4],minute=+match[5],second=+match[6],match[7]){fraction=match[7].slice(0,3);while(fraction.length<3)fraction+="0";fraction=+fraction}if(match[9]){if(tz_hour=+match[10],tz_minute=+(match[11]||0),delta=(tz_hour*60+tz_minute)*60000,match[9]==="-")delta=-delta}if(date=new Date(Date.UTC(year,month,day,hour,minute,second,fraction)),delta)date.setTime(date.getTime()-delta);return date}function representYamlTimestamp(object){return object.toISOString()}function resolveYamlMerge(data){return data==="<<"||data===null}function resolveYamlBinary(data){if(data===null)return!1;var code,idx,bitlen=0,max=data.length,map2=BASE64_MAP;for(idx=0;idx<max;idx++){if(code=map2.indexOf(data.charAt(idx)),code>64)continue;if(code<0)return!1;bitlen+=6}return bitlen%8===0}function constructYamlBinary(data){var idx,tailbits,input=data.replace(/[\r\n=]/g,""),max=input.length,map2=BASE64_MAP,bits=0,result2=[];for(idx=0;idx<max;idx++){if(idx%4===0&&idx)result2.push(bits>>16&255),result2.push(bits>>8&255),result2.push(bits&255);bits=bits<<6|map2.indexOf(input.charAt(idx))}if(tailbits=max%4*6,tailbits===0)result2.push(bits>>16&255),result2.push(bits>>8&255),result2.push(bits&255);else if(tailbits===18)result2.push(bits>>10&255),result2.push(bits>>2&255);else if(tailbits===12)result2.push(bits>>4&255);return new Uint8Array(result2)}function representYamlBinary(object){var result2="",bits=0,idx,tail,max=object.length,map2=BASE64_MAP;for(idx=0;idx<max;idx++){if(idx%3===0&&idx)result2+=map2[bits>>18&63],result2+=map2[bits>>12&63],result2+=map2[bits>>6&63],result2+=map2[bits&63];bits=(bits<<8)+object[idx]}if(tail=max%3,tail===0)result2+=map2[bits>>18&63],result2+=map2[bits>>12&63],result2+=map2[bits>>6&63],result2+=map2[bits&63];else if(tail===2)result2+=map2[bits>>10&63],result2+=map2[bits>>4&63],result2+=map2[bits<<2&63],result2+=map2[64];else if(tail===1)result2+=map2[bits>>2&63],result2+=map2[bits<<4&63],result2+=map2[64],result2+=map2[64];return result2}function isBinary(obj){return Object.prototype.toString.call(obj)==="[object Uint8Array]"}function resolveYamlOmap(data){if(data===null)return!0;var objectKeys=[],index,length,pair,pairKey,pairHasKey,object=data;for(index=0,length=object.length;index<length;index+=1){if(pair=object[index],pairHasKey=!1,_toString$2.call(pair)!=="[object Object]")return!1;for(pairKey in pair)if(_hasOwnProperty$3.call(pair,pairKey))if(!pairHasKey)pairHasKey=!0;else return!1;if(!pairHasKey)return!1;if(objectKeys.indexOf(pairKey)===-1)objectKeys.push(pairKey);else return!1}return!0}function constructYamlOmap(data){return data!==null?data:[]}function resolveYamlPairs(data){if(data===null)return!0;var index,length,pair,keys,result2,object=data;result2=Array(object.length);for(index=0,length=object.length;index<length;index+=1){if(pair=object[index],_toString$1.call(pair)!=="[object Object]")return!1;if(keys=Object.keys(pair),keys.length!==1)return!1;result2[index]=[keys[0],pair[keys[0]]]}return!0}function constructYamlPairs(data){if(data===null)return[];var index,length,pair,keys,result2,object=data;result2=Array(object.length);for(index=0,length=object.length;index<length;index+=1)pair=object[index],keys=Object.keys(pair),result2[index]=[keys[0],pair[keys[0]]];return result2}function resolveYamlSet(data){if(data===null)return!0;var key,object=data;for(key in object)if(_hasOwnProperty$2.call(object,key)){if(object[key]!==null)return!1}return!0}function constructYamlSet(data){return data!==null?data:{}}function _class(obj){return Object.prototype.toString.call(obj)}function is_EOL(c){return c===10||c===13}function is_WHITE_SPACE(c){return c===9||c===32}function is_WS_OR_EOL(c){return c===9||c===32||c===10||c===13}function is_FLOW_INDICATOR(c){return c===44||c===91||c===93||c===123||c===125}function fromHexCode(c){var lc;if(48<=c&&c<=57)return c-48;if(lc=c|32,97<=lc&&lc<=102)return lc-97+10;return-1}function escapedHexLen(c){if(c===120)return 2;if(c===117)return 4;if(c===85)return 8;return 0}function fromDecimalCode(c){if(48<=c&&c<=57)return c-48;return-1}function simpleEscapeSequence(c){return c===48?"\x00":c===97?"\x07":c===98?"\b":c===116?"\t":c===9?"\t":c===110?`
|
|
117
|
+
`:c===118?"\v":c===102?"\f":c===114?"\r":c===101?"\x1B":c===32?" ":c===34?'"':c===47?"/":c===92?"\\":c===78?"\x85":c===95?"\xA0":c===76?"\u2028":c===80?"\u2029":""}function charFromCodepoint(c){if(c<=65535)return String.fromCharCode(c);return String.fromCharCode((c-65536>>10)+55296,(c-65536&1023)+56320)}function setProperty(object,key,value){if(key==="__proto__")Object.defineProperty(object,key,{configurable:!0,enumerable:!0,writable:!0,value});else object[key]=value}function State$1(input,options){this.input=input,this.filename=options.filename||null,this.schema=options.schema||_default,this.onWarning=options.onWarning||null,this.legacy=options.legacy||!1,this.json=options.json||!1,this.listener=options.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=input.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function generateError(state,message){var mark={name:state.filename,buffer:state.input.slice(0,-1),position:state.position,line:state.line,column:state.position-state.lineStart};return mark.snippet=snippet(mark),new exception(message,mark)}function throwError(state,message){throw generateError(state,message)}function throwWarning(state,message){if(state.onWarning)state.onWarning.call(null,generateError(state,message))}function captureSegment(state,start,end,checkJson){var _position,_length,_character,_result;if(start<end){if(_result=state.input.slice(start,end),checkJson){for(_position=0,_length=_result.length;_position<_length;_position+=1)if(_character=_result.charCodeAt(_position),!(_character===9||32<=_character&&_character<=1114111))throwError(state,"expected valid JSON character")}else if(PATTERN_NON_PRINTABLE.test(_result))throwError(state,"the stream contains non-printable characters");state.result+=_result}}function mergeMappings(state,destination,source,overridableKeys){var sourceKeys,key,index,quantity;if(!common.isObject(source))throwError(state,"cannot merge mappings; the provided source object is unacceptable");sourceKeys=Object.keys(source);for(index=0,quantity=sourceKeys.length;index<quantity;index+=1)if(key=sourceKeys[index],!_hasOwnProperty$1.call(destination,key))setProperty(destination,key,source[key]),overridableKeys[key]=!0}function storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,startLine,startLineStart,startPos){var index,quantity;if(Array.isArray(keyNode)){keyNode=Array.prototype.slice.call(keyNode);for(index=0,quantity=keyNode.length;index<quantity;index+=1){if(Array.isArray(keyNode[index]))throwError(state,"nested arrays are not supported inside keys");if(typeof keyNode==="object"&&_class(keyNode[index])==="[object Object]")keyNode[index]="[object Object]"}}if(typeof keyNode==="object"&&_class(keyNode)==="[object Object]")keyNode="[object Object]";if(keyNode=String(keyNode),_result===null)_result={};if(keyTag==="tag:yaml.org,2002:merge")if(Array.isArray(valueNode))for(index=0,quantity=valueNode.length;index<quantity;index+=1)mergeMappings(state,_result,valueNode[index],overridableKeys);else mergeMappings(state,_result,valueNode,overridableKeys);else{if(!state.json&&!_hasOwnProperty$1.call(overridableKeys,keyNode)&&_hasOwnProperty$1.call(_result,keyNode))state.line=startLine||state.line,state.lineStart=startLineStart||state.lineStart,state.position=startPos||state.position,throwError(state,"duplicated mapping key");setProperty(_result,keyNode,valueNode),delete overridableKeys[keyNode]}return _result}function readLineBreak(state){var ch=state.input.charCodeAt(state.position);if(ch===10)state.position++;else if(ch===13){if(state.position++,state.input.charCodeAt(state.position)===10)state.position++}else throwError(state,"a line break is expected");state.line+=1,state.lineStart=state.position,state.firstTabInLine=-1}function skipSeparationSpace(state,allowComments,checkIndent){var lineBreaks=0,ch=state.input.charCodeAt(state.position);while(ch!==0){while(is_WHITE_SPACE(ch)){if(ch===9&&state.firstTabInLine===-1)state.firstTabInLine=state.position;ch=state.input.charCodeAt(++state.position)}if(allowComments&&ch===35)do ch=state.input.charCodeAt(++state.position);while(ch!==10&&ch!==13&&ch!==0);if(is_EOL(ch)){readLineBreak(state),ch=state.input.charCodeAt(state.position),lineBreaks++,state.lineIndent=0;while(ch===32)state.lineIndent++,ch=state.input.charCodeAt(++state.position)}else break}if(checkIndent!==-1&&lineBreaks!==0&&state.lineIndent<checkIndent)throwWarning(state,"deficient indentation");return lineBreaks}function testDocumentSeparator(state){var _position=state.position,ch;if(ch=state.input.charCodeAt(_position),(ch===45||ch===46)&&ch===state.input.charCodeAt(_position+1)&&ch===state.input.charCodeAt(_position+2)){if(_position+=3,ch=state.input.charCodeAt(_position),ch===0||is_WS_OR_EOL(ch))return!0}return!1}function writeFoldedLines(state,count){if(count===1)state.result+=" ";else if(count>1)state.result+=common.repeat(`
|
|
118
|
+
`,count-1)}function readPlainScalar(state,nodeIndent,withinFlowCollection){var preceding,following,captureStart,captureEnd,hasPendingContent,_line,_lineStart,_lineIndent,_kind=state.kind,_result=state.result,ch;if(ch=state.input.charCodeAt(state.position),is_WS_OR_EOL(ch)||is_FLOW_INDICATOR(ch)||ch===35||ch===38||ch===42||ch===33||ch===124||ch===62||ch===39||ch===34||ch===37||ch===64||ch===96)return!1;if(ch===63||ch===45){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)||withinFlowCollection&&is_FLOW_INDICATOR(following))return!1}state.kind="scalar",state.result="",captureStart=captureEnd=state.position,hasPendingContent=!1;while(ch!==0){if(ch===58){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)||withinFlowCollection&&is_FLOW_INDICATOR(following))break}else if(ch===35){if(preceding=state.input.charCodeAt(state.position-1),is_WS_OR_EOL(preceding))break}else if(state.position===state.lineStart&&testDocumentSeparator(state)||withinFlowCollection&&is_FLOW_INDICATOR(ch))break;else if(is_EOL(ch))if(_line=state.line,_lineStart=state.lineStart,_lineIndent=state.lineIndent,skipSeparationSpace(state,!1,-1),state.lineIndent>=nodeIndent){hasPendingContent=!0,ch=state.input.charCodeAt(state.position);continue}else{state.position=captureEnd,state.line=_line,state.lineStart=_lineStart,state.lineIndent=_lineIndent;break}if(hasPendingContent)captureSegment(state,captureStart,captureEnd,!1),writeFoldedLines(state,state.line-_line),captureStart=captureEnd=state.position,hasPendingContent=!1;if(!is_WHITE_SPACE(ch))captureEnd=state.position+1;ch=state.input.charCodeAt(++state.position)}if(captureSegment(state,captureStart,captureEnd,!1),state.result)return!0;return state.kind=_kind,state.result=_result,!1}function readSingleQuotedScalar(state,nodeIndent){var ch,captureStart,captureEnd;if(ch=state.input.charCodeAt(state.position),ch!==39)return!1;state.kind="scalar",state.result="",state.position++,captureStart=captureEnd=state.position;while((ch=state.input.charCodeAt(state.position))!==0)if(ch===39)if(captureSegment(state,captureStart,state.position,!0),ch=state.input.charCodeAt(++state.position),ch===39)captureStart=state.position,state.position++,captureEnd=state.position;else return!0;else if(is_EOL(ch))captureSegment(state,captureStart,captureEnd,!0),writeFoldedLines(state,skipSeparationSpace(state,!1,nodeIndent)),captureStart=captureEnd=state.position;else if(state.position===state.lineStart&&testDocumentSeparator(state))throwError(state,"unexpected end of the document within a single quoted scalar");else state.position++,captureEnd=state.position;throwError(state,"unexpected end of the stream within a single quoted scalar")}function readDoubleQuotedScalar(state,nodeIndent){var captureStart,captureEnd,hexLength,hexResult,tmp,ch;if(ch=state.input.charCodeAt(state.position),ch!==34)return!1;state.kind="scalar",state.result="",state.position++,captureStart=captureEnd=state.position;while((ch=state.input.charCodeAt(state.position))!==0)if(ch===34)return captureSegment(state,captureStart,state.position,!0),state.position++,!0;else if(ch===92){if(captureSegment(state,captureStart,state.position,!0),ch=state.input.charCodeAt(++state.position),is_EOL(ch))skipSeparationSpace(state,!1,nodeIndent);else if(ch<256&&simpleEscapeCheck[ch])state.result+=simpleEscapeMap[ch],state.position++;else if((tmp=escapedHexLen(ch))>0){hexLength=tmp,hexResult=0;for(;hexLength>0;hexLength--)if(ch=state.input.charCodeAt(++state.position),(tmp=fromHexCode(ch))>=0)hexResult=(hexResult<<4)+tmp;else throwError(state,"expected hexadecimal character");state.result+=charFromCodepoint(hexResult),state.position++}else throwError(state,"unknown escape sequence");captureStart=captureEnd=state.position}else if(is_EOL(ch))captureSegment(state,captureStart,captureEnd,!0),writeFoldedLines(state,skipSeparationSpace(state,!1,nodeIndent)),captureStart=captureEnd=state.position;else if(state.position===state.lineStart&&testDocumentSeparator(state))throwError(state,"unexpected end of the document within a double quoted scalar");else state.position++,captureEnd=state.position;throwError(state,"unexpected end of the stream within a double quoted scalar")}function readFlowCollection(state,nodeIndent){var readNext=!0,_line,_lineStart,_pos,_tag=state.tag,_result,_anchor=state.anchor,following,terminator,isPair,isExplicitPair,isMapping,overridableKeys=Object.create(null),keyNode,keyTag,valueNode,ch;if(ch=state.input.charCodeAt(state.position),ch===91)terminator=93,isMapping=!1,_result=[];else if(ch===123)terminator=125,isMapping=!0,_result={};else return!1;if(state.anchor!==null)state.anchorMap[state.anchor]=_result;ch=state.input.charCodeAt(++state.position);while(ch!==0){if(skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),ch===terminator)return state.position++,state.tag=_tag,state.anchor=_anchor,state.kind=isMapping?"mapping":"sequence",state.result=_result,!0;else if(!readNext)throwError(state,"missed comma between flow collection entries");else if(ch===44)throwError(state,"expected the node content, but found ','");if(keyTag=keyNode=valueNode=null,isPair=isExplicitPair=!1,ch===63){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following))isPair=isExplicitPair=!0,state.position++,skipSeparationSpace(state,!0,nodeIndent)}if(_line=state.line,_lineStart=state.lineStart,_pos=state.position,composeNode(state,nodeIndent,CONTEXT_FLOW_IN,!1,!0),keyTag=state.tag,keyNode=state.result,skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),(isExplicitPair||state.line===_line)&&ch===58)isPair=!0,ch=state.input.charCodeAt(++state.position),skipSeparationSpace(state,!0,nodeIndent),composeNode(state,nodeIndent,CONTEXT_FLOW_IN,!1,!0),valueNode=state.result;if(isMapping)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,_line,_lineStart,_pos);else if(isPair)_result.push(storeMappingPair(state,null,overridableKeys,keyTag,keyNode,valueNode,_line,_lineStart,_pos));else _result.push(keyNode);if(skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),ch===44)readNext=!0,ch=state.input.charCodeAt(++state.position);else readNext=!1}throwError(state,"unexpected end of the stream within a flow collection")}function readBlockScalar(state,nodeIndent){var captureStart,folding,chomping=CHOMPING_CLIP,didReadContent=!1,detectedIndent=!1,textIndent=nodeIndent,emptyLines=0,atMoreIndented=!1,tmp,ch;if(ch=state.input.charCodeAt(state.position),ch===124)folding=!1;else if(ch===62)folding=!0;else return!1;state.kind="scalar",state.result="";while(ch!==0)if(ch=state.input.charCodeAt(++state.position),ch===43||ch===45)if(CHOMPING_CLIP===chomping)chomping=ch===43?CHOMPING_KEEP:CHOMPING_STRIP;else throwError(state,"repeat of a chomping mode identifier");else if((tmp=fromDecimalCode(ch))>=0)if(tmp===0)throwError(state,"bad explicit indentation width of a block scalar; it cannot be less than one");else if(!detectedIndent)textIndent=nodeIndent+tmp-1,detectedIndent=!0;else throwError(state,"repeat of an indentation width identifier");else break;if(is_WHITE_SPACE(ch)){do ch=state.input.charCodeAt(++state.position);while(is_WHITE_SPACE(ch));if(ch===35)do ch=state.input.charCodeAt(++state.position);while(!is_EOL(ch)&&ch!==0)}while(ch!==0){readLineBreak(state),state.lineIndent=0,ch=state.input.charCodeAt(state.position);while((!detectedIndent||state.lineIndent<textIndent)&&ch===32)state.lineIndent++,ch=state.input.charCodeAt(++state.position);if(!detectedIndent&&state.lineIndent>textIndent)textIndent=state.lineIndent;if(is_EOL(ch)){emptyLines++;continue}if(state.lineIndent<textIndent){if(chomping===CHOMPING_KEEP)state.result+=common.repeat(`
|
|
119
|
+
`,didReadContent?1+emptyLines:emptyLines);else if(chomping===CHOMPING_CLIP){if(didReadContent)state.result+=`
|
|
120
|
+
`}break}if(folding)if(is_WHITE_SPACE(ch))atMoreIndented=!0,state.result+=common.repeat(`
|
|
121
|
+
`,didReadContent?1+emptyLines:emptyLines);else if(atMoreIndented)atMoreIndented=!1,state.result+=common.repeat(`
|
|
122
|
+
`,emptyLines+1);else if(emptyLines===0){if(didReadContent)state.result+=" "}else state.result+=common.repeat(`
|
|
123
|
+
`,emptyLines);else state.result+=common.repeat(`
|
|
124
|
+
`,didReadContent?1+emptyLines:emptyLines);didReadContent=!0,detectedIndent=!0,emptyLines=0,captureStart=state.position;while(!is_EOL(ch)&&ch!==0)ch=state.input.charCodeAt(++state.position);captureSegment(state,captureStart,state.position,!1)}return!0}function readBlockSequence(state,nodeIndent){var _line,_tag=state.tag,_anchor=state.anchor,_result=[],following,detected=!1,ch;if(state.firstTabInLine!==-1)return!1;if(state.anchor!==null)state.anchorMap[state.anchor]=_result;ch=state.input.charCodeAt(state.position);while(ch!==0){if(state.firstTabInLine!==-1)state.position=state.firstTabInLine,throwError(state,"tab characters must not be used in indentation");if(ch!==45)break;if(following=state.input.charCodeAt(state.position+1),!is_WS_OR_EOL(following))break;if(detected=!0,state.position++,skipSeparationSpace(state,!0,-1)){if(state.lineIndent<=nodeIndent){_result.push(null),ch=state.input.charCodeAt(state.position);continue}}if(_line=state.line,composeNode(state,nodeIndent,CONTEXT_BLOCK_IN,!1,!0),_result.push(state.result),skipSeparationSpace(state,!0,-1),ch=state.input.charCodeAt(state.position),(state.line===_line||state.lineIndent>nodeIndent)&&ch!==0)throwError(state,"bad indentation of a sequence entry");else if(state.lineIndent<nodeIndent)break}if(detected)return state.tag=_tag,state.anchor=_anchor,state.kind="sequence",state.result=_result,!0;return!1}function readBlockMapping(state,nodeIndent,flowIndent){var following,allowCompact,_line,_keyLine,_keyLineStart,_keyPos,_tag=state.tag,_anchor=state.anchor,_result={},overridableKeys=Object.create(null),keyTag=null,keyNode=null,valueNode=null,atExplicitKey=!1,detected=!1,ch;if(state.firstTabInLine!==-1)return!1;if(state.anchor!==null)state.anchorMap[state.anchor]=_result;ch=state.input.charCodeAt(state.position);while(ch!==0){if(!atExplicitKey&&state.firstTabInLine!==-1)state.position=state.firstTabInLine,throwError(state,"tab characters must not be used in indentation");if(following=state.input.charCodeAt(state.position+1),_line=state.line,(ch===63||ch===58)&&is_WS_OR_EOL(following)){if(ch===63){if(atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,null,_keyLine,_keyLineStart,_keyPos),keyTag=keyNode=valueNode=null;detected=!0,atExplicitKey=!0,allowCompact=!0}else if(atExplicitKey)atExplicitKey=!1,allowCompact=!0;else throwError(state,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");state.position+=1,ch=following}else{if(_keyLine=state.line,_keyLineStart=state.lineStart,_keyPos=state.position,!composeNode(state,flowIndent,CONTEXT_FLOW_OUT,!1,!0))break;if(state.line===_line){ch=state.input.charCodeAt(state.position);while(is_WHITE_SPACE(ch))ch=state.input.charCodeAt(++state.position);if(ch===58){if(ch=state.input.charCodeAt(++state.position),!is_WS_OR_EOL(ch))throwError(state,"a whitespace character is expected after the key-value separator within a block mapping");if(atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,null,_keyLine,_keyLineStart,_keyPos),keyTag=keyNode=valueNode=null;detected=!0,atExplicitKey=!1,allowCompact=!1,keyTag=state.tag,keyNode=state.result}else if(detected)throwError(state,"can not read an implicit mapping pair; a colon is missed");else return state.tag=_tag,state.anchor=_anchor,!0}else if(detected)throwError(state,"can not read a block mapping entry; a multiline key may not be an implicit key");else return state.tag=_tag,state.anchor=_anchor,!0}if(state.line===_line||state.lineIndent>nodeIndent){if(atExplicitKey)_keyLine=state.line,_keyLineStart=state.lineStart,_keyPos=state.position;if(composeNode(state,nodeIndent,CONTEXT_BLOCK_OUT,!0,allowCompact))if(atExplicitKey)keyNode=state.result;else valueNode=state.result;if(!atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,_keyLine,_keyLineStart,_keyPos),keyTag=keyNode=valueNode=null;skipSeparationSpace(state,!0,-1),ch=state.input.charCodeAt(state.position)}if((state.line===_line||state.lineIndent>nodeIndent)&&ch!==0)throwError(state,"bad indentation of a mapping entry");else if(state.lineIndent<nodeIndent)break}if(atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,null,_keyLine,_keyLineStart,_keyPos);if(detected)state.tag=_tag,state.anchor=_anchor,state.kind="mapping",state.result=_result;return detected}function readTagProperty(state){var _position,isVerbatim=!1,isNamed=!1,tagHandle,tagName,ch;if(ch=state.input.charCodeAt(state.position),ch!==33)return!1;if(state.tag!==null)throwError(state,"duplication of a tag property");if(ch=state.input.charCodeAt(++state.position),ch===60)isVerbatim=!0,ch=state.input.charCodeAt(++state.position);else if(ch===33)isNamed=!0,tagHandle="!!",ch=state.input.charCodeAt(++state.position);else tagHandle="!";if(_position=state.position,isVerbatim){do ch=state.input.charCodeAt(++state.position);while(ch!==0&&ch!==62);if(state.position<state.length)tagName=state.input.slice(_position,state.position),ch=state.input.charCodeAt(++state.position);else throwError(state,"unexpected end of the stream within a verbatim tag")}else{while(ch!==0&&!is_WS_OR_EOL(ch)){if(ch===33)if(!isNamed){if(tagHandle=state.input.slice(_position-1,state.position+1),!PATTERN_TAG_HANDLE.test(tagHandle))throwError(state,"named tag handle cannot contain such characters");isNamed=!0,_position=state.position+1}else throwError(state,"tag suffix cannot contain exclamation marks");ch=state.input.charCodeAt(++state.position)}if(tagName=state.input.slice(_position,state.position),PATTERN_FLOW_INDICATORS.test(tagName))throwError(state,"tag suffix cannot contain flow indicator characters")}if(tagName&&!PATTERN_TAG_URI.test(tagName))throwError(state,"tag name cannot contain such characters: "+tagName);try{tagName=decodeURIComponent(tagName)}catch(err){throwError(state,"tag name is malformed: "+tagName)}if(isVerbatim)state.tag=tagName;else if(_hasOwnProperty$1.call(state.tagMap,tagHandle))state.tag=state.tagMap[tagHandle]+tagName;else if(tagHandle==="!")state.tag="!"+tagName;else if(tagHandle==="!!")state.tag="tag:yaml.org,2002:"+tagName;else throwError(state,'undeclared tag handle "'+tagHandle+'"');return!0}function readAnchorProperty(state){var _position,ch;if(ch=state.input.charCodeAt(state.position),ch!==38)return!1;if(state.anchor!==null)throwError(state,"duplication of an anchor property");ch=state.input.charCodeAt(++state.position),_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch)&&!is_FLOW_INDICATOR(ch))ch=state.input.charCodeAt(++state.position);if(state.position===_position)throwError(state,"name of an anchor node must contain at least one character");return state.anchor=state.input.slice(_position,state.position),!0}function readAlias(state){var _position,alias,ch;if(ch=state.input.charCodeAt(state.position),ch!==42)return!1;ch=state.input.charCodeAt(++state.position),_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch)&&!is_FLOW_INDICATOR(ch))ch=state.input.charCodeAt(++state.position);if(state.position===_position)throwError(state,"name of an alias node must contain at least one character");if(alias=state.input.slice(_position,state.position),!_hasOwnProperty$1.call(state.anchorMap,alias))throwError(state,'unidentified alias "'+alias+'"');return state.result=state.anchorMap[alias],skipSeparationSpace(state,!0,-1),!0}function composeNode(state,parentIndent,nodeContext,allowToSeek,allowCompact){var allowBlockStyles,allowBlockScalars,allowBlockCollections,indentStatus=1,atNewLine=!1,hasContent=!1,typeIndex,typeQuantity,typeList,type2,flowIndent,blockIndent;if(state.listener!==null)state.listener("open",state);if(state.tag=null,state.anchor=null,state.kind=null,state.result=null,allowBlockStyles=allowBlockScalars=allowBlockCollections=CONTEXT_BLOCK_OUT===nodeContext||CONTEXT_BLOCK_IN===nodeContext,allowToSeek){if(skipSeparationSpace(state,!0,-1)){if(atNewLine=!0,state.lineIndent>parentIndent)indentStatus=1;else if(state.lineIndent===parentIndent)indentStatus=0;else if(state.lineIndent<parentIndent)indentStatus=-1}}if(indentStatus===1)while(readTagProperty(state)||readAnchorProperty(state))if(skipSeparationSpace(state,!0,-1)){if(atNewLine=!0,allowBlockCollections=allowBlockStyles,state.lineIndent>parentIndent)indentStatus=1;else if(state.lineIndent===parentIndent)indentStatus=0;else if(state.lineIndent<parentIndent)indentStatus=-1}else allowBlockCollections=!1;if(allowBlockCollections)allowBlockCollections=atNewLine||allowCompact;if(indentStatus===1||CONTEXT_BLOCK_OUT===nodeContext){if(CONTEXT_FLOW_IN===nodeContext||CONTEXT_FLOW_OUT===nodeContext)flowIndent=parentIndent;else flowIndent=parentIndent+1;if(blockIndent=state.position-state.lineStart,indentStatus===1)if(allowBlockCollections&&(readBlockSequence(state,blockIndent)||readBlockMapping(state,blockIndent,flowIndent))||readFlowCollection(state,flowIndent))hasContent=!0;else{if(allowBlockScalars&&readBlockScalar(state,flowIndent)||readSingleQuotedScalar(state,flowIndent)||readDoubleQuotedScalar(state,flowIndent))hasContent=!0;else if(readAlias(state)){if(hasContent=!0,state.tag!==null||state.anchor!==null)throwError(state,"alias node should not have any properties")}else if(readPlainScalar(state,flowIndent,CONTEXT_FLOW_IN===nodeContext)){if(hasContent=!0,state.tag===null)state.tag="?"}if(state.anchor!==null)state.anchorMap[state.anchor]=state.result}else if(indentStatus===0)hasContent=allowBlockCollections&&readBlockSequence(state,blockIndent)}if(state.tag===null){if(state.anchor!==null)state.anchorMap[state.anchor]=state.result}else if(state.tag==="?"){if(state.result!==null&&state.kind!=="scalar")throwError(state,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+state.kind+'"');for(typeIndex=0,typeQuantity=state.implicitTypes.length;typeIndex<typeQuantity;typeIndex+=1)if(type2=state.implicitTypes[typeIndex],type2.resolve(state.result)){if(state.result=type2.construct(state.result),state.tag=type2.tag,state.anchor!==null)state.anchorMap[state.anchor]=state.result;break}}else if(state.tag!=="!"){if(_hasOwnProperty$1.call(state.typeMap[state.kind||"fallback"],state.tag))type2=state.typeMap[state.kind||"fallback"][state.tag];else{type2=null,typeList=state.typeMap.multi[state.kind||"fallback"];for(typeIndex=0,typeQuantity=typeList.length;typeIndex<typeQuantity;typeIndex+=1)if(state.tag.slice(0,typeList[typeIndex].tag.length)===typeList[typeIndex].tag){type2=typeList[typeIndex];break}}if(!type2)throwError(state,"unknown tag !<"+state.tag+">");if(state.result!==null&&type2.kind!==state.kind)throwError(state,"unacceptable node kind for !<"+state.tag+'> tag; it should be "'+type2.kind+'", not "'+state.kind+'"');if(!type2.resolve(state.result,state.tag))throwError(state,"cannot resolve a node with !<"+state.tag+"> explicit tag");else if(state.result=type2.construct(state.result,state.tag),state.anchor!==null)state.anchorMap[state.anchor]=state.result}if(state.listener!==null)state.listener("close",state);return state.tag!==null||state.anchor!==null||hasContent}function readDocument(state){var documentStart=state.position,_position,directiveName,directiveArgs,hasDirectives=!1,ch;state.version=null,state.checkLineBreaks=state.legacy,state.tagMap=Object.create(null),state.anchorMap=Object.create(null);while((ch=state.input.charCodeAt(state.position))!==0){if(skipSeparationSpace(state,!0,-1),ch=state.input.charCodeAt(state.position),state.lineIndent>0||ch!==37)break;hasDirectives=!0,ch=state.input.charCodeAt(++state.position),_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch))ch=state.input.charCodeAt(++state.position);if(directiveName=state.input.slice(_position,state.position),directiveArgs=[],directiveName.length<1)throwError(state,"directive name must not be less than one character in length");while(ch!==0){while(is_WHITE_SPACE(ch))ch=state.input.charCodeAt(++state.position);if(ch===35){do ch=state.input.charCodeAt(++state.position);while(ch!==0&&!is_EOL(ch));break}if(is_EOL(ch))break;_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch))ch=state.input.charCodeAt(++state.position);directiveArgs.push(state.input.slice(_position,state.position))}if(ch!==0)readLineBreak(state);if(_hasOwnProperty$1.call(directiveHandlers,directiveName))directiveHandlers[directiveName](state,directiveName,directiveArgs);else throwWarning(state,'unknown document directive "'+directiveName+'"')}if(skipSeparationSpace(state,!0,-1),state.lineIndent===0&&state.input.charCodeAt(state.position)===45&&state.input.charCodeAt(state.position+1)===45&&state.input.charCodeAt(state.position+2)===45)state.position+=3,skipSeparationSpace(state,!0,-1);else if(hasDirectives)throwError(state,"directives end mark is expected");if(composeNode(state,state.lineIndent-1,CONTEXT_BLOCK_OUT,!1,!0),skipSeparationSpace(state,!0,-1),state.checkLineBreaks&&PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart,state.position)))throwWarning(state,"non-ASCII line breaks are interpreted as content");if(state.documents.push(state.result),state.position===state.lineStart&&testDocumentSeparator(state)){if(state.input.charCodeAt(state.position)===46)state.position+=3,skipSeparationSpace(state,!0,-1);return}if(state.position<state.length-1)throwError(state,"end of the stream or a document separator is expected");else return}function loadDocuments(input,options){if(input=String(input),options=options||{},input.length!==0){if(input.charCodeAt(input.length-1)!==10&&input.charCodeAt(input.length-1)!==13)input+=`
|
|
125
|
+
`;if(input.charCodeAt(0)===65279)input=input.slice(1)}var state=new State$1(input,options),nullpos=input.indexOf("\x00");if(nullpos!==-1)state.position=nullpos,throwError(state,"null byte is not allowed in input");state.input+="\x00";while(state.input.charCodeAt(state.position)===32)state.lineIndent+=1,state.position+=1;while(state.position<state.length-1)readDocument(state);return state.documents}function loadAll$1(input,iterator,options){if(iterator!==null&&typeof iterator==="object"&&typeof options>"u")options=iterator,iterator=null;var documents=loadDocuments(input,options);if(typeof iterator!=="function")return documents;for(var index=0,length=documents.length;index<length;index+=1)iterator(documents[index])}function load$1(input,options){var documents=loadDocuments(input,options);if(documents.length===0)return;else if(documents.length===1)return documents[0];throw new exception("expected a single document in the stream, but found more")}function compileStyleMap(schema2,map2){var result2,keys,index,length,tag,style,type2;if(map2===null)return{};result2={},keys=Object.keys(map2);for(index=0,length=keys.length;index<length;index+=1){if(tag=keys[index],style=String(map2[tag]),tag.slice(0,2)==="!!")tag="tag:yaml.org,2002:"+tag.slice(2);if(type2=schema2.compiledTypeMap.fallback[tag],type2&&_hasOwnProperty.call(type2.styleAliases,style))style=type2.styleAliases[style];result2[tag]=style}return result2}function encodeHex(character){var string,handle,length;if(string=character.toString(16).toUpperCase(),character<=255)handle="x",length=2;else if(character<=65535)handle="u",length=4;else if(character<=4294967295)handle="U",length=8;else throw new exception("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+handle+common.repeat("0",length-string.length)+string}function State(options){this.schema=options.schema||_default,this.indent=Math.max(1,options.indent||2),this.noArrayIndent=options.noArrayIndent||!1,this.skipInvalid=options.skipInvalid||!1,this.flowLevel=common.isNothing(options.flowLevel)?-1:options.flowLevel,this.styleMap=compileStyleMap(this.schema,options.styles||null),this.sortKeys=options.sortKeys||!1,this.lineWidth=options.lineWidth||80,this.noRefs=options.noRefs||!1,this.noCompatMode=options.noCompatMode||!1,this.condenseFlow=options.condenseFlow||!1,this.quotingType=options.quotingType==='"'?QUOTING_TYPE_DOUBLE:QUOTING_TYPE_SINGLE,this.forceQuotes=options.forceQuotes||!1,this.replacer=typeof options.replacer==="function"?options.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function indentString(string,spaces){var ind=common.repeat(" ",spaces),position=0,next=-1,result2="",line,length=string.length;while(position<length){if(next=string.indexOf(`
|
|
126
|
+
`,position),next===-1)line=string.slice(position),position=length;else line=string.slice(position,next+1),position=next+1;if(line.length&&line!==`
|
|
127
|
+
`)result2+=ind;result2+=line}return result2}function generateNextLine(state,level){return`
|
|
128
|
+
`+common.repeat(" ",state.indent*level)}function testImplicitResolving(state,str2){var index,length,type2;for(index=0,length=state.implicitTypes.length;index<length;index+=1)if(type2=state.implicitTypes[index],type2.resolve(str2))return!0;return!1}function isWhitespace(c){return c===CHAR_SPACE||c===CHAR_TAB}function isPrintable(c){return 32<=c&&c<=126||161<=c&&c<=55295&&c!==8232&&c!==8233||57344<=c&&c<=65533&&c!==CHAR_BOM||65536<=c&&c<=1114111}function isNsCharOrWhitespace(c){return isPrintable(c)&&c!==CHAR_BOM&&c!==CHAR_CARRIAGE_RETURN&&c!==CHAR_LINE_FEED}function isPlainSafe(c,prev,inblock){var cIsNsCharOrWhitespace=isNsCharOrWhitespace(c),cIsNsChar=cIsNsCharOrWhitespace&&!isWhitespace(c);return(inblock?cIsNsCharOrWhitespace:cIsNsCharOrWhitespace&&c!==CHAR_COMMA&&c!==CHAR_LEFT_SQUARE_BRACKET&&c!==CHAR_RIGHT_SQUARE_BRACKET&&c!==CHAR_LEFT_CURLY_BRACKET&&c!==CHAR_RIGHT_CURLY_BRACKET)&&c!==CHAR_SHARP&&!(prev===CHAR_COLON&&!cIsNsChar)||isNsCharOrWhitespace(prev)&&!isWhitespace(prev)&&c===CHAR_SHARP||prev===CHAR_COLON&&cIsNsChar}function isPlainSafeFirst(c){return isPrintable(c)&&c!==CHAR_BOM&&!isWhitespace(c)&&c!==CHAR_MINUS&&c!==CHAR_QUESTION&&c!==CHAR_COLON&&c!==CHAR_COMMA&&c!==CHAR_LEFT_SQUARE_BRACKET&&c!==CHAR_RIGHT_SQUARE_BRACKET&&c!==CHAR_LEFT_CURLY_BRACKET&&c!==CHAR_RIGHT_CURLY_BRACKET&&c!==CHAR_SHARP&&c!==CHAR_AMPERSAND&&c!==CHAR_ASTERISK&&c!==CHAR_EXCLAMATION&&c!==CHAR_VERTICAL_LINE&&c!==CHAR_EQUALS&&c!==CHAR_GREATER_THAN&&c!==CHAR_SINGLE_QUOTE&&c!==CHAR_DOUBLE_QUOTE&&c!==CHAR_PERCENT&&c!==CHAR_COMMERCIAL_AT&&c!==CHAR_GRAVE_ACCENT}function isPlainSafeLast(c){return!isWhitespace(c)&&c!==CHAR_COLON}function codePointAt(string,pos){var first=string.charCodeAt(pos),second;if(first>=55296&&first<=56319&&pos+1<string.length){if(second=string.charCodeAt(pos+1),second>=56320&&second<=57343)return(first-55296)*1024+second-56320+65536}return first}function needIndentIndicator(string){var leadingSpaceRe=/^\n* /;return leadingSpaceRe.test(string)}function chooseScalarStyle(string,singleLineOnly,indentPerLevel,lineWidth,testAmbiguousType,quotingType,forceQuotes,inblock){var i2,char=0,prevChar=null,hasLineBreak=!1,hasFoldableLine=!1,shouldTrackWidth=lineWidth!==-1,previousLineBreak=-1,plain=isPlainSafeFirst(codePointAt(string,0))&&isPlainSafeLast(codePointAt(string,string.length-1));if(singleLineOnly||forceQuotes)for(i2=0;i2<string.length;char>=65536?i2+=2:i2++){if(char=codePointAt(string,i2),!isPrintable(char))return STYLE_DOUBLE;plain=plain&&isPlainSafe(char,prevChar,inblock),prevChar=char}else{for(i2=0;i2<string.length;char>=65536?i2+=2:i2++){if(char=codePointAt(string,i2),char===CHAR_LINE_FEED){if(hasLineBreak=!0,shouldTrackWidth)hasFoldableLine=hasFoldableLine||i2-previousLineBreak-1>lineWidth&&string[previousLineBreak+1]!==" ",previousLineBreak=i2}else if(!isPrintable(char))return STYLE_DOUBLE;plain=plain&&isPlainSafe(char,prevChar,inblock),prevChar=char}hasFoldableLine=hasFoldableLine||shouldTrackWidth&&(i2-previousLineBreak-1>lineWidth&&string[previousLineBreak+1]!==" ")}if(!hasLineBreak&&!hasFoldableLine){if(plain&&!forceQuotes&&!testAmbiguousType(string))return STYLE_PLAIN;return quotingType===QUOTING_TYPE_DOUBLE?STYLE_DOUBLE:STYLE_SINGLE}if(indentPerLevel>9&&needIndentIndicator(string))return STYLE_DOUBLE;if(!forceQuotes)return hasFoldableLine?STYLE_FOLDED:STYLE_LITERAL;return quotingType===QUOTING_TYPE_DOUBLE?STYLE_DOUBLE:STYLE_SINGLE}function writeScalar(state,string,level,iskey,inblock){state.dump=function(){if(string.length===0)return state.quotingType===QUOTING_TYPE_DOUBLE?'""':"''";if(!state.noCompatMode){if(DEPRECATED_BOOLEANS_SYNTAX.indexOf(string)!==-1||DEPRECATED_BASE60_SYNTAX.test(string))return state.quotingType===QUOTING_TYPE_DOUBLE?'"'+string+'"':"'"+string+"'"}var indent=state.indent*Math.max(1,level),lineWidth=state.lineWidth===-1?-1:Math.max(Math.min(state.lineWidth,40),state.lineWidth-indent),singleLineOnly=iskey||state.flowLevel>-1&&level>=state.flowLevel;function testAmbiguity(string2){return testImplicitResolving(state,string2)}switch(chooseScalarStyle(string,singleLineOnly,state.indent,lineWidth,testAmbiguity,state.quotingType,state.forceQuotes&&!iskey,inblock)){case STYLE_PLAIN:return string;case STYLE_SINGLE:return"'"+string.replace(/'/g,"''")+"'";case STYLE_LITERAL:return"|"+blockHeader(string,state.indent)+dropEndingNewline(indentString(string,indent));case STYLE_FOLDED:return">"+blockHeader(string,state.indent)+dropEndingNewline(indentString(foldString(string,lineWidth),indent));case STYLE_DOUBLE:return'"'+escapeString(string)+'"';default:throw new exception("impossible error: invalid scalar style")}}()}function blockHeader(string,indentPerLevel){var indentIndicator=needIndentIndicator(string)?String(indentPerLevel):"",clip=string[string.length-1]===`
|
|
129
|
+
`,keep=clip&&(string[string.length-2]===`
|
|
130
|
+
`||string===`
|
|
131
|
+
`),chomp=keep?"+":clip?"":"-";return indentIndicator+chomp+`
|
|
132
|
+
`}function dropEndingNewline(string){return string[string.length-1]===`
|
|
133
|
+
`?string.slice(0,-1):string}function foldString(string,width){var lineRe=/(\n+)([^\n]*)/g,result2=function(){var nextLF=string.indexOf(`
|
|
134
|
+
`);return nextLF=nextLF!==-1?nextLF:string.length,lineRe.lastIndex=nextLF,foldLine(string.slice(0,nextLF),width)}(),prevMoreIndented=string[0]===`
|
|
135
|
+
`||string[0]===" ",moreIndented,match;while(match=lineRe.exec(string)){var prefix=match[1],line=match[2];moreIndented=line[0]===" ",result2+=prefix+(!prevMoreIndented&&!moreIndented&&line!==""?`
|
|
136
|
+
`:"")+foldLine(line,width),prevMoreIndented=moreIndented}return result2}function foldLine(line,width){if(line===""||line[0]===" ")return line;var breakRe=/ [^ ]/g,match,start=0,end,curr=0,next=0,result2="";while(match=breakRe.exec(line)){if(next=match.index,next-start>width)end=curr>start?curr:next,result2+=`
|
|
137
|
+
`+line.slice(start,end),start=end+1;curr=next}if(result2+=`
|
|
138
|
+
`,line.length-start>width&&curr>start)result2+=line.slice(start,curr)+`
|
|
139
|
+
`+line.slice(curr+1);else result2+=line.slice(start);return result2.slice(1)}function escapeString(string){var result2="",char=0,escapeSeq;for(var i2=0;i2<string.length;char>=65536?i2+=2:i2++)if(char=codePointAt(string,i2),escapeSeq=ESCAPE_SEQUENCES[char],!escapeSeq&&isPrintable(char)){if(result2+=string[i2],char>=65536)result2+=string[i2+1]}else result2+=escapeSeq||encodeHex(char);return result2}function writeFlowSequence(state,level,object){var _result="",_tag=state.tag,index,length,value;for(index=0,length=object.length;index<length;index+=1){if(value=object[index],state.replacer)value=state.replacer.call(object,String(index),value);if(writeNode(state,level,value,!1,!1)||typeof value>"u"&&writeNode(state,level,null,!1,!1)){if(_result!=="")_result+=","+(!state.condenseFlow?" ":"");_result+=state.dump}}state.tag=_tag,state.dump="["+_result+"]"}function writeBlockSequence(state,level,object,compact){var _result="",_tag=state.tag,index,length,value;for(index=0,length=object.length;index<length;index+=1){if(value=object[index],state.replacer)value=state.replacer.call(object,String(index),value);if(writeNode(state,level+1,value,!0,!0,!1,!0)||typeof value>"u"&&writeNode(state,level+1,null,!0,!0,!1,!0)){if(!compact||_result!=="")_result+=generateNextLine(state,level);if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))_result+="-";else _result+="- ";_result+=state.dump}}state.tag=_tag,state.dump=_result||"[]"}function writeFlowMapping(state,level,object){var _result="",_tag=state.tag,objectKeyList=Object.keys(object),index,length,objectKey,objectValue,pairBuffer;for(index=0,length=objectKeyList.length;index<length;index+=1){if(pairBuffer="",_result!=="")pairBuffer+=", ";if(state.condenseFlow)pairBuffer+='"';if(objectKey=objectKeyList[index],objectValue=object[objectKey],state.replacer)objectValue=state.replacer.call(object,objectKey,objectValue);if(!writeNode(state,level,objectKey,!1,!1))continue;if(state.dump.length>1024)pairBuffer+="? ";if(pairBuffer+=state.dump+(state.condenseFlow?'"':"")+":"+(state.condenseFlow?"":" "),!writeNode(state,level,objectValue,!1,!1))continue;pairBuffer+=state.dump,_result+=pairBuffer}state.tag=_tag,state.dump="{"+_result+"}"}function writeBlockMapping(state,level,object,compact){var _result="",_tag=state.tag,objectKeyList=Object.keys(object),index,length,objectKey,objectValue,explicitPair,pairBuffer;if(state.sortKeys===!0)objectKeyList.sort();else if(typeof state.sortKeys==="function")objectKeyList.sort(state.sortKeys);else if(state.sortKeys)throw new exception("sortKeys must be a boolean or a function");for(index=0,length=objectKeyList.length;index<length;index+=1){if(pairBuffer="",!compact||_result!=="")pairBuffer+=generateNextLine(state,level);if(objectKey=objectKeyList[index],objectValue=object[objectKey],state.replacer)objectValue=state.replacer.call(object,objectKey,objectValue);if(!writeNode(state,level+1,objectKey,!0,!0,!0))continue;if(explicitPair=state.tag!==null&&state.tag!=="?"||state.dump&&state.dump.length>1024,explicitPair)if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))pairBuffer+="?";else pairBuffer+="? ";if(pairBuffer+=state.dump,explicitPair)pairBuffer+=generateNextLine(state,level);if(!writeNode(state,level+1,objectValue,!0,explicitPair))continue;if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))pairBuffer+=":";else pairBuffer+=": ";pairBuffer+=state.dump,_result+=pairBuffer}state.tag=_tag,state.dump=_result||"{}"}function detectType(state,object,explicit){var _result,typeList,index,length,type2,style;typeList=explicit?state.explicitTypes:state.implicitTypes;for(index=0,length=typeList.length;index<length;index+=1)if(type2=typeList[index],(type2.instanceOf||type2.predicate)&&(!type2.instanceOf||typeof object==="object"&&object instanceof type2.instanceOf)&&(!type2.predicate||type2.predicate(object))){if(explicit)if(type2.multi&&type2.representName)state.tag=type2.representName(object);else state.tag=type2.tag;else state.tag="?";if(type2.represent){if(style=state.styleMap[type2.tag]||type2.defaultStyle,_toString.call(type2.represent)==="[object Function]")_result=type2.represent(object,style);else if(_hasOwnProperty.call(type2.represent,style))_result=type2.represent[style](object,style);else throw new exception("!<"+type2.tag+'> tag resolver accepts not "'+style+'" style');state.dump=_result}return!0}return!1}function writeNode(state,level,object,block,compact,iskey,isblockseq){if(state.tag=null,state.dump=object,!detectType(state,object,!1))detectType(state,object,!0);var type2=_toString.call(state.dump),inblock=block,tagStr;if(block)block=state.flowLevel<0||state.flowLevel>level;var objectOrArray=type2==="[object Object]"||type2==="[object Array]",duplicateIndex,duplicate;if(objectOrArray)duplicateIndex=state.duplicates.indexOf(object),duplicate=duplicateIndex!==-1;if(state.tag!==null&&state.tag!=="?"||duplicate||state.indent!==2&&level>0)compact=!1;if(duplicate&&state.usedDuplicates[duplicateIndex])state.dump="*ref_"+duplicateIndex;else{if(objectOrArray&&duplicate&&!state.usedDuplicates[duplicateIndex])state.usedDuplicates[duplicateIndex]=!0;if(type2==="[object Object]"){if(block&&Object.keys(state.dump).length!==0){if(writeBlockMapping(state,level,state.dump,compact),duplicate)state.dump="&ref_"+duplicateIndex+state.dump}else if(writeFlowMapping(state,level,state.dump),duplicate)state.dump="&ref_"+duplicateIndex+" "+state.dump}else if(type2==="[object Array]"){if(block&&state.dump.length!==0){if(state.noArrayIndent&&!isblockseq&&level>0)writeBlockSequence(state,level-1,state.dump,compact);else writeBlockSequence(state,level,state.dump,compact);if(duplicate)state.dump="&ref_"+duplicateIndex+state.dump}else if(writeFlowSequence(state,level,state.dump),duplicate)state.dump="&ref_"+duplicateIndex+" "+state.dump}else if(type2==="[object String]"){if(state.tag!=="?")writeScalar(state,state.dump,level,iskey,inblock)}else if(type2==="[object Undefined]")return!1;else{if(state.skipInvalid)return!1;throw new exception("unacceptable kind of an object to dump "+type2)}if(state.tag!==null&&state.tag!=="?"){if(tagStr=encodeURI(state.tag[0]==="!"?state.tag.slice(1):state.tag).replace(/!/g,"%21"),state.tag[0]==="!")tagStr="!"+tagStr;else if(tagStr.slice(0,18)==="tag:yaml.org,2002:")tagStr="!!"+tagStr.slice(18);else tagStr="!<"+tagStr+">";state.dump=tagStr+" "+state.dump}}return!0}function getDuplicateReferences(object,state){var objects=[],duplicatesIndexes=[],index,length;inspectNode(object,objects,duplicatesIndexes);for(index=0,length=duplicatesIndexes.length;index<length;index+=1)state.duplicates.push(objects[duplicatesIndexes[index]]);state.usedDuplicates=Array(length)}function inspectNode(object,objects,duplicatesIndexes){var objectKeyList,index,length;if(object!==null&&typeof object==="object")if(index=objects.indexOf(object),index!==-1){if(duplicatesIndexes.indexOf(index)===-1)duplicatesIndexes.push(index)}else if(objects.push(object),Array.isArray(object))for(index=0,length=object.length;index<length;index+=1)inspectNode(object[index],objects,duplicatesIndexes);else{objectKeyList=Object.keys(object);for(index=0,length=objectKeyList.length;index<length;index+=1)inspectNode(object[objectKeyList[index]],objects,duplicatesIndexes)}}function dump$1(input,options){options=options||{};var state=new State(options);if(!state.noRefs)getDuplicateReferences(input,state);var value=input;if(state.replacer)value=state.replacer.call({"":value},"",value);if(writeNode(state,0,value,!0,!0))return state.dump+`
|
|
140
|
+
`;return""}function renamed(from,to){return function(){throw Error("Function yaml."+from+" is removed in js-yaml 4. Use yaml."+to+" instead, which is now safe by default.")}}var isNothing_1,isObject_1,toArray_1,repeat_1,isNegativeZero_1,extend_1,common,exception,snippet,TYPE_CONSTRUCTOR_OPTIONS,YAML_NODE_KINDS,type,schema,str,seq,map,failsafe,_null,bool,int,YAML_FLOAT_PATTERN,SCIENTIFIC_WITHOUT_DOT,float,json,core,YAML_DATE_REGEXP,YAML_TIMESTAMP_REGEXP,timestamp,merge,BASE64_MAP=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
141
|
+
\r`,binary,_hasOwnProperty$3,_toString$2,omap,_toString$1,pairs,_hasOwnProperty$2,set,_default,_hasOwnProperty$1,CONTEXT_FLOW_IN=1,CONTEXT_FLOW_OUT=2,CONTEXT_BLOCK_IN=3,CONTEXT_BLOCK_OUT=4,CHOMPING_CLIP=1,CHOMPING_STRIP=2,CHOMPING_KEEP=3,PATTERN_NON_PRINTABLE,PATTERN_NON_ASCII_LINE_BREAKS,PATTERN_FLOW_INDICATORS,PATTERN_TAG_HANDLE,PATTERN_TAG_URI,simpleEscapeCheck,simpleEscapeMap,i,directiveHandlers,loadAll_1,load_1,loader,_toString,_hasOwnProperty,CHAR_BOM=65279,CHAR_TAB=9,CHAR_LINE_FEED=10,CHAR_CARRIAGE_RETURN=13,CHAR_SPACE=32,CHAR_EXCLAMATION=33,CHAR_DOUBLE_QUOTE=34,CHAR_SHARP=35,CHAR_PERCENT=37,CHAR_AMPERSAND=38,CHAR_SINGLE_QUOTE=39,CHAR_ASTERISK=42,CHAR_COMMA=44,CHAR_MINUS=45,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_GREATER_THAN=62,CHAR_QUESTION=63,CHAR_COMMERCIAL_AT=64,CHAR_LEFT_SQUARE_BRACKET=91,CHAR_RIGHT_SQUARE_BRACKET=93,CHAR_GRAVE_ACCENT=96,CHAR_LEFT_CURLY_BRACKET=123,CHAR_VERTICAL_LINE=124,CHAR_RIGHT_CURLY_BRACKET=125,ESCAPE_SEQUENCES,DEPRECATED_BOOLEANS_SYNTAX,DEPRECATED_BASE60_SYNTAX,QUOTING_TYPE_SINGLE=1,QUOTING_TYPE_DOUBLE=2,STYLE_PLAIN=1,STYLE_SINGLE=2,STYLE_LITERAL=3,STYLE_FOLDED=4,STYLE_DOUBLE=5,dump_1,dumper,Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load,loadAll,dump,YAMLException,types2,safeLoad,safeLoadAll,safeDump,jsYaml;var init_js_yaml=__esm(()=>{/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */isNothing_1=isNothing,isObject_1=isObject,toArray_1=toArray,repeat_1=repeat,isNegativeZero_1=isNegativeZero,extend_1=extend,common={isNothing:isNothing_1,isObject:isObject_1,toArray:toArray_1,repeat:repeat_1,isNegativeZero:isNegativeZero_1,extend:extend_1};YAMLException$1.prototype=Object.create(Error.prototype);YAMLException$1.prototype.constructor=YAMLException$1;YAMLException$1.prototype.toString=function(compact){return this.name+": "+formatError(this,compact)};exception=YAMLException$1;snippet=makeSnippet,TYPE_CONSTRUCTOR_OPTIONS=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],YAML_NODE_KINDS=["scalar","sequence","mapping"];type=Type$1;Schema$1.prototype.extend=function(definition){var implicit=[],explicit=[];if(definition instanceof type)explicit.push(definition);else if(Array.isArray(definition))explicit=explicit.concat(definition);else if(definition&&(Array.isArray(definition.implicit)||Array.isArray(definition.explicit))){if(definition.implicit)implicit=implicit.concat(definition.implicit);if(definition.explicit)explicit=explicit.concat(definition.explicit)}else throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");implicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(type$1.loadKind&&type$1.loadKind!=="scalar")throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(type$1.multi)throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),explicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var result2=Object.create(Schema$1.prototype);return result2.implicit=(this.implicit||[]).concat(implicit),result2.explicit=(this.explicit||[]).concat(explicit),result2.compiledImplicit=compileList(result2,"implicit"),result2.compiledExplicit=compileList(result2,"explicit"),result2.compiledTypeMap=compileMap(result2.compiledImplicit,result2.compiledExplicit),result2};schema=Schema$1,str=new type("tag:yaml.org,2002:str",{kind:"scalar",construct:function(data){return data!==null?data:""}}),seq=new type("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(data){return data!==null?data:[]}}),map=new type("tag:yaml.org,2002:map",{kind:"mapping",construct:function(data){return data!==null?data:{}}}),failsafe=new schema({explicit:[str,seq,map]});_null=new type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});bool=new type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:function(object){return object?"true":"false"},uppercase:function(object){return object?"TRUE":"FALSE"},camelcase:function(object){return object?"True":"False"}},defaultStyle:"lowercase"});int=new type("tag:yaml.org,2002:int",{kind:"scalar",resolve:resolveYamlInteger,construct:constructYamlInteger,predicate:isInteger,represent:{binary:function(obj){return obj>=0?"0b"+obj.toString(2):"-0b"+obj.toString(2).slice(1)},octal:function(obj){return obj>=0?"0o"+obj.toString(8):"-0o"+obj.toString(8).slice(1)},decimal:function(obj){return obj.toString(10)},hexadecimal:function(obj){return obj>=0?"0x"+obj.toString(16).toUpperCase():"-0x"+obj.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;float=new type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat,represent:representYamlFloat,defaultStyle:"lowercase"}),json=failsafe.extend({implicit:[_null,bool,int,float]}),core=json,YAML_DATE_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),YAML_TIMESTAMP_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");timestamp=new type("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:resolveYamlTimestamp,construct:constructYamlTimestamp,instanceOf:Date,represent:representYamlTimestamp});merge=new type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge});binary=new type("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary}),_hasOwnProperty$3=Object.prototype.hasOwnProperty,_toString$2=Object.prototype.toString;omap=new type("tag:yaml.org,2002:omap",{kind:"sequence",resolve:resolveYamlOmap,construct:constructYamlOmap}),_toString$1=Object.prototype.toString;pairs=new type("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:resolveYamlPairs,construct:constructYamlPairs}),_hasOwnProperty$2=Object.prototype.hasOwnProperty;set=new type("tag:yaml.org,2002:set",{kind:"mapping",resolve:resolveYamlSet,construct:constructYamlSet}),_default=core.extend({implicit:[timestamp,merge],explicit:[binary,omap,pairs,set]}),_hasOwnProperty$1=Object.prototype.hasOwnProperty,PATTERN_NON_PRINTABLE=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,PATTERN_NON_ASCII_LINE_BREAKS=/[\x85\u2028\u2029]/,PATTERN_FLOW_INDICATORS=/[,\[\]\{\}]/,PATTERN_TAG_HANDLE=/^(?:!|!!|![a-z\-]+!)$/i,PATTERN_TAG_URI=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;simpleEscapeCheck=Array(256),simpleEscapeMap=Array(256);for(i=0;i<256;i++)simpleEscapeCheck[i]=simpleEscapeSequence(i)?1:0,simpleEscapeMap[i]=simpleEscapeSequence(i);directiveHandlers={YAML:function(state,name,args){var match,major,minor;if(state.version!==null)throwError(state,"duplication of %YAML directive");if(args.length!==1)throwError(state,"YAML directive accepts exactly one argument");if(match=/^([0-9]+)\.([0-9]+)$/.exec(args[0]),match===null)throwError(state,"ill-formed argument of the YAML directive");if(major=parseInt(match[1],10),minor=parseInt(match[2],10),major!==1)throwError(state,"unacceptable YAML version of the document");if(state.version=args[0],state.checkLineBreaks=minor<2,minor!==1&&minor!==2)throwWarning(state,"unsupported YAML version of the document")},TAG:function(state,name,args){var handle,prefix;if(args.length!==2)throwError(state,"TAG directive accepts exactly two arguments");if(handle=args[0],prefix=args[1],!PATTERN_TAG_HANDLE.test(handle))throwError(state,"ill-formed tag handle (first argument) of the TAG directive");if(_hasOwnProperty$1.call(state.tagMap,handle))throwError(state,'there is a previously declared suffix for "'+handle+'" tag handle');if(!PATTERN_TAG_URI.test(prefix))throwError(state,"ill-formed tag prefix (second argument) of the TAG directive");try{prefix=decodeURIComponent(prefix)}catch(err){throwError(state,"tag prefix is malformed: "+prefix)}state.tagMap[handle]=prefix}};loadAll_1=loadAll$1,load_1=load$1,loader={loadAll:loadAll_1,load:load_1},_toString=Object.prototype.toString,_hasOwnProperty=Object.prototype.hasOwnProperty,ESCAPE_SEQUENCES={};ESCAPE_SEQUENCES[0]="\\0";ESCAPE_SEQUENCES[7]="\\a";ESCAPE_SEQUENCES[8]="\\b";ESCAPE_SEQUENCES[9]="\\t";ESCAPE_SEQUENCES[10]="\\n";ESCAPE_SEQUENCES[11]="\\v";ESCAPE_SEQUENCES[12]="\\f";ESCAPE_SEQUENCES[13]="\\r";ESCAPE_SEQUENCES[27]="\\e";ESCAPE_SEQUENCES[34]="\\\"";ESCAPE_SEQUENCES[92]="\\\\";ESCAPE_SEQUENCES[133]="\\N";ESCAPE_SEQUENCES[160]="\\_";ESCAPE_SEQUENCES[8232]="\\L";ESCAPE_SEQUENCES[8233]="\\P";DEPRECATED_BOOLEANS_SYNTAX=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],DEPRECATED_BASE60_SYNTAX=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;dump_1=dump$1,dumper={dump:dump_1};Type=type,Schema=schema,FAILSAFE_SCHEMA=failsafe,JSON_SCHEMA=json,CORE_SCHEMA=core,DEFAULT_SCHEMA=_default,load=loader.load,loadAll=loader.loadAll,dump=dumper.dump,YAMLException=exception,types2={binary,float,map,null:_null,pairs,set,timestamp,bool,int,merge,omap,seq,str},safeLoad=renamed("safeLoad","load"),safeLoadAll=renamed("safeLoadAll","loadAll"),safeDump=renamed("safeDump","dump"),jsYaml={Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load,loadAll,dump,YAMLException,types:types2,safeLoad,safeLoadAll,safeDump}});var exports_frontmatter={};__export(exports_frontmatter,{parseFrontmatter:()=>parseFrontmatter,AgentFrontmatterSchema:()=>AgentFrontmatterSchema});function extractRawYaml(content){let match=content.match(/^---\n([\s\S]*?)\n---/);if(!match)return null;try{let parsed=load(match[1]);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function warnUnknownFields(raw){for(let key of Object.keys(raw))if(!knownKeys.has(key))console.warn(`[frontmatter] Unknown field "${key}" \u2014 ignored.`)}function validateFieldByField(raw){let out={};for(let key of knownKeys){let fieldResult=AgentFrontmatterSchema.shape[key].safeParse(raw[key]);if(fieldResult.success){if(fieldResult.data!==void 0)out[key]=fieldResult.data}else if(raw[key]!==void 0)console.warn(`[frontmatter] Invalid value for "${key}": ${JSON.stringify(raw[key])} \u2014 using default.`)}return out}function parseFrontmatter(content){let raw=extractRawYaml(content);if(!raw)return{};warnUnknownFields(raw);let result2=AgentFrontmatterSchema.safeParse(raw);if(result2.success)return result2.data;return validateFieldByField(raw)}var promptModeValues,providerValues,AgentFrontmatterSchema,knownKeys;var init_frontmatter=__esm(()=>{init_js_yaml();init_zod();promptModeValues=["system","append"],providerValues=["claude","codex","claude-sdk"],AgentFrontmatterSchema=exports_external.object({name:exports_external.string().optional(),description:exports_external.string().optional(),model:exports_external.string().optional(),color:exports_external.string().optional(),promptMode:exports_external.enum(promptModeValues).optional(),provider:exports_external.enum(providerValues).optional(),tools:exports_external.array(exports_external.string()).optional(),permissionMode:exports_external.string().optional(),disallowedTools:exports_external.array(exports_external.string()).optional(),permissions:exports_external.object({allow:exports_external.array(exports_external.string()).optional(),deny:exports_external.array(exports_external.string()).optional()}).optional(),omniScopes:exports_external.array(exports_external.string()).optional(),hooks:exports_external.record(exports_external.unknown()).optional(),sdk:exports_external.record(exports_external.unknown()).optional()}),knownKeys=new Set(Object.keys(AgentFrontmatterSchema.shape))});import{existsSync as existsSync4,readFileSync as readFileSync3,readdirSync,realpathSync}from"fs";import{dirname,join as join4,resolve}from"path";function resolvePackageRoot(){let scriptPath=realpathSync(process.argv[1]||""),candidates=[resolve(dirname(scriptPath),".."),resolve(dirname(scriptPath),"..",".."),resolve(dirname(import.meta.dir??__dirname),"..",".."),resolve(dirname(import.meta.dir??__dirname),"..")];for(let candidate of candidates)if(existsSync4(join4(candidate,"plugins","genie","agents")))return candidate;return candidates[0]}function scanAgents(agentsDir){if(!existsSync4(agentsDir))return[];let agents=[],entries;try{entries=readdirSync(agentsDir,{withFileTypes:!0})}catch{return[]}for(let entry of entries){if(!entry.isDirectory())continue;let agentsPath=join4(agentsDir,entry.name,"AGENTS.md");if(!existsSync4(agentsPath))continue;let content=readFileSync3(agentsPath,"utf-8"),fm=parseFrontmatter(content),name=fm.name||entry.name,isCouncil=name.startsWith("council");agents.push({name,description:fm.description||"",agentPath:agentsPath,model:normalizeValue(fm.model),promptMode:fm.promptMode||void 0,category:isCouncil?"council":"role",color:fm.color})}return agents}function getBuiltin(name){return ALL_BUILTINS.find((a)=>a.name===name)??null}function resolveBuiltinAgentPath(name){return getBuiltin(name)?.agentPath??null}var __dirname="/home/runner/_work/genie/genie/src/lib",AGENTS_DIR,_allAgents,BUILTIN_ROLES,BUILTIN_COUNCIL_MEMBERS,ALL_BUILTINS;var init_builtin_agents=__esm(()=>{init_defaults();init_frontmatter();AGENTS_DIR=join4(resolvePackageRoot(),"plugins","genie","agents"),_allAgents=scanAgents(AGENTS_DIR),BUILTIN_ROLES=_allAgents.filter((a)=>a.category==="role"),BUILTIN_COUNCIL_MEMBERS=_allAgents.filter((a)=>a.category==="council"),ALL_BUILTINS=_allAgents});var exports_frontmatter_writer={};__export(exports_frontmatter_writer,{writeFrontmatter:()=>writeFrontmatter,serializeSdkConfig:()=>serializeSdkConfig});import{readFileSync as readFileSync4,writeFileSync as writeFileSync4}from"fs";function writeFrontmatter(filePath,updates){let content=readFileSync4(filePath,"utf-8"),{yamlObj,body}=splitFrontmatter(content),merged={...yamlObj,...stripUndefined(updates)},output=`---
|
|
142
|
+
${dump(merged,{lineWidth:-1,noRefs:!0,sortKeys:!1,quotingType:'"'})}---
|
|
143
|
+
${body}`;writeFileSync4(filePath,output,"utf-8")}function serializeSdkConfig(sdk){let result2={};for(let[key,value]of Object.entries(sdk)){if(value===void 0||value===null)continue;if(Array.isArray(value)&&value.length===0)continue;if(typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)continue;result2[key]=value}return result2}function splitFrontmatter(content){let match=content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!match)return{yamlObj:{},body:content};let yamlStr=match[1],body=match[2],yamlObj={};try{let parsed=load(yamlStr);if(typeof parsed==="object"&&parsed!==null)yamlObj=parsed}catch{}return{yamlObj,body}}function stripUndefined(obj){let result2={};for(let[key,value]of Object.entries(obj))if(value!==void 0)result2[key]=value;return result2}var init_frontmatter_writer=__esm(()=>{init_js_yaml()});import{readdirSync as readdirSync2}from"fs";import{dirname as dirname2,join as join5}from"path";function getMigrationsDir(){return join5(import.meta.dir,"..","db","migrations")}function getPackageRootMigrationsDir(){return join5(dirname2(import.meta.dir),"src","db","migrations")}async function loadMigrationFiles(){let candidates=[getMigrationsDir(),getPackageRootMigrationsDir()];for(let dir of candidates)try{let files=readdirSync2(dir).filter((f)=>f.endsWith(".sql")).sort();if(files.length===0)continue;let migrations=[];for(let file of files){let content=await Bun.file(join5(dir,file)).text();migrations.push({name:file.replace(/\.sql$/,""),sql:content})}return migrations}catch{}return[]}async function ensureMigrationsTable(sql){await sql`
|
|
69
144
|
CREATE TABLE IF NOT EXISTS _genie_migrations (
|
|
70
145
|
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
71
146
|
name TEXT UNIQUE NOT NULL,
|
|
@@ -75,7 +150,7 @@ ${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(f
|
|
|
75
150
|
SELECT name FROM _genie_migrations ORDER BY name
|
|
76
151
|
`,appliedSet=new Set(applied.map((r)=>r.name)),pending=files.filter((f)=>!appliedSet.has(f.name)),results=[];for(let migration of pending)await sql.begin(async(tx)=>{await tx.unsafe(migration.sql),await tx.unsafe("INSERT INTO _genie_migrations (name) VALUES ($1)",[migration.name])}),results.push({name:migration.name,applied_at:new Date().toISOString()});return results}async function getMigrationStatus(sql){await ensureMigrationsTable(sql);let files=await loadMigrationFiles(),applied=await sql`
|
|
77
152
|
SELECT name, applied_at FROM _genie_migrations ORDER BY name
|
|
78
|
-
`,appliedMap=new Map(applied.map((r)=>[r.name,r.applied_at.toISOString()])),appliedRecords=[],pendingRecords=[];for(let file of files){let appliedAt=appliedMap.get(file.name);if(appliedAt)appliedRecords.push({name:file.name,applied_at:appliedAt});else pendingRecords.push({name:file.name,applied_at:null})}return{applied:appliedRecords,pending:pendingRecords}}var init_db_migrations=()=>{};import{existsSync as
|
|
153
|
+
`,appliedMap=new Map(applied.map((r)=>[r.name,r.applied_at.toISOString()])),appliedRecords=[],pendingRecords=[];for(let file of files){let appliedAt=appliedMap.get(file.name);if(appliedAt)appliedRecords.push({name:file.name,applied_at:appliedAt});else pendingRecords.push({name:file.name,applied_at:null})}return{applied:appliedRecords,pending:pendingRecords}}var init_db_migrations=()=>{};import{existsSync as existsSync5}from"fs";import{readFile,readdir,rename}from"fs/promises";import{homedir as homedir4}from"os";import{join as join6}from"path";function getGenieHome(){return process.env.GENIE_HOME??join6(homedir4(),".genie")}function workersJsonPath(){return join6(getGenieHome(),"workers.json")}function teamsDirPath(){return join6(getGenieHome(),"teams")}function needsMigration(filePath){return existsSync5(filePath)&&!existsSync5(`${filePath}.migrated`)}async function readJson(filePath){try{let content=await readFile(filePath,"utf-8");return JSON.parse(content)}catch{return null}}async function renameMatchingFiles(dir,filter){if(!existsSync5(dir))return;try{let files=await readdir(dir);for(let f of files){if(!filter(f))continue;let fp=join6(dir,f);if(needsMigration(fp))await rename(fp,`${fp}.migrated`)}}catch{}}function needsSeed(){if(needsMigration(workersJsonPath()))return!0;let teamsDir=teamsDirPath();if(!existsSync5(teamsDir))return!1;try{return __require("fs").readdirSync(teamsDir).some((f)=>f.endsWith(".json")&&!f.endsWith(".migrated")&&needsMigration(join6(teamsDir,f)))}catch{return!1}}function toAgentRow(a){let now=new Date().toISOString();return{id:a.id,pane_id:a.paneId??"",session:a.session??"",worktree:a.worktree??null,task_id:a.taskId??null,task_title:a.taskTitle??null,wish_slug:a.wishSlug??null,group_number:a.groupNumber??null,started_at:a.startedAt??now,state:a.state??"spawning",last_state_change:a.lastStateChange??now,repo_path:a.repoPath??"",claude_session_id:a.claudeSessionId??null,window_name:a.windowName??null,window_id:a.windowId??null,role:a.role??null,custom_name:a.customName??null,sub_panes:JSON.stringify(a.subPanes??[]),provider:a.provider??null,transport:a.transport??"tmux",skill:a.skill??null,team:a.team??null,tmux_window:a.window??null,native_agent_id:a.nativeAgentId??null,native_color:a.nativeColor??null,native_team_enabled:a.nativeTeamEnabled??!1,parent_session_id:a.parentSessionId??null,suspended_at:a.suspendedAt??null,auto_resume:a.autoResume??!0,resume_attempts:a.resumeAttempts??0,last_resume_attempt:a.lastResumeAttempt??null,max_resume_attempts:a.maxResumeAttempts??3,pane_color:null}}async function upsertAgent(sql,a){let r=toAgentRow(a);await sql`
|
|
79
154
|
INSERT INTO agents (
|
|
80
155
|
id, pane_id, session, worktree, task_id, task_title,
|
|
81
156
|
wish_slug, group_number, started_at, state, last_state_change,
|
|
@@ -138,7 +213,7 @@ ${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(f
|
|
|
138
213
|
${c.tmuxSessionName??null}, ${c.wishSlug??null},
|
|
139
214
|
${c.createdAt??new Date().toISOString()}
|
|
140
215
|
) ON CONFLICT (name) DO NOTHING
|
|
141
|
-
`}async function seedTeams(sql){let dir=teamsDirPath();if(!
|
|
216
|
+
`}async function seedTeams(sql){let dir=teamsDirPath();if(!existsSync5(dir))return 0;let files;try{files=await readdir(dir)}catch{return 0}let count=0;for(let file of files){if(!file.endsWith(".json")||file.endsWith(".migrated"))continue;if(!needsMigration(join6(dir,file)))continue;let config=await readJson(join6(dir,file));if(!config?.name)continue;await upsertTeam(sql,config),count++}return count}async function upsertMailboxMessage(sql,msg,repoPath,fallbackTo){await sql`
|
|
142
217
|
INSERT INTO mailbox (
|
|
143
218
|
id, from_worker, to_worker, body, repo_path,
|
|
144
219
|
read, delivered_at, created_at
|
|
@@ -147,7 +222,7 @@ ${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(f
|
|
|
147
222
|
${msg.body??""}, ${repoPath}, ${msg.read??!1},
|
|
148
223
|
${msg.deliveredAt??null}, ${msg.createdAt??new Date().toISOString()}
|
|
149
224
|
) ON CONFLICT (id) DO NOTHING
|
|
150
|
-
`}function isMailboxFile(filename){return filename.endsWith(".json")&&!filename.endsWith(".migrated")&&!filename.includes("-sent")}async function seedMailbox(sql,repoPath){let dir=
|
|
225
|
+
`}function isMailboxFile(filename){return filename.endsWith(".json")&&!filename.endsWith(".migrated")&&!filename.includes("-sent")}async function seedMailbox(sql,repoPath){let dir=join6(repoPath,".genie","mailbox");if(!existsSync5(dir))return 0;let files;try{files=await readdir(dir)}catch{return 0}let count=0;for(let file of files){if(!isMailboxFile(file))continue;if(!needsMigration(join6(dir,file)))continue;let data=await readJson(join6(dir,file));if(!data?.messages||!Array.isArray(data.messages))continue;let fallbackTo=file.replace(".json","");for(let msg of data.messages){if(!msg.id)continue;await upsertMailboxMessage(sql,msg,repoPath,fallbackTo),count++}}return count}async function upsertChatMessage(sql,msg,teamName,repoPath){await sql`
|
|
151
226
|
INSERT INTO team_chat (
|
|
152
227
|
id, team, repo_path, sender, body, created_at
|
|
153
228
|
) VALUES (
|
|
@@ -156,8 +231,8 @@ ${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(f
|
|
|
156
231
|
${msg.timestamp??new Date().toISOString()}
|
|
157
232
|
) ON CONFLICT (id) DO NOTHING
|
|
158
233
|
`}function parseJsonlRecords(content){let records=[];for(let line of content.trim().split(`
|
|
159
|
-
`).filter(Boolean))try{let msg=JSON.parse(line);if(msg.id)records.push(msg)}catch{}return records}async function seedTeamChat(sql,repoPath){let dir=join9(repoPath,".genie","chat");if(!existsSync7(dir))return 0;let files;try{files=await readdir2(dir)}catch{return 0}let count=0;for(let file of files){if(!file.endsWith(".jsonl")||file.endsWith(".migrated"))continue;if(!needsMigration(join9(dir,file)))continue;let teamName=file.replace(".jsonl","").replace(/--/g,"/"),content;try{content=await readFile3(join9(dir,file),"utf-8")}catch{continue}for(let msg of parseJsonlRecords(content))await upsertChatMessage(sql,msg,teamName,repoPath),count++}return count}async function markMigrated(repoPath){let workersPath=workersJsonPath();if(needsMigration(workersPath))await rename(workersPath,`${workersPath}.migrated`);if(await renameMatchingFiles(teamsDirPath(),(f)=>f.endsWith(".json")&&!f.endsWith(".migrated")),!repoPath)return;await renameMatchingFiles(join9(repoPath,".genie","mailbox"),isMailboxFile),await renameMatchingFiles(join9(repoPath,".genie","chat"),(f)=>f.endsWith(".jsonl")&&!f.endsWith(".migrated"))}async function runSeed(sql,repoPath){let result2={agents:0,templates:0,teams:0,mailboxMessages:0,chatMessages:0},workers=await seedWorkers(sql);if(result2.agents=workers.agents,result2.templates=workers.templates,result2.teams=await seedTeams(sql),repoPath)result2.mailboxMessages=await seedMailbox(sql,repoPath),result2.chatMessages=await seedTeamChat(sql,repoPath);return await markMigrated(repoPath),result2}var init_pg_seed=()=>{};function cachedError(xs){if(originCache.has(xs))return originCache.get(xs);let x=Error.stackTraceLimit;return Error.stackTraceLimit=4,originCache.set(xs,Error()),Error.stackTraceLimit=x,originCache.get(xs)}var originCache,originStackCache,originError,CLOSE,Query;var init_query=__esm(()=>{originCache=new Map,originStackCache=new Map,originError=Symbol("OriginError"),CLOSE={};Query=class Query extends Promise{constructor(strings,args,handler,canceller,options={}){let resolve,reject;super((a,b)=>{resolve=a,reject=b});this.tagged=Array.isArray(strings.raw),this.strings=strings,this.args=args,this.handler=handler,this.canceller=canceller,this.options=options,this.state=null,this.statement=null,this.resolve=(x)=>(this.active=!1,resolve(x)),this.reject=(x)=>(this.active=!1,reject(x)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[originError]=this.handler.debug?Error():this.tagged&&cachedError(this.strings)}get origin(){return(this.handler.debug?this[originError].stack:this.tagged&&originStackCache.has(this.strings)?originStackCache.get(this.strings):originStackCache.set(this.strings,this[originError].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(rows=1,fn){if(this.options.simple=!1,typeof rows==="function")fn=rows,rows=1;if(this.cursorRows=rows,typeof fn==="function")return this.cursorFn=fn,this;let prev;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};prev&&prev();let promise=new Promise((resolve,reject)=>{this.cursorFn=(value)=>{return resolve({value,done:!1}),new Promise((r)=>prev=r)},this.resolve=()=>(this.active=!1,resolve({done:!0})),this.reject=(x)=>(this.active=!1,reject(x))});return this.execute(),promise},return(){return prev&&prev(CLOSE),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(fn){return this.forEachFn=fn,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}});function connection(x,options,socket){let{host,port}=socket||options,error=Object.assign(Error("write "+x+" "+(options.path||host+":"+port)),{code:x,errno:x,address:options.path||host},options.path?{}:{port});return Error.captureStackTrace(error,connection),error}function postgres(x){let error=new PostgresError(x);return Error.captureStackTrace(error,postgres),error}function generic(code,message){let error=Object.assign(Error(code+": "+message),{code});return Error.captureStackTrace(error,generic),error}function notSupported(x){let error=Object.assign(Error(x+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:x});return Error.captureStackTrace(error,notSupported),error}var PostgresError,Errors;var init_errors2=__esm(()=>{PostgresError=class PostgresError extends Error{constructor(x){super(x.message);this.name=this.constructor.name,Object.assign(this,x)}};Errors={connection,postgres,generic,notSupported}});class NotTagged{then(){notTagged()}catch(){notTagged()}finally(){notTagged()}}function handleValue(x,parameters,types3,options){let value=x instanceof Parameter?x.value:x;if(value===void 0){if(x instanceof Parameter?x.value=options.transform.undefined:value=x=options.transform.undefined,value===void 0)throw Errors.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+types3.push(x instanceof Parameter?(parameters.push(x.value),x.array?x.array[x.type||inferType(x.value)]||x.type||firstIsString(x.value):x.type):(parameters.push(x),inferType(x)))}function stringify(q,string,value,parameters,types3,options){for(let i=1;i<q.strings.length;i++)string+=stringifyValue(string,value,parameters,types3,options)+q.strings[i],value=q.args[i];return string}function stringifyValue(string,value,parameters,types3,o){return value instanceof Builder?value.build(string,parameters,types3,o):value instanceof Query?fragment(value,parameters,types3,o):value instanceof Identifier?value.value:value&&value[0]instanceof Query?value.reduce((acc,x)=>acc+" "+fragment(x,parameters,types3,o),""):handleValue(value,parameters,types3,o)}function fragment(q,parameters,types3,options){return q.fragment=!0,stringify(q,q.strings[0],q.args[0],parameters,types3,options)}function valuesBuilder(first,parameters,types3,columns,options){return first.map((row)=>"("+columns.map((column)=>stringifyValue("values",row[column],parameters,types3,options)).join(",")+")").join(",")}function values(first,rest,parameters,types3,options){let multi=Array.isArray(first[0]),columns=rest.length?rest.flat():Object.keys(multi?first[0]:first);return valuesBuilder(multi?first:[first],parameters,types3,columns,options)}function select(first,rest,parameters,types3,options){if(typeof first==="string"&&(first=[first].concat(rest)),Array.isArray(first))return escapeIdentifiers(first,options);let value;return(rest.length?rest.flat():Object.keys(first)).map((x)=>{return value=first[x],(value instanceof Query?fragment(value,parameters,types3,options):value instanceof Identifier?value.value:handleValue(value,parameters,types3,options))+" as "+escapeIdentifier(options.transform.column.to?options.transform.column.to(x):x)}).join(",")}function notTagged(){throw Errors.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function firstIsString(x){if(Array.isArray(x))return firstIsString(x[0]);return typeof x==="string"?1009:0}function typeHandlers(types3){return Object.keys(types3).reduce((acc,k)=>{if(types3[k].from&&[].concat(types3[k].from).forEach((x)=>acc.parsers[x]=types3[k].parse),types3[k].serialize)acc.serializers[types3[k].to]=types3[k].serialize,types3[k].from&&[].concat(types3[k].from).forEach((x)=>acc.serializers[x]=types3[k].serialize);return acc},{parsers:{},serializers:{}})}function escapeIdentifiers(xs,{transform:{column}}){return xs.map((x)=>escapeIdentifier(column.to?column.to(x):x)).join(",")}function arrayEscape(x){return x.replace(escapeBackslash,"\\\\").replace(escapeQuote,"\\\"")}function arrayParserLoop(s,x,parser,typarray){let xs=[],delimiter=typarray===1020?";":",";for(;s.i<x.length;s.i++){if(s.char=x[s.i],s.quoted)if(s.char==="\\")s.str+=x[++s.i];else if(s.char==='"')xs.push(parser?parser(s.str):s.str),s.str="",s.quoted=x[s.i+1]==='"',s.last=s.i+2;else s.str+=s.char;else if(s.char==='"')s.quoted=!0;else if(s.char==="{")s.last=++s.i,xs.push(arrayParserLoop(s,x,parser,typarray));else if(s.char==="}"){s.quoted=!1,s.last<s.i&&xs.push(parser?parser(x.slice(s.last,s.i)):x.slice(s.last,s.i)),s.last=s.i+1;break}else if(s.char===delimiter&&s.p!=="}"&&s.p!=='"')xs.push(parser?parser(x.slice(s.last,s.i)):x.slice(s.last,s.i)),s.last=s.i+1;s.p=s.char}return s.last<s.i&&xs.push(parser?parser(x.slice(s.last,s.i+1)):x.slice(s.last,s.i+1)),xs}function createJsonTransform(fn){return function jsonTransform(x,column){return typeof x==="object"&&x!==null&&(column.type===114||column.type===3802)?Array.isArray(x)?x.map((x2)=>jsonTransform(x2,column)):Object.entries(x).reduce((acc,[k,v])=>Object.assign(acc,{[fn(k)]:jsonTransform(v,column)}),{}):x}}var types2,Identifier,Parameter,Builder,defaultHandlers,builders,serializers,parsers,mergeUserTypes=function(types3){let user=typeHandlers(types3||{});return{serializers:Object.assign({},serializers,user.serializers),parsers:Object.assign({},parsers,user.parsers)}},escapeIdentifier=function(str){return'"'+str.replace(/"/g,'""').replace(/\./g,'"."')+'"'},inferType=function inferType2(x){return x instanceof Parameter?x.type:x instanceof Date?1184:x instanceof Uint8Array?17:x===!0||x===!1?16:typeof x==="bigint"?20:Array.isArray(x)?inferType2(x[0]):0},escapeBackslash,escapeQuote,arraySerializer=function arraySerializer2(xs,serializer,options,typarray){if(Array.isArray(xs)===!1)return xs;if(!xs.length)return"{}";let first=xs[0],delimiter=typarray===1020?";":",";if(Array.isArray(first)&&!first.type)return"{"+xs.map((x)=>arraySerializer2(x,serializer,options,typarray)).join(delimiter)+"}";return"{"+xs.map((x)=>{if(x===void 0){if(x=options.transform.undefined,x===void 0)throw Errors.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return x===null?"null":'"'+arrayEscape(serializer?serializer(x.type?x.value:x):""+x)+'"'}).join(delimiter)+"}"},arrayParserState,arrayParser=function(x,parser,typarray){return arrayParserState.i=arrayParserState.last=0,arrayParserLoop(arrayParserState,x,parser,typarray)},toCamel=(x)=>{let str=x[0];for(let i=1;i<x.length;i++)str+=x[i]==="_"?x[++i].toUpperCase():x[i];return str},toPascal=(x)=>{let str=x[0].toUpperCase();for(let i=1;i<x.length;i++)str+=x[i]==="_"?x[++i].toUpperCase():x[i];return str},toKebab=(x)=>x.replace(/_/g,"-"),fromCamel=(x)=>x.replace(/([A-Z])/g,"_$1").toLowerCase(),fromPascal=(x)=>(x.slice(0,1)+x.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),fromKebab=(x)=>x.replace(/-/g,"_"),camel,pascal,kebab;var init_types3=__esm(()=>{init_query();init_errors2();types2={string:{to:25,from:null,serialize:(x)=>""+x},number:{to:0,from:[21,23,26,700,701],serialize:(x)=>""+x,parse:(x)=>+x},json:{to:114,from:[114,3802],serialize:(x)=>JSON.stringify(x),parse:(x)=>JSON.parse(x)},boolean:{to:16,from:16,serialize:(x)=>x===!0?"t":"f",parse:(x)=>x==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(x)=>(x instanceof Date?x:new Date(x)).toISOString(),parse:(x)=>new Date(x)},bytea:{to:17,from:17,serialize:(x)=>"\\x"+Buffer.from(x).toString("hex"),parse:(x)=>Buffer.from(x.slice(2),"hex")}};Identifier=class Identifier extends NotTagged{constructor(value){super();this.value=escapeIdentifier(value)}};Parameter=class Parameter extends NotTagged{constructor(value,type,array){super();this.value=value,this.type=type,this.array=array}};Builder=class Builder extends NotTagged{constructor(first,rest){super();this.first=first,this.rest=rest}build(before,parameters,types3,options){let keyword=builders.map(([x,fn])=>({fn,i:before.search(x)})).sort((a,b)=>a.i-b.i).pop();return keyword.i===-1?escapeIdentifiers(this.first,options):keyword.fn(this.first,this.rest,parameters,types3,options)}};defaultHandlers=typeHandlers(types2);builders=Object.entries({values,in:(...xs)=>{let x=values(...xs);return x==="()"?"(null)":x},select,as:select,returning:select,"\\(":select,update(first,rest,parameters,types3,options){return(rest.length?rest.flat():Object.keys(first)).map((x)=>escapeIdentifier(options.transform.column.to?options.transform.column.to(x):x)+"="+stringifyValue("values",first[x],parameters,types3,options))},insert(first,rest,parameters,types3,options){let columns=rest.length?rest.flat():Object.keys(Array.isArray(first)?first[0]:first);return"("+escapeIdentifiers(columns,options)+")values"+valuesBuilder(Array.isArray(first)?first:[first],parameters,types3,columns,options)}}).map(([x,fn])=>[new RegExp("((?:^|[\\s(])"+x+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),fn]);serializers=defaultHandlers.serializers,parsers=defaultHandlers.parsers;escapeBackslash=/\\/g,escapeQuote=/"/g;arrayParserState={i:0,char:null,str:"",quoted:!1,last:0};toCamel.column={from:toCamel};toCamel.value={from:createJsonTransform(toCamel)};fromCamel.column={to:fromCamel};camel={...toCamel};camel.column.to=fromCamel;toPascal.column={from:toPascal};toPascal.value={from:createJsonTransform(toPascal)};fromPascal.column={to:fromPascal};pascal={...toPascal};pascal.column.to=fromPascal;toKebab.column={from:toKebab};toKebab.value={from:createJsonTransform(toKebab)};fromKebab.column={to:fromKebab};kebab={...toKebab};kebab.column.to=fromKebab});var Result;var init_result=__esm(()=>{Result=class Result extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}});function Queue(initial=[]){let xs=initial.slice(),index=0;return{get length(){return xs.length-index},remove:(x)=>{let index2=xs.indexOf(x);return index2===-1?null:(xs.splice(index2,1),x)},push:(x)=>(xs.push(x),x),shift:()=>{let out=xs[index++];if(index===xs.length)index=0,xs=[];else xs[index-1]=void 0;return out}}}var queue_default;var init_queue=__esm(()=>{queue_default=Queue});function fit(x){if(buffer.length-b.i<x){let prev=buffer,length=prev.length;buffer=Buffer.allocUnsafe(length+(length>>1)+x),prev.copy(buffer)}}function reset(){return b.i=0,b}var buffer,messages,b,bytes_default;var init_bytes=__esm(()=>{buffer=Buffer.allocUnsafe(256),messages="BCcDdEFfHPpQSX".split("").reduce((acc,x)=>{let v=x.charCodeAt(0);return acc[x]=()=>{return buffer[0]=v,b.i=5,b},acc},{}),b=Object.assign(reset,messages,{N:String.fromCharCode(0),i:0,inc(x){return b.i+=x,b},str(x){let length=Buffer.byteLength(x);return fit(length),b.i+=buffer.write(x,b.i,length,"utf8"),b},i16(x){return fit(2),buffer.writeUInt16BE(x,b.i),b.i+=2,b},i32(x,i){if(i||i===0)return buffer.writeUInt32BE(x,i),b;return fit(4),buffer.writeUInt32BE(x,b.i),b.i+=4,b},z(x){return fit(x),buffer.fill(0,b.i,b.i+x),b.i+=x,b},raw(x){return buffer=Buffer.concat([buffer.subarray(0,b.i),x]),b.i=buffer.length,b},end(at=1){buffer.writeUInt32BE(b.i-at,at);let out=buffer.subarray(0,b.i);return b.i=0,buffer=Buffer.allocUnsafe(256),out}}),bytes_default=b});import net from"net";import tls from"tls";import crypto2 from"crypto";import Stream from"stream";import{performance as performance2}from"perf_hooks";function Connection(options,queues={},{onopen=noop,onend=noop,onclose=noop}={}){let{sslnegotiation,ssl,max,user,host,port,database,parsers:parsers2,transform,onnotice,onnotify,onparameter,max_pipeline,keep_alive,backoff,target_session_attrs}=options,sent=queue_default(),id=uid++,backend={pid:null,secret:null},idleTimer=timer(end,options.idle_timeout),lifeTimer=timer(end,options.max_lifetime),connectTimer=timer(connectTimedOut,options.connect_timeout),socket=null,cancelMessage,errorResponse=null,result2=new Result,incoming=Buffer.alloc(0),needsTypes=options.fetch_types,backendParameters={},statements={},statementId=Math.random().toString(36).slice(2),statementCount=1,closedTime=0,remaining=0,hostIndex=0,retries=0,length=0,delay=0,rows=0,serverSignature=null,nextWriteTimer=null,terminated=!1,incomings=null,results=null,initial=null,ending=null,stream=null,chunk=null,ended=null,nonce=null,query=null,final=null,connection2={queue:queues.closed,idleTimer,connect(query2){initial=query2,reconnect()},terminate,execute,cancel,end,count:0,id};return queues.closed&&queues.closed.push(connection2),connection2;async function createSocket(){let x;try{x=options.socket?await Promise.resolve(options.socket(options)):new net.Socket}catch(e){error(e);return}return x.on("error",error),x.on("close",closed),x.on("drain",drain),x}async function cancel({pid,secret},resolve,reject){try{cancelMessage=bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16),await connect(),socket.once("error",reject),socket.once("close",resolve)}catch(error2){reject(error2)}}function execute(q){if(terminated)return queryError(q,Errors.connection("CONNECTION_DESTROYED",options));if(stream)return queryError(q,Errors.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(q.cancelled)return;try{return q.state=backend,query?sent.push(q):(query=q,query.active=!0),build(q),write(toBuffer(q))&&!q.describeFirst&&!q.cursorFn&&sent.length<max_pipeline&&(!q.options.onexecute||q.options.onexecute(connection2))}catch(error2){return sent.length===0&&write(Sync),errored(error2),!0}}function toBuffer(q){if(q.parameters.length>=65534)throw Errors.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return q.options.simple?bytes_default().Q().str(q.statement.string+bytes_default.N).end():q.describeFirst?Buffer.concat([describe(q),Flush]):q.prepare?q.prepared?prepared(q):Buffer.concat([describe(q),prepared(q)]):unnamed(q)}function describe(q){return Buffer.concat([Parse(q.statement.string,q.parameters,q.statement.types,q.statement.name),Describe("S",q.statement.name)])}function prepared(q){return Buffer.concat([Bind(q.parameters,q.statement.types,q.statement.name,q.cursorName),q.cursorFn?Execute("",q.cursorRows):ExecuteUnnamed])}function unnamed(q){return Buffer.concat([Parse(q.statement.string,q.parameters,q.statement.types),DescribeUnnamed,prepared(q)])}function build(q){let parameters=[],types3=[],string=stringify(q,q.strings[0],q.args[0],parameters,types3,options);!q.tagged&&q.args.forEach((x)=>handleValue(x,parameters,types3,options)),q.prepare=options.prepare&&("prepare"in q.options?q.options.prepare:!0),q.string=string,q.signature=q.prepare&&types3+string,q.onlyDescribe&&delete statements[q.signature],q.parameters=q.parameters||parameters,q.prepared=q.prepare&&q.signature in statements,q.describeFirst=q.onlyDescribe||parameters.length&&!q.prepared,q.statement=q.prepared?statements[q.signature]:{string,types:types3,name:q.prepare?statementId+statementCount++:""},typeof options.debug==="function"&&options.debug(id,string,parameters,types3)}function write(x,fn){if(chunk=chunk?Buffer.concat([chunk,x]):Buffer.from(x),fn||chunk.length>=1024)return nextWrite(fn);return nextWriteTimer===null&&(nextWriteTimer=setImmediate(nextWrite)),!0}function nextWrite(fn){let x=socket.write(chunk,fn);return nextWriteTimer!==null&&clearImmediate(nextWriteTimer),chunk=nextWriteTimer=null,x}function connectTimedOut(){errored(Errors.connection("CONNECT_TIMEOUT",options,socket)),socket.destroy()}async function secure(){if(sslnegotiation!=="direct"){if(write(SSLRequest),!await new Promise((r)=>socket.once("data",(x)=>r(x[0]===83)))&&ssl==="prefer")return connected()}let options2={socket,servername:net.isIP(socket.host)?void 0:socket.host};if(sslnegotiation==="direct")options2.ALPNProtocols=["postgresql"];if(ssl==="require"||ssl==="allow"||ssl==="prefer")options2.rejectUnauthorized=!1;else if(typeof ssl==="object")Object.assign(options2,ssl);socket.removeAllListeners(),socket=tls.connect(options2),socket.on("secureConnect",connected),socket.on("error",error),socket.on("close",closed),socket.on("drain",drain)}function drain(){!query&&onopen(connection2)}function data(x){if(incomings){if(incomings.push(x),remaining-=x.length,remaining>0)return}incoming=incomings?Buffer.concat(incomings,length-remaining):incoming.length===0?x:Buffer.concat([incoming,x],incoming.length+x.length);while(incoming.length>4){if(length=incoming.readUInt32BE(1),length>=incoming.length){remaining=length-incoming.length,incomings=[incoming];break}try{handle(incoming.subarray(0,length+1))}catch(e){query&&(query.cursorFn||query.describeFirst)&&write(Sync),errored(e)}incoming=incoming.subarray(length+1),remaining=0,incomings=null}}async function connect(){if(terminated=!1,backendParameters={},socket||(socket=await createSocket()),!socket)return;if(connectTimer.start(),options.socket)return ssl?secure():connected();if(socket.on("connect",ssl?secure:connected),options.path)return socket.connect(options.path);socket.ssl=ssl,socket.connect(port[hostIndex],host[hostIndex]),socket.host=host[hostIndex],socket.port=port[hostIndex],hostIndex=(hostIndex+1)%port.length}function reconnect(){setTimeout(connect,closedTime?Math.max(0,closedTime+delay-performance2.now()):0)}function connected(){try{statements={},needsTypes=options.fetch_types,statementId=Math.random().toString(36).slice(2),statementCount=1,lifeTimer.start(),socket.on("data",data),keep_alive&&socket.setKeepAlive&&socket.setKeepAlive(!0,1000*keep_alive);let s=StartupMessage();write(s)}catch(err){error(err)}}function error(err){if(connection2.queue===queues.connecting&&options.host[retries+1])return;errored(err);while(sent.length)queryError(sent.shift(),err)}function errored(err){stream&&(stream.destroy(err),stream=null),query&&queryError(query,err),initial&&(queryError(initial,err),initial=null)}function queryError(query2,err){if(query2.reserve)return query2.reject(err);if(!err||typeof err!=="object")err=Error(err);"query"in err||"parameters"in err||Object.defineProperties(err,{stack:{value:err.stack+query2.origin.replace(/.*\n/,`
|
|
160
|
-
`),enumerable:options.debug},query:{value:query2.string,enumerable:options.debug},parameters:{value:query2.parameters,enumerable:options.debug},args:{value:query2.args,enumerable:options.debug},types:{value:query2.statement&&query2.statement.types,enumerable:options.debug}}),query2.reject(err)}function end(){return ending||(!connection2.reserved&&onend(connection2),!connection2.reserved&&!initial&&!query&&sent.length===0?(terminate(),new Promise((r)=>socket&&socket.readyState!=="closed"?socket.once("close",r):r())):ending=new Promise((r)=>ended=r))}function terminate(){if(terminated=!0,stream||query||initial||sent.length)error(Errors.connection("CONNECTION_DESTROYED",options));if(clearImmediate(nextWriteTimer),socket)socket.removeListener("data",data),socket.removeListener("connect",connected),socket.readyState==="open"&&socket.end(bytes_default().X().end());ended&&(ended(),ending=ended=null)}async function closed(hadError){if(incoming=Buffer.alloc(0),remaining=0,incomings=null,clearImmediate(nextWriteTimer),socket.removeListener("data",data),socket.removeListener("connect",connected),idleTimer.cancel(),lifeTimer.cancel(),connectTimer.cancel(),socket.removeAllListeners(),socket=null,initial)return reconnect();!hadError&&(query||sent.length)&&error(Errors.connection("CONNECTION_CLOSED",options,socket)),closedTime=performance2.now(),hadError&&options.shared.retries++,delay=(typeof backoff==="function"?backoff(options.shared.retries):backoff)*1000,onclose(connection2,Errors.connection("CONNECTION_CLOSED",options,socket))}function handle(xs,x=xs[0]){(x===68?DataRow:x===100?CopyData:x===65?NotificationResponse:x===83?ParameterStatus:x===90?ReadyForQuery:x===67?CommandComplete:x===50?BindComplete:x===49?ParseComplete:x===116?ParameterDescription:x===84?RowDescription:x===82?Authentication:x===110?NoData:x===75?BackendKeyData:x===69?ErrorResponse:x===115?PortalSuspended:x===51?CloseComplete:x===71?CopyInResponse:x===78?NoticeResponse:x===72?CopyOutResponse:x===99?CopyDone:x===73?EmptyQueryResponse:x===86?FunctionCallResponse:x===118?NegotiateProtocolVersion:x===87?CopyBothResponse:UnknownMessage)(xs)}function DataRow(x){let index=7,length2,column,value,row=query.isRaw?Array(query.statement.columns.length):{};for(let
|
|
234
|
+
`).filter(Boolean))try{let msg=JSON.parse(line);if(msg.id)records.push(msg)}catch{}return records}async function seedTeamChat(sql,repoPath){let dir=join6(repoPath,".genie","chat");if(!existsSync5(dir))return 0;let files;try{files=await readdir(dir)}catch{return 0}let count=0;for(let file of files){if(!file.endsWith(".jsonl")||file.endsWith(".migrated"))continue;if(!needsMigration(join6(dir,file)))continue;let teamName=file.replace(".jsonl","").replace(/--/g,"/"),content;try{content=await readFile(join6(dir,file),"utf-8")}catch{continue}for(let msg of parseJsonlRecords(content))await upsertChatMessage(sql,msg,teamName,repoPath),count++}return count}async function markMigrated(repoPath){let workersPath=workersJsonPath();if(needsMigration(workersPath))await rename(workersPath,`${workersPath}.migrated`);if(await renameMatchingFiles(teamsDirPath(),(f)=>f.endsWith(".json")&&!f.endsWith(".migrated")),!repoPath)return;await renameMatchingFiles(join6(repoPath,".genie","mailbox"),isMailboxFile),await renameMatchingFiles(join6(repoPath,".genie","chat"),(f)=>f.endsWith(".jsonl")&&!f.endsWith(".migrated"))}async function runSeed(sql,repoPath){let result2={agents:0,templates:0,teams:0,mailboxMessages:0,chatMessages:0},workers=await seedWorkers(sql);if(result2.agents=workers.agents,result2.templates=workers.templates,result2.teams=await seedTeams(sql),repoPath)result2.mailboxMessages=await seedMailbox(sql,repoPath),result2.chatMessages=await seedTeamChat(sql,repoPath);return await markMigrated(repoPath),result2}var init_pg_seed=()=>{};function cachedError(xs){if(originCache.has(xs))return originCache.get(xs);let x=Error.stackTraceLimit;return Error.stackTraceLimit=4,originCache.set(xs,Error()),Error.stackTraceLimit=x,originCache.get(xs)}var originCache,originStackCache,originError,CLOSE,Query;var init_query=__esm(()=>{originCache=new Map,originStackCache=new Map,originError=Symbol("OriginError"),CLOSE={};Query=class Query extends Promise{constructor(strings,args,handler,canceller,options={}){let resolve2,reject;super((a,b)=>{resolve2=a,reject=b});this.tagged=Array.isArray(strings.raw),this.strings=strings,this.args=args,this.handler=handler,this.canceller=canceller,this.options=options,this.state=null,this.statement=null,this.resolve=(x)=>(this.active=!1,resolve2(x)),this.reject=(x)=>(this.active=!1,reject(x)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[originError]=this.handler.debug?Error():this.tagged&&cachedError(this.strings)}get origin(){return(this.handler.debug?this[originError].stack:this.tagged&&originStackCache.has(this.strings)?originStackCache.get(this.strings):originStackCache.set(this.strings,this[originError].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(rows=1,fn){if(this.options.simple=!1,typeof rows==="function")fn=rows,rows=1;if(this.cursorRows=rows,typeof fn==="function")return this.cursorFn=fn,this;let prev;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};prev&&prev();let promise=new Promise((resolve2,reject)=>{this.cursorFn=(value)=>{return resolve2({value,done:!1}),new Promise((r)=>prev=r)},this.resolve=()=>(this.active=!1,resolve2({done:!0})),this.reject=(x)=>(this.active=!1,reject(x))});return this.execute(),promise},return(){return prev&&prev(CLOSE),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(fn){return this.forEachFn=fn,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}});function connection(x,options,socket){let{host,port}=socket||options,error=Object.assign(Error("write "+x+" "+(options.path||host+":"+port)),{code:x,errno:x,address:options.path||host},options.path?{}:{port});return Error.captureStackTrace(error,connection),error}function postgres(x){let error=new PostgresError(x);return Error.captureStackTrace(error,postgres),error}function generic(code,message){let error=Object.assign(Error(code+": "+message),{code});return Error.captureStackTrace(error,generic),error}function notSupported(x){let error=Object.assign(Error(x+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:x});return Error.captureStackTrace(error,notSupported),error}var PostgresError,Errors;var init_errors2=__esm(()=>{PostgresError=class PostgresError extends Error{constructor(x){super(x.message);this.name=this.constructor.name,Object.assign(this,x)}};Errors={connection,postgres,generic,notSupported}});class NotTagged{then(){notTagged()}catch(){notTagged()}finally(){notTagged()}}function handleValue(x,parameters,types4,options){let value=x instanceof Parameter?x.value:x;if(value===void 0){if(x instanceof Parameter?x.value=options.transform.undefined:value=x=options.transform.undefined,value===void 0)throw Errors.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+types4.push(x instanceof Parameter?(parameters.push(x.value),x.array?x.array[x.type||inferType(x.value)]||x.type||firstIsString(x.value):x.type):(parameters.push(x),inferType(x)))}function stringify(q,string,value,parameters,types4,options){for(let i2=1;i2<q.strings.length;i2++)string+=stringifyValue(string,value,parameters,types4,options)+q.strings[i2],value=q.args[i2];return string}function stringifyValue(string,value,parameters,types4,o){return value instanceof Builder?value.build(string,parameters,types4,o):value instanceof Query?fragment(value,parameters,types4,o):value instanceof Identifier?value.value:value&&value[0]instanceof Query?value.reduce((acc,x)=>acc+" "+fragment(x,parameters,types4,o),""):handleValue(value,parameters,types4,o)}function fragment(q,parameters,types4,options){return q.fragment=!0,stringify(q,q.strings[0],q.args[0],parameters,types4,options)}function valuesBuilder(first,parameters,types4,columns,options){return first.map((row)=>"("+columns.map((column)=>stringifyValue("values",row[column],parameters,types4,options)).join(",")+")").join(",")}function values(first,rest,parameters,types4,options){let multi=Array.isArray(first[0]),columns=rest.length?rest.flat():Object.keys(multi?first[0]:first);return valuesBuilder(multi?first:[first],parameters,types4,columns,options)}function select(first,rest,parameters,types4,options){if(typeof first==="string"&&(first=[first].concat(rest)),Array.isArray(first))return escapeIdentifiers(first,options);let value;return(rest.length?rest.flat():Object.keys(first)).map((x)=>{return value=first[x],(value instanceof Query?fragment(value,parameters,types4,options):value instanceof Identifier?value.value:handleValue(value,parameters,types4,options))+" as "+escapeIdentifier(options.transform.column.to?options.transform.column.to(x):x)}).join(",")}function notTagged(){throw Errors.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function firstIsString(x){if(Array.isArray(x))return firstIsString(x[0]);return typeof x==="string"?1009:0}function typeHandlers(types4){return Object.keys(types4).reduce((acc,k)=>{if(types4[k].from&&[].concat(types4[k].from).forEach((x)=>acc.parsers[x]=types4[k].parse),types4[k].serialize)acc.serializers[types4[k].to]=types4[k].serialize,types4[k].from&&[].concat(types4[k].from).forEach((x)=>acc.serializers[x]=types4[k].serialize);return acc},{parsers:{},serializers:{}})}function escapeIdentifiers(xs,{transform:{column}}){return xs.map((x)=>escapeIdentifier(column.to?column.to(x):x)).join(",")}function arrayEscape(x){return x.replace(escapeBackslash,"\\\\").replace(escapeQuote,"\\\"")}function arrayParserLoop(s,x,parser,typarray){let xs=[],delimiter=typarray===1020?";":",";for(;s.i<x.length;s.i++){if(s.char=x[s.i],s.quoted)if(s.char==="\\")s.str+=x[++s.i];else if(s.char==='"')xs.push(parser?parser(s.str):s.str),s.str="",s.quoted=x[s.i+1]==='"',s.last=s.i+2;else s.str+=s.char;else if(s.char==='"')s.quoted=!0;else if(s.char==="{")s.last=++s.i,xs.push(arrayParserLoop(s,x,parser,typarray));else if(s.char==="}"){s.quoted=!1,s.last<s.i&&xs.push(parser?parser(x.slice(s.last,s.i)):x.slice(s.last,s.i)),s.last=s.i+1;break}else if(s.char===delimiter&&s.p!=="}"&&s.p!=='"')xs.push(parser?parser(x.slice(s.last,s.i)):x.slice(s.last,s.i)),s.last=s.i+1;s.p=s.char}return s.last<s.i&&xs.push(parser?parser(x.slice(s.last,s.i+1)):x.slice(s.last,s.i+1)),xs}function createJsonTransform(fn){return function jsonTransform(x,column){return typeof x==="object"&&x!==null&&(column.type===114||column.type===3802)?Array.isArray(x)?x.map((x2)=>jsonTransform(x2,column)):Object.entries(x).reduce((acc,[k,v])=>Object.assign(acc,{[fn(k)]:jsonTransform(v,column)}),{}):x}}var types3,Identifier,Parameter,Builder,defaultHandlers,builders,serializers,parsers,mergeUserTypes=function(types4){let user=typeHandlers(types4||{});return{serializers:Object.assign({},serializers,user.serializers),parsers:Object.assign({},parsers,user.parsers)}},escapeIdentifier=function(str2){return'"'+str2.replace(/"/g,'""').replace(/\./g,'"."')+'"'},inferType=function inferType2(x){return x instanceof Parameter?x.type:x instanceof Date?1184:x instanceof Uint8Array?17:x===!0||x===!1?16:typeof x==="bigint"?20:Array.isArray(x)?inferType2(x[0]):0},escapeBackslash,escapeQuote,arraySerializer=function arraySerializer2(xs,serializer,options,typarray){if(Array.isArray(xs)===!1)return xs;if(!xs.length)return"{}";let first=xs[0],delimiter=typarray===1020?";":",";if(Array.isArray(first)&&!first.type)return"{"+xs.map((x)=>arraySerializer2(x,serializer,options,typarray)).join(delimiter)+"}";return"{"+xs.map((x)=>{if(x===void 0){if(x=options.transform.undefined,x===void 0)throw Errors.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return x===null?"null":'"'+arrayEscape(serializer?serializer(x.type?x.value:x):""+x)+'"'}).join(delimiter)+"}"},arrayParserState,arrayParser=function(x,parser,typarray){return arrayParserState.i=arrayParserState.last=0,arrayParserLoop(arrayParserState,x,parser,typarray)},toCamel=(x)=>{let str2=x[0];for(let i2=1;i2<x.length;i2++)str2+=x[i2]==="_"?x[++i2].toUpperCase():x[i2];return str2},toPascal=(x)=>{let str2=x[0].toUpperCase();for(let i2=1;i2<x.length;i2++)str2+=x[i2]==="_"?x[++i2].toUpperCase():x[i2];return str2},toKebab=(x)=>x.replace(/_/g,"-"),fromCamel=(x)=>x.replace(/([A-Z])/g,"_$1").toLowerCase(),fromPascal=(x)=>(x.slice(0,1)+x.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),fromKebab=(x)=>x.replace(/-/g,"_"),camel,pascal,kebab;var init_types2=__esm(()=>{init_query();init_errors2();types3={string:{to:25,from:null,serialize:(x)=>""+x},number:{to:0,from:[21,23,26,700,701],serialize:(x)=>""+x,parse:(x)=>+x},json:{to:114,from:[114,3802],serialize:(x)=>JSON.stringify(x),parse:(x)=>JSON.parse(x)},boolean:{to:16,from:16,serialize:(x)=>x===!0?"t":"f",parse:(x)=>x==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(x)=>(x instanceof Date?x:new Date(x)).toISOString(),parse:(x)=>new Date(x)},bytea:{to:17,from:17,serialize:(x)=>"\\x"+Buffer.from(x).toString("hex"),parse:(x)=>Buffer.from(x.slice(2),"hex")}};Identifier=class Identifier extends NotTagged{constructor(value){super();this.value=escapeIdentifier(value)}};Parameter=class Parameter extends NotTagged{constructor(value,type2,array){super();this.value=value,this.type=type2,this.array=array}};Builder=class Builder extends NotTagged{constructor(first,rest){super();this.first=first,this.rest=rest}build(before,parameters,types4,options){let keyword=builders.map(([x,fn])=>({fn,i:before.search(x)})).sort((a,b)=>a.i-b.i).pop();return keyword.i===-1?escapeIdentifiers(this.first,options):keyword.fn(this.first,this.rest,parameters,types4,options)}};defaultHandlers=typeHandlers(types3);builders=Object.entries({values,in:(...xs)=>{let x=values(...xs);return x==="()"?"(null)":x},select,as:select,returning:select,"\\(":select,update(first,rest,parameters,types4,options){return(rest.length?rest.flat():Object.keys(first)).map((x)=>escapeIdentifier(options.transform.column.to?options.transform.column.to(x):x)+"="+stringifyValue("values",first[x],parameters,types4,options))},insert(first,rest,parameters,types4,options){let columns=rest.length?rest.flat():Object.keys(Array.isArray(first)?first[0]:first);return"("+escapeIdentifiers(columns,options)+")values"+valuesBuilder(Array.isArray(first)?first:[first],parameters,types4,columns,options)}}).map(([x,fn])=>[new RegExp("((?:^|[\\s(])"+x+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),fn]);serializers=defaultHandlers.serializers,parsers=defaultHandlers.parsers;escapeBackslash=/\\/g,escapeQuote=/"/g;arrayParserState={i:0,char:null,str:"",quoted:!1,last:0};toCamel.column={from:toCamel};toCamel.value={from:createJsonTransform(toCamel)};fromCamel.column={to:fromCamel};camel={...toCamel};camel.column.to=fromCamel;toPascal.column={from:toPascal};toPascal.value={from:createJsonTransform(toPascal)};fromPascal.column={to:fromPascal};pascal={...toPascal};pascal.column.to=fromPascal;toKebab.column={from:toKebab};toKebab.value={from:createJsonTransform(toKebab)};fromKebab.column={to:fromKebab};kebab={...toKebab};kebab.column.to=fromKebab});var Result;var init_result=__esm(()=>{Result=class Result extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}});function Queue(initial=[]){let xs=initial.slice(),index=0;return{get length(){return xs.length-index},remove:(x)=>{let index2=xs.indexOf(x);return index2===-1?null:(xs.splice(index2,1),x)},push:(x)=>(xs.push(x),x),shift:()=>{let out=xs[index++];if(index===xs.length)index=0,xs=[];else xs[index-1]=void 0;return out}}}var queue_default;var init_queue=__esm(()=>{queue_default=Queue});function fit(x){if(buffer.length-b.i<x){let prev=buffer,length=prev.length;buffer=Buffer.allocUnsafe(length+(length>>1)+x),prev.copy(buffer)}}function reset(){return b.i=0,b}var buffer,messages,b,bytes_default;var init_bytes=__esm(()=>{buffer=Buffer.allocUnsafe(256),messages="BCcDdEFfHPpQSX".split("").reduce((acc,x)=>{let v=x.charCodeAt(0);return acc[x]=()=>{return buffer[0]=v,b.i=5,b},acc},{}),b=Object.assign(reset,messages,{N:String.fromCharCode(0),i:0,inc(x){return b.i+=x,b},str(x){let length=Buffer.byteLength(x);return fit(length),b.i+=buffer.write(x,b.i,length,"utf8"),b},i16(x){return fit(2),buffer.writeUInt16BE(x,b.i),b.i+=2,b},i32(x,i2){if(i2||i2===0)return buffer.writeUInt32BE(x,i2),b;return fit(4),buffer.writeUInt32BE(x,b.i),b.i+=4,b},z(x){return fit(x),buffer.fill(0,b.i,b.i+x),b.i+=x,b},raw(x){return buffer=Buffer.concat([buffer.subarray(0,b.i),x]),b.i=buffer.length,b},end(at=1){buffer.writeUInt32BE(b.i-at,at);let out=buffer.subarray(0,b.i);return b.i=0,buffer=Buffer.allocUnsafe(256),out}}),bytes_default=b});import net from"net";import tls from"tls";import crypto2 from"crypto";import Stream from"stream";import{performance as performance2}from"perf_hooks";function Connection(options,queues={},{onopen=noop,onend=noop,onclose=noop}={}){let{sslnegotiation,ssl,max,user,host,port,database,parsers:parsers2,transform,onnotice,onnotify,onparameter,max_pipeline,keep_alive,backoff,target_session_attrs}=options,sent=queue_default(),id=uid++,backend={pid:null,secret:null},idleTimer=timer(end,options.idle_timeout),lifeTimer=timer(end,options.max_lifetime),connectTimer=timer(connectTimedOut,options.connect_timeout),socket=null,cancelMessage,errorResponse=null,result2=new Result,incoming=Buffer.alloc(0),needsTypes=options.fetch_types,backendParameters={},statements={},statementId=Math.random().toString(36).slice(2),statementCount=1,closedTime=0,remaining=0,hostIndex=0,retries=0,length=0,delay=0,rows=0,serverSignature=null,nextWriteTimer=null,terminated=!1,incomings=null,results=null,initial=null,ending=null,stream=null,chunk=null,ended=null,nonce=null,query=null,final=null,connection2={queue:queues.closed,idleTimer,connect(query2){initial=query2,reconnect()},terminate,execute,cancel,end,count:0,id};return queues.closed&&queues.closed.push(connection2),connection2;async function createSocket(){let x;try{x=options.socket?await Promise.resolve(options.socket(options)):new net.Socket}catch(e){error(e);return}return x.on("error",error),x.on("close",closed),x.on("drain",drain),x}async function cancel({pid,secret},resolve2,reject){try{cancelMessage=bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16),await connect(),socket.once("error",reject),socket.once("close",resolve2)}catch(error2){reject(error2)}}function execute(q){if(terminated)return queryError(q,Errors.connection("CONNECTION_DESTROYED",options));if(stream)return queryError(q,Errors.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(q.cancelled)return;try{return q.state=backend,query?sent.push(q):(query=q,query.active=!0),build(q),write(toBuffer(q))&&!q.describeFirst&&!q.cursorFn&&sent.length<max_pipeline&&(!q.options.onexecute||q.options.onexecute(connection2))}catch(error2){return sent.length===0&&write(Sync),errored(error2),!0}}function toBuffer(q){if(q.parameters.length>=65534)throw Errors.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return q.options.simple?bytes_default().Q().str(q.statement.string+bytes_default.N).end():q.describeFirst?Buffer.concat([describe(q),Flush]):q.prepare?q.prepared?prepared(q):Buffer.concat([describe(q),prepared(q)]):unnamed(q)}function describe(q){return Buffer.concat([Parse(q.statement.string,q.parameters,q.statement.types,q.statement.name),Describe("S",q.statement.name)])}function prepared(q){return Buffer.concat([Bind(q.parameters,q.statement.types,q.statement.name,q.cursorName),q.cursorFn?Execute("",q.cursorRows):ExecuteUnnamed])}function unnamed(q){return Buffer.concat([Parse(q.statement.string,q.parameters,q.statement.types),DescribeUnnamed,prepared(q)])}function build(q){let parameters=[],types4=[],string=stringify(q,q.strings[0],q.args[0],parameters,types4,options);!q.tagged&&q.args.forEach((x)=>handleValue(x,parameters,types4,options)),q.prepare=options.prepare&&("prepare"in q.options?q.options.prepare:!0),q.string=string,q.signature=q.prepare&&types4+string,q.onlyDescribe&&delete statements[q.signature],q.parameters=q.parameters||parameters,q.prepared=q.prepare&&q.signature in statements,q.describeFirst=q.onlyDescribe||parameters.length&&!q.prepared,q.statement=q.prepared?statements[q.signature]:{string,types:types4,name:q.prepare?statementId+statementCount++:""},typeof options.debug==="function"&&options.debug(id,string,parameters,types4)}function write(x,fn){if(chunk=chunk?Buffer.concat([chunk,x]):Buffer.from(x),fn||chunk.length>=1024)return nextWrite(fn);return nextWriteTimer===null&&(nextWriteTimer=setImmediate(nextWrite)),!0}function nextWrite(fn){let x=socket.write(chunk,fn);return nextWriteTimer!==null&&clearImmediate(nextWriteTimer),chunk=nextWriteTimer=null,x}function connectTimedOut(){errored(Errors.connection("CONNECT_TIMEOUT",options,socket)),socket.destroy()}async function secure(){if(sslnegotiation!=="direct"){if(write(SSLRequest),!await new Promise((r)=>socket.once("data",(x)=>r(x[0]===83)))&&ssl==="prefer")return connected()}let options2={socket,servername:net.isIP(socket.host)?void 0:socket.host};if(sslnegotiation==="direct")options2.ALPNProtocols=["postgresql"];if(ssl==="require"||ssl==="allow"||ssl==="prefer")options2.rejectUnauthorized=!1;else if(typeof ssl==="object")Object.assign(options2,ssl);socket.removeAllListeners(),socket=tls.connect(options2),socket.on("secureConnect",connected),socket.on("error",error),socket.on("close",closed),socket.on("drain",drain)}function drain(){!query&&onopen(connection2)}function data(x){if(incomings){if(incomings.push(x),remaining-=x.length,remaining>0)return}incoming=incomings?Buffer.concat(incomings,length-remaining):incoming.length===0?x:Buffer.concat([incoming,x],incoming.length+x.length);while(incoming.length>4){if(length=incoming.readUInt32BE(1),length>=incoming.length){remaining=length-incoming.length,incomings=[incoming];break}try{handle(incoming.subarray(0,length+1))}catch(e){query&&(query.cursorFn||query.describeFirst)&&write(Sync),errored(e)}incoming=incoming.subarray(length+1),remaining=0,incomings=null}}async function connect(){if(terminated=!1,backendParameters={},socket||(socket=await createSocket()),!socket)return;if(connectTimer.start(),options.socket)return ssl?secure():connected();if(socket.on("connect",ssl?secure:connected),options.path)return socket.connect(options.path);socket.ssl=ssl,socket.connect(port[hostIndex],host[hostIndex]),socket.host=host[hostIndex],socket.port=port[hostIndex],hostIndex=(hostIndex+1)%port.length}function reconnect(){setTimeout(connect,closedTime?Math.max(0,closedTime+delay-performance2.now()):0)}function connected(){try{statements={},needsTypes=options.fetch_types,statementId=Math.random().toString(36).slice(2),statementCount=1,lifeTimer.start(),socket.on("data",data),keep_alive&&socket.setKeepAlive&&socket.setKeepAlive(!0,1000*keep_alive);let s=StartupMessage();write(s)}catch(err){error(err)}}function error(err){if(connection2.queue===queues.connecting&&options.host[retries+1])return;errored(err);while(sent.length)queryError(sent.shift(),err)}function errored(err){stream&&(stream.destroy(err),stream=null),query&&queryError(query,err),initial&&(queryError(initial,err),initial=null)}function queryError(query2,err){if(query2.reserve)return query2.reject(err);if(!err||typeof err!=="object")err=Error(err);"query"in err||"parameters"in err||Object.defineProperties(err,{stack:{value:err.stack+query2.origin.replace(/.*\n/,`
|
|
235
|
+
`),enumerable:options.debug},query:{value:query2.string,enumerable:options.debug},parameters:{value:query2.parameters,enumerable:options.debug},args:{value:query2.args,enumerable:options.debug},types:{value:query2.statement&&query2.statement.types,enumerable:options.debug}}),query2.reject(err)}function end(){return ending||(!connection2.reserved&&onend(connection2),!connection2.reserved&&!initial&&!query&&sent.length===0?(terminate(),new Promise((r)=>socket&&socket.readyState!=="closed"?socket.once("close",r):r())):ending=new Promise((r)=>ended=r))}function terminate(){if(terminated=!0,stream||query||initial||sent.length)error(Errors.connection("CONNECTION_DESTROYED",options));if(clearImmediate(nextWriteTimer),socket)socket.removeListener("data",data),socket.removeListener("connect",connected),socket.readyState==="open"&&socket.end(bytes_default().X().end());ended&&(ended(),ending=ended=null)}async function closed(hadError){if(incoming=Buffer.alloc(0),remaining=0,incomings=null,clearImmediate(nextWriteTimer),socket.removeListener("data",data),socket.removeListener("connect",connected),idleTimer.cancel(),lifeTimer.cancel(),connectTimer.cancel(),socket.removeAllListeners(),socket=null,initial)return reconnect();!hadError&&(query||sent.length)&&error(Errors.connection("CONNECTION_CLOSED",options,socket)),closedTime=performance2.now(),hadError&&options.shared.retries++,delay=(typeof backoff==="function"?backoff(options.shared.retries):backoff)*1000,onclose(connection2,Errors.connection("CONNECTION_CLOSED",options,socket))}function handle(xs,x=xs[0]){(x===68?DataRow:x===100?CopyData:x===65?NotificationResponse:x===83?ParameterStatus:x===90?ReadyForQuery:x===67?CommandComplete:x===50?BindComplete:x===49?ParseComplete:x===116?ParameterDescription:x===84?RowDescription:x===82?Authentication:x===110?NoData:x===75?BackendKeyData:x===69?ErrorResponse:x===115?PortalSuspended:x===51?CloseComplete:x===71?CopyInResponse:x===78?NoticeResponse:x===72?CopyOutResponse:x===99?CopyDone:x===73?EmptyQueryResponse:x===86?FunctionCallResponse:x===118?NegotiateProtocolVersion:x===87?CopyBothResponse:UnknownMessage)(xs)}function DataRow(x){let index=7,length2,column,value,row=query.isRaw?Array(query.statement.columns.length):{};for(let i2=0;i2<query.statement.columns.length;i2++)column=query.statement.columns[i2],length2=x.readInt32BE(index),index+=4,value=length2===-1?null:query.isRaw===!0?x.subarray(index,index+=length2):column.parser===void 0?x.toString("utf8",index,index+=length2):column.parser.array===!0?column.parser(x.toString("utf8",index+1,index+=length2)):column.parser(x.toString("utf8",index,index+=length2)),query.isRaw?row[i2]=query.isRaw===!0?value:transform.value.from?transform.value.from(value,column):value:row[column.name]=transform.value.from?transform.value.from(value,column):value;query.forEachFn?query.forEachFn(transform.row.from?transform.row.from(row):row,result2):result2[rows++]=transform.row.from?transform.row.from(row):row}function ParameterStatus(x){let[k,v]=x.toString("utf8",5,x.length-1).split(bytes_default.N);if(backendParameters[k]=v,options.parameters[k]!==v)options.parameters[k]=v,onparameter&&onparameter(k,v)}function ReadyForQuery(x){if(query)if(errorResponse)query.retried?errored(query.retried):query.prepared&&retryRoutines.has(errorResponse.routine)?retry(query,errorResponse):errored(errorResponse);else query.resolve(results||result2);else if(errorResponse)errored(errorResponse);if(query=results=errorResponse=null,result2=new Result,connectTimer.cancel(),initial){if(target_session_attrs){if(!backendParameters.in_hot_standby||!backendParameters.default_transaction_read_only)return fetchState();else if(tryNext(target_session_attrs,backendParameters))return terminate()}if(needsTypes)return initial.reserve&&(initial=null),fetchArrayTypes();initial&&!initial.reserve&&execute(initial),options.shared.retries=retries=0,initial=null;return}while(sent.length&&(query=sent.shift())&&(query.active=!0,query.cancelled))Connection(options).cancel(query.state,query.cancelled.resolve,query.cancelled.reject);if(query)return;connection2.reserved?!connection2.reserved.release&&x[5]===73?ending?terminate():(connection2.reserved=null,onopen(connection2)):connection2.reserved():ending?terminate():onopen(connection2)}function CommandComplete(x){rows=0;for(let i2=x.length-1;i2>0;i2--){if(x[i2]===32&&x[i2+1]<58&&result2.count===null)result2.count=+x.toString("utf8",i2+1,x.length-1);if(x[i2-1]>=65){result2.command=x.toString("utf8",5,i2),result2.state=backend;break}}if(final&&(final(),final=null),result2.command==="BEGIN"&&max!==1&&!connection2.reserved)return errored(Errors.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(query.options.simple)return BindComplete();if(query.cursorFn)result2.count&&query.cursorFn(result2),write(Sync)}function ParseComplete(){query.parsing=!1}function BindComplete(){!result2.statement&&(result2.statement=query.statement),result2.columns=query.statement.columns}function ParameterDescription(x){let length2=x.readUInt16BE(5);for(let i2=0;i2<length2;++i2)!query.statement.types[i2]&&(query.statement.types[i2]=x.readUInt32BE(7+i2*4));query.prepare&&(statements[query.signature]=query.statement),query.describeFirst&&!query.onlyDescribe&&(write(prepared(query)),query.describeFirst=!1)}function RowDescription(x){if(result2.command)results=results||[result2],results.push(result2=new Result),result2.count=null,query.statement.columns=null;let length2=x.readUInt16BE(5),index=7,start;query.statement.columns=Array(length2);for(let i2=0;i2<length2;++i2){start=index;while(x[index++]!==0);let table=x.readUInt32BE(index),number=x.readUInt16BE(index+4),type2=x.readUInt32BE(index+6);query.statement.columns[i2]={name:transform.column.from?transform.column.from(x.toString("utf8",start,index-1)):x.toString("utf8",start,index-1),parser:parsers2[type2],table,number,type:type2},index+=18}if(result2.statement=query.statement,query.onlyDescribe)return query.resolve(query.statement),write(Sync)}async function Authentication(x,type2=x.readUInt32BE(5)){(type2===3?AuthenticationCleartextPassword:type2===5?AuthenticationMD5Password:type2===10?SASL:type2===11?SASLContinue:type2===12?SASLFinal:type2!==0?UnknownAuth:noop)(x,type2)}async function AuthenticationCleartextPassword(){let payload=await Pass();write(bytes_default().p().str(payload).z(1).end())}async function AuthenticationMD5Password(x){let payload="md5"+await md5(Buffer.concat([Buffer.from(await md5(await Pass()+user)),x.subarray(9)]));write(bytes_default().p().str(payload).z(1).end())}async function SASL(){nonce=(await crypto2.randomBytes(18)).toString("base64"),bytes_default().p().str("SCRAM-SHA-256"+bytes_default.N);let i2=bytes_default.i;write(bytes_default.inc(4).str("n,,n=*,r="+nonce).i32(bytes_default.i-i2-4,i2).end())}async function SASLContinue(x){let res=x.toString("utf8",9).split(",").reduce((acc,x2)=>(acc[x2[0]]=x2.slice(2),acc),{}),saltedPassword=await crypto2.pbkdf2Sync(await Pass(),Buffer.from(res.s,"base64"),parseInt(res.i),32,"sha256"),clientKey=await hmac(saltedPassword,"Client Key"),auth="n=*,r="+nonce+",r="+res.r+",s="+res.s+",i="+res.i+",c=biws,r="+res.r;serverSignature=(await hmac(await hmac(saltedPassword,"Server Key"),auth)).toString("base64");let payload="c=biws,r="+res.r+",p="+xor(clientKey,Buffer.from(await hmac(await sha256(clientKey),auth))).toString("base64");write(bytes_default().p().str(payload).end())}function SASLFinal(x){if(x.toString("utf8",9).split(bytes_default.N,1)[0].slice(2)===serverSignature)return;errored(Errors.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),socket.destroy()}function Pass(){return Promise.resolve(typeof options.pass==="function"?options.pass():options.pass)}function NoData(){if(result2.statement=query.statement,result2.statement.columns=[],query.onlyDescribe)return query.resolve(query.statement),write(Sync)}function BackendKeyData(x){backend.pid=x.readUInt32BE(5),backend.secret=x.readUInt32BE(9)}async function fetchArrayTypes(){needsTypes=!1,(await new Query([`
|
|
161
236
|
select b.oid, b.typarray
|
|
162
237
|
from pg_catalog.pg_type a
|
|
163
238
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
@@ -167,7 +242,7 @@ ${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(f
|
|
|
167
242
|
`],[],execute)).forEach(({oid,typarray})=>addArrayType(oid,typarray))}function addArrayType(oid,typarray){if(!!options.parsers[typarray]&&!!options.serializers[typarray])return;let parser=options.parsers[oid];options.shared.typeArrayMap[oid]=typarray,options.parsers[typarray]=(xs)=>arrayParser(xs,parser,typarray),options.parsers[typarray].array=!0,options.serializers[typarray]=(xs)=>arraySerializer(xs,options.serializers[oid],options,typarray)}function tryNext(x,xs){return x==="read-write"&&xs.default_transaction_read_only==="on"||x==="read-only"&&xs.default_transaction_read_only==="off"||x==="primary"&&xs.in_hot_standby==="on"||x==="standby"&&xs.in_hot_standby==="off"||x==="prefer-standby"&&xs.in_hot_standby==="off"&&options.host[retries]}function fetchState(){let query2=new Query([`
|
|
168
243
|
show transaction_read_only;
|
|
169
244
|
select pg_catalog.pg_is_in_recovery()
|
|
170
|
-
`],[],execute,null,{simple:!0});query2.resolve=([[a],[b2]])=>{backendParameters.default_transaction_read_only=a.transaction_read_only,backendParameters.in_hot_standby=b2.pg_is_in_recovery?"on":"off"},query2.execute()}function ErrorResponse(x){if(query)(query.cursorFn||query.describeFirst)&&write(Sync),errorResponse=Errors.postgres(parseError(x));else errored(Errors.postgres(parseError(x)))}function retry(q,error2){delete statements[q.signature],q.retried=error2,execute(q)}function NotificationResponse(x){if(!onnotify)return;let index=9;while(x[index++]!==0);onnotify(x.toString("utf8",9,index-1),x.toString("utf8",index,x.length-1))}async function PortalSuspended(){try{let x=await Promise.resolve(query.cursorFn(result2));rows=0,x===CLOSE?write(Close(query.portal)):(result2=new Result,write(Execute("",query.cursorRows)))}catch(err){write(Sync),query.reject(err)}}function CloseComplete(){result2.count&&query.cursorFn(result2),query.resolve(result2)}function CopyInResponse(){stream=new Stream.Writable({autoDestroy:!0,write(chunk2,encoding,callback){socket.write(bytes_default().d().raw(chunk2).end(),callback)},destroy(error2,callback){callback(error2),socket.write(bytes_default().f().str(error2+bytes_default.N).end()),stream=null},final(callback){socket.write(bytes_default().c().end()),final=callback,stream=null}}),query.resolve(stream)}function CopyOutResponse(){stream=new Stream.Readable({read(){socket.resume()}}),query.resolve(stream)}function CopyBothResponse(){stream=new Stream.Duplex({autoDestroy:!0,read(){socket.resume()},write(chunk2,encoding,callback){socket.write(bytes_default().d().raw(chunk2).end(),callback)},destroy(error2,callback){callback(error2),socket.write(bytes_default().f().str(error2+bytes_default.N).end()),stream=null},final(callback){socket.write(bytes_default().c().end()),final=callback}}),query.resolve(stream)}function CopyData(x){stream&&(stream.push(x.subarray(5))||socket.pause())}function CopyDone(){stream&&stream.push(null),stream=null}function NoticeResponse(x){onnotice?onnotice(parseError(x)):console.log(parseError(x))}function EmptyQueryResponse(){}function FunctionCallResponse(){errored(Errors.notSupported("FunctionCallResponse"))}function NegotiateProtocolVersion(){errored(Errors.notSupported("NegotiateProtocolVersion"))}function UnknownMessage(x){console.error("Postgres.js : Unknown Message:",x[0])}function UnknownAuth(x,type){console.error("Postgres.js : Unknown Auth:",type)}function Bind(parameters,types3,statement="",portal=""){let prev,type;return bytes_default().B().str(portal+bytes_default.N).str(statement+bytes_default.N).i16(0).i16(parameters.length),parameters.forEach((x,i)=>{if(x===null)return bytes_default.i32(4294967295);type=types3[i],parameters[i]=x=type in options.serializers?options.serializers[type](x):""+x,prev=bytes_default.i,bytes_default.inc(4).str(x).i32(bytes_default.i-prev-4,prev)}),bytes_default.i16(0),bytes_default.end()}function Parse(str,parameters,types3,name=""){return bytes_default().P().str(name+bytes_default.N).str(str+bytes_default.N).i16(parameters.length),parameters.forEach((x,i)=>bytes_default.i32(types3[i]||0)),bytes_default.end()}function Describe(x,name=""){return bytes_default().D().str(x).str(name+bytes_default.N).end()}function Execute(portal="",rows2=0){return Buffer.concat([bytes_default().E().str(portal+bytes_default.N).i32(rows2).end(),Flush])}function Close(portal=""){return Buffer.concat([bytes_default().C().str("P").str(portal+bytes_default.N).end(),bytes_default().S().end()])}function StartupMessage(){return cancelMessage||bytes_default().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user,database,client_encoding:"UTF8"},options.connection)).filter(([,v])=>v).map(([k,v])=>k+bytes_default.N+v).join(bytes_default.N)).z(2).end(0)}}function parseError(x){let error={},start=5;for(let i=5;i<x.length-1;i++)if(x[i]===0)error[errorFields[x[start]]]=x.toString("utf8",start+1,i),start=i+1;return error}function md5(x){return crypto2.createHash("md5").update(x).digest("hex")}function hmac(key,x){return crypto2.createHmac("sha256",key).update(x).digest()}function sha256(x){return crypto2.createHash("sha256").update(x).digest()}function xor(a,b2){let length=Math.max(a.length,b2.length),buffer2=Buffer.allocUnsafe(length);for(let i=0;i<length;i++)buffer2[i]=a[i]^b2[i];return buffer2}function timer(fn,seconds){if(seconds=typeof seconds==="function"?seconds():seconds,!seconds)return{cancel:noop,start:noop};let timer2;return{cancel(){timer2&&(clearTimeout(timer2),timer2=null)},start(){timer2&&clearTimeout(timer2),timer2=setTimeout(done,seconds*1000,arguments)}};function done(args){fn.apply(null,args),timer2=null}}var connection_default,uid=1,Sync,Flush,SSLRequest,ExecuteUnnamed,DescribeUnnamed,noop=()=>{},retryRoutines,errorFields;var init_connection=__esm(()=>{init_types3();init_errors2();init_result();init_queue();init_query();init_bytes();connection_default=Connection,Sync=bytes_default().S().end(),Flush=bytes_default().H().end(),SSLRequest=bytes_default().i32(8).i32(80877103).end(8),ExecuteUnnamed=Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(),Sync]),DescribeUnnamed=bytes_default().D().str("S").str(bytes_default.N).end(),retryRoutines=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),errorFields={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"}});function Subscribe(postgres2,options){let subscribers=new Map,slot="postgresjs_"+Math.random().toString(36).slice(2),state={},connection2,stream,ended=!1,sql=subscribe.sql=postgres2({...options,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...options.connection,replication:"database"},onclose:async function(){if(ended)return;stream=null,state.pid=state.secret=void 0,connected(await init(sql,slot,options.publications)),subscribers.forEach((event)=>event.forEach(({onsubscribe})=>onsubscribe()))},no_subscribe:!0}),end=sql.end,close=sql.close;return sql.end=async()=>{return ended=!0,stream&&await new Promise((r)=>(stream.once("close",r),stream.end())),end()},sql.close=async()=>{return stream&&await new Promise((r)=>(stream.once("close",r),stream.end())),close()},subscribe;async function subscribe(event,fn,onsubscribe=noop2,onerror=noop2){if(event=parseEvent(event),!connection2)connection2=init(sql,slot,options.publications);let subscriber={fn,onsubscribe},fns=subscribers.has(event)?subscribers.get(event).add(subscriber):subscribers.set(event,new Set([subscriber])).get(event),unsubscribe=()=>{fns.delete(subscriber),fns.size===0&&subscribers.delete(event)};return connection2.then((x)=>{return connected(x),onsubscribe(),stream&&stream.on("error",onerror),{unsubscribe,state,sql}})}function connected(x){stream=x.stream,state.pid=x.state.pid,state.secret=x.state.secret}async function init(sql2,slot2,publications){if(!publications)throw Error("Missing publication names");let xs=await sql2.unsafe(`CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[x]=xs,stream2=await sql2.unsafe(`START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`).writable(),state2={lsn:Buffer.concat(x.consistent_point.split("/").map((x2)=>Buffer.from(("00000000"+x2).slice(-8),"hex")))};return stream2.on("data",data),stream2.on("error",error),stream2.on("close",sql2.close),{stream:stream2,state:xs.state};function error(e){console.error("Unexpected error during logical streaming - reconnecting",e)}function data(x2){if(x2[0]===119)parse(x2.subarray(25),state2,sql2.options.parsers,handle,options.transform);else if(x2[0]===107&&x2[17])state2.lsn=x2.subarray(1,9),pong()}function handle(a,b2){let path=b2.relation.schema+"."+b2.relation.table;call("*",a,b2),call("*:"+path,a,b2),b2.relation.keys.length&&call("*:"+path+"="+b2.relation.keys.map((x2)=>a[x2.name]),a,b2),call(b2.command,a,b2),call(b2.command+":"+path,a,b2),b2.relation.keys.length&&call(b2.command+":"+path+"="+b2.relation.keys.map((x2)=>a[x2.name]),a,b2)}function pong(){let x2=Buffer.alloc(34);x2[0]=114,x2.fill(state2.lsn,1),x2.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),stream2.write(x2)}}function call(x,a,b2){subscribers.has(x)&&subscribers.get(x).forEach(({fn})=>fn(a,b2,x))}}function Time(x){return new Date(Date.UTC(2000,0,1)+Number(x/BigInt(1000)))}function parse(x,state,parsers2,handle,transform){let char=(acc,[k,v])=>(acc[k.charCodeAt(0)]=v,acc);Object.entries({R:(x2)=>{let i=1,r=state[x2.readUInt32BE(i)]={schema:x2.toString("utf8",i+=4,i=x2.indexOf(0,i))||"pg_catalog",table:x2.toString("utf8",i+1,i=x2.indexOf(0,i+1)),columns:Array(x2.readUInt16BE(i+=2)),keys:[]};i+=2;let columnIndex=0,column;while(i<x2.length)column=r.columns[columnIndex++]={key:x2[i++],name:transform.column.from?transform.column.from(x2.toString("utf8",i,i=x2.indexOf(0,i))):x2.toString("utf8",i,i=x2.indexOf(0,i)),type:x2.readUInt32BE(i+=1),parser:parsers2[x2.readUInt32BE(i)],atttypmod:x2.readUInt32BE(i+=4)},column.key&&r.keys.push(column),i+=4},Y:()=>{},O:()=>{},B:(x2)=>{state.date=Time(x2.readBigInt64BE(9)),state.lsn=x2.subarray(1,9)},I:(x2)=>{let i=1,relation=state[x2.readUInt32BE(i)],{row}=tuples(x2,relation.columns,i+=7,transform);handle(row,{command:"insert",relation})},D:(x2)=>{let i=1,relation=state[x2.readUInt32BE(i)];i+=4;let key=x2[i]===75;handle(key||x2[i]===79?tuples(x2,relation.columns,i+=3,transform).row:null,{command:"delete",relation,key})},U:(x2)=>{let i=1,relation=state[x2.readUInt32BE(i)];i+=4;let key=x2[i]===75,xs=key||x2[i]===79?tuples(x2,relation.columns,i+=3,transform):null;xs&&(i=xs.i);let{row}=tuples(x2,relation.columns,i+3,transform);handle(row,{command:"update",relation,key,old:xs&&xs.row})},T:()=>{},C:()=>{}}).reduce(char,{})[x[0]](x)}function tuples(x,columns,xi,transform){let type,column,value,row=transform.raw?Array(columns.length):{};for(let i=0;i<columns.length;i++)type=x[xi++],column=columns[i],value=type===110?null:type===117?void 0:column.parser===void 0?x.toString("utf8",xi+4,xi+=4+x.readUInt32BE(xi)):column.parser.array===!0?column.parser(x.toString("utf8",xi+5,xi+=4+x.readUInt32BE(xi))):column.parser(x.toString("utf8",xi+4,xi+=4+x.readUInt32BE(xi))),transform.raw?row[i]=transform.raw===!0?value:transform.value.from?transform.value.from(value,column):value:row[column.name]=transform.value.from?transform.value.from(value,column):value;return{i:xi,row:transform.row.from?transform.row.from(row):row}}function parseEvent(x){let xs=x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!xs)throw Error("Malformed subscribe pattern: "+x);let[,command,path,key]=xs;return(command||"*")+(path?":"+(path.indexOf(".")===-1?"public."+path:path):"")+(key?"="+key:"")}var noop2=()=>{};import Stream2 from"stream";function largeObject(sql,oid,mode=393216){return new Promise(async(resolve,reject)=>{await sql.begin(async(sql2)=>{let finish;!oid&&([{oid}]=await sql2`select lo_creat(-1) as oid`);let[{fd}]=await sql2`select lo_open(${oid}, ${mode}) as fd`,lo={writable,readable,close:()=>sql2`select lo_close(${fd})`.then(finish),tell:()=>sql2`select lo_tell64(${fd})`,read:(x)=>sql2`select loread(${fd}, ${x}) as data`,write:(x)=>sql2`select lowrite(${fd}, ${x})`,truncate:(x)=>sql2`select lo_truncate64(${fd}, ${x})`,seek:(x,whence=0)=>sql2`select lo_lseek64(${fd}, ${x}, ${whence})`,size:()=>sql2`
|
|
245
|
+
`],[],execute,null,{simple:!0});query2.resolve=([[a],[b2]])=>{backendParameters.default_transaction_read_only=a.transaction_read_only,backendParameters.in_hot_standby=b2.pg_is_in_recovery?"on":"off"},query2.execute()}function ErrorResponse(x){if(query)(query.cursorFn||query.describeFirst)&&write(Sync),errorResponse=Errors.postgres(parseError(x));else errored(Errors.postgres(parseError(x)))}function retry(q,error2){delete statements[q.signature],q.retried=error2,execute(q)}function NotificationResponse(x){if(!onnotify)return;let index=9;while(x[index++]!==0);onnotify(x.toString("utf8",9,index-1),x.toString("utf8",index,x.length-1))}async function PortalSuspended(){try{let x=await Promise.resolve(query.cursorFn(result2));rows=0,x===CLOSE?write(Close(query.portal)):(result2=new Result,write(Execute("",query.cursorRows)))}catch(err){write(Sync),query.reject(err)}}function CloseComplete(){result2.count&&query.cursorFn(result2),query.resolve(result2)}function CopyInResponse(){stream=new Stream.Writable({autoDestroy:!0,write(chunk2,encoding,callback){socket.write(bytes_default().d().raw(chunk2).end(),callback)},destroy(error2,callback){callback(error2),socket.write(bytes_default().f().str(error2+bytes_default.N).end()),stream=null},final(callback){socket.write(bytes_default().c().end()),final=callback,stream=null}}),query.resolve(stream)}function CopyOutResponse(){stream=new Stream.Readable({read(){socket.resume()}}),query.resolve(stream)}function CopyBothResponse(){stream=new Stream.Duplex({autoDestroy:!0,read(){socket.resume()},write(chunk2,encoding,callback){socket.write(bytes_default().d().raw(chunk2).end(),callback)},destroy(error2,callback){callback(error2),socket.write(bytes_default().f().str(error2+bytes_default.N).end()),stream=null},final(callback){socket.write(bytes_default().c().end()),final=callback}}),query.resolve(stream)}function CopyData(x){stream&&(stream.push(x.subarray(5))||socket.pause())}function CopyDone(){stream&&stream.push(null),stream=null}function NoticeResponse(x){onnotice?onnotice(parseError(x)):console.log(parseError(x))}function EmptyQueryResponse(){}function FunctionCallResponse(){errored(Errors.notSupported("FunctionCallResponse"))}function NegotiateProtocolVersion(){errored(Errors.notSupported("NegotiateProtocolVersion"))}function UnknownMessage(x){console.error("Postgres.js : Unknown Message:",x[0])}function UnknownAuth(x,type2){console.error("Postgres.js : Unknown Auth:",type2)}function Bind(parameters,types4,statement="",portal=""){let prev,type2;return bytes_default().B().str(portal+bytes_default.N).str(statement+bytes_default.N).i16(0).i16(parameters.length),parameters.forEach((x,i2)=>{if(x===null)return bytes_default.i32(4294967295);type2=types4[i2],parameters[i2]=x=type2 in options.serializers?options.serializers[type2](x):""+x,prev=bytes_default.i,bytes_default.inc(4).str(x).i32(bytes_default.i-prev-4,prev)}),bytes_default.i16(0),bytes_default.end()}function Parse(str2,parameters,types4,name=""){return bytes_default().P().str(name+bytes_default.N).str(str2+bytes_default.N).i16(parameters.length),parameters.forEach((x,i2)=>bytes_default.i32(types4[i2]||0)),bytes_default.end()}function Describe(x,name=""){return bytes_default().D().str(x).str(name+bytes_default.N).end()}function Execute(portal="",rows2=0){return Buffer.concat([bytes_default().E().str(portal+bytes_default.N).i32(rows2).end(),Flush])}function Close(portal=""){return Buffer.concat([bytes_default().C().str("P").str(portal+bytes_default.N).end(),bytes_default().S().end()])}function StartupMessage(){return cancelMessage||bytes_default().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user,database,client_encoding:"UTF8"},options.connection)).filter(([,v])=>v).map(([k,v])=>k+bytes_default.N+v).join(bytes_default.N)).z(2).end(0)}}function parseError(x){let error={},start=5;for(let i2=5;i2<x.length-1;i2++)if(x[i2]===0)error[errorFields[x[start]]]=x.toString("utf8",start+1,i2),start=i2+1;return error}function md5(x){return crypto2.createHash("md5").update(x).digest("hex")}function hmac(key,x){return crypto2.createHmac("sha256",key).update(x).digest()}function sha256(x){return crypto2.createHash("sha256").update(x).digest()}function xor(a,b2){let length=Math.max(a.length,b2.length),buffer2=Buffer.allocUnsafe(length);for(let i2=0;i2<length;i2++)buffer2[i2]=a[i2]^b2[i2];return buffer2}function timer(fn,seconds){if(seconds=typeof seconds==="function"?seconds():seconds,!seconds)return{cancel:noop,start:noop};let timer2;return{cancel(){timer2&&(clearTimeout(timer2),timer2=null)},start(){timer2&&clearTimeout(timer2),timer2=setTimeout(done,seconds*1000,arguments)}};function done(args){fn.apply(null,args),timer2=null}}var connection_default,uid=1,Sync,Flush,SSLRequest,ExecuteUnnamed,DescribeUnnamed,noop=()=>{},retryRoutines,errorFields;var init_connection=__esm(()=>{init_types2();init_errors2();init_result();init_queue();init_query();init_bytes();connection_default=Connection,Sync=bytes_default().S().end(),Flush=bytes_default().H().end(),SSLRequest=bytes_default().i32(8).i32(80877103).end(8),ExecuteUnnamed=Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(),Sync]),DescribeUnnamed=bytes_default().D().str("S").str(bytes_default.N).end(),retryRoutines=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),errorFields={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"}});function Subscribe(postgres2,options){let subscribers=new Map,slot="postgresjs_"+Math.random().toString(36).slice(2),state={},connection2,stream,ended=!1,sql=subscribe.sql=postgres2({...options,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...options.connection,replication:"database"},onclose:async function(){if(ended)return;stream=null,state.pid=state.secret=void 0,connected(await init(sql,slot,options.publications)),subscribers.forEach((event)=>event.forEach(({onsubscribe})=>onsubscribe()))},no_subscribe:!0}),end=sql.end,close=sql.close;return sql.end=async()=>{return ended=!0,stream&&await new Promise((r)=>(stream.once("close",r),stream.end())),end()},sql.close=async()=>{return stream&&await new Promise((r)=>(stream.once("close",r),stream.end())),close()},subscribe;async function subscribe(event,fn,onsubscribe=noop2,onerror=noop2){if(event=parseEvent(event),!connection2)connection2=init(sql,slot,options.publications);let subscriber={fn,onsubscribe},fns=subscribers.has(event)?subscribers.get(event).add(subscriber):subscribers.set(event,new Set([subscriber])).get(event),unsubscribe=()=>{fns.delete(subscriber),fns.size===0&&subscribers.delete(event)};return connection2.then((x)=>{return connected(x),onsubscribe(),stream&&stream.on("error",onerror),{unsubscribe,state,sql}})}function connected(x){stream=x.stream,state.pid=x.state.pid,state.secret=x.state.secret}async function init(sql2,slot2,publications){if(!publications)throw Error("Missing publication names");let xs=await sql2.unsafe(`CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[x]=xs,stream2=await sql2.unsafe(`START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`).writable(),state2={lsn:Buffer.concat(x.consistent_point.split("/").map((x2)=>Buffer.from(("00000000"+x2).slice(-8),"hex")))};return stream2.on("data",data),stream2.on("error",error),stream2.on("close",sql2.close),{stream:stream2,state:xs.state};function error(e){console.error("Unexpected error during logical streaming - reconnecting",e)}function data(x2){if(x2[0]===119)parse(x2.subarray(25),state2,sql2.options.parsers,handle,options.transform);else if(x2[0]===107&&x2[17])state2.lsn=x2.subarray(1,9),pong()}function handle(a,b2){let path=b2.relation.schema+"."+b2.relation.table;call("*",a,b2),call("*:"+path,a,b2),b2.relation.keys.length&&call("*:"+path+"="+b2.relation.keys.map((x2)=>a[x2.name]),a,b2),call(b2.command,a,b2),call(b2.command+":"+path,a,b2),b2.relation.keys.length&&call(b2.command+":"+path+"="+b2.relation.keys.map((x2)=>a[x2.name]),a,b2)}function pong(){let x2=Buffer.alloc(34);x2[0]=114,x2.fill(state2.lsn,1),x2.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),stream2.write(x2)}}function call(x,a,b2){subscribers.has(x)&&subscribers.get(x).forEach(({fn})=>fn(a,b2,x))}}function Time(x){return new Date(Date.UTC(2000,0,1)+Number(x/BigInt(1000)))}function parse(x,state,parsers2,handle,transform){let char=(acc,[k,v])=>(acc[k.charCodeAt(0)]=v,acc);Object.entries({R:(x2)=>{let i2=1,r=state[x2.readUInt32BE(i2)]={schema:x2.toString("utf8",i2+=4,i2=x2.indexOf(0,i2))||"pg_catalog",table:x2.toString("utf8",i2+1,i2=x2.indexOf(0,i2+1)),columns:Array(x2.readUInt16BE(i2+=2)),keys:[]};i2+=2;let columnIndex=0,column;while(i2<x2.length)column=r.columns[columnIndex++]={key:x2[i2++],name:transform.column.from?transform.column.from(x2.toString("utf8",i2,i2=x2.indexOf(0,i2))):x2.toString("utf8",i2,i2=x2.indexOf(0,i2)),type:x2.readUInt32BE(i2+=1),parser:parsers2[x2.readUInt32BE(i2)],atttypmod:x2.readUInt32BE(i2+=4)},column.key&&r.keys.push(column),i2+=4},Y:()=>{},O:()=>{},B:(x2)=>{state.date=Time(x2.readBigInt64BE(9)),state.lsn=x2.subarray(1,9)},I:(x2)=>{let i2=1,relation=state[x2.readUInt32BE(i2)],{row}=tuples(x2,relation.columns,i2+=7,transform);handle(row,{command:"insert",relation})},D:(x2)=>{let i2=1,relation=state[x2.readUInt32BE(i2)];i2+=4;let key=x2[i2]===75;handle(key||x2[i2]===79?tuples(x2,relation.columns,i2+=3,transform).row:null,{command:"delete",relation,key})},U:(x2)=>{let i2=1,relation=state[x2.readUInt32BE(i2)];i2+=4;let key=x2[i2]===75,xs=key||x2[i2]===79?tuples(x2,relation.columns,i2+=3,transform):null;xs&&(i2=xs.i);let{row}=tuples(x2,relation.columns,i2+3,transform);handle(row,{command:"update",relation,key,old:xs&&xs.row})},T:()=>{},C:()=>{}}).reduce(char,{})[x[0]](x)}function tuples(x,columns,xi,transform){let type2,column,value,row=transform.raw?Array(columns.length):{};for(let i2=0;i2<columns.length;i2++)type2=x[xi++],column=columns[i2],value=type2===110?null:type2===117?void 0:column.parser===void 0?x.toString("utf8",xi+4,xi+=4+x.readUInt32BE(xi)):column.parser.array===!0?column.parser(x.toString("utf8",xi+5,xi+=4+x.readUInt32BE(xi))):column.parser(x.toString("utf8",xi+4,xi+=4+x.readUInt32BE(xi))),transform.raw?row[i2]=transform.raw===!0?value:transform.value.from?transform.value.from(value,column):value:row[column.name]=transform.value.from?transform.value.from(value,column):value;return{i:xi,row:transform.row.from?transform.row.from(row):row}}function parseEvent(x){let xs=x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!xs)throw Error("Malformed subscribe pattern: "+x);let[,command,path,key]=xs;return(command||"*")+(path?":"+(path.indexOf(".")===-1?"public."+path:path):"")+(key?"="+key:"")}var noop2=()=>{};import Stream2 from"stream";function largeObject(sql,oid,mode=393216){return new Promise(async(resolve2,reject)=>{await sql.begin(async(sql2)=>{let finish;!oid&&([{oid}]=await sql2`select lo_creat(-1) as oid`);let[{fd}]=await sql2`select lo_open(${oid}, ${mode}) as fd`,lo={writable,readable,close:()=>sql2`select lo_close(${fd})`.then(finish),tell:()=>sql2`select lo_tell64(${fd})`,read:(x)=>sql2`select loread(${fd}, ${x}) as data`,write:(x)=>sql2`select lowrite(${fd}, ${x})`,truncate:(x)=>sql2`select lo_truncate64(${fd}, ${x})`,seek:(x,whence=0)=>sql2`select lo_lseek64(${fd}, ${x}, ${whence})`,size:()=>sql2`
|
|
171
246
|
select
|
|
172
247
|
lo_lseek64(${fd}, location, 0) as position,
|
|
173
248
|
seek.size
|
|
@@ -177,107 +252,17 @@ ${readFileSync3(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(f
|
|
|
177
252
|
tell.location
|
|
178
253
|
from (select lo_tell64($1) as location) tell
|
|
179
254
|
) seek
|
|
180
|
-
`};return resolve(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(),open2=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open2,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 result3=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result3.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.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=open2.length?open2.shift():await new Promise((resolve,reject)=>{let query={reserve:resolve,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(error){throw error}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,result2;name&&await sql2`savepoint ${sql2(name)}`;try{if(result2=await new Promise((resolve,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve,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 result2;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===open2?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(open2.length)return go(open2.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((resolve,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve,reject):query.cancelled={resolve,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve())})}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(resolve){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve()}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,open2);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_types3();init_connection();init_query();init_queue();init_errors2();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 execSync2,spawn}from"child_process";import{existsSync as existsSync8,mkdirSync as mkdirSync5,readFileSync as readFileSync4,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync4}from"fs";import{homedir as homedir8}from"os";import{join as join10}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function selfHealPostgres(dataDir){try{execSync2(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync2(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join10(dataDir,"postmaster.pid");if(existsSync8(pidFile))try{unlinkSync3(pidFile)}catch{}try{execSync2("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((resolve)=>{setTimeout(()=>resolve(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync4(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{mkdirSync5(GENIE_HOME,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync4(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync3(LOCKFILE_PATH)}catch{}}async function runRetention(sql){try{await sql.unsafe(`
|
|
255
|
+
`};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,type2])=>{return acc[name]=(x)=>new Parameter(x,type2.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json:json2,file}),sql2;function typed(value,type2){return new Parameter(value,type2)}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 result3=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result3.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.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(error){throw error}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,result2;name&&await sql2`savepoint ${sql2(name)}`;try{if(result2=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 result2;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 json2(x){return new Parameter(x,3802)}function array(x,type2){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type2||(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_errors2();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 execSync2,spawn}from"child_process";import{existsSync as existsSync6,mkdirSync as mkdirSync4,readFileSync as readFileSync5,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync5}from"fs";import{homedir as homedir5}from"os";import{join as join7}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function selfHealPostgres(dataDir){try{execSync2(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync2(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join7(dataDir,"postmaster.pid");if(existsSync6(pidFile))try{unlinkSync3(pidFile)}catch{}try{execSync2("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=readFileSync5(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{mkdirSync4(GENIE_HOME,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync5(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync3(LOCKFILE_PATH)}catch{}}async function runRetention(sql){try{await sql.unsafe(`
|
|
181
256
|
DELETE FROM heartbeats WHERE created_at < now() - interval '7 days';
|
|
182
257
|
DELETE FROM machine_snapshots WHERE created_at < now() - interval '30 days';
|
|
183
258
|
DELETE FROM audit_events WHERE entity_type LIKE 'otel_%' AND created_at < now() - interval '30 days';
|
|
184
259
|
DELETE FROM genie_runtime_events WHERE created_at < now() - interval '14 days';
|
|
185
260
|
`),retentionRan=!0}catch(retErr){retentionRan=!0;let msg=retErr instanceof Error?retErr.message:String(retErr);process.stderr.write(`[genie] retention cleanup warning: ${msg}
|
|
186
|
-
`)}}async function ensurePgserve(){if(activePort===null){let testPort=await resolveTestPort();if(testPort!==null)return activePort=testPort,process.env.GENIE_PG_AVAILABLE="true",testPort}if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}async function autoStartDaemon(){for(let pidName of["serve.pid","scheduler.pid"]){let pidPath=
|
|
187
|
-
`).map((line)=>{let[id,name,attached,windows]=line.split(":");return{id,name,attached:attached==="1",windows:Number.parseInt(windows,10)}})}catch(error){if((error instanceof Error?error.message:String(error)).includes("no server running"))return[];throw error}}async function findSessionByName(name){try{return(await listSessions()).find((session)=>session.name===name)||null}catch(_error){return null}}async function getWindowEnv(target,varName){try{let output=await executeTmux2(`show-environment -t ${shellQuote(target)} ${shellQuote(varName)}`),prefix=`${varName}=`;if(output?.startsWith(prefix))return output.slice(prefix.length).trim();return null}catch{return null}}async function setWindowEnv(target,varName,value){await executeTmux2(`set-environment -t ${shellQuote(target)} ${shellQuote(varName)} ${shellQuote(value)}`)}async function killSession(sessionId){await executeTmux2(`kill-session -t '${sessionId}'`)}async function listWindows(sessionId){try{let output=await executeTmux2(`list-windows -t '${sessionId}' -F '#{window_id}:#{window_name}:#{window_index}:#{?window_active,1,0}'`);if(!output)return[];return output.split(`
|
|
188
|
-
`).map((line)=>{let[id,name,indexStr,active]=line.split(":");return{id,name,index:Number.parseInt(indexStr,10),active:active==="1",sessionId}})}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("session not found"))return[];throw error}}async function listPanes(windowId){try{let output=await executeTmux2(`list-panes -t '${windowId}' -F '#{pane_id}:#{pane_title}:#{?pane_active,1,0}'`);if(!output)return[];return output.split(`
|
|
189
|
-
`).map((line)=>{let[id,title,active]=line.split(":");return{id,windowId,title,active:active==="1"}})}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("window not found"))return[];throw error}}async function capturePaneContent(paneId,lines=200,includeColors=!1){try{return await executeTmux2(`capture-pane -p ${includeColors?"-e":""} -t '${paneId}' -S -${lines} -E -`)}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("pane not found"))return"";throw error}}async function createSession(name){return await executeTmux2(`new-session -d -s "${name}" -e LC_ALL=C.UTF-8 -e LANG=C.UTF-8`),findSessionByName(name)}async function createWindow(sessionId,name,workingDir){let cdFlag=workingDir?` -c '${workingDir.replace(/'/g,"'\\''")}'`:"",output=await executeTmux2(`new-window -d -P -F '#{window_id}:#{window_index}' -t '${sessionId}:' -n '${name}'${cdFlag}`),[windowId,indexStr]=output.trim().split(":");if(!windowId)return null;try{await executeTmux2(`set-window-option -t '${windowId}' automatic-rename off`)}catch{}return{id:windowId,name,index:Number.parseInt(indexStr,10)||0,active:!1,sessionId}}async function findWindowByName(sessionId,name){return(await listWindows(sessionId)).find((w)=>w.name===name)||null}async function ensureMasterWindow(session,masterName){try{let windows=await listWindows(session);if(windows.length<2)return;let masterWindow=windows.find((w)=>w.name===masterName);if(!masterWindow)return;let minIndex=Math.min(...windows.map((w)=>w.index));if(masterWindow.index===minIndex)return;await executeTmux2(`swap-window -s '${session}:${masterWindow.index}' -t '${session}:${minIndex}'`)}catch{}}async function ensureSessionExists(name){try{await executeTmux2(`new-session -d -s "${name}" -e LC_ALL=C.UTF-8 -e LANG=C.UTF-8`)}catch(error){if((error instanceof Error?error.message:String(error)).includes("duplicate session"))return;throw error}}async function ensureTeamWindow(session,teamName,workingDir){for(let attempt=0;attempt<3;attempt++)try{return await ensureTeamWindowOnce(session,teamName,workingDir)}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("server exited")||message.includes("error connecting")){if(attempt<2){let delay=250*2**attempt;console.warn(`[genie-tmux] tmux server unreachable (attempt ${attempt+1}/3), retrying in ${delay}ms...`),await new Promise((resolve)=>setTimeout(resolve,delay));continue}}throw error}throw Error("Failed to ensure team window after 3 attempts")}async function ensureTeamWindowOnce(session,teamName,workingDir){await ensureSessionExists(session);let existing=await findWindowByName(session,teamName);if(existing){try{await executeTmux2(`set-window-option -t '${existing.id}' automatic-rename off`)}catch{}await rehydratePaneColorHook(existing.id);let panes2=await listPanes(existing.id),paneId2=panes2.length>0?panes2[0].id:`${session}:${teamName}.0`;return{windowId:existing.id,windowName:teamName,paneId:paneId2,created:!1}}let windowsBefore=await listWindows(session),masterBefore=windowsBefore.length>0?windowsBefore.reduce((a,b2)=>a.index<=b2.index?a:b2):null,newWindow=await createWindow(session,teamName,workingDir);if(!newWindow)throw Error(`Failed to create team window "${teamName}" in session "${session}"`);if(masterBefore)await ensureMasterWindow(session,masterBefore.name);await rehydratePaneColorHook(newWindow.id);let panes=await listPanes(newWindow.id),paneId=panes.length>0?panes[0].id:`${session}:${teamName}.0`;return{windowId:newWindow.id,windowName:teamName,paneId,created:!0}}function ensurePaneColorScript(){let{existsSync:existsSync9,writeFileSync:writeFileSync5,mkdirSync:mkdirSync6,chmodSync:chmodSync2}=__require("fs"),{dirname:dirname2}=__require("path");if(existsSync9(PANE_COLOR_SCRIPT))return;mkdirSync6(dirname2(PANE_COLOR_SCRIPT),{recursive:!0});let bin=tmuxBin();writeFileSync5(PANE_COLOR_SCRIPT,`#!/bin/bash
|
|
190
|
-
# Genie tmux pane color router \u2014 reads @genie_color pane option
|
|
191
|
-
PANE_ID="$1"
|
|
192
|
-
COLOR=$(${bin} display-message -p -t "$PANE_ID" '#{@genie_color}' 2>/dev/null)
|
|
193
|
-
[ -z "$COLOR" ] && COLOR="default"
|
|
194
|
-
${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
195
|
-
`),chmodSync2(PANE_COLOR_SCRIPT,493)}async function applyPaneColor(paneId,color,windowId){let hex=TMUX_COLOR_MAP[color]??TMUX_COLOR_MAP.blue;try{ensurePaneColorScript(),await executeTmux2(`set-option -p -t '${paneId}' @genie_color '${hex}'`);try{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));await(await getConnection2())`UPDATE executors SET pane_color = ${hex} WHERE tmux_pane_id = ${paneId}`}catch{}if(windowId)await executeTmux2(`set-hook -w -t '${windowId}' pane-focus-in "run-shell '${PANE_COLOR_SCRIPT} #{pane_id}'"`)}catch{}}async function rehydratePaneColorHook(windowId){try{ensurePaneColorScript(),await executeTmux2(`set-hook -w -t '${windowId}' pane-focus-in "run-shell '${PANE_COLOR_SCRIPT} #{pane_id}'"`)}catch{}}async function resolveRepoSession(repoPath){let derived=basename2(repoPath);try{let sessions=await listSessions(),exact=sessions.find((s)=>s.name===derived);if(exact)return exact.name;if(process.env.TMUX)try{let name=(await executeTmux2("display-message -p '#{session_name}'")).trim();if(name)return name}catch{}let partial=sessions.find((s)=>s.name.includes(derived));if(partial)return partial.name}catch{}return derived}async function isPaneAlive(paneId){if(!paneId||paneId==="inline")return!1;if(!/^%\d+$/.test(paneId))return!1;try{return(await executeTmux2(`display-message -t '${paneId}' -p '#{pane_dead}'`)).trim()==="0"}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("server exited")||message.includes("error connecting"))throw new TmuxUnreachableError(message);return!1}}async function isPaneProcessRunning(paneId,processName,execSyncFn){if(!paneId||paneId==="inline")return!1;if(!/^%\d+$/.test(paneId))return!1;try{let panePid=(await executeTmux2(`display-message -t '${paneId}' -p '#{pane_pid}'`)).trim();if(!panePid||!/^\d+$/.test(panePid))return!1;return(execSyncFn??(await import("child_process")).execSync)(`pgrep -la -P ${panePid} 2>/dev/null; for cpid in $(pgrep -P ${panePid} 2>/dev/null); do pgrep -la -P "$cpid" 2>/dev/null; done; true`,{encoding:"utf-8",timeout:5000}).toLowerCase().includes(processName.toLowerCase())}catch{return!1}}async function killWindow(sessionName,windowName){try{return await executeTmux2(`kill-window -t ${shellQuote(`${sessionName}:${windowName}`)}`),!0}catch{return!1}}var TMUX_COLOR_MAP,PANE_COLOR_SCRIPT,TmuxUnreachableError;var init_tmux=__esm(()=>{init_ensure_tmux();init_team_lead_command();TMUX_COLOR_MAP={red:"#b83030",blue:"#2a6cb8",green:"#20a050",yellow:"#b8a020",purple:"#7830b8",orange:"#b86820",pink:"#b83078",cyan:"#20a0a0"},PANE_COLOR_SCRIPT=`${__require("os").homedir()}/.genie/tmux-pane-color.sh`;TmuxUnreachableError=class TmuxUnreachableError extends Error{constructor(message){super(message);this.name="TmuxUnreachableError"}}});class BridgeSessionStore{sql;constructor(sql){this.sql=sql}async create(opts){let[row]=await this.sql`
|
|
196
|
-
INSERT INTO genie_bridge_sessions (
|
|
197
|
-
instance_id, chat_id, agent_name, executor_id,
|
|
198
|
-
tmux_pane_id, claude_session_id, metadata
|
|
199
|
-
) VALUES (
|
|
200
|
-
${opts.instanceId}, ${opts.chatId}, ${opts.agentName},
|
|
201
|
-
${opts.executorId??null}, ${opts.tmuxPaneId??null},
|
|
202
|
-
${opts.claudeSessionId??null}, ${JSON.stringify(opts.metadata??{})}::jsonb
|
|
203
|
-
)
|
|
204
|
-
RETURNING id
|
|
205
|
-
`;return row.id}async recordActivity(sessionId){await this.sql`
|
|
206
|
-
UPDATE genie_bridge_sessions
|
|
207
|
-
SET last_activity_at = now()
|
|
208
|
-
WHERE id = ${sessionId} AND status = 'active'
|
|
209
|
-
`}async close(sessionId){await this.sql`
|
|
210
|
-
UPDATE genie_bridge_sessions
|
|
211
|
-
SET status = 'closed', closed_at = now()
|
|
212
|
-
WHERE id = ${sessionId} AND status = 'active'
|
|
213
|
-
`}async markOrphaned(sessionIds){if(sessionIds.length===0)return;await this.sql`
|
|
214
|
-
UPDATE genie_bridge_sessions
|
|
215
|
-
SET status = 'orphaned'
|
|
216
|
-
WHERE id = ANY(${sessionIds}) AND status = 'active'
|
|
217
|
-
`}async markAllOrphaned(){return(await this.sql`
|
|
218
|
-
UPDATE genie_bridge_sessions
|
|
219
|
-
SET status = 'orphaned'
|
|
220
|
-
WHERE status = 'active'
|
|
221
|
-
RETURNING id
|
|
222
|
-
`).length}async list(status){if(status)return this.sql`
|
|
223
|
-
SELECT * FROM genie_bridge_sessions
|
|
224
|
-
WHERE status = ${status}
|
|
225
|
-
ORDER BY started_at DESC
|
|
226
|
-
`;return this.sql`
|
|
227
|
-
SELECT * FROM genie_bridge_sessions
|
|
228
|
-
ORDER BY started_at DESC
|
|
229
|
-
LIMIT 500
|
|
230
|
-
`}async getActive(instanceId,chatId){let[row]=await this.sql`
|
|
231
|
-
SELECT * FROM genie_bridge_sessions
|
|
232
|
-
WHERE instance_id = ${instanceId}
|
|
233
|
-
AND chat_id = ${chatId}
|
|
234
|
-
AND status = 'active'
|
|
235
|
-
LIMIT 1
|
|
236
|
-
`;return row??null}async updateExecutorInfo(sessionId,info){let sets=[],values2=[];if(info.executorId!==void 0)sets.push("executor_id"),values2.push(info.executorId);if(info.tmuxPaneId!==void 0)sets.push("tmux_pane_id"),values2.push(info.tmuxPaneId);if(info.claudeSessionId!==void 0)sets.push("claude_session_id"),values2.push(info.claudeSessionId);if(sets.length===0)return;await this.sql`
|
|
237
|
-
UPDATE genie_bridge_sessions SET
|
|
238
|
-
executor_id = COALESCE(${info.executorId??null}, executor_id),
|
|
239
|
-
tmux_pane_id = COALESCE(${info.tmuxPaneId??null}, tmux_pane_id),
|
|
240
|
-
claude_session_id = COALESCE(${info.claudeSessionId??null}, claude_session_id),
|
|
241
|
-
last_activity_at = now()
|
|
242
|
-
WHERE id = ${sessionId}
|
|
243
|
-
`}}function normalizeValue(v){if(v===void 0||v===null)return;if(v==="")return;if(v==="inherit")return;return v}function resolveField(agent,field,ctx){return resolveFieldWithSource(agent,field,ctx).value}function resolveFieldWithSource(agent,field,ctx){let agentVal=normalizeValue(agent[field]);if(agentVal!==void 0)return{value:agentVal,source:"explicit"};if(ctx.parent){let parentVal=normalizeValue(ctx.parent.fields[field]);if(parentVal!==void 0)return{value:parentVal,source:`parent:${ctx.parent.name}`}}if(ctx.workspaceDefaults){let wsVal=normalizeValue(ctx.workspaceDefaults[field]);if(wsVal!==void 0)return{value:wsVal,source:"workspace"}}return{value:BUILTIN_DEFAULTS[field],source:"built-in"}}function computeEffectiveDefaults(workspaceDefaults){if(!workspaceDefaults)return{...BUILTIN_DEFAULTS};let result2={...BUILTIN_DEFAULTS};for(let key of Object.keys(BUILTIN_DEFAULTS)){let wsVal=normalizeValue(workspaceDefaults[key]);if(wsVal!==void 0)result2[key]=wsVal}return result2}var BUILTIN_DEFAULTS,RESOLVED_FIELDS;var init_defaults=__esm(()=>{BUILTIN_DEFAULTS={model:"opus",promptMode:"append",color:"blue",effort:"high",thinking:"enabled",permissionMode:"bypassPermissions"},RESOLVED_FIELDS=["model"]});var exports_js_yaml={};__export(exports_js_yaml,{types:()=>types3,safeLoadAll:()=>safeLoadAll,safeLoad:()=>safeLoad,safeDump:()=>safeDump,loadAll:()=>loadAll,load:()=>load,dump:()=>dump,default:()=>jsYaml,YAMLException:()=>YAMLException,Type:()=>Type,Schema:()=>Schema,JSON_SCHEMA:()=>JSON_SCHEMA,FAILSAFE_SCHEMA:()=>FAILSAFE_SCHEMA,DEFAULT_SCHEMA:()=>DEFAULT_SCHEMA,CORE_SCHEMA:()=>CORE_SCHEMA});function isNothing(subject){return typeof subject>"u"||subject===null}function isObject(subject){return typeof subject==="object"&&subject!==null}function toArray(sequence){if(Array.isArray(sequence))return sequence;else if(isNothing(sequence))return[];return[sequence]}function extend(target,source){var index,length,key,sourceKeys;if(source){sourceKeys=Object.keys(source);for(index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key]}return target}function repeat(string,count){var result2="",cycle;for(cycle=0;cycle<count;cycle+=1)result2+=string;return result2}function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}function formatError(exception,compact){var where="",message=exception.reason||"(unknown reason)";if(!exception.mark)return message;if(exception.mark.name)where+='in "'+exception.mark.name+'" ';if(where+="("+(exception.mark.line+1)+":"+(exception.mark.column+1)+")",!compact&&exception.mark.snippet)where+=`
|
|
244
|
-
|
|
245
|
-
`+exception.mark.snippet;return message+" "+where}function YAMLException$1(reason,mark){if(Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=formatError(this,!1),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else this.stack=Error().stack||""}function getLine(buffer2,lineStart,lineEnd,position,maxLineLength){var head="",tail="",maxHalfLength=Math.floor(maxLineLength/2)-1;if(position-lineStart>maxHalfLength)head=" ... ",lineStart=position-maxHalfLength+head.length;if(lineEnd-position>maxHalfLength)tail=" ...",lineEnd=position+maxHalfLength-tail.length;return{str:head+buffer2.slice(lineStart,lineEnd).replace(/\t/g,"\u2192")+tail,pos:position-lineStart+head.length}}function padStart(string,max){return common.repeat(" ",max-string.length)+string}function makeSnippet(mark,options){if(options=Object.create(options||null),!mark.buffer)return null;if(!options.maxLength)options.maxLength=79;if(typeof options.indent!=="number")options.indent=1;if(typeof options.linesBefore!=="number")options.linesBefore=3;if(typeof options.linesAfter!=="number")options.linesAfter=2;var re=/\r?\n|\r|\0/g,lineStarts=[0],lineEnds=[],match,foundLineNo=-1;while(match=re.exec(mark.buffer))if(lineEnds.push(match.index),lineStarts.push(match.index+match[0].length),mark.position<=match.index&&foundLineNo<0)foundLineNo=lineStarts.length-2;if(foundLineNo<0)foundLineNo=lineStarts.length-1;var result2="",i,line,lineNoLength=Math.min(mark.line+options.linesAfter,lineEnds.length).toString().length,maxLineLength=options.maxLength-(options.indent+lineNoLength+3);for(i=1;i<=options.linesBefore;i++){if(foundLineNo-i<0)break;line=getLine(mark.buffer,lineStarts[foundLineNo-i],lineEnds[foundLineNo-i],mark.position-(lineStarts[foundLineNo]-lineStarts[foundLineNo-i]),maxLineLength),result2=common.repeat(" ",options.indent)+padStart((mark.line-i+1).toString(),lineNoLength)+" | "+line.str+`
|
|
246
|
-
`+result2}line=getLine(mark.buffer,lineStarts[foundLineNo],lineEnds[foundLineNo],mark.position,maxLineLength),result2+=common.repeat(" ",options.indent)+padStart((mark.line+1).toString(),lineNoLength)+" | "+line.str+`
|
|
247
|
-
`,result2+=common.repeat("-",options.indent+lineNoLength+3+line.pos)+`^
|
|
248
|
-
`;for(i=1;i<=options.linesAfter;i++){if(foundLineNo+i>=lineEnds.length)break;line=getLine(mark.buffer,lineStarts[foundLineNo+i],lineEnds[foundLineNo+i],mark.position-(lineStarts[foundLineNo]-lineStarts[foundLineNo+i]),maxLineLength),result2+=common.repeat(" ",options.indent)+padStart((mark.line+i+1).toString(),lineNoLength)+" | "+line.str+`
|
|
249
|
-
`}return result2.replace(/\n$/,"")}function compileStyleAliases(map){var result2={};if(map!==null)Object.keys(map).forEach(function(style){map[style].forEach(function(alias){result2[String(alias)]=style})});return result2}function Type$1(tag,options){if(options=options||{},Object.keys(options).forEach(function(name){if(TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)===-1)throw new exception('Unknown option "'+name+'" is met in definition of "'+tag+'" YAML type.')}),this.options=options,this.tag=tag,this.kind=options.kind||null,this.resolve=options.resolve||function(){return!0},this.construct=options.construct||function(data){return data},this.instanceOf=options.instanceOf||null,this.predicate=options.predicate||null,this.represent=options.represent||null,this.representName=options.representName||null,this.defaultStyle=options.defaultStyle||null,this.multi=options.multi||!1,this.styleAliases=compileStyleAliases(options.styleAliases||null),YAML_NODE_KINDS.indexOf(this.kind)===-1)throw new exception('Unknown kind "'+this.kind+'" is specified for "'+tag+'" YAML type.')}function compileList(schema,name){var result2=[];return schema[name].forEach(function(currentType){var newIndex=result2.length;result2.forEach(function(previousType,previousIndex){if(previousType.tag===currentType.tag&&previousType.kind===currentType.kind&&previousType.multi===currentType.multi)newIndex=previousIndex}),result2[newIndex]=currentType}),result2}function compileMap(){var result2={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},index,length;function collectType(type2){if(type2.multi)result2.multi[type2.kind].push(type2),result2.multi.fallback.push(type2);else result2[type2.kind][type2.tag]=result2.fallback[type2.tag]=type2}for(index=0,length=arguments.length;index<length;index+=1)arguments[index].forEach(collectType);return result2}function Schema$1(definition){return this.extend(definition)}function resolveYamlNull(data){if(data===null)return!0;var max=data.length;return max===1&&data==="~"||max===4&&(data==="null"||data==="Null"||data==="NULL")}function constructYamlNull(){return null}function isNull(object){return object===null}function resolveYamlBoolean(data){if(data===null)return!1;var max=data.length;return max===4&&(data==="true"||data==="True"||data==="TRUE")||max===5&&(data==="false"||data==="False"||data==="FALSE")}function constructYamlBoolean(data){return data==="true"||data==="True"||data==="TRUE"}function isBoolean(object){return Object.prototype.toString.call(object)==="[object Boolean]"}function isHexCode(c){return 48<=c&&c<=57||65<=c&&c<=70||97<=c&&c<=102}function isOctCode(c){return 48<=c&&c<=55}function isDecCode(c){return 48<=c&&c<=57}function resolveYamlInteger(data){if(data===null)return!1;var max=data.length,index=0,hasDigits=!1,ch;if(!max)return!1;if(ch=data[index],ch==="-"||ch==="+")ch=data[++index];if(ch==="0"){if(index+1===max)return!0;if(ch=data[++index],ch==="b"){index++;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(ch!=="0"&&ch!=="1")return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="x"){index++;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(!isHexCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="o"){index++;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(!isOctCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}}if(ch==="_")return!1;for(;index<max;index++){if(ch=data[index],ch==="_")continue;if(!isDecCode(data.charCodeAt(index)))return!1;hasDigits=!0}if(!hasDigits||ch==="_")return!1;return!0}function constructYamlInteger(data){var value=data,sign=1,ch;if(value.indexOf("_")!==-1)value=value.replace(/_/g,"");if(ch=value[0],ch==="-"||ch==="+"){if(ch==="-")sign=-1;value=value.slice(1),ch=value[0]}if(value==="0")return 0;if(ch==="0"){if(value[1]==="b")return sign*parseInt(value.slice(2),2);if(value[1]==="x")return sign*parseInt(value.slice(2),16);if(value[1]==="o")return sign*parseInt(value.slice(2),8)}return sign*parseInt(value,10)}function isInteger(object){return Object.prototype.toString.call(object)==="[object Number]"&&(object%1===0&&!common.isNegativeZero(object))}function resolveYamlFloat(data){if(data===null)return!1;if(!YAML_FLOAT_PATTERN.test(data)||data[data.length-1]==="_")return!1;return!0}function constructYamlFloat(data){var value,sign;if(value=data.replace(/_/g,"").toLowerCase(),sign=value[0]==="-"?-1:1,"+-".indexOf(value[0])>=0)value=value.slice(1);if(value===".inf")return sign===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;else if(value===".nan")return NaN;return sign*parseFloat(value,10)}function representYamlFloat(object,style){var res;if(isNaN(object))switch(style){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===object)switch(style){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===object)switch(style){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(common.isNegativeZero(object))return"-0.0";return res=object.toString(10),SCIENTIFIC_WITHOUT_DOT.test(res)?res.replace("e",".e"):res}function isFloat(object){return Object.prototype.toString.call(object)==="[object Number]"&&(object%1!==0||common.isNegativeZero(object))}function resolveYamlTimestamp(data){if(data===null)return!1;if(YAML_DATE_REGEXP.exec(data)!==null)return!0;if(YAML_TIMESTAMP_REGEXP.exec(data)!==null)return!0;return!1}function constructYamlTimestamp(data){var match,year,month,day,hour,minute,second,fraction=0,delta=null,tz_hour,tz_minute,date;if(match=YAML_DATE_REGEXP.exec(data),match===null)match=YAML_TIMESTAMP_REGEXP.exec(data);if(match===null)throw Error("Date resolve error");if(year=+match[1],month=+match[2]-1,day=+match[3],!match[4])return new Date(Date.UTC(year,month,day));if(hour=+match[4],minute=+match[5],second=+match[6],match[7]){fraction=match[7].slice(0,3);while(fraction.length<3)fraction+="0";fraction=+fraction}if(match[9]){if(tz_hour=+match[10],tz_minute=+(match[11]||0),delta=(tz_hour*60+tz_minute)*60000,match[9]==="-")delta=-delta}if(date=new Date(Date.UTC(year,month,day,hour,minute,second,fraction)),delta)date.setTime(date.getTime()-delta);return date}function representYamlTimestamp(object){return object.toISOString()}function resolveYamlMerge(data){return data==="<<"||data===null}function resolveYamlBinary(data){if(data===null)return!1;var code,idx,bitlen=0,max=data.length,map2=BASE64_MAP;for(idx=0;idx<max;idx++){if(code=map2.indexOf(data.charAt(idx)),code>64)continue;if(code<0)return!1;bitlen+=6}return bitlen%8===0}function constructYamlBinary(data){var idx,tailbits,input=data.replace(/[\r\n=]/g,""),max=input.length,map2=BASE64_MAP,bits=0,result2=[];for(idx=0;idx<max;idx++){if(idx%4===0&&idx)result2.push(bits>>16&255),result2.push(bits>>8&255),result2.push(bits&255);bits=bits<<6|map2.indexOf(input.charAt(idx))}if(tailbits=max%4*6,tailbits===0)result2.push(bits>>16&255),result2.push(bits>>8&255),result2.push(bits&255);else if(tailbits===18)result2.push(bits>>10&255),result2.push(bits>>2&255);else if(tailbits===12)result2.push(bits>>4&255);return new Uint8Array(result2)}function representYamlBinary(object){var result2="",bits=0,idx,tail,max=object.length,map2=BASE64_MAP;for(idx=0;idx<max;idx++){if(idx%3===0&&idx)result2+=map2[bits>>18&63],result2+=map2[bits>>12&63],result2+=map2[bits>>6&63],result2+=map2[bits&63];bits=(bits<<8)+object[idx]}if(tail=max%3,tail===0)result2+=map2[bits>>18&63],result2+=map2[bits>>12&63],result2+=map2[bits>>6&63],result2+=map2[bits&63];else if(tail===2)result2+=map2[bits>>10&63],result2+=map2[bits>>4&63],result2+=map2[bits<<2&63],result2+=map2[64];else if(tail===1)result2+=map2[bits>>2&63],result2+=map2[bits<<4&63],result2+=map2[64],result2+=map2[64];return result2}function isBinary(obj){return Object.prototype.toString.call(obj)==="[object Uint8Array]"}function resolveYamlOmap(data){if(data===null)return!0;var objectKeys=[],index,length,pair,pairKey,pairHasKey,object=data;for(index=0,length=object.length;index<length;index+=1){if(pair=object[index],pairHasKey=!1,_toString$2.call(pair)!=="[object Object]")return!1;for(pairKey in pair)if(_hasOwnProperty$3.call(pair,pairKey))if(!pairHasKey)pairHasKey=!0;else return!1;if(!pairHasKey)return!1;if(objectKeys.indexOf(pairKey)===-1)objectKeys.push(pairKey);else return!1}return!0}function constructYamlOmap(data){return data!==null?data:[]}function resolveYamlPairs(data){if(data===null)return!0;var index,length,pair,keys,result2,object=data;result2=Array(object.length);for(index=0,length=object.length;index<length;index+=1){if(pair=object[index],_toString$1.call(pair)!=="[object Object]")return!1;if(keys=Object.keys(pair),keys.length!==1)return!1;result2[index]=[keys[0],pair[keys[0]]]}return!0}function constructYamlPairs(data){if(data===null)return[];var index,length,pair,keys,result2,object=data;result2=Array(object.length);for(index=0,length=object.length;index<length;index+=1)pair=object[index],keys=Object.keys(pair),result2[index]=[keys[0],pair[keys[0]]];return result2}function resolveYamlSet(data){if(data===null)return!0;var key,object=data;for(key in object)if(_hasOwnProperty$2.call(object,key)){if(object[key]!==null)return!1}return!0}function constructYamlSet(data){return data!==null?data:{}}function _class(obj){return Object.prototype.toString.call(obj)}function is_EOL(c){return c===10||c===13}function is_WHITE_SPACE(c){return c===9||c===32}function is_WS_OR_EOL(c){return c===9||c===32||c===10||c===13}function is_FLOW_INDICATOR(c){return c===44||c===91||c===93||c===123||c===125}function fromHexCode(c){var lc;if(48<=c&&c<=57)return c-48;if(lc=c|32,97<=lc&&lc<=102)return lc-97+10;return-1}function escapedHexLen(c){if(c===120)return 2;if(c===117)return 4;if(c===85)return 8;return 0}function fromDecimalCode(c){if(48<=c&&c<=57)return c-48;return-1}function simpleEscapeSequence(c){return c===48?"\x00":c===97?"\x07":c===98?"\b":c===116?"\t":c===9?"\t":c===110?`
|
|
250
|
-
`:c===118?"\v":c===102?"\f":c===114?"\r":c===101?"\x1B":c===32?" ":c===34?'"':c===47?"/":c===92?"\\":c===78?"\x85":c===95?"\xA0":c===76?"\u2028":c===80?"\u2029":""}function charFromCodepoint(c){if(c<=65535)return String.fromCharCode(c);return String.fromCharCode((c-65536>>10)+55296,(c-65536&1023)+56320)}function setProperty(object,key,value){if(key==="__proto__")Object.defineProperty(object,key,{configurable:!0,enumerable:!0,writable:!0,value});else object[key]=value}function State$1(input,options){this.input=input,this.filename=options.filename||null,this.schema=options.schema||_default,this.onWarning=options.onWarning||null,this.legacy=options.legacy||!1,this.json=options.json||!1,this.listener=options.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=input.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function generateError(state,message){var mark={name:state.filename,buffer:state.input.slice(0,-1),position:state.position,line:state.line,column:state.position-state.lineStart};return mark.snippet=snippet(mark),new exception(message,mark)}function throwError(state,message){throw generateError(state,message)}function throwWarning(state,message){if(state.onWarning)state.onWarning.call(null,generateError(state,message))}function captureSegment(state,start,end,checkJson){var _position,_length,_character,_result;if(start<end){if(_result=state.input.slice(start,end),checkJson){for(_position=0,_length=_result.length;_position<_length;_position+=1)if(_character=_result.charCodeAt(_position),!(_character===9||32<=_character&&_character<=1114111))throwError(state,"expected valid JSON character")}else if(PATTERN_NON_PRINTABLE.test(_result))throwError(state,"the stream contains non-printable characters");state.result+=_result}}function mergeMappings(state,destination,source,overridableKeys){var sourceKeys,key,index,quantity;if(!common.isObject(source))throwError(state,"cannot merge mappings; the provided source object is unacceptable");sourceKeys=Object.keys(source);for(index=0,quantity=sourceKeys.length;index<quantity;index+=1)if(key=sourceKeys[index],!_hasOwnProperty$1.call(destination,key))setProperty(destination,key,source[key]),overridableKeys[key]=!0}function storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,startLine,startLineStart,startPos){var index,quantity;if(Array.isArray(keyNode)){keyNode=Array.prototype.slice.call(keyNode);for(index=0,quantity=keyNode.length;index<quantity;index+=1){if(Array.isArray(keyNode[index]))throwError(state,"nested arrays are not supported inside keys");if(typeof keyNode==="object"&&_class(keyNode[index])==="[object Object]")keyNode[index]="[object Object]"}}if(typeof keyNode==="object"&&_class(keyNode)==="[object Object]")keyNode="[object Object]";if(keyNode=String(keyNode),_result===null)_result={};if(keyTag==="tag:yaml.org,2002:merge")if(Array.isArray(valueNode))for(index=0,quantity=valueNode.length;index<quantity;index+=1)mergeMappings(state,_result,valueNode[index],overridableKeys);else mergeMappings(state,_result,valueNode,overridableKeys);else{if(!state.json&&!_hasOwnProperty$1.call(overridableKeys,keyNode)&&_hasOwnProperty$1.call(_result,keyNode))state.line=startLine||state.line,state.lineStart=startLineStart||state.lineStart,state.position=startPos||state.position,throwError(state,"duplicated mapping key");setProperty(_result,keyNode,valueNode),delete overridableKeys[keyNode]}return _result}function readLineBreak(state){var ch=state.input.charCodeAt(state.position);if(ch===10)state.position++;else if(ch===13){if(state.position++,state.input.charCodeAt(state.position)===10)state.position++}else throwError(state,"a line break is expected");state.line+=1,state.lineStart=state.position,state.firstTabInLine=-1}function skipSeparationSpace(state,allowComments,checkIndent){var lineBreaks=0,ch=state.input.charCodeAt(state.position);while(ch!==0){while(is_WHITE_SPACE(ch)){if(ch===9&&state.firstTabInLine===-1)state.firstTabInLine=state.position;ch=state.input.charCodeAt(++state.position)}if(allowComments&&ch===35)do ch=state.input.charCodeAt(++state.position);while(ch!==10&&ch!==13&&ch!==0);if(is_EOL(ch)){readLineBreak(state),ch=state.input.charCodeAt(state.position),lineBreaks++,state.lineIndent=0;while(ch===32)state.lineIndent++,ch=state.input.charCodeAt(++state.position)}else break}if(checkIndent!==-1&&lineBreaks!==0&&state.lineIndent<checkIndent)throwWarning(state,"deficient indentation");return lineBreaks}function testDocumentSeparator(state){var _position=state.position,ch;if(ch=state.input.charCodeAt(_position),(ch===45||ch===46)&&ch===state.input.charCodeAt(_position+1)&&ch===state.input.charCodeAt(_position+2)){if(_position+=3,ch=state.input.charCodeAt(_position),ch===0||is_WS_OR_EOL(ch))return!0}return!1}function writeFoldedLines(state,count){if(count===1)state.result+=" ";else if(count>1)state.result+=common.repeat(`
|
|
251
|
-
`,count-1)}function readPlainScalar(state,nodeIndent,withinFlowCollection){var preceding,following,captureStart,captureEnd,hasPendingContent,_line,_lineStart,_lineIndent,_kind=state.kind,_result=state.result,ch;if(ch=state.input.charCodeAt(state.position),is_WS_OR_EOL(ch)||is_FLOW_INDICATOR(ch)||ch===35||ch===38||ch===42||ch===33||ch===124||ch===62||ch===39||ch===34||ch===37||ch===64||ch===96)return!1;if(ch===63||ch===45){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)||withinFlowCollection&&is_FLOW_INDICATOR(following))return!1}state.kind="scalar",state.result="",captureStart=captureEnd=state.position,hasPendingContent=!1;while(ch!==0){if(ch===58){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)||withinFlowCollection&&is_FLOW_INDICATOR(following))break}else if(ch===35){if(preceding=state.input.charCodeAt(state.position-1),is_WS_OR_EOL(preceding))break}else if(state.position===state.lineStart&&testDocumentSeparator(state)||withinFlowCollection&&is_FLOW_INDICATOR(ch))break;else if(is_EOL(ch))if(_line=state.line,_lineStart=state.lineStart,_lineIndent=state.lineIndent,skipSeparationSpace(state,!1,-1),state.lineIndent>=nodeIndent){hasPendingContent=!0,ch=state.input.charCodeAt(state.position);continue}else{state.position=captureEnd,state.line=_line,state.lineStart=_lineStart,state.lineIndent=_lineIndent;break}if(hasPendingContent)captureSegment(state,captureStart,captureEnd,!1),writeFoldedLines(state,state.line-_line),captureStart=captureEnd=state.position,hasPendingContent=!1;if(!is_WHITE_SPACE(ch))captureEnd=state.position+1;ch=state.input.charCodeAt(++state.position)}if(captureSegment(state,captureStart,captureEnd,!1),state.result)return!0;return state.kind=_kind,state.result=_result,!1}function readSingleQuotedScalar(state,nodeIndent){var ch,captureStart,captureEnd;if(ch=state.input.charCodeAt(state.position),ch!==39)return!1;state.kind="scalar",state.result="",state.position++,captureStart=captureEnd=state.position;while((ch=state.input.charCodeAt(state.position))!==0)if(ch===39)if(captureSegment(state,captureStart,state.position,!0),ch=state.input.charCodeAt(++state.position),ch===39)captureStart=state.position,state.position++,captureEnd=state.position;else return!0;else if(is_EOL(ch))captureSegment(state,captureStart,captureEnd,!0),writeFoldedLines(state,skipSeparationSpace(state,!1,nodeIndent)),captureStart=captureEnd=state.position;else if(state.position===state.lineStart&&testDocumentSeparator(state))throwError(state,"unexpected end of the document within a single quoted scalar");else state.position++,captureEnd=state.position;throwError(state,"unexpected end of the stream within a single quoted scalar")}function readDoubleQuotedScalar(state,nodeIndent){var captureStart,captureEnd,hexLength,hexResult,tmp,ch;if(ch=state.input.charCodeAt(state.position),ch!==34)return!1;state.kind="scalar",state.result="",state.position++,captureStart=captureEnd=state.position;while((ch=state.input.charCodeAt(state.position))!==0)if(ch===34)return captureSegment(state,captureStart,state.position,!0),state.position++,!0;else if(ch===92){if(captureSegment(state,captureStart,state.position,!0),ch=state.input.charCodeAt(++state.position),is_EOL(ch))skipSeparationSpace(state,!1,nodeIndent);else if(ch<256&&simpleEscapeCheck[ch])state.result+=simpleEscapeMap[ch],state.position++;else if((tmp=escapedHexLen(ch))>0){hexLength=tmp,hexResult=0;for(;hexLength>0;hexLength--)if(ch=state.input.charCodeAt(++state.position),(tmp=fromHexCode(ch))>=0)hexResult=(hexResult<<4)+tmp;else throwError(state,"expected hexadecimal character");state.result+=charFromCodepoint(hexResult),state.position++}else throwError(state,"unknown escape sequence");captureStart=captureEnd=state.position}else if(is_EOL(ch))captureSegment(state,captureStart,captureEnd,!0),writeFoldedLines(state,skipSeparationSpace(state,!1,nodeIndent)),captureStart=captureEnd=state.position;else if(state.position===state.lineStart&&testDocumentSeparator(state))throwError(state,"unexpected end of the document within a double quoted scalar");else state.position++,captureEnd=state.position;throwError(state,"unexpected end of the stream within a double quoted scalar")}function readFlowCollection(state,nodeIndent){var readNext=!0,_line,_lineStart,_pos,_tag=state.tag,_result,_anchor=state.anchor,following,terminator,isPair,isExplicitPair,isMapping,overridableKeys=Object.create(null),keyNode,keyTag,valueNode,ch;if(ch=state.input.charCodeAt(state.position),ch===91)terminator=93,isMapping=!1,_result=[];else if(ch===123)terminator=125,isMapping=!0,_result={};else return!1;if(state.anchor!==null)state.anchorMap[state.anchor]=_result;ch=state.input.charCodeAt(++state.position);while(ch!==0){if(skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),ch===terminator)return state.position++,state.tag=_tag,state.anchor=_anchor,state.kind=isMapping?"mapping":"sequence",state.result=_result,!0;else if(!readNext)throwError(state,"missed comma between flow collection entries");else if(ch===44)throwError(state,"expected the node content, but found ','");if(keyTag=keyNode=valueNode=null,isPair=isExplicitPair=!1,ch===63){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following))isPair=isExplicitPair=!0,state.position++,skipSeparationSpace(state,!0,nodeIndent)}if(_line=state.line,_lineStart=state.lineStart,_pos=state.position,composeNode(state,nodeIndent,CONTEXT_FLOW_IN,!1,!0),keyTag=state.tag,keyNode=state.result,skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),(isExplicitPair||state.line===_line)&&ch===58)isPair=!0,ch=state.input.charCodeAt(++state.position),skipSeparationSpace(state,!0,nodeIndent),composeNode(state,nodeIndent,CONTEXT_FLOW_IN,!1,!0),valueNode=state.result;if(isMapping)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,_line,_lineStart,_pos);else if(isPair)_result.push(storeMappingPair(state,null,overridableKeys,keyTag,keyNode,valueNode,_line,_lineStart,_pos));else _result.push(keyNode);if(skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),ch===44)readNext=!0,ch=state.input.charCodeAt(++state.position);else readNext=!1}throwError(state,"unexpected end of the stream within a flow collection")}function readBlockScalar(state,nodeIndent){var captureStart,folding,chomping=CHOMPING_CLIP,didReadContent=!1,detectedIndent=!1,textIndent=nodeIndent,emptyLines=0,atMoreIndented=!1,tmp,ch;if(ch=state.input.charCodeAt(state.position),ch===124)folding=!1;else if(ch===62)folding=!0;else return!1;state.kind="scalar",state.result="";while(ch!==0)if(ch=state.input.charCodeAt(++state.position),ch===43||ch===45)if(CHOMPING_CLIP===chomping)chomping=ch===43?CHOMPING_KEEP:CHOMPING_STRIP;else throwError(state,"repeat of a chomping mode identifier");else if((tmp=fromDecimalCode(ch))>=0)if(tmp===0)throwError(state,"bad explicit indentation width of a block scalar; it cannot be less than one");else if(!detectedIndent)textIndent=nodeIndent+tmp-1,detectedIndent=!0;else throwError(state,"repeat of an indentation width identifier");else break;if(is_WHITE_SPACE(ch)){do ch=state.input.charCodeAt(++state.position);while(is_WHITE_SPACE(ch));if(ch===35)do ch=state.input.charCodeAt(++state.position);while(!is_EOL(ch)&&ch!==0)}while(ch!==0){readLineBreak(state),state.lineIndent=0,ch=state.input.charCodeAt(state.position);while((!detectedIndent||state.lineIndent<textIndent)&&ch===32)state.lineIndent++,ch=state.input.charCodeAt(++state.position);if(!detectedIndent&&state.lineIndent>textIndent)textIndent=state.lineIndent;if(is_EOL(ch)){emptyLines++;continue}if(state.lineIndent<textIndent){if(chomping===CHOMPING_KEEP)state.result+=common.repeat(`
|
|
252
|
-
`,didReadContent?1+emptyLines:emptyLines);else if(chomping===CHOMPING_CLIP){if(didReadContent)state.result+=`
|
|
253
|
-
`}break}if(folding)if(is_WHITE_SPACE(ch))atMoreIndented=!0,state.result+=common.repeat(`
|
|
254
|
-
`,didReadContent?1+emptyLines:emptyLines);else if(atMoreIndented)atMoreIndented=!1,state.result+=common.repeat(`
|
|
255
|
-
`,emptyLines+1);else if(emptyLines===0){if(didReadContent)state.result+=" "}else state.result+=common.repeat(`
|
|
256
|
-
`,emptyLines);else state.result+=common.repeat(`
|
|
257
|
-
`,didReadContent?1+emptyLines:emptyLines);didReadContent=!0,detectedIndent=!0,emptyLines=0,captureStart=state.position;while(!is_EOL(ch)&&ch!==0)ch=state.input.charCodeAt(++state.position);captureSegment(state,captureStart,state.position,!1)}return!0}function readBlockSequence(state,nodeIndent){var _line,_tag=state.tag,_anchor=state.anchor,_result=[],following,detected=!1,ch;if(state.firstTabInLine!==-1)return!1;if(state.anchor!==null)state.anchorMap[state.anchor]=_result;ch=state.input.charCodeAt(state.position);while(ch!==0){if(state.firstTabInLine!==-1)state.position=state.firstTabInLine,throwError(state,"tab characters must not be used in indentation");if(ch!==45)break;if(following=state.input.charCodeAt(state.position+1),!is_WS_OR_EOL(following))break;if(detected=!0,state.position++,skipSeparationSpace(state,!0,-1)){if(state.lineIndent<=nodeIndent){_result.push(null),ch=state.input.charCodeAt(state.position);continue}}if(_line=state.line,composeNode(state,nodeIndent,CONTEXT_BLOCK_IN,!1,!0),_result.push(state.result),skipSeparationSpace(state,!0,-1),ch=state.input.charCodeAt(state.position),(state.line===_line||state.lineIndent>nodeIndent)&&ch!==0)throwError(state,"bad indentation of a sequence entry");else if(state.lineIndent<nodeIndent)break}if(detected)return state.tag=_tag,state.anchor=_anchor,state.kind="sequence",state.result=_result,!0;return!1}function readBlockMapping(state,nodeIndent,flowIndent){var following,allowCompact,_line,_keyLine,_keyLineStart,_keyPos,_tag=state.tag,_anchor=state.anchor,_result={},overridableKeys=Object.create(null),keyTag=null,keyNode=null,valueNode=null,atExplicitKey=!1,detected=!1,ch;if(state.firstTabInLine!==-1)return!1;if(state.anchor!==null)state.anchorMap[state.anchor]=_result;ch=state.input.charCodeAt(state.position);while(ch!==0){if(!atExplicitKey&&state.firstTabInLine!==-1)state.position=state.firstTabInLine,throwError(state,"tab characters must not be used in indentation");if(following=state.input.charCodeAt(state.position+1),_line=state.line,(ch===63||ch===58)&&is_WS_OR_EOL(following)){if(ch===63){if(atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,null,_keyLine,_keyLineStart,_keyPos),keyTag=keyNode=valueNode=null;detected=!0,atExplicitKey=!0,allowCompact=!0}else if(atExplicitKey)atExplicitKey=!1,allowCompact=!0;else throwError(state,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");state.position+=1,ch=following}else{if(_keyLine=state.line,_keyLineStart=state.lineStart,_keyPos=state.position,!composeNode(state,flowIndent,CONTEXT_FLOW_OUT,!1,!0))break;if(state.line===_line){ch=state.input.charCodeAt(state.position);while(is_WHITE_SPACE(ch))ch=state.input.charCodeAt(++state.position);if(ch===58){if(ch=state.input.charCodeAt(++state.position),!is_WS_OR_EOL(ch))throwError(state,"a whitespace character is expected after the key-value separator within a block mapping");if(atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,null,_keyLine,_keyLineStart,_keyPos),keyTag=keyNode=valueNode=null;detected=!0,atExplicitKey=!1,allowCompact=!1,keyTag=state.tag,keyNode=state.result}else if(detected)throwError(state,"can not read an implicit mapping pair; a colon is missed");else return state.tag=_tag,state.anchor=_anchor,!0}else if(detected)throwError(state,"can not read a block mapping entry; a multiline key may not be an implicit key");else return state.tag=_tag,state.anchor=_anchor,!0}if(state.line===_line||state.lineIndent>nodeIndent){if(atExplicitKey)_keyLine=state.line,_keyLineStart=state.lineStart,_keyPos=state.position;if(composeNode(state,nodeIndent,CONTEXT_BLOCK_OUT,!0,allowCompact))if(atExplicitKey)keyNode=state.result;else valueNode=state.result;if(!atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,_keyLine,_keyLineStart,_keyPos),keyTag=keyNode=valueNode=null;skipSeparationSpace(state,!0,-1),ch=state.input.charCodeAt(state.position)}if((state.line===_line||state.lineIndent>nodeIndent)&&ch!==0)throwError(state,"bad indentation of a mapping entry");else if(state.lineIndent<nodeIndent)break}if(atExplicitKey)storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,null,_keyLine,_keyLineStart,_keyPos);if(detected)state.tag=_tag,state.anchor=_anchor,state.kind="mapping",state.result=_result;return detected}function readTagProperty(state){var _position,isVerbatim=!1,isNamed=!1,tagHandle,tagName,ch;if(ch=state.input.charCodeAt(state.position),ch!==33)return!1;if(state.tag!==null)throwError(state,"duplication of a tag property");if(ch=state.input.charCodeAt(++state.position),ch===60)isVerbatim=!0,ch=state.input.charCodeAt(++state.position);else if(ch===33)isNamed=!0,tagHandle="!!",ch=state.input.charCodeAt(++state.position);else tagHandle="!";if(_position=state.position,isVerbatim){do ch=state.input.charCodeAt(++state.position);while(ch!==0&&ch!==62);if(state.position<state.length)tagName=state.input.slice(_position,state.position),ch=state.input.charCodeAt(++state.position);else throwError(state,"unexpected end of the stream within a verbatim tag")}else{while(ch!==0&&!is_WS_OR_EOL(ch)){if(ch===33)if(!isNamed){if(tagHandle=state.input.slice(_position-1,state.position+1),!PATTERN_TAG_HANDLE.test(tagHandle))throwError(state,"named tag handle cannot contain such characters");isNamed=!0,_position=state.position+1}else throwError(state,"tag suffix cannot contain exclamation marks");ch=state.input.charCodeAt(++state.position)}if(tagName=state.input.slice(_position,state.position),PATTERN_FLOW_INDICATORS.test(tagName))throwError(state,"tag suffix cannot contain flow indicator characters")}if(tagName&&!PATTERN_TAG_URI.test(tagName))throwError(state,"tag name cannot contain such characters: "+tagName);try{tagName=decodeURIComponent(tagName)}catch(err){throwError(state,"tag name is malformed: "+tagName)}if(isVerbatim)state.tag=tagName;else if(_hasOwnProperty$1.call(state.tagMap,tagHandle))state.tag=state.tagMap[tagHandle]+tagName;else if(tagHandle==="!")state.tag="!"+tagName;else if(tagHandle==="!!")state.tag="tag:yaml.org,2002:"+tagName;else throwError(state,'undeclared tag handle "'+tagHandle+'"');return!0}function readAnchorProperty(state){var _position,ch;if(ch=state.input.charCodeAt(state.position),ch!==38)return!1;if(state.anchor!==null)throwError(state,"duplication of an anchor property");ch=state.input.charCodeAt(++state.position),_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch)&&!is_FLOW_INDICATOR(ch))ch=state.input.charCodeAt(++state.position);if(state.position===_position)throwError(state,"name of an anchor node must contain at least one character");return state.anchor=state.input.slice(_position,state.position),!0}function readAlias(state){var _position,alias,ch;if(ch=state.input.charCodeAt(state.position),ch!==42)return!1;ch=state.input.charCodeAt(++state.position),_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch)&&!is_FLOW_INDICATOR(ch))ch=state.input.charCodeAt(++state.position);if(state.position===_position)throwError(state,"name of an alias node must contain at least one character");if(alias=state.input.slice(_position,state.position),!_hasOwnProperty$1.call(state.anchorMap,alias))throwError(state,'unidentified alias "'+alias+'"');return state.result=state.anchorMap[alias],skipSeparationSpace(state,!0,-1),!0}function composeNode(state,parentIndent,nodeContext,allowToSeek,allowCompact){var allowBlockStyles,allowBlockScalars,allowBlockCollections,indentStatus=1,atNewLine=!1,hasContent=!1,typeIndex,typeQuantity,typeList,type2,flowIndent,blockIndent;if(state.listener!==null)state.listener("open",state);if(state.tag=null,state.anchor=null,state.kind=null,state.result=null,allowBlockStyles=allowBlockScalars=allowBlockCollections=CONTEXT_BLOCK_OUT===nodeContext||CONTEXT_BLOCK_IN===nodeContext,allowToSeek){if(skipSeparationSpace(state,!0,-1)){if(atNewLine=!0,state.lineIndent>parentIndent)indentStatus=1;else if(state.lineIndent===parentIndent)indentStatus=0;else if(state.lineIndent<parentIndent)indentStatus=-1}}if(indentStatus===1)while(readTagProperty(state)||readAnchorProperty(state))if(skipSeparationSpace(state,!0,-1)){if(atNewLine=!0,allowBlockCollections=allowBlockStyles,state.lineIndent>parentIndent)indentStatus=1;else if(state.lineIndent===parentIndent)indentStatus=0;else if(state.lineIndent<parentIndent)indentStatus=-1}else allowBlockCollections=!1;if(allowBlockCollections)allowBlockCollections=atNewLine||allowCompact;if(indentStatus===1||CONTEXT_BLOCK_OUT===nodeContext){if(CONTEXT_FLOW_IN===nodeContext||CONTEXT_FLOW_OUT===nodeContext)flowIndent=parentIndent;else flowIndent=parentIndent+1;if(blockIndent=state.position-state.lineStart,indentStatus===1)if(allowBlockCollections&&(readBlockSequence(state,blockIndent)||readBlockMapping(state,blockIndent,flowIndent))||readFlowCollection(state,flowIndent))hasContent=!0;else{if(allowBlockScalars&&readBlockScalar(state,flowIndent)||readSingleQuotedScalar(state,flowIndent)||readDoubleQuotedScalar(state,flowIndent))hasContent=!0;else if(readAlias(state)){if(hasContent=!0,state.tag!==null||state.anchor!==null)throwError(state,"alias node should not have any properties")}else if(readPlainScalar(state,flowIndent,CONTEXT_FLOW_IN===nodeContext)){if(hasContent=!0,state.tag===null)state.tag="?"}if(state.anchor!==null)state.anchorMap[state.anchor]=state.result}else if(indentStatus===0)hasContent=allowBlockCollections&&readBlockSequence(state,blockIndent)}if(state.tag===null){if(state.anchor!==null)state.anchorMap[state.anchor]=state.result}else if(state.tag==="?"){if(state.result!==null&&state.kind!=="scalar")throwError(state,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+state.kind+'"');for(typeIndex=0,typeQuantity=state.implicitTypes.length;typeIndex<typeQuantity;typeIndex+=1)if(type2=state.implicitTypes[typeIndex],type2.resolve(state.result)){if(state.result=type2.construct(state.result),state.tag=type2.tag,state.anchor!==null)state.anchorMap[state.anchor]=state.result;break}}else if(state.tag!=="!"){if(_hasOwnProperty$1.call(state.typeMap[state.kind||"fallback"],state.tag))type2=state.typeMap[state.kind||"fallback"][state.tag];else{type2=null,typeList=state.typeMap.multi[state.kind||"fallback"];for(typeIndex=0,typeQuantity=typeList.length;typeIndex<typeQuantity;typeIndex+=1)if(state.tag.slice(0,typeList[typeIndex].tag.length)===typeList[typeIndex].tag){type2=typeList[typeIndex];break}}if(!type2)throwError(state,"unknown tag !<"+state.tag+">");if(state.result!==null&&type2.kind!==state.kind)throwError(state,"unacceptable node kind for !<"+state.tag+'> tag; it should be "'+type2.kind+'", not "'+state.kind+'"');if(!type2.resolve(state.result,state.tag))throwError(state,"cannot resolve a node with !<"+state.tag+"> explicit tag");else if(state.result=type2.construct(state.result,state.tag),state.anchor!==null)state.anchorMap[state.anchor]=state.result}if(state.listener!==null)state.listener("close",state);return state.tag!==null||state.anchor!==null||hasContent}function readDocument(state){var documentStart=state.position,_position,directiveName,directiveArgs,hasDirectives=!1,ch;state.version=null,state.checkLineBreaks=state.legacy,state.tagMap=Object.create(null),state.anchorMap=Object.create(null);while((ch=state.input.charCodeAt(state.position))!==0){if(skipSeparationSpace(state,!0,-1),ch=state.input.charCodeAt(state.position),state.lineIndent>0||ch!==37)break;hasDirectives=!0,ch=state.input.charCodeAt(++state.position),_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch))ch=state.input.charCodeAt(++state.position);if(directiveName=state.input.slice(_position,state.position),directiveArgs=[],directiveName.length<1)throwError(state,"directive name must not be less than one character in length");while(ch!==0){while(is_WHITE_SPACE(ch))ch=state.input.charCodeAt(++state.position);if(ch===35){do ch=state.input.charCodeAt(++state.position);while(ch!==0&&!is_EOL(ch));break}if(is_EOL(ch))break;_position=state.position;while(ch!==0&&!is_WS_OR_EOL(ch))ch=state.input.charCodeAt(++state.position);directiveArgs.push(state.input.slice(_position,state.position))}if(ch!==0)readLineBreak(state);if(_hasOwnProperty$1.call(directiveHandlers,directiveName))directiveHandlers[directiveName](state,directiveName,directiveArgs);else throwWarning(state,'unknown document directive "'+directiveName+'"')}if(skipSeparationSpace(state,!0,-1),state.lineIndent===0&&state.input.charCodeAt(state.position)===45&&state.input.charCodeAt(state.position+1)===45&&state.input.charCodeAt(state.position+2)===45)state.position+=3,skipSeparationSpace(state,!0,-1);else if(hasDirectives)throwError(state,"directives end mark is expected");if(composeNode(state,state.lineIndent-1,CONTEXT_BLOCK_OUT,!1,!0),skipSeparationSpace(state,!0,-1),state.checkLineBreaks&&PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart,state.position)))throwWarning(state,"non-ASCII line breaks are interpreted as content");if(state.documents.push(state.result),state.position===state.lineStart&&testDocumentSeparator(state)){if(state.input.charCodeAt(state.position)===46)state.position+=3,skipSeparationSpace(state,!0,-1);return}if(state.position<state.length-1)throwError(state,"end of the stream or a document separator is expected");else return}function loadDocuments(input,options){if(input=String(input),options=options||{},input.length!==0){if(input.charCodeAt(input.length-1)!==10&&input.charCodeAt(input.length-1)!==13)input+=`
|
|
258
|
-
`;if(input.charCodeAt(0)===65279)input=input.slice(1)}var state=new State$1(input,options),nullpos=input.indexOf("\x00");if(nullpos!==-1)state.position=nullpos,throwError(state,"null byte is not allowed in input");state.input+="\x00";while(state.input.charCodeAt(state.position)===32)state.lineIndent+=1,state.position+=1;while(state.position<state.length-1)readDocument(state);return state.documents}function loadAll$1(input,iterator,options){if(iterator!==null&&typeof iterator==="object"&&typeof options>"u")options=iterator,iterator=null;var documents=loadDocuments(input,options);if(typeof iterator!=="function")return documents;for(var index=0,length=documents.length;index<length;index+=1)iterator(documents[index])}function load$1(input,options){var documents=loadDocuments(input,options);if(documents.length===0)return;else if(documents.length===1)return documents[0];throw new exception("expected a single document in the stream, but found more")}function compileStyleMap(schema2,map2){var result2,keys,index,length,tag,style,type2;if(map2===null)return{};result2={},keys=Object.keys(map2);for(index=0,length=keys.length;index<length;index+=1){if(tag=keys[index],style=String(map2[tag]),tag.slice(0,2)==="!!")tag="tag:yaml.org,2002:"+tag.slice(2);if(type2=schema2.compiledTypeMap.fallback[tag],type2&&_hasOwnProperty.call(type2.styleAliases,style))style=type2.styleAliases[style];result2[tag]=style}return result2}function encodeHex(character){var string,handle,length;if(string=character.toString(16).toUpperCase(),character<=255)handle="x",length=2;else if(character<=65535)handle="u",length=4;else if(character<=4294967295)handle="U",length=8;else throw new exception("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+handle+common.repeat("0",length-string.length)+string}function State(options){this.schema=options.schema||_default,this.indent=Math.max(1,options.indent||2),this.noArrayIndent=options.noArrayIndent||!1,this.skipInvalid=options.skipInvalid||!1,this.flowLevel=common.isNothing(options.flowLevel)?-1:options.flowLevel,this.styleMap=compileStyleMap(this.schema,options.styles||null),this.sortKeys=options.sortKeys||!1,this.lineWidth=options.lineWidth||80,this.noRefs=options.noRefs||!1,this.noCompatMode=options.noCompatMode||!1,this.condenseFlow=options.condenseFlow||!1,this.quotingType=options.quotingType==='"'?QUOTING_TYPE_DOUBLE:QUOTING_TYPE_SINGLE,this.forceQuotes=options.forceQuotes||!1,this.replacer=typeof options.replacer==="function"?options.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function indentString(string,spaces){var ind=common.repeat(" ",spaces),position=0,next=-1,result2="",line,length=string.length;while(position<length){if(next=string.indexOf(`
|
|
259
|
-
`,position),next===-1)line=string.slice(position),position=length;else line=string.slice(position,next+1),position=next+1;if(line.length&&line!==`
|
|
260
|
-
`)result2+=ind;result2+=line}return result2}function generateNextLine(state,level){return`
|
|
261
|
-
`+common.repeat(" ",state.indent*level)}function testImplicitResolving(state,str2){var index,length,type2;for(index=0,length=state.implicitTypes.length;index<length;index+=1)if(type2=state.implicitTypes[index],type2.resolve(str2))return!0;return!1}function isWhitespace(c){return c===CHAR_SPACE||c===CHAR_TAB}function isPrintable(c){return 32<=c&&c<=126||161<=c&&c<=55295&&c!==8232&&c!==8233||57344<=c&&c<=65533&&c!==CHAR_BOM||65536<=c&&c<=1114111}function isNsCharOrWhitespace(c){return isPrintable(c)&&c!==CHAR_BOM&&c!==CHAR_CARRIAGE_RETURN&&c!==CHAR_LINE_FEED}function isPlainSafe(c,prev,inblock){var cIsNsCharOrWhitespace=isNsCharOrWhitespace(c),cIsNsChar=cIsNsCharOrWhitespace&&!isWhitespace(c);return(inblock?cIsNsCharOrWhitespace:cIsNsCharOrWhitespace&&c!==CHAR_COMMA&&c!==CHAR_LEFT_SQUARE_BRACKET&&c!==CHAR_RIGHT_SQUARE_BRACKET&&c!==CHAR_LEFT_CURLY_BRACKET&&c!==CHAR_RIGHT_CURLY_BRACKET)&&c!==CHAR_SHARP&&!(prev===CHAR_COLON&&!cIsNsChar)||isNsCharOrWhitespace(prev)&&!isWhitespace(prev)&&c===CHAR_SHARP||prev===CHAR_COLON&&cIsNsChar}function isPlainSafeFirst(c){return isPrintable(c)&&c!==CHAR_BOM&&!isWhitespace(c)&&c!==CHAR_MINUS&&c!==CHAR_QUESTION&&c!==CHAR_COLON&&c!==CHAR_COMMA&&c!==CHAR_LEFT_SQUARE_BRACKET&&c!==CHAR_RIGHT_SQUARE_BRACKET&&c!==CHAR_LEFT_CURLY_BRACKET&&c!==CHAR_RIGHT_CURLY_BRACKET&&c!==CHAR_SHARP&&c!==CHAR_AMPERSAND&&c!==CHAR_ASTERISK&&c!==CHAR_EXCLAMATION&&c!==CHAR_VERTICAL_LINE&&c!==CHAR_EQUALS&&c!==CHAR_GREATER_THAN&&c!==CHAR_SINGLE_QUOTE&&c!==CHAR_DOUBLE_QUOTE&&c!==CHAR_PERCENT&&c!==CHAR_COMMERCIAL_AT&&c!==CHAR_GRAVE_ACCENT}function isPlainSafeLast(c){return!isWhitespace(c)&&c!==CHAR_COLON}function codePointAt(string,pos){var first=string.charCodeAt(pos),second;if(first>=55296&&first<=56319&&pos+1<string.length){if(second=string.charCodeAt(pos+1),second>=56320&&second<=57343)return(first-55296)*1024+second-56320+65536}return first}function needIndentIndicator(string){var leadingSpaceRe=/^\n* /;return leadingSpaceRe.test(string)}function chooseScalarStyle(string,singleLineOnly,indentPerLevel,lineWidth,testAmbiguousType,quotingType,forceQuotes,inblock){var i2,char=0,prevChar=null,hasLineBreak=!1,hasFoldableLine=!1,shouldTrackWidth=lineWidth!==-1,previousLineBreak=-1,plain=isPlainSafeFirst(codePointAt(string,0))&&isPlainSafeLast(codePointAt(string,string.length-1));if(singleLineOnly||forceQuotes)for(i2=0;i2<string.length;char>=65536?i2+=2:i2++){if(char=codePointAt(string,i2),!isPrintable(char))return STYLE_DOUBLE;plain=plain&&isPlainSafe(char,prevChar,inblock),prevChar=char}else{for(i2=0;i2<string.length;char>=65536?i2+=2:i2++){if(char=codePointAt(string,i2),char===CHAR_LINE_FEED){if(hasLineBreak=!0,shouldTrackWidth)hasFoldableLine=hasFoldableLine||i2-previousLineBreak-1>lineWidth&&string[previousLineBreak+1]!==" ",previousLineBreak=i2}else if(!isPrintable(char))return STYLE_DOUBLE;plain=plain&&isPlainSafe(char,prevChar,inblock),prevChar=char}hasFoldableLine=hasFoldableLine||shouldTrackWidth&&(i2-previousLineBreak-1>lineWidth&&string[previousLineBreak+1]!==" ")}if(!hasLineBreak&&!hasFoldableLine){if(plain&&!forceQuotes&&!testAmbiguousType(string))return STYLE_PLAIN;return quotingType===QUOTING_TYPE_DOUBLE?STYLE_DOUBLE:STYLE_SINGLE}if(indentPerLevel>9&&needIndentIndicator(string))return STYLE_DOUBLE;if(!forceQuotes)return hasFoldableLine?STYLE_FOLDED:STYLE_LITERAL;return quotingType===QUOTING_TYPE_DOUBLE?STYLE_DOUBLE:STYLE_SINGLE}function writeScalar(state,string,level,iskey,inblock){state.dump=function(){if(string.length===0)return state.quotingType===QUOTING_TYPE_DOUBLE?'""':"''";if(!state.noCompatMode){if(DEPRECATED_BOOLEANS_SYNTAX.indexOf(string)!==-1||DEPRECATED_BASE60_SYNTAX.test(string))return state.quotingType===QUOTING_TYPE_DOUBLE?'"'+string+'"':"'"+string+"'"}var indent=state.indent*Math.max(1,level),lineWidth=state.lineWidth===-1?-1:Math.max(Math.min(state.lineWidth,40),state.lineWidth-indent),singleLineOnly=iskey||state.flowLevel>-1&&level>=state.flowLevel;function testAmbiguity(string2){return testImplicitResolving(state,string2)}switch(chooseScalarStyle(string,singleLineOnly,state.indent,lineWidth,testAmbiguity,state.quotingType,state.forceQuotes&&!iskey,inblock)){case STYLE_PLAIN:return string;case STYLE_SINGLE:return"'"+string.replace(/'/g,"''")+"'";case STYLE_LITERAL:return"|"+blockHeader(string,state.indent)+dropEndingNewline(indentString(string,indent));case STYLE_FOLDED:return">"+blockHeader(string,state.indent)+dropEndingNewline(indentString(foldString(string,lineWidth),indent));case STYLE_DOUBLE:return'"'+escapeString(string)+'"';default:throw new exception("impossible error: invalid scalar style")}}()}function blockHeader(string,indentPerLevel){var indentIndicator=needIndentIndicator(string)?String(indentPerLevel):"",clip=string[string.length-1]===`
|
|
262
|
-
`,keep=clip&&(string[string.length-2]===`
|
|
263
|
-
`||string===`
|
|
264
|
-
`),chomp=keep?"+":clip?"":"-";return indentIndicator+chomp+`
|
|
265
|
-
`}function dropEndingNewline(string){return string[string.length-1]===`
|
|
266
|
-
`?string.slice(0,-1):string}function foldString(string,width){var lineRe=/(\n+)([^\n]*)/g,result2=function(){var nextLF=string.indexOf(`
|
|
267
|
-
`);return nextLF=nextLF!==-1?nextLF:string.length,lineRe.lastIndex=nextLF,foldLine(string.slice(0,nextLF),width)}(),prevMoreIndented=string[0]===`
|
|
268
|
-
`||string[0]===" ",moreIndented,match;while(match=lineRe.exec(string)){var prefix=match[1],line=match[2];moreIndented=line[0]===" ",result2+=prefix+(!prevMoreIndented&&!moreIndented&&line!==""?`
|
|
269
|
-
`:"")+foldLine(line,width),prevMoreIndented=moreIndented}return result2}function foldLine(line,width){if(line===""||line[0]===" ")return line;var breakRe=/ [^ ]/g,match,start=0,end,curr=0,next=0,result2="";while(match=breakRe.exec(line)){if(next=match.index,next-start>width)end=curr>start?curr:next,result2+=`
|
|
270
|
-
`+line.slice(start,end),start=end+1;curr=next}if(result2+=`
|
|
271
|
-
`,line.length-start>width&&curr>start)result2+=line.slice(start,curr)+`
|
|
272
|
-
`+line.slice(curr+1);else result2+=line.slice(start);return result2.slice(1)}function escapeString(string){var result2="",char=0,escapeSeq;for(var i2=0;i2<string.length;char>=65536?i2+=2:i2++)if(char=codePointAt(string,i2),escapeSeq=ESCAPE_SEQUENCES[char],!escapeSeq&&isPrintable(char)){if(result2+=string[i2],char>=65536)result2+=string[i2+1]}else result2+=escapeSeq||encodeHex(char);return result2}function writeFlowSequence(state,level,object){var _result="",_tag=state.tag,index,length,value;for(index=0,length=object.length;index<length;index+=1){if(value=object[index],state.replacer)value=state.replacer.call(object,String(index),value);if(writeNode(state,level,value,!1,!1)||typeof value>"u"&&writeNode(state,level,null,!1,!1)){if(_result!=="")_result+=","+(!state.condenseFlow?" ":"");_result+=state.dump}}state.tag=_tag,state.dump="["+_result+"]"}function writeBlockSequence(state,level,object,compact){var _result="",_tag=state.tag,index,length,value;for(index=0,length=object.length;index<length;index+=1){if(value=object[index],state.replacer)value=state.replacer.call(object,String(index),value);if(writeNode(state,level+1,value,!0,!0,!1,!0)||typeof value>"u"&&writeNode(state,level+1,null,!0,!0,!1,!0)){if(!compact||_result!=="")_result+=generateNextLine(state,level);if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))_result+="-";else _result+="- ";_result+=state.dump}}state.tag=_tag,state.dump=_result||"[]"}function writeFlowMapping(state,level,object){var _result="",_tag=state.tag,objectKeyList=Object.keys(object),index,length,objectKey,objectValue,pairBuffer;for(index=0,length=objectKeyList.length;index<length;index+=1){if(pairBuffer="",_result!=="")pairBuffer+=", ";if(state.condenseFlow)pairBuffer+='"';if(objectKey=objectKeyList[index],objectValue=object[objectKey],state.replacer)objectValue=state.replacer.call(object,objectKey,objectValue);if(!writeNode(state,level,objectKey,!1,!1))continue;if(state.dump.length>1024)pairBuffer+="? ";if(pairBuffer+=state.dump+(state.condenseFlow?'"':"")+":"+(state.condenseFlow?"":" "),!writeNode(state,level,objectValue,!1,!1))continue;pairBuffer+=state.dump,_result+=pairBuffer}state.tag=_tag,state.dump="{"+_result+"}"}function writeBlockMapping(state,level,object,compact){var _result="",_tag=state.tag,objectKeyList=Object.keys(object),index,length,objectKey,objectValue,explicitPair,pairBuffer;if(state.sortKeys===!0)objectKeyList.sort();else if(typeof state.sortKeys==="function")objectKeyList.sort(state.sortKeys);else if(state.sortKeys)throw new exception("sortKeys must be a boolean or a function");for(index=0,length=objectKeyList.length;index<length;index+=1){if(pairBuffer="",!compact||_result!=="")pairBuffer+=generateNextLine(state,level);if(objectKey=objectKeyList[index],objectValue=object[objectKey],state.replacer)objectValue=state.replacer.call(object,objectKey,objectValue);if(!writeNode(state,level+1,objectKey,!0,!0,!0))continue;if(explicitPair=state.tag!==null&&state.tag!=="?"||state.dump&&state.dump.length>1024,explicitPair)if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))pairBuffer+="?";else pairBuffer+="? ";if(pairBuffer+=state.dump,explicitPair)pairBuffer+=generateNextLine(state,level);if(!writeNode(state,level+1,objectValue,!0,explicitPair))continue;if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))pairBuffer+=":";else pairBuffer+=": ";pairBuffer+=state.dump,_result+=pairBuffer}state.tag=_tag,state.dump=_result||"{}"}function detectType(state,object,explicit){var _result,typeList,index,length,type2,style;typeList=explicit?state.explicitTypes:state.implicitTypes;for(index=0,length=typeList.length;index<length;index+=1)if(type2=typeList[index],(type2.instanceOf||type2.predicate)&&(!type2.instanceOf||typeof object==="object"&&object instanceof type2.instanceOf)&&(!type2.predicate||type2.predicate(object))){if(explicit)if(type2.multi&&type2.representName)state.tag=type2.representName(object);else state.tag=type2.tag;else state.tag="?";if(type2.represent){if(style=state.styleMap[type2.tag]||type2.defaultStyle,_toString.call(type2.represent)==="[object Function]")_result=type2.represent(object,style);else if(_hasOwnProperty.call(type2.represent,style))_result=type2.represent[style](object,style);else throw new exception("!<"+type2.tag+'> tag resolver accepts not "'+style+'" style');state.dump=_result}return!0}return!1}function writeNode(state,level,object,block,compact,iskey,isblockseq){if(state.tag=null,state.dump=object,!detectType(state,object,!1))detectType(state,object,!0);var type2=_toString.call(state.dump),inblock=block,tagStr;if(block)block=state.flowLevel<0||state.flowLevel>level;var objectOrArray=type2==="[object Object]"||type2==="[object Array]",duplicateIndex,duplicate;if(objectOrArray)duplicateIndex=state.duplicates.indexOf(object),duplicate=duplicateIndex!==-1;if(state.tag!==null&&state.tag!=="?"||duplicate||state.indent!==2&&level>0)compact=!1;if(duplicate&&state.usedDuplicates[duplicateIndex])state.dump="*ref_"+duplicateIndex;else{if(objectOrArray&&duplicate&&!state.usedDuplicates[duplicateIndex])state.usedDuplicates[duplicateIndex]=!0;if(type2==="[object Object]"){if(block&&Object.keys(state.dump).length!==0){if(writeBlockMapping(state,level,state.dump,compact),duplicate)state.dump="&ref_"+duplicateIndex+state.dump}else if(writeFlowMapping(state,level,state.dump),duplicate)state.dump="&ref_"+duplicateIndex+" "+state.dump}else if(type2==="[object Array]"){if(block&&state.dump.length!==0){if(state.noArrayIndent&&!isblockseq&&level>0)writeBlockSequence(state,level-1,state.dump,compact);else writeBlockSequence(state,level,state.dump,compact);if(duplicate)state.dump="&ref_"+duplicateIndex+state.dump}else if(writeFlowSequence(state,level,state.dump),duplicate)state.dump="&ref_"+duplicateIndex+" "+state.dump}else if(type2==="[object String]"){if(state.tag!=="?")writeScalar(state,state.dump,level,iskey,inblock)}else if(type2==="[object Undefined]")return!1;else{if(state.skipInvalid)return!1;throw new exception("unacceptable kind of an object to dump "+type2)}if(state.tag!==null&&state.tag!=="?"){if(tagStr=encodeURI(state.tag[0]==="!"?state.tag.slice(1):state.tag).replace(/!/g,"%21"),state.tag[0]==="!")tagStr="!"+tagStr;else if(tagStr.slice(0,18)==="tag:yaml.org,2002:")tagStr="!!"+tagStr.slice(18);else tagStr="!<"+tagStr+">";state.dump=tagStr+" "+state.dump}}return!0}function getDuplicateReferences(object,state){var objects=[],duplicatesIndexes=[],index,length;inspectNode(object,objects,duplicatesIndexes);for(index=0,length=duplicatesIndexes.length;index<length;index+=1)state.duplicates.push(objects[duplicatesIndexes[index]]);state.usedDuplicates=Array(length)}function inspectNode(object,objects,duplicatesIndexes){var objectKeyList,index,length;if(object!==null&&typeof object==="object")if(index=objects.indexOf(object),index!==-1){if(duplicatesIndexes.indexOf(index)===-1)duplicatesIndexes.push(index)}else if(objects.push(object),Array.isArray(object))for(index=0,length=object.length;index<length;index+=1)inspectNode(object[index],objects,duplicatesIndexes);else{objectKeyList=Object.keys(object);for(index=0,length=objectKeyList.length;index<length;index+=1)inspectNode(object[objectKeyList[index]],objects,duplicatesIndexes)}}function dump$1(input,options){options=options||{};var state=new State(options);if(!state.noRefs)getDuplicateReferences(input,state);var value=input;if(state.replacer)value=state.replacer.call({"":value},"",value);if(writeNode(state,0,value,!0,!0))return state.dump+`
|
|
273
|
-
`;return""}function renamed(from,to){return function(){throw Error("Function yaml."+from+" is removed in js-yaml 4. Use yaml."+to+" instead, which is now safe by default.")}}var isNothing_1,isObject_1,toArray_1,repeat_1,isNegativeZero_1,extend_1,common,exception,snippet,TYPE_CONSTRUCTOR_OPTIONS,YAML_NODE_KINDS,type,schema,str,seq,map,failsafe,_null,bool,int,YAML_FLOAT_PATTERN,SCIENTIFIC_WITHOUT_DOT,float,json,core,YAML_DATE_REGEXP,YAML_TIMESTAMP_REGEXP,timestamp,merge,BASE64_MAP=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
274
|
-
\r`,binary,_hasOwnProperty$3,_toString$2,omap,_toString$1,pairs,_hasOwnProperty$2,set,_default,_hasOwnProperty$1,CONTEXT_FLOW_IN=1,CONTEXT_FLOW_OUT=2,CONTEXT_BLOCK_IN=3,CONTEXT_BLOCK_OUT=4,CHOMPING_CLIP=1,CHOMPING_STRIP=2,CHOMPING_KEEP=3,PATTERN_NON_PRINTABLE,PATTERN_NON_ASCII_LINE_BREAKS,PATTERN_FLOW_INDICATORS,PATTERN_TAG_HANDLE,PATTERN_TAG_URI,simpleEscapeCheck,simpleEscapeMap,i,directiveHandlers,loadAll_1,load_1,loader,_toString,_hasOwnProperty,CHAR_BOM=65279,CHAR_TAB=9,CHAR_LINE_FEED=10,CHAR_CARRIAGE_RETURN=13,CHAR_SPACE=32,CHAR_EXCLAMATION=33,CHAR_DOUBLE_QUOTE=34,CHAR_SHARP=35,CHAR_PERCENT=37,CHAR_AMPERSAND=38,CHAR_SINGLE_QUOTE=39,CHAR_ASTERISK=42,CHAR_COMMA=44,CHAR_MINUS=45,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_GREATER_THAN=62,CHAR_QUESTION=63,CHAR_COMMERCIAL_AT=64,CHAR_LEFT_SQUARE_BRACKET=91,CHAR_RIGHT_SQUARE_BRACKET=93,CHAR_GRAVE_ACCENT=96,CHAR_LEFT_CURLY_BRACKET=123,CHAR_VERTICAL_LINE=124,CHAR_RIGHT_CURLY_BRACKET=125,ESCAPE_SEQUENCES,DEPRECATED_BOOLEANS_SYNTAX,DEPRECATED_BASE60_SYNTAX,QUOTING_TYPE_SINGLE=1,QUOTING_TYPE_DOUBLE=2,STYLE_PLAIN=1,STYLE_SINGLE=2,STYLE_LITERAL=3,STYLE_FOLDED=4,STYLE_DOUBLE=5,dump_1,dumper,Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load,loadAll,dump,YAMLException,types3,safeLoad,safeLoadAll,safeDump,jsYaml;var init_js_yaml=__esm(()=>{/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */isNothing_1=isNothing,isObject_1=isObject,toArray_1=toArray,repeat_1=repeat,isNegativeZero_1=isNegativeZero,extend_1=extend,common={isNothing:isNothing_1,isObject:isObject_1,toArray:toArray_1,repeat:repeat_1,isNegativeZero:isNegativeZero_1,extend:extend_1};YAMLException$1.prototype=Object.create(Error.prototype);YAMLException$1.prototype.constructor=YAMLException$1;YAMLException$1.prototype.toString=function(compact){return this.name+": "+formatError(this,compact)};exception=YAMLException$1;snippet=makeSnippet,TYPE_CONSTRUCTOR_OPTIONS=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],YAML_NODE_KINDS=["scalar","sequence","mapping"];type=Type$1;Schema$1.prototype.extend=function(definition){var implicit=[],explicit=[];if(definition instanceof type)explicit.push(definition);else if(Array.isArray(definition))explicit=explicit.concat(definition);else if(definition&&(Array.isArray(definition.implicit)||Array.isArray(definition.explicit))){if(definition.implicit)implicit=implicit.concat(definition.implicit);if(definition.explicit)explicit=explicit.concat(definition.explicit)}else throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");implicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(type$1.loadKind&&type$1.loadKind!=="scalar")throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(type$1.multi)throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),explicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var result2=Object.create(Schema$1.prototype);return result2.implicit=(this.implicit||[]).concat(implicit),result2.explicit=(this.explicit||[]).concat(explicit),result2.compiledImplicit=compileList(result2,"implicit"),result2.compiledExplicit=compileList(result2,"explicit"),result2.compiledTypeMap=compileMap(result2.compiledImplicit,result2.compiledExplicit),result2};schema=Schema$1,str=new type("tag:yaml.org,2002:str",{kind:"scalar",construct:function(data){return data!==null?data:""}}),seq=new type("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(data){return data!==null?data:[]}}),map=new type("tag:yaml.org,2002:map",{kind:"mapping",construct:function(data){return data!==null?data:{}}}),failsafe=new schema({explicit:[str,seq,map]});_null=new type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});bool=new type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:function(object){return object?"true":"false"},uppercase:function(object){return object?"TRUE":"FALSE"},camelcase:function(object){return object?"True":"False"}},defaultStyle:"lowercase"});int=new type("tag:yaml.org,2002:int",{kind:"scalar",resolve:resolveYamlInteger,construct:constructYamlInteger,predicate:isInteger,represent:{binary:function(obj){return obj>=0?"0b"+obj.toString(2):"-0b"+obj.toString(2).slice(1)},octal:function(obj){return obj>=0?"0o"+obj.toString(8):"-0o"+obj.toString(8).slice(1)},decimal:function(obj){return obj.toString(10)},hexadecimal:function(obj){return obj>=0?"0x"+obj.toString(16).toUpperCase():"-0x"+obj.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;float=new type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat,represent:representYamlFloat,defaultStyle:"lowercase"}),json=failsafe.extend({implicit:[_null,bool,int,float]}),core=json,YAML_DATE_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),YAML_TIMESTAMP_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");timestamp=new type("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:resolveYamlTimestamp,construct:constructYamlTimestamp,instanceOf:Date,represent:representYamlTimestamp});merge=new type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge});binary=new type("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary}),_hasOwnProperty$3=Object.prototype.hasOwnProperty,_toString$2=Object.prototype.toString;omap=new type("tag:yaml.org,2002:omap",{kind:"sequence",resolve:resolveYamlOmap,construct:constructYamlOmap}),_toString$1=Object.prototype.toString;pairs=new type("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:resolveYamlPairs,construct:constructYamlPairs}),_hasOwnProperty$2=Object.prototype.hasOwnProperty;set=new type("tag:yaml.org,2002:set",{kind:"mapping",resolve:resolveYamlSet,construct:constructYamlSet}),_default=core.extend({implicit:[timestamp,merge],explicit:[binary,omap,pairs,set]}),_hasOwnProperty$1=Object.prototype.hasOwnProperty,PATTERN_NON_PRINTABLE=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,PATTERN_NON_ASCII_LINE_BREAKS=/[\x85\u2028\u2029]/,PATTERN_FLOW_INDICATORS=/[,\[\]\{\}]/,PATTERN_TAG_HANDLE=/^(?:!|!!|![a-z\-]+!)$/i,PATTERN_TAG_URI=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;simpleEscapeCheck=Array(256),simpleEscapeMap=Array(256);for(i=0;i<256;i++)simpleEscapeCheck[i]=simpleEscapeSequence(i)?1:0,simpleEscapeMap[i]=simpleEscapeSequence(i);directiveHandlers={YAML:function(state,name,args){var match,major,minor;if(state.version!==null)throwError(state,"duplication of %YAML directive");if(args.length!==1)throwError(state,"YAML directive accepts exactly one argument");if(match=/^([0-9]+)\.([0-9]+)$/.exec(args[0]),match===null)throwError(state,"ill-formed argument of the YAML directive");if(major=parseInt(match[1],10),minor=parseInt(match[2],10),major!==1)throwError(state,"unacceptable YAML version of the document");if(state.version=args[0],state.checkLineBreaks=minor<2,minor!==1&&minor!==2)throwWarning(state,"unsupported YAML version of the document")},TAG:function(state,name,args){var handle,prefix;if(args.length!==2)throwError(state,"TAG directive accepts exactly two arguments");if(handle=args[0],prefix=args[1],!PATTERN_TAG_HANDLE.test(handle))throwError(state,"ill-formed tag handle (first argument) of the TAG directive");if(_hasOwnProperty$1.call(state.tagMap,handle))throwError(state,'there is a previously declared suffix for "'+handle+'" tag handle');if(!PATTERN_TAG_URI.test(prefix))throwError(state,"ill-formed tag prefix (second argument) of the TAG directive");try{prefix=decodeURIComponent(prefix)}catch(err){throwError(state,"tag prefix is malformed: "+prefix)}state.tagMap[handle]=prefix}};loadAll_1=loadAll$1,load_1=load$1,loader={loadAll:loadAll_1,load:load_1},_toString=Object.prototype.toString,_hasOwnProperty=Object.prototype.hasOwnProperty,ESCAPE_SEQUENCES={};ESCAPE_SEQUENCES[0]="\\0";ESCAPE_SEQUENCES[7]="\\a";ESCAPE_SEQUENCES[8]="\\b";ESCAPE_SEQUENCES[9]="\\t";ESCAPE_SEQUENCES[10]="\\n";ESCAPE_SEQUENCES[11]="\\v";ESCAPE_SEQUENCES[12]="\\f";ESCAPE_SEQUENCES[13]="\\r";ESCAPE_SEQUENCES[27]="\\e";ESCAPE_SEQUENCES[34]="\\\"";ESCAPE_SEQUENCES[92]="\\\\";ESCAPE_SEQUENCES[133]="\\N";ESCAPE_SEQUENCES[160]="\\_";ESCAPE_SEQUENCES[8232]="\\L";ESCAPE_SEQUENCES[8233]="\\P";DEPRECATED_BOOLEANS_SYNTAX=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],DEPRECATED_BASE60_SYNTAX=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;dump_1=dump$1,dumper={dump:dump_1};Type=type,Schema=schema,FAILSAFE_SCHEMA=failsafe,JSON_SCHEMA=json,CORE_SCHEMA=core,DEFAULT_SCHEMA=_default,load=loader.load,loadAll=loader.loadAll,dump=dumper.dump,YAMLException=exception,types3={binary,float,map,null:_null,pairs,set,timestamp,bool,int,merge,omap,seq,str},safeLoad=renamed("safeLoad","load"),safeLoadAll=renamed("safeLoadAll","loadAll"),safeDump=renamed("safeDump","dump"),jsYaml={Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load,loadAll,dump,YAMLException,types:types3,safeLoad,safeLoadAll,safeDump}});var exports_frontmatter={};__export(exports_frontmatter,{parseFrontmatter:()=>parseFrontmatter,AgentFrontmatterSchema:()=>AgentFrontmatterSchema});function extractRawYaml(content){let match=content.match(/^---\n([\s\S]*?)\n---/);if(!match)return null;try{let parsed=load(match[1]);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function warnUnknownFields(raw){for(let key of Object.keys(raw))if(!knownKeys.has(key))console.warn(`[frontmatter] Unknown field "${key}" \u2014 ignored.`)}function validateFieldByField(raw){let out={};for(let key of knownKeys){let fieldResult=AgentFrontmatterSchema.shape[key].safeParse(raw[key]);if(fieldResult.success){if(fieldResult.data!==void 0)out[key]=fieldResult.data}else if(raw[key]!==void 0)console.warn(`[frontmatter] Invalid value for "${key}": ${JSON.stringify(raw[key])} \u2014 using default.`)}return out}function parseFrontmatter(content){let raw=extractRawYaml(content);if(!raw)return{};warnUnknownFields(raw);let result2=AgentFrontmatterSchema.safeParse(raw);if(result2.success)return result2.data;return validateFieldByField(raw)}var promptModeValues,providerValues,AgentFrontmatterSchema,knownKeys;var init_frontmatter=__esm(()=>{init_js_yaml();init_zod();promptModeValues=["system","append"],providerValues=["claude","codex","claude-sdk"],AgentFrontmatterSchema=exports_external.object({name:exports_external.string().optional(),description:exports_external.string().optional(),model:exports_external.string().optional(),color:exports_external.string().optional(),promptMode:exports_external.enum(promptModeValues).optional(),provider:exports_external.enum(providerValues).optional(),tools:exports_external.array(exports_external.string()).optional(),permissionMode:exports_external.string().optional(),disallowedTools:exports_external.array(exports_external.string()).optional(),permissions:exports_external.object({allow:exports_external.array(exports_external.string()).optional(),deny:exports_external.array(exports_external.string()).optional()}).optional(),omniScopes:exports_external.array(exports_external.string()).optional(),hooks:exports_external.record(exports_external.unknown()).optional(),sdk:exports_external.record(exports_external.unknown()).optional()}),knownKeys=new Set(Object.keys(AgentFrontmatterSchema.shape))});import{existsSync as existsSync9,readFileSync as readFileSync5,readdirSync as readdirSync3,realpathSync}from"fs";import{dirname as dirname2,join as join11,resolve}from"path";function resolvePackageRoot(){let scriptPath=realpathSync(process.argv[1]||""),candidates=[resolve(dirname2(scriptPath),".."),resolve(dirname2(scriptPath),"..",".."),resolve(dirname2(import.meta.dir??__dirname),"..",".."),resolve(dirname2(import.meta.dir??__dirname),"..")];for(let candidate of candidates)if(existsSync9(join11(candidate,"plugins","genie","agents")))return candidate;return candidates[0]}function scanAgents(agentsDir){if(!existsSync9(agentsDir))return[];let agents=[],entries;try{entries=readdirSync3(agentsDir,{withFileTypes:!0})}catch{return[]}for(let entry of entries){if(!entry.isDirectory())continue;let agentsPath=join11(agentsDir,entry.name,"AGENTS.md");if(!existsSync9(agentsPath))continue;let content=readFileSync5(agentsPath,"utf-8"),fm=parseFrontmatter(content),name=fm.name||entry.name,isCouncil=name.startsWith("council");agents.push({name,description:fm.description||"",agentPath:agentsPath,model:normalizeValue(fm.model),promptMode:fm.promptMode||void 0,category:isCouncil?"council":"role",color:fm.color})}return agents}function getBuiltin(name){return ALL_BUILTINS.find((a)=>a.name===name)??null}function resolveBuiltinAgentPath(name){return getBuiltin(name)?.agentPath??null}var __dirname="/home/runner/_work/genie/genie/src/lib",AGENTS_DIR,_allAgents,BUILTIN_ROLES,BUILTIN_COUNCIL_MEMBERS,ALL_BUILTINS;var init_builtin_agents=__esm(()=>{init_defaults();init_frontmatter();AGENTS_DIR=join11(resolvePackageRoot(),"plugins","genie","agents"),_allAgents=scanAgents(AGENTS_DIR),BUILTIN_ROLES=_allAgents.filter((a)=>a.category==="role"),BUILTIN_COUNCIL_MEMBERS=_allAgents.filter((a)=>a.category==="council"),ALL_BUILTINS=_allAgents});var exports_frontmatter_writer={};__export(exports_frontmatter_writer,{writeFrontmatter:()=>writeFrontmatter,serializeSdkConfig:()=>serializeSdkConfig});import{readFileSync as readFileSync6,writeFileSync as writeFileSync5}from"fs";function writeFrontmatter(filePath,updates){let content=readFileSync6(filePath,"utf-8"),{yamlObj,body}=splitFrontmatter(content),merged={...yamlObj,...stripUndefined(updates)},output=`---
|
|
275
|
-
${dump(merged,{lineWidth:-1,noRefs:!0,sortKeys:!1,quotingType:'"'})}---
|
|
276
|
-
${body}`;writeFileSync5(filePath,output,"utf-8")}function serializeSdkConfig(sdk){let result2={};for(let[key,value]of Object.entries(sdk)){if(value===void 0||value===null)continue;if(Array.isArray(value)&&value.length===0)continue;if(typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)continue;result2[key]=value}return result2}function splitFrontmatter(content){let match=content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!match)return{yamlObj:{},body:content};let yamlStr=match[1],body=match[2],yamlObj={};try{let parsed=load(yamlStr);if(typeof parsed==="object"&&parsed!==null)yamlObj=parsed}catch{}return{yamlObj,body}}function stripUndefined(obj){let result2={};for(let[key,value]of Object.entries(obj))if(value!==void 0)result2[key]=value;return result2}var init_frontmatter_writer=__esm(()=>{init_js_yaml()});var exports_agent_directory={};__export(exports_agent_directory,{syncFrontmatterToDisk:()=>syncFrontmatterToDisk,rm:()=>rm2,resolve:()=>resolve2,ls:()=>ls,loadIdentity:()=>loadIdentity,getProjectRoot:()=>getProjectRoot,get:()=>get,findSessionByRepo:()=>findSessionByRepo,edit:()=>edit,add:()=>add});import{existsSync as existsSync10}from"fs";import{join as join12}from"path";function getProjectRoot(){if(process.env.GENIE_PROJECT_ROOT)return process.env.GENIE_PROJECT_ROOT;try{let{execSync:execSync3}=__require("child_process");return execSync3("git rev-parse --show-toplevel",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return process.cwd()}}async function add(entry,_options){if(!entry.name||entry.name.trim()==="")throw Error("Agent name is required.");if(!entry.dir||entry.dir.trim()==="")throw Error("Agent directory (--dir) is required.");if(!existsSync10(entry.dir))throw Error(`Directory does not exist: ${entry.dir}`);let agentsPath=join12(entry.dir,"AGENTS.md");if(!existsSync10(agentsPath))throw Error(`AGENTS.md not found in ${entry.dir}. Each agent directory must contain an AGENTS.md file.`);let full={...entry,promptMode:entry.promptMode??"append",registeredAt:new Date().toISOString()},existing=await resolve2(entry.name);if(existing&&!existing.builtin)throw Error(`Agent "${entry.name}" already exists. Use "genie dir edit" to update or "genie dir rm" first.`);let metadata=buildMetadata(full),{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2();return await sql`
|
|
261
|
+
`)}}async function ensurePgserve(){if(activePort===null){let testPort=await resolveTestPort();if(testPort!==null)return activePort=testPort,process.env.GENIE_PG_AVAILABLE="true",testPort}if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}async function autoStartDaemon(){for(let pidName of["serve.pid","scheduler.pid"]){let pidPath=join7(GENIE_HOME,pidName);try{let pidStr=readFileSync5(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";spawn(bunPath,[genieBin,"serve","start","--headless"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()}async function resolveTestPort(){let raw=process.env.GENIE_TEST_PG_PORT;if(!raw)return null;let parsed=Number.parseInt(raw,10);if(Number.isNaN(parsed)||parsed<=0||parsed>=65536||!await isPostgresHealthy(parsed))throw Error(`GENIE_TEST_PG_PORT=${raw} set but not reachable`);return parsed}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"){mkdirSync4(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 genie serve to start pgserve (16s). Run: genie serve")}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync6(resolved))return resolved}catch{}let globalBin=join7(homedir5(),".bun","bin","pgserve");if(existsSync6(globalBin))return globalBin;try{return execSync2("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync4(DATA_DIR,{recursive:!0});let child=spawn(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster","--pgvector"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let timeout=Number(process.env.GENIE_PGSERVE_TIMEOUT)||30000,deadline=Date.now()+timeout;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 ${timeout/1000}s)`)}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 healthCheckCachedClient(){if(!sqlClient)return null;try{return await sqlClient`SELECT 1`,sqlClient}catch{try{await sqlClient.end({timeout:2})}catch{}return sqlClient=null,activePort=null,null}}async function runPostConnectSetup(client,testSchema,timings){let _t2=Date.now();if(!testSchema)await runMigrations(client);let _t3=Date.now();if(!testSchema&&needsSeed())await runSeed(client);let _t4=Date.now();if(!testSchema&&!retentionRan)await runRetention(client);let _t5=Date.now();if(process.env.GENIE_PROFILE_DB)console.error(`[db-profile] pgserve=${timings.t1-timings.t0}ms migrate=${_t3-_t2}ms seed=${_t4-_t3}ms retention=${_t5-_t4}ms total=${_t5-timings.t0}ms`)}async function getConnection(){let cached=await healthCheckCachedClient();if(cached)return cached;let _t0=Date.now(),port=await ensurePgserve(),_t1=Date.now(),pgModule=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testSchema=process.env.GENIE_TEST_SCHEMA;sqlClient=pgModule({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{await runPostConnectSetup(sqlClient,testSchema,{t0:_t0,t1:_t1})}catch(err){try{await sqlClient.end({timeout:2})}catch{}throw sqlClient=null,activePort=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_HOME,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,ownsLockfile=!1,exitHandlerRegistered=!1,retentionRan=!1;var init_db=__esm(()=>{init_db_migrations();init_pg_seed();GENIE_HOME=process.env.GENIE_HOME??join7(homedir5(),".genie"),DATA_DIR=join7(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join7(GENIE_HOME,"pgserve.port")});var exports_agent_directory={};__export(exports_agent_directory,{syncFrontmatterToDisk:()=>syncFrontmatterToDisk,rm:()=>rm,resolve:()=>resolve2,ls:()=>ls,loadIdentity:()=>loadIdentity,getProjectRoot:()=>getProjectRoot,get:()=>get,findSessionByRepo:()=>findSessionByRepo,edit:()=>edit,add:()=>add});import{existsSync as existsSync7}from"fs";import{join as join8}from"path";function getProjectRoot(){if(process.env.GENIE_PROJECT_ROOT)return process.env.GENIE_PROJECT_ROOT;try{let{execSync:execSync3}=__require("child_process");return execSync3("git rev-parse --show-toplevel",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return process.cwd()}}async function add(entry,_options){if(!entry.name||entry.name.trim()==="")throw Error("Agent name is required.");if(!entry.dir||entry.dir.trim()==="")throw Error("Agent directory (--dir) is required.");if(!existsSync7(entry.dir))throw Error(`Directory does not exist: ${entry.dir}`);let agentsPath=join8(entry.dir,"AGENTS.md");if(!existsSync7(agentsPath))throw Error(`AGENTS.md not found in ${entry.dir}. Each agent directory must contain an AGENTS.md file.`);let full={...entry,promptMode:entry.promptMode??"append",registeredAt:new Date().toISOString()},existing=await resolve2(entry.name);if(existing&&!existing.builtin)throw Error(`Agent "${entry.name}" already exists. Use "genie dir edit" to update or "genie dir rm" first.`);let metadata=buildMetadata(full),{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2();return await sql`
|
|
277
262
|
INSERT INTO agents (id, role, custom_name, started_at, metadata)
|
|
278
263
|
VALUES (${`dir:${entry.name}`}, ${entry.name}, ${entry.name}, now(), ${sql.json(metadata)})
|
|
279
264
|
ON CONFLICT (id) DO UPDATE SET metadata = ${sql.json(metadata)}
|
|
280
|
-
`,full}async function
|
|
265
|
+
`,full}async function rm(name,_options){let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return(await(await getConnection2())`DELETE FROM agents WHERE id = ${`dir:${name}`}`).count>0}async function resolve2(name){try{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),rows=await(await getConnection2())`
|
|
281
266
|
SELECT role, metadata FROM agents
|
|
282
267
|
WHERE role = ${name}
|
|
283
268
|
ORDER BY (CASE WHEN id LIKE 'dir:%' THEN 0 ELSE 1 END), started_at DESC
|
|
@@ -296,7 +281,7 @@ ${body}`;writeFileSync5(filePath,output,"utf-8")}function serializeSdkConfig(sdk
|
|
|
296
281
|
LEFT JOIN executors e ON a.current_executor_id = e.id
|
|
297
282
|
WHERE a.role IS NOT NULL
|
|
298
283
|
ORDER BY a.role, (CASE WHEN a.id LIKE 'dir:%' THEN 0 ELSE 1 END), a.started_at DESC
|
|
299
|
-
`;for(let row of rows){let name=row.role;if(!seen.has(name)){let meta=parseMetadata(row.metadata),entry=roleToEntry(name,row.team,meta),repoPath=row.repo_path;if(repoPath)entry.dir=repoPath,entry.repo=repoPath;result2.push({...entry,scope:"global"}),seen.add(name)}}}catch{}return result2}async function get(name,_options){return(await resolve2(name))?.entry??null}async function edit(name,updates,_options){if(updates.dir){if(!
|
|
284
|
+
`;for(let row of rows){let name=row.role;if(!seen.has(name)){let meta=parseMetadata(row.metadata),entry=roleToEntry(name,row.team,meta),repoPath=row.repo_path;if(repoPath)entry.dir=repoPath,entry.repo=repoPath;result2.push({...entry,scope:"global"}),seen.add(name)}}}catch{}return result2}async function get(name,_options){return(await resolve2(name))?.entry??null}async function edit(name,updates,_options){if(updates.dir){if(!existsSync7(updates.dir))throw Error(`Directory does not exist: ${updates.dir}`);let agentsPath=join8(updates.dir,"AGENTS.md");if(!existsSync7(agentsPath))throw Error(`AGENTS.md not found in ${updates.dir}.`)}let existing=await get(name);if(!existing)throw Error(`Agent "${name}" not found in directory.`);let updated=Object.assign(existing,updates),metadataPatch=buildMetadata(updated);try{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2();if((await sql`
|
|
300
285
|
UPDATE agents
|
|
301
286
|
SET metadata = metadata || ${sql.json(metadataPatch)}
|
|
302
287
|
WHERE id = ${`dir:${name}`}
|
|
@@ -304,7 +289,7 @@ ${body}`;writeFileSync5(filePath,output,"utf-8")}function serializeSdkConfig(sdk
|
|
|
304
289
|
UPDATE agents
|
|
305
290
|
SET metadata = metadata || ${sql.json(metadataPatch)}
|
|
306
291
|
WHERE role = ${name}
|
|
307
|
-
`}catch{}return updated}function loadIdentity(entry){if(!entry.dir)return null;let agentsPath=
|
|
292
|
+
`}catch{}return updated}function loadIdentity(entry){if(!entry.dir)return null;let agentsPath=join8(entry.dir,"AGENTS.md");if(existsSync7(agentsPath))return agentsPath;return null}function builtinToEntry(agent){return{name:agent.name,dir:"",promptMode:agent.promptMode??"append",model:agent.model,roles:[],registeredAt:"(built-in)"}}function roleToEntry(role,team,metadata){if(!(metadata&&Object.keys(metadata).length>0)){let builtin=[...BUILTIN_ROLES,...BUILTIN_COUNCIL_MEMBERS].find((b2)=>b2.name===role);if(builtin)return builtinToEntry(builtin)}return{name:role,dir:metadata?.dir||"",promptMode:metadata?.promptMode||"append",model:metadata?.model,roles:[],registeredAt:new Date().toISOString(),description:metadata?.description,color:metadata?.color,provider:metadata?.provider,permissions:metadata?.permissions,disallowedTools:metadata?.disallowedTools,omniScopes:metadata?.omniScopes,hooks:metadata?.hooks,sdk:metadata?.sdk,...metadata?.repo?{repo:metadata.repo}:team?{repo:team}:{}}}function buildMetadata(entry){let meta={};if(entry.dir)meta.dir=entry.dir;if(entry.repo)meta.repo=entry.repo;if(entry.model)meta.model=entry.model;if(entry.promptMode&&entry.promptMode!=="append")meta.promptMode=entry.promptMode;if(entry.description)meta.description=entry.description;if(entry.color)meta.color=entry.color;if(entry.provider)meta.provider=entry.provider;if(entry.permissions)meta.permissions=entry.permissions;if(entry.disallowedTools)meta.disallowedTools=entry.disallowedTools;if(entry.omniScopes)meta.omniScopes=entry.omniScopes;if(entry.hooks)meta.hooks=entry.hooks;if(entry.sdk)meta.sdk=entry.sdk;return meta}function parseMetadata(raw){if(!raw)return{};if(typeof raw==="object"&&!Array.isArray(raw))return raw;if(typeof raw==="string")try{return JSON.parse(raw)}catch{return{}}return{}}function syncFrontmatterToDisk(entry,updates){try{if(!entry.dir)return;let agentsPath=join8(entry.dir,"AGENTS.md");if(!existsSync7(agentsPath))return;if(!Object.keys(updates).some((k)=>FRONTMATTER_KEYS.has(k)))return;let fmUpdates={};if(updates.model!==void 0)fmUpdates.model=updates.model;if(updates.description!==void 0)fmUpdates.description=updates.description;if(updates.color!==void 0)fmUpdates.color=updates.color;if(updates.promptMode!==void 0)fmUpdates.promptMode=updates.promptMode;if(updates.provider!==void 0)fmUpdates.provider=updates.provider;if(updates.sdk!==void 0)fmUpdates.sdk=serializeSdkConfig(updates.sdk);if(Object.keys(fmUpdates).length===0)return;writeFrontmatter(agentsPath,fmUpdates)}catch{}}var FRONTMATTER_KEYS;var init_agent_directory=__esm(()=>{init_builtin_agents();init_frontmatter_writer();FRONTMATTER_KEYS=new Set(["name","description","model","color","promptMode","provider","sdk"])});var exports_audit={};__export(exports_audit,{recordAuditEvent:()=>recordAuditEvent,queryToolUsage:()=>queryToolUsage,queryTimeline:()=>queryTimeline,querySummary:()=>querySummary,queryErrorPatterns:()=>queryErrorPatterns,queryCostBreakdown:()=>queryCostBreakdown,queryAuditEvents:()=>queryAuditEvents,getActor:()=>getActor,generateTraceId:()=>generateTraceId,followAuditEvents:()=>followAuditEvents});async function recordAuditEvent(entityType,entityId,eventType,actor,details){try{if(!await isAvailable())return;let sql=await getConnection();await sql`
|
|
308
293
|
INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
|
|
309
294
|
VALUES (${entityType}, ${entityId}, ${eventType}, ${actor??null}, ${sql.json(details??{})})
|
|
310
295
|
`}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
|
|
@@ -364,7 +349,22 @@ ${body}`;writeFileSync5(filePath,output,"utf-8")}function serializeSdkConfig(sdk
|
|
|
364
349
|
COUNT(*) FILTER (WHERE entity_type = 'otel_tool')::int AS tool_calls,
|
|
365
350
|
COUNT(*) FILTER (WHERE entity_type = 'otel_api')::int AS api_requests
|
|
366
351
|
FROM audit_events
|
|
367
|
-
WHERE created_at >= $1::timestamptz`,[sinceTs]))[0]??{};return{agents_spawned:r.agents_spawned??0,tasks_moved:r.tasks_moved??0,total_cost:r.total_cost??0,error_count:r.error_count??0,total_events:r.total_events??0,tool_calls:r.tool_calls??0,api_requests:r.api_requests??0}}function generateTraceId(){return crypto.randomUUID()}var init_audit=__esm(()=>{init_db()});function
|
|
352
|
+
WHERE created_at >= $1::timestamptz`,[sinceTs]))[0]??{};return{agents_spawned:r.agents_spawned??0,tasks_moved:r.tasks_moved??0,total_cost:r.total_cost??0,error_count:r.error_count??0,total_events:r.total_events??0,tool_calls:r.tool_calls??0,api_requests:r.api_requests??0}}function generateTraceId(){return crypto.randomUUID()}var init_audit=__esm(()=>{init_db()});function isBlockingEvent(event){return BLOCKING_EVENTS.has(event)}var DISPATCHED_EVENTS,BLOCKING_EVENTS;var init_types3=__esm(()=>{DISPATCHED_EVENTS=["PreToolUse","PostToolUse","SessionStart","SessionEnd","TeammateIdle","TaskCompleted"],BLOCKING_EVENTS=new Set(["PreToolUse","UserPromptSubmit","TeammateIdle","TaskCompleted","PermissionRequest"])});var exports_inject={};__export(exports_inject,{isTeamHooked:()=>isTeamHooked,injectTeamHooks:()=>injectTeamHooks,buildDispatchCommand:()=>buildDispatchCommand});import{existsSync as existsSync8}from"fs";import{mkdir,readFile as readFile2,writeFile}from"fs/promises";import{homedir as homedir6}from"os";import{join as join9}from"path";import{fileURLToPath}from"url";function escapeShellArg(arg){return`'${arg.replace(/'/g,"'\\''")}'`}function buildDispatchCommand(){let entrypoint=fileURLToPath(new URL("../genie.ts",import.meta.url));if(!existsSync8(entrypoint))return"genie hook dispatch";let bun=process.execPath||"bun";return`${escapeShellArg(bun)} run ${escapeShellArg(entrypoint)} hook dispatch`}function isGenieDispatchCommand(command){return typeof command==="string"&&/(?:^|\s)hook\s+dispatch(?:\s|$)/.test(command)}function claudeConfigDir(){return process.env.CLAUDE_CONFIG_DIR??join9(homedir6(),".claude")}function teamSettingsPath(teamName){let sanitized=teamName.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase();return join9(claudeConfigDir(),"teams",sanitized,"settings.json")}function buildHooksConfig(){let hooks={},dispatchCommand=buildDispatchCommand();for(let event of DISPATCHED_EVENTS)hooks[event]=[{matcher:"*",hooks:[{type:"command",command:dispatchCommand,timeout:DISPATCH_TIMEOUT}]}];return hooks}async function injectIntoFile(settingsPath){let settings={};if(existsSync8(settingsPath))try{let content=await readFile2(settingsPath,"utf-8");settings=JSON.parse(content)}catch{}let hooksConfig=buildHooksConfig(),existingHooks=settings.hooks;if(existingHooks){if(DISPATCHED_EVENTS.every((event)=>{let existing=existingHooks[event],desiredCommand=hooksConfig[event][0].hooks[0].command;return existing?.some((m)=>m.hooks?.some((h)=>h.command===desiredCommand))}))return!1}let mergedHooks=existingHooks?{...existingHooks}:{};for(let event of DISPATCHED_EVENTS){let genieEntry=hooksConfig[event][0],existingEntries=(mergedHooks[event]??[]).map((matcher)=>({...matcher,hooks:matcher.hooks?.map((hook)=>isGenieDispatchCommand(hook.command)?{...hook,command:genieEntry.hooks[0].command,timeout:DISPATCH_TIMEOUT}:hook)}));if(!existingEntries.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command))))mergedHooks[event]=[...existingEntries,genieEntry];else mergedHooks[event]=existingEntries}settings.hooks=mergedHooks;let dir=join9(settingsPath,"..");return await mkdir(dir,{recursive:!0}),await writeFile(settingsPath,JSON.stringify(settings,null,2)),!0}async function injectTeamHooks(teamName){let path=teamSettingsPath(teamName);return injectIntoFile(path)}async function isTeamHooked(teamName){let path=teamSettingsPath(teamName);if(!existsSync8(path))return!1;try{let content=await readFile2(path,"utf-8"),hooks=JSON.parse(content).hooks;if(!hooks)return!1;return DISPATCHED_EVENTS.every((event)=>{return hooks[event]?.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)))})}catch{return!1}}var DISPATCH_TIMEOUT=15;var init_inject=__esm(()=>{init_types3()});var exports_provider_adapters={};__export(exports_provider_adapters,{validateSpawnParams:()=>validateSpawnParams,buildLaunchCommand:()=>buildLaunchCommand,buildCodexCommand:()=>buildCodexCommand,buildClaudeCommand:()=>buildClaudeCommand,CLAUDE_TEAM_COLORS:()=>CLAUDE_TEAM_COLORS});function validateSpawnParams(params){return spawnParamsSchema.parse(params)}function escapeShellArg2(arg){return`'${arg.replace(/'/g,"'\\''")}'`}function hasBinary(name){try{let BunExt=Bun;if(typeof BunExt.which==="function")return Boolean(BunExt.which(name));let{execSync:execSync3}=__require("child_process");return execSync3(`which ${name}`,{stdio:"ignore"}),!0}catch{return!1}}function resolveShellBinary(name){try{let{execFileSync}=__require("child_process"),shell=process.env.SHELL||"/bin/sh";return execFileSync(shell,["-lc",`command -v ${name}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function preflightCheck(provider){if(!hasBinary(provider))throw Error(`Provider binary "${provider}" not found on PATH. Install ${provider} or check your environment.`)}function appendNativeTeamFlags(parts,env,nt,params){env.CLAUDECODE="1",env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1";let agentName=nt.agentName??params.role??"worker";if(env.GENIE_AGENT_NAME=agentName,parts.push("--agent-id",escapeShellArg2(`${agentName}@${params.team}`)),parts.push("--agent-name",escapeShellArg2(agentName)),parts.push("--team-name",escapeShellArg2(params.team)),nt.color)parts.push("--agent-color",escapeShellArg2(nt.color));if(nt.parentSessionId)parts.push("--parent-session-id",escapeShellArg2(nt.parentSessionId));if(nt.agentType)parts.push("--agent-type",escapeShellArg2(nt.agentType));if(nt.planModeRequired)parts.push("--plan-mode-required");let effectivePermMode=nt.permissionMode??"bypassPermissions";parts.push("--permission-mode",escapeShellArg2(effectivePermMode))}function appendSystemPromptFlags(parts,params){if(params.systemPrompt){let{mkdirSync:mkdirSync5,writeFileSync:writeFileSync6,readFileSync:readFileSync6}=__require("fs"),{join:join10}=__require("path"),dir="/tmp/genie-prompts";mkdirSync5("/tmp/genie-prompts",{recursive:!0});let ts=Date.now().toString(36),promptFile=join10("/tmp/genie-prompts",`${params.role||"agent"}-${ts}.md`),content=params.systemPrompt;if(params.systemPromptFile)content=`${readFileSync6(params.systemPromptFile,"utf-8")}
|
|
353
|
+
|
|
354
|
+
${content}`;if(params.extraArgs){let fileIdx=params.extraArgs.indexOf("--append-system-prompt-file");if(fileIdx!==-1&¶ms.extraArgs[fileIdx+1])content=`${content}
|
|
355
|
+
|
|
356
|
+
${readFileSync6(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync6(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function buildClaudeCommand(params){preflightCheck("claude");let parts=[resolveShellBinary("claude")??"claude","--dangerously-skip-permissions"],env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(appendOtelEnv(env,params),params.nativeTeam?.enabled)appendNativeTeamFlags(parts,env,params.nativeTeam,params);if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));if(params.role)parts.push("--agent",escapeShellArg2(params.role));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name));appendSystemPromptFlags(parts,params);let settingsObj={};if(!params.skipHooks){let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15};settingsObj.hooks={PreToolUse:[{matcher:"*",hooks:[hookEntry]}],PostToolUse:[{matcher:"*",hooks:[hookEntry]}],UserPromptSubmit:[{hooks:[hookEntry]}],Stop:[{hooks:[hookEntry]}]}}if(params.permissions){let perms={};if(params.permissions.allow?.length)perms.allow=params.permissions.allow;if(params.permissions.deny?.length)perms.deny=params.permissions.deny;if(Object.keys(perms).length>0)settingsObj.permissions=perms}if(Object.keys(settingsObj).length>0)parts.push("--settings",escapeShellArg2(JSON.stringify(settingsObj)));if(params.disallowedTools?.length)for(let tool of params.disallowedTools)parts.push("--disallowedTools",escapeShellArg2(tool));if(params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));if(params.initialPrompt)parts.push(escapeShellArg2(params.initialPrompt));return{command:parts.join(" "),provider:"claude",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildCodexCommand(params){preflightCheck("codex");let parts=["codex"];if(parts.push("--yolo"),parts.push("--no-alt-screen"),params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));let promptParts=[`Genie worker. Team: ${params.team}.`];if(params.role)promptParts.push(`Role: ${params.role}.`);if(params.skill)promptParts.push(`Execute the ${params.skill} skill instructions.`);let prompt=promptParts.join(" ");return parts.push(escapeShellArg2(prompt)),{command:parts.join(" "),provider:"codex",meta:{role:params.role,skill:params.skill}}}function buildLaunchCommand(params){let validated=validateSpawnParams(params);switch(validated.provider){case"claude":return buildClaudeCommand(validated);case"codex":return buildCodexCommand(validated);case"claude-sdk":return{command:"claude-sdk-in-process",provider:"claude-sdk",meta:{role:validated.role,skill:validated.skill}};default:throw Error(`Unknown provider "${validated.provider}". Valid providers: claude, codex, claude-sdk`)}}var CLAUDE_TEAM_COLORS,spawnParamsSchema;var init_provider_adapters=__esm(()=>{init_zod();init_inject();CLAUDE_TEAM_COLORS=["red","blue","green","yellow","purple","orange","pink","cyan"],spawnParamsSchema=exports_external.object({provider:exports_external.enum(["claude","codex","claude-sdk","app-pty"]),team:exports_external.string().min(1,"Team name is required"),role:exports_external.string().optional(),skill:exports_external.string().optional(),extraArgs:exports_external.array(exports_external.string()).optional(),nativeTeam:exports_external.object({enabled:exports_external.boolean(),parentSessionId:exports_external.string().optional(),color:exports_external.string().optional(),agentType:exports_external.string().optional(),planModeRequired:exports_external.boolean().optional(),permissionMode:exports_external.string().optional(),agentName:exports_external.string().optional()}).optional(),sessionId:exports_external.string().uuid().optional(),resume:exports_external.string().optional(),systemPromptFile:exports_external.string().optional(),systemPrompt:exports_external.string().optional(),promptMode:exports_external.enum(["system","append"]).optional(),model:exports_external.string().optional(),initialPrompt:exports_external.string().optional(),name:exports_external.string().optional(),otelPort:exports_external.number().optional(),otelLogPrompts:exports_external.boolean().optional(),otelWishSlug:exports_external.string().optional(),newWindow:exports_external.boolean().optional(),windowTarget:exports_external.string().optional()})});var exports_claude_native_teams={};__export(exports_claude_native_teams,{writeNativeInbox:()=>writeNativeInbox,unregisterNativeMember:()=>unregisterNativeMember,sanitizeTeamName:()=>sanitizeTeamName,resolveNativeMemberName:()=>resolveNativeMemberName,registerNativeMember:()=>registerNativeMember,registerAsTeamLead:()=>registerAsTeamLead,loadConfig:()=>loadConfig,listTeamsWithUnreadInbox:()=>listTeamsWithUnreadInbox,listTeams:()=>listTeams,isInsideClaudeCode:()=>isInsideClaudeCode,ensureNativeTeam:()=>ensureNativeTeam,discoverTeamName:()=>discoverTeamName,discoverClaudeParentSessionId:()=>discoverClaudeParentSessionId,deleteNativeTeam:()=>deleteNativeTeam,clearNativeInbox:()=>clearNativeInbox,assignColor:()=>assignColor});import{existsSync as existsSync9}from"fs";import{mkdir as mkdir2,open,readFile as readFile3,readdir as readdir2,rm as rm2,stat,unlink,writeFile as writeFile2}from"fs/promises";import{homedir as homedir7}from"os";import{join as join10}from"path";function claudeConfigDir2(){return process.env.CLAUDE_CONFIG_DIR??join10(homedir7(),".claude")}function teamsBaseDir(){return join10(claudeConfigDir2(),"teams")}function sanitizeTeamName(name){return name.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}async function listTeams(){try{return(await readdir2(teamsBaseDir())).filter((e)=>!e.startsWith("."))}catch{return[]}}function teamDir(teamName){return join10(teamsBaseDir(),sanitizeTeamName(teamName))}function configPath(teamName){return join10(teamDir(teamName),"config.json")}function inboxesDir(teamName){return join10(teamDir(teamName),"inboxes")}function inboxPath(teamName,agentName){return join10(inboxesDir(teamName),`${sanitizeTeamName(agentName)}.json`)}function lockPath(filePath){return`${filePath}.lock`}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function acquireLock(path){let lock=lockPath(path),deadline=Date.now()+LOCK_TIMEOUT_MS;while(Date.now()<deadline)try{await writeFile2(lock,String(process.pid),{flag:"wx"});return}catch{try{let content=await readFile3(lock,"utf-8"),holderPid=Number.parseInt(content.trim(),10);if(!Number.isNaN(holderPid)&&!isPidAlive(holderPid)){try{await unlink(lock)}catch{}continue}}catch{continue}let jitter=Math.floor(Math.random()*LOCK_POLL_MS);await new Promise((r)=>setTimeout(r,LOCK_POLL_MS+jitter))}console.warn(`[claude-native-teams] Force-acquiring stale lock: ${lock}`),await writeFile2(lock,String(process.pid))}async function releaseLock(path){try{await unlink(lockPath(path))}catch{}}async function loadConfig(teamName){try{let content=await readFile3(configPath(teamName),"utf-8");return JSON.parse(content)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return null;let message=err instanceof Error?err.message:String(err);return console.warn(`[claude-native-teams] Failed to load config for "${teamName}": ${message}`),null}}async function saveConfig(teamName,config){await writeFile2(configPath(teamName),JSON.stringify(config,null,2))}async function countLeadSessionRefs(){let counts=new Map,teams=await listTeams();for(let team of teams){let leadSessionId=(await loadConfig(team))?.leadSessionId;if(!leadSessionId)continue;counts.set(leadSessionId,(counts.get(leadSessionId)??0)+1)}return counts}async function ensureNativeTeam(teamName,description,leadSessionId,leaderName){let dir=teamDir(teamName),inboxDir=inboxesDir(teamName);await mkdir2(dir,{recursive:!0}),await mkdir2(inboxDir,{recursive:!0}),ensureTeammateBypassPermissions();let existing=await loadConfig(teamName);if(existing)return existing;let sanitized=sanitizeTeamName(teamName),resolvedLeader=sanitizeTeamName(leaderName??teamName),config={name:sanitized,description,createdAt:Date.now(),leadAgentId:`${resolvedLeader}@${sanitized}`,leadSessionId,members:[]};return await saveConfig(teamName,config),config}async function registerNativeMember(teamName,member){let config=await loadConfig(teamName);if(!config)throw Error(`Native team "${teamName}" not found`);let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(member.agentName)}@${sanitized}`;config.members=config.members.filter((m)=>m.agentId!==agentId),config.members.push({agentId,name:sanitizeTeamName(member.agentName),agentType:member.agentType??"general-purpose",joinedAt:Date.now(),tmuxPaneId:member.tmuxPaneId,cwd:member.cwd??process.cwd(),backendType:"tmux",color:member.color,planModeRequired:member.planModeRequired??!1,isActive:!0}),await saveConfig(teamName,config);let inbox=inboxPath(teamName,member.agentName);if(!existsSync9(inbox))await writeFile2(inbox,"[]")}async function unregisterNativeMember(teamName,agentName){let config=await loadConfig(teamName);if(!config)return;let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(agentName)}@${sanitized}`,member=config.members.find((m)=>m.agentId===agentId);if(member)member.isActive=!1;await saveConfig(teamName,config)}async function writeNativeInbox(teamName,agentName,message){let path=inboxPath(teamName,agentName);await mkdir2(inboxesDir(teamName),{recursive:!0}),await acquireLock(path);try{let messages2=[];try{let content=await readFile3(path,"utf-8");messages2=JSON.parse(content)}catch{}messages2.push(message),await writeFile2(path,JSON.stringify(messages2,null,2))}finally{await releaseLock(path)}}async function resolveNativeMemberName(teamName,genieWorkerId){let config=await loadConfig(teamName);if(!config||config.members.length===0)return null;let sanitizedId=sanitizeTeamName(genieWorkerId),sanitizedTeam=sanitizeTeamName(teamName),exactMatch=config.members.find((m)=>m.name===sanitizedId&&m.isActive);if(exactMatch)return exactMatch.name;let agentIdMatch=config.members.find((m)=>m.agentId===`${sanitizedId}@${sanitizedTeam}`&&m.isActive);if(agentIdMatch)return agentIdMatch.name;let teamPrefix=`${sanitizedTeam}-`;if(sanitizedId.startsWith(teamPrefix)){let stripped=sanitizedId.slice(teamPrefix.length),prefixMatch=config.members.find((m)=>m.name===stripped&&m.isActive);if(prefixMatch)return prefixMatch.name}let inactiveMatch=config.members.find((m)=>m.name===sanitizedId);if(inactiveMatch)return inactiveMatch.name;return null}async function assignColor(teamName){let config=await loadConfig(teamName);if(!config)return CLAUDE_TEAM_COLORS[0];let usedColors=new Set(config.members.map((m)=>m.color));for(let color of CLAUDE_TEAM_COLORS)if(!usedColors.has(color))return color;return CLAUDE_TEAM_COLORS[config.members.length%CLAUDE_TEAM_COLORS.length]}async function clearNativeInbox(teamName,agentName){let path=inboxPath(teamName,agentName);await acquireLock(path);try{await writeFile2(path,"[]")}finally{await releaseLock(path)}}async function deleteNativeTeam(teamName){let dir=teamDir(teamName);if(!existsSync9(dir))return!1;return await rm2(dir,{recursive:!0,force:!0}),!0}function extractLeaderInboxName(config,teamName){if(!config?.leadAgentId)return teamName??"unknown";let atIdx=config.leadAgentId.indexOf("@");return atIdx>0?config.leadAgentId.slice(0,atIdx):teamName??"unknown"}async function scanTeamInbox(base,name){let config=null;try{let cfgContent=await readFile3(join10(base,name,"config.json"),"utf-8");config=JSON.parse(cfgContent)}catch{}let leaderInboxName=extractLeaderInboxName(config,name),inboxFile=join10(base,name,"inboxes",`${leaderInboxName}.json`),messages2;try{let content=await readFile3(inboxFile,"utf-8");messages2=JSON.parse(content)}catch{return null}if(!Array.isArray(messages2))return null;let unread=messages2.filter((m)=>m.read===!1);if(unread.length===0)return null;let workingDir=null;if(config){let leadMember=config.members.find((m)=>m.agentId===config?.leadAgentId||m.name===leaderInboxName);if(leadMember?.cwd)workingDir=leadMember.cwd}return{teamName:name,unreadCount:unread.length,workingDir,firstUnreadText:unread[0]?.text??null}}async function listTeamsWithUnreadInbox(){let base=teamsBaseDir(),teamDirs;try{teamDirs=await readdir2(base)}catch{return[]}let results=[];for(let name of teamDirs){let entry=await scanTeamInbox(base,name);if(entry)results.push(entry)}return results}function sanitizePath(p){return p.replace(/[^a-zA-Z0-9]/g,"-")}async function discoverClaudeSessionId(cwd){let envSessionId=process.env.CLAUDE_CODE_SESSION_ID;if(envSessionId)return envSessionId;let projectDir=join10(claudeConfigDir2(),"projects",sanitizePath(cwd??process.cwd()));try{let jsonls=(await readdir2(projectDir)).filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let newest=null;for(let name of jsonls){let s=await stat(join10(projectDir,name));if(!newest||s.mtimeMs>newest.mtime)newest={name,mtime:s.mtimeMs}}if(!newest)return null;return newest.name.replace(".jsonl","")}catch{return null}}async function readSessionMetadata(filePath){let handle=null;try{handle=await open(filePath,"r");let buffer2=Buffer.alloc(8192),{bytesRead}=await handle.read(buffer2,0,buffer2.length,0),head=buffer2.toString("utf-8",0,bytesRead);for(let line of head.split(`
|
|
357
|
+
`).slice(0,20)){let trimmed=line.trim();if(!trimmed)continue;try{let entry=JSON.parse(trimmed),teamName=typeof entry.teamName==="string"?entry.teamName:void 0,agentName=typeof entry.agentName==="string"?entry.agentName:void 0;if(teamName||agentName)return{teamName,agentName}}catch{}}}catch{return{}}finally{await handle?.close().catch(()=>{})}return{}}function rootScore(metadata){if(!metadata.teamName&&!metadata.agentName)return 2;if(metadata.teamName&&!metadata.agentName)return 1;return 0}function compareSessionRanking(a,b2,leadRefs){let aLeadRefs=leadRefs.get(a.name.replace(".jsonl",""))??0,bLeadRefs=leadRefs.get(b2.name.replace(".jsonl",""))??0;if(aLeadRefs!==bLeadRefs)return bLeadRefs-aLeadRefs;let aRoot=rootScore(a.metadata),bRoot=rootScore(b2.metadata);if(aRoot!==bRoot)return bRoot-aRoot;return b2.mtime-a.mtime}async function discoverClaudeParentSessionId(cwd){let envSessionId=process.env.CLAUDE_CODE_SESSION_ID;if(envSessionId)return envSessionId;let projectDir=join10(claudeConfigDir2(),"projects",sanitizePath(cwd??process.cwd()));try{let jsonls=(await readdir2(projectDir)).filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let ranked=await Promise.all(jsonls.map(async(name)=>{let filePath=join10(projectDir,name),s=await stat(filePath),metadata=await readSessionMetadata(filePath);return{name,mtime:s.mtimeMs,metadata}})),leadRefs=await countLeadSessionRefs();return ranked.sort((a,b2)=>compareSessionRanking(a,b2,leadRefs)),ranked[0]?.name.replace(".jsonl","")??null}catch{return null}}function isInsideClaudeCode(){return process.env.CLAUDECODE==="1"}async function discoverTeamName(cwd){let envTeam=process.env.GENIE_TEAM;if(envTeam)return envTeam;let sessionId=await discoverClaudeSessionId(cwd);if(!sessionId)return null;let base=teamsBaseDir();try{let teams=await readdir2(base);for(let name of teams){let cfgPath=join10(base,name,"config.json");try{let content=await readFile3(cfgPath,"utf-8"),config=JSON.parse(content);if(config.leadSessionId===sessionId)return config.name}catch{}}}catch{}return null}async function registerAsTeamLead(teamName,opts){let sessionId=await discoverClaudeSessionId(opts?.cwd);if(!sessionId)throw Error("Could not discover Claude Code session ID. Are you running inside Claude Code with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1?");let resolvedLeaderName=opts?.leaderName??teamName,config=await ensureNativeTeam(teamName,`Genie team: ${teamName}`,sessionId,resolvedLeaderName);if(config.leadSessionId!==sessionId)config.leadSessionId=sessionId,await saveConfig(teamName,config);let sanitized=sanitizeTeamName(teamName),leadAgentId=`${sanitizeTeamName(resolvedLeaderName)}@${sanitized}`,existingLead=config.members.find((m)=>m.agentId===leadAgentId),resolvedPaneId=opts?.tmuxPaneId??process.env.TMUX_PANE;if(!existingLead||!existingLead.isActive)await registerNativeMember(teamName,{agentName:resolvedLeaderName,agentType:"general-purpose",color:opts?.color??"blue",tmuxPaneId:resolvedPaneId,cwd:opts?.cwd??process.cwd()});else if(resolvedPaneId&&existingLead.tmuxPaneId!==resolvedPaneId)existingLead.tmuxPaneId=resolvedPaneId,await saveConfig(teamName,config);let inbox=inboxPath(teamName,resolvedLeaderName);if(!existsSync9(inbox))await writeFile2(inbox,"[]");let finalConfig=await loadConfig(teamName);if(!finalConfig)throw Error(`Failed to load config for team "${teamName}" after creation`);return{sessionId,config:finalConfig}}var LOCK_TIMEOUT_MS=5000,LOCK_POLL_MS=50;var init_claude_native_teams=__esm(()=>{init_claude_settings();init_provider_adapters()});var exports_team_lead_command={};__export(exports_team_lead_command,{shellQuote:()=>shellQuote,sessionExists:()=>sessionExists,ccProjectDirName:()=>ccProjectDirName,buildTeamLeadCommand:()=>buildTeamLeadCommand});import{readFileSync as readFileSync6,readdirSync as readdirSync3}from"fs";import{basename,join as join11}from"path";function shellQuote(s){return`'${s.replace(/'/g,"'\\''")}'`}function buildTeamLeadCommand(teamName,options){let sanitized=sanitizeTeamName(teamName),qTeam=shellQuote(sanitized),folderName=basename(process.cwd()),resolvedLeader=options?.leaderName??teamName,sanitizedLeader=sanitizeTeamName(resolvedLeader),parts=["GENIE_WORKER=1","CLAUDECODE=1","CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1",`GENIE_TEAM=${qTeam}`,`GENIE_AGENT_NAME=${shellQuote(folderName)}`,"claude",`--agent-id ${shellQuote(`${sanitizedLeader}@${sanitized}`)}`,`--agent-name ${shellQuote(sanitizedLeader)}`,`--team-name ${qTeam}`,"--agent-type team-lead","--dangerously-skip-permissions"];if(parts.push(`--name ${shellQuote(sanitized)}`),options?.continueName)parts.push(`--resume ${shellQuote(options.continueName)}`);else if(options?.sessionId)parts.push(`--session-id ${shellQuote(options.sessionId)}`);if(options?.systemPromptFile){let promptFlag=(options?.promptMode??loadGenieConfigSync().promptMode)==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(`${promptFlag} ${shellQuote(options.systemPromptFile)}`)}return parts.join(" ")}function ccProjectDirName(dir){return dir.replace(/\//g,"-")}function fileHasSessionName(filePath,needle){try{let lines=readFileSync6(filePath,"utf-8").split(`
|
|
358
|
+
`).slice(0,10);for(let line of lines){if(!line.includes("custom-title"))continue;let entry=JSON.parse(line);if(entry.type==="custom-title"&&entry.customTitle?.toLowerCase()===needle)return!0}}catch{}return!1}function sessionExists(name,cwd){try{let home=process.env.HOME??"/root",projectDir=ccProjectDirName(cwd??process.cwd()),projectPath=join11(home,".claude","projects",projectDir),files;try{files=readdirSync3(projectPath).filter((f)=>f.endsWith(".jsonl"))}catch{return!1}let needle=name.toLowerCase();return files.some((file)=>{let full=join11(projectPath,file);return fileHasSessionName(full,needle)||fileHasSessionName(full,`${needle}-${needle}`)})}catch{return!1}}var init_team_lead_command=__esm(()=>{init_claude_native_teams();init_genie_config2()});var exports_tmux_wrapper={};__export(exports_tmux_wrapper,{genieTmuxPrefix:()=>genieTmuxPrefix,genieTmuxCmd:()=>genieTmuxCmd,executeTmux:()=>executeTmux});import{exec as execCallback}from"child_process";import{existsSync as existsSync10,mkdirSync as mkdirSync5}from"fs";import{homedir as homedir8}from"os";import{join as join12}from"path";import{promisify}from"util";function resolveGenieTmuxConf(){let home=homedir8(),genieHome2=process.env.GENIE_HOME??join12(home,".genie");return[join12(genieHome2,"tmux.conf"),join12(__dirname,"..","..","scripts","tmux","genie.tmux.conf"),join12(home,".bun","install","global","node_modules","@automagik","genie","scripts","tmux","genie.tmux.conf")].find((p)=>existsSync10(p))??"/dev/null"}function genieTmuxPrefix(){return["-L",GENIE_TMUX_SOCKET,"-f",resolveGenieTmuxConf()]}function genieTmuxCmd(subcommand){return`${tmuxBin()} ${genieTmuxPrefix().join(" ")} ${subcommand}`}function getLogDir(){let logDir=join12(homedir8(),".genie","logs","tmux");if(!existsSync10(logDir))mkdirSync5(logDir,{recursive:!0});return logDir}function stripVerboseFlags(args){return args.filter((arg)=>!/^-v+$/.test(arg))}function isTmuxDebugEnabled(){return process.env.GENIE_TMUX_DEBUG==="1"}async function executeTmux(args){let argList=typeof args==="string"?args.split(/\s+/).filter(Boolean):args,finalArgs=stripVerboseFlags(argList),debugMode=isTmuxDebugEnabled(),options={};if(debugMode)finalArgs=["-v",...finalArgs],options.cwd=getLogDir();finalArgs=[...genieTmuxPrefix(),...finalArgs];let command=`${tmuxBin()} ${finalArgs.join(" ")}`,{stdout}=await exec(command,options);return stdout.trim()}var __dirname="/home/runner/_work/genie/genie/src/lib",exec,GENIE_TMUX_SOCKET;var init_tmux_wrapper=__esm(()=>{init_ensure_tmux();exec=promisify(execCallback),GENIE_TMUX_SOCKET=process.env.GENIE_TMUX_SOCKET||"genie"});var exports_tmux={};__export(exports_tmux,{setWindowEnv:()=>setWindowEnv,resolveRepoSession:()=>resolveRepoSession,listWindows:()=>listWindows,listPanes:()=>listPanes,killWindow:()=>killWindow,killSession:()=>killSession,isPaneProcessRunning:()=>isPaneProcessRunning,isPaneAlive:()=>isPaneAlive,getWindowEnv:()=>getWindowEnv,getCurrentSessionName:()=>getCurrentSessionName,findWindowByName:()=>findWindowByName,findSessionByName:()=>findSessionByName,executeTmux:()=>executeTmux2,ensureTeamWindow:()=>ensureTeamWindow,createSession:()=>createSession,capturePaneContent:()=>capturePaneContent,applyPaneColor:()=>applyPaneColor,TmuxUnreachableError:()=>TmuxUnreachableError});import{basename as basename2}from"path";async function executeTmux2(tmuxCommand){let{executeTmux:wrapperExec}=await Promise.resolve().then(() => (init_tmux_wrapper(),exports_tmux_wrapper));try{return await wrapperExec(tmuxCommand)}catch(error){let message=error instanceof Error?error.message:String(error);throw Error(`Failed to execute tmux command: ${message}`)}}async function getCurrentSessionName(hint){if(process.env.TMUX)try{return(await executeTmux2("display-message -p '#{session_name}'")).trim()||null}catch{return null}try{let sessions=await listSessions();if(sessions.length===0)return null;if(hint){let match=sessions.find((s)=>s.name.includes(hint));if(match)return match.name}return sessions[0].name}catch{return null}}async function listSessions(){try{let output=await executeTmux2("list-sessions -F '#{session_id}:#{session_name}:#{?session_attached,1,0}:#{session_windows}'");if(!output)return[];return output.split(`
|
|
359
|
+
`).map((line)=>{let[id,name,attached,windows]=line.split(":");return{id,name,attached:attached==="1",windows:Number.parseInt(windows,10)}})}catch(error){if((error instanceof Error?error.message:String(error)).includes("no server running"))return[];throw error}}async function findSessionByName(name){try{return(await listSessions()).find((session)=>session.name===name)||null}catch(_error){return null}}async function getWindowEnv(target,varName){try{let output=await executeTmux2(`show-environment -t ${shellQuote(target)} ${shellQuote(varName)}`),prefix=`${varName}=`;if(output?.startsWith(prefix))return output.slice(prefix.length).trim();return null}catch{return null}}async function setWindowEnv(target,varName,value){await executeTmux2(`set-environment -t ${shellQuote(target)} ${shellQuote(varName)} ${shellQuote(value)}`)}async function killSession(sessionId){await executeTmux2(`kill-session -t '${sessionId}'`)}async function listWindows(sessionId){try{let output=await executeTmux2(`list-windows -t '${sessionId}' -F '#{window_id}:#{window_name}:#{window_index}:#{?window_active,1,0}'`);if(!output)return[];return output.split(`
|
|
360
|
+
`).map((line)=>{let[id,name,indexStr,active]=line.split(":");return{id,name,index:Number.parseInt(indexStr,10),active:active==="1",sessionId}})}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("session not found"))return[];throw error}}async function listPanes(windowId){try{let output=await executeTmux2(`list-panes -t '${windowId}' -F '#{pane_id}:#{pane_title}:#{?pane_active,1,0}'`);if(!output)return[];return output.split(`
|
|
361
|
+
`).map((line)=>{let[id,title,active]=line.split(":");return{id,windowId,title,active:active==="1"}})}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("window not found"))return[];throw error}}async function capturePaneContent(paneId,lines=200,includeColors=!1){try{return await executeTmux2(`capture-pane -p ${includeColors?"-e":""} -t '${paneId}' -S -${lines} -E -`)}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("pane not found"))return"";throw error}}async function createSession(name){return await executeTmux2(`new-session -d -s "${name}" -e LC_ALL=C.UTF-8 -e LANG=C.UTF-8`),findSessionByName(name)}async function createWindow(sessionId,name,workingDir){let cdFlag=workingDir?` -c '${workingDir.replace(/'/g,"'\\''")}'`:"",output=await executeTmux2(`new-window -d -P -F '#{window_id}:#{window_index}' -t '${sessionId}:' -n '${name}'${cdFlag}`),[windowId,indexStr]=output.trim().split(":");if(!windowId)return null;try{await executeTmux2(`set-window-option -t '${windowId}' automatic-rename off`)}catch{}return{id:windowId,name,index:Number.parseInt(indexStr,10)||0,active:!1,sessionId}}async function findWindowByName(sessionId,name){return(await listWindows(sessionId)).find((w)=>w.name===name)||null}async function ensureMasterWindow(session,masterName){try{let windows=await listWindows(session);if(windows.length<2)return;let masterWindow=windows.find((w)=>w.name===masterName);if(!masterWindow)return;let minIndex=Math.min(...windows.map((w)=>w.index));if(masterWindow.index===minIndex)return;await executeTmux2(`swap-window -s '${session}:${masterWindow.index}' -t '${session}:${minIndex}'`)}catch{}}async function ensureSessionExists(name){try{await executeTmux2(`new-session -d -s "${name}" -e LC_ALL=C.UTF-8 -e LANG=C.UTF-8`)}catch(error){if((error instanceof Error?error.message:String(error)).includes("duplicate session"))return;throw error}}async function ensureTeamWindow(session,teamName,workingDir){for(let attempt=0;attempt<3;attempt++)try{return await ensureTeamWindowOnce(session,teamName,workingDir)}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("server exited")||message.includes("error connecting")){if(attempt<2){let delay=250*2**attempt;console.warn(`[genie-tmux] tmux server unreachable (attempt ${attempt+1}/3), retrying in ${delay}ms...`),await new Promise((resolve3)=>setTimeout(resolve3,delay));continue}}throw error}throw Error("Failed to ensure team window after 3 attempts")}async function ensureTeamWindowOnce(session,teamName,workingDir){await ensureSessionExists(session);let existing=await findWindowByName(session,teamName);if(existing){try{await executeTmux2(`set-window-option -t '${existing.id}' automatic-rename off`)}catch{}await rehydratePaneColorHook(existing.id);let panes2=await listPanes(existing.id),paneId2=panes2.length>0?panes2[0].id:`${session}:${teamName}.0`;return{windowId:existing.id,windowName:teamName,paneId:paneId2,created:!1}}let windowsBefore=await listWindows(session),masterBefore=windowsBefore.length>0?windowsBefore.reduce((a,b2)=>a.index<=b2.index?a:b2):null,newWindow=await createWindow(session,teamName,workingDir);if(!newWindow)throw Error(`Failed to create team window "${teamName}" in session "${session}"`);if(masterBefore)await ensureMasterWindow(session,masterBefore.name);await rehydratePaneColorHook(newWindow.id);let panes=await listPanes(newWindow.id),paneId=panes.length>0?panes[0].id:`${session}:${teamName}.0`;return{windowId:newWindow.id,windowName:teamName,paneId,created:!0}}function ensurePaneColorScript(){let{existsSync:existsSync11,writeFileSync:writeFileSync6,mkdirSync:mkdirSync6,chmodSync:chmodSync2}=__require("fs"),{dirname:dirname3}=__require("path");if(existsSync11(PANE_COLOR_SCRIPT))return;mkdirSync6(dirname3(PANE_COLOR_SCRIPT),{recursive:!0});let bin=tmuxBin();writeFileSync6(PANE_COLOR_SCRIPT,`#!/bin/bash
|
|
362
|
+
# Genie tmux pane color router \u2014 reads @genie_color pane option
|
|
363
|
+
PANE_ID="$1"
|
|
364
|
+
COLOR=$(${bin} display-message -p -t "$PANE_ID" '#{@genie_color}' 2>/dev/null)
|
|
365
|
+
[ -z "$COLOR" ] && COLOR="default"
|
|
366
|
+
${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
367
|
+
`),chmodSync2(PANE_COLOR_SCRIPT,493)}async function applyPaneColor(paneId,color,windowId){let hex=TMUX_COLOR_MAP[color]??TMUX_COLOR_MAP.blue;try{ensurePaneColorScript(),await executeTmux2(`set-option -p -t '${paneId}' @genie_color '${hex}'`);try{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));await(await getConnection2())`UPDATE executors SET pane_color = ${hex} WHERE tmux_pane_id = ${paneId}`}catch{}if(windowId)await executeTmux2(`set-hook -w -t '${windowId}' pane-focus-in "run-shell '${PANE_COLOR_SCRIPT} #{pane_id}'"`)}catch{}}async function rehydratePaneColorHook(windowId){try{ensurePaneColorScript(),await executeTmux2(`set-hook -w -t '${windowId}' pane-focus-in "run-shell '${PANE_COLOR_SCRIPT} #{pane_id}'"`)}catch{}}async function resolveRepoSession(repoPath){let derived=basename2(repoPath);try{let sessions=await listSessions(),exact=sessions.find((s)=>s.name===derived);if(exact)return exact.name;if(process.env.TMUX)try{let name=(await executeTmux2("display-message -p '#{session_name}'")).trim();if(name)return name}catch{}let partial=sessions.find((s)=>s.name.includes(derived));if(partial)return partial.name}catch{}return derived}async function isPaneAlive(paneId){if(!paneId||paneId==="inline")return!1;if(!/^%\d+$/.test(paneId))return!1;try{return(await executeTmux2(`display-message -t '${paneId}' -p '#{pane_dead}'`)).trim()==="0"}catch(error){let message=error instanceof Error?error.message:String(error);if(message.includes("no server running")||message.includes("server exited")||message.includes("error connecting"))throw new TmuxUnreachableError(message);return!1}}async function isPaneProcessRunning(paneId,processName,execSyncFn){if(!paneId||paneId==="inline")return!1;if(!/^%\d+$/.test(paneId))return!1;try{let panePid=(await executeTmux2(`display-message -t '${paneId}' -p '#{pane_pid}'`)).trim();if(!panePid||!/^\d+$/.test(panePid))return!1;return(execSyncFn??(await import("child_process")).execSync)(`pgrep -la -P ${panePid} 2>/dev/null; for cpid in $(pgrep -P ${panePid} 2>/dev/null); do pgrep -la -P "$cpid" 2>/dev/null; done; true`,{encoding:"utf-8",timeout:5000}).toLowerCase().includes(processName.toLowerCase())}catch{return!1}}async function killWindow(sessionName,windowName){try{return await executeTmux2(`kill-window -t ${shellQuote(`${sessionName}:${windowName}`)}`),!0}catch{return!1}}var TMUX_COLOR_MAP,PANE_COLOR_SCRIPT,TmuxUnreachableError;var init_tmux=__esm(()=>{init_ensure_tmux();init_team_lead_command();TMUX_COLOR_MAP={red:"#b83030",blue:"#2a6cb8",green:"#20a050",yellow:"#b8a020",purple:"#7830b8",orange:"#b86820",pink:"#b83078",cyan:"#20a0a0"},PANE_COLOR_SCRIPT=`${__require("os").homedir()}/.genie/tmux-pane-color.sh`;TmuxUnreachableError=class TmuxUnreachableError extends Error{constructor(message){super(message);this.name="TmuxUnreachableError"}}});function ts(v){if(!v)return new Date().toISOString();return v instanceof Date?v.toISOString():v}function rowToExecutor(r){return{id:r.id,agentId:r.agent_id,provider:r.provider,transport:r.transport,pid:r.pid,tmuxSession:r.tmux_session,tmuxPaneId:r.tmux_pane_id,tmuxWindow:r.tmux_window,tmuxWindowId:r.tmux_window_id,claudeSessionId:r.claude_session_id,state:r.state,metadata:typeof r.metadata==="string"?JSON.parse(r.metadata):r.metadata??{},worktree:r.worktree,repoPath:r.repo_path,paneColor:r.pane_color,startedAt:ts(r.started_at),endedAt:r.ended_at?ts(r.ended_at):null,createdAt:ts(r.created_at),updatedAt:ts(r.updated_at)}}function rowToAssignment(r){return{id:r.id,executorId:r.executor_id,taskId:r.task_id,wishSlug:r.wish_slug,groupNumber:r.group_number,startedAt:ts(r.started_at),endedAt:r.ended_at?ts(r.ended_at):null,outcome:r.outcome,createdAt:ts(r.created_at)}}var exports_executor_registry={};__export(exports_executor_registry,{updateExecutorState:()=>updateExecutorState,updateClaudeSessionId:()=>updateClaudeSessionId,terminateExecutor:()=>terminateExecutor,terminateActiveExecutor:()=>terminateActiveExecutor,relinkExecutorToAgent:()=>relinkExecutorToAgent,listExecutors:()=>listExecutors,getExecutor:()=>getExecutor,getCurrentExecutor:()=>getCurrentExecutor,findLatestByMetadata:()=>findLatestByMetadata,findExecutorBySession:()=>findExecutorBySession,findExecutorByPane:()=>findExecutorByPane,createExecutor:()=>createExecutor,createAndLinkExecutor:()=>createAndLinkExecutor});import{randomUUID}from"crypto";async function createExecutor(agentId,provider,transport,opts={}){let sql=await getConnection(),id=opts.id??randomUUID(),now=new Date().toISOString(),rows=await sql`
|
|
368
368
|
INSERT INTO executors (
|
|
369
369
|
id, agent_id, provider, transport, pid,
|
|
370
370
|
tmux_session, tmux_pane_id, tmux_window, tmux_window_id,
|
|
@@ -620,7 +620,7 @@ The user's message:
|
|
|
620
620
|
|
|
621
621
|
---
|
|
622
622
|
|
|
623
|
-
${initialMessage}`:turnContext;return{provider:entry.provider??"claude",team:agentName,role:agentName,sessionId:randomUUID4(),model:entry.model,promptMode:entry.promptMode,systemPromptFile:join14(entry.dir,"AGENTS.md"),initialPrompt:fullInitialPrompt,nativeTeam:{enabled:!0,agentName,color:entry.color??void 0}}}class ClaudeCodeOmniExecutor{sessions=new Map;safePgCall=null;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(_fn){}async injectNudge(session,text){let paneId=session.tmux?.paneId;if(!paneId)return;let nudgeText=`[system] ${text}`;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(nudgeText)} Enter`)}async spawn(agentName,chatId,env,initialMessage){let resolved=await resolve2(agentName);if(!resolved)throw Error(`Agent "${agentName}" not found in genie directory`);let entry=resolved.entry,tmuxSession=agentName,chatName=await lookupChatName(chatId,env.OMNI_INSTANCE??""),windowName=sanitizeWindowName(chatId,chatName??void 0),{paneId,created}=await ensureTeamWindow(tmuxSession,windowName,entry.dir);if(created){let omniEnv={...env,GENIE_OMNI_CHAT_ID:chatId,GENIE_OMNI_AGENT:agentName},params=buildOmniSpawnParams(agentName,chatId,entry,omniEnv,initialMessage),launch=buildLaunchCommand(params),allEnv={...omniEnv,...launch.env},envPrefix=Object.entries(allEnv).map(([k,v])=>`${k}=${shellQuote(v)}`).join(" "),cmd=envPrefix?`${envPrefix} ${launch.command}`:launch.command;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(cmd)} Enter`)}let sessionKey=`${agentName}:${chatId}`,registration=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"",tmuxSession,windowName,paneId,entry.dir);if(this.sessions.set(sessionKey,{executorId:registration?.executorId??null,agentId:registration?.agentId??null,repoPath:entry.dir}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionKey,agentName,chatId,executorType:"tmux",createdAt:now,lastActivityAt:now,tmux:{session:tmuxSession,window:windowName,paneId}}}async registerInWorldA(agentName,chatId,instanceId,tmuxSession,tmuxWindow,tmuxPaneId,repoPath){if(!this.safePgCall)return null;let agent=await this.safePgCall("tmux-find-or-create-agent",()=>findOrCreateAgent(agentName
|
|
623
|
+
${initialMessage}`:turnContext;return{provider:entry.provider??"claude",team:agentName,role:agentName,sessionId:randomUUID4(),model:entry.model,promptMode:entry.promptMode,systemPromptFile:join14(entry.dir,"AGENTS.md"),initialPrompt:fullInitialPrompt,skipHooks:!0,nativeTeam:{enabled:!0,agentName,color:entry.color??void 0}}}class ClaudeCodeOmniExecutor{sessions=new Map;safePgCall=null;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(_fn){}async injectNudge(session,text){let paneId=session.tmux?.paneId;if(!paneId)return;let nudgeText=`[system] ${text}`;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(nudgeText)} Enter`)}async spawn(agentName,chatId,env,initialMessage){let resolved=await resolve2(agentName);if(!resolved)throw Error(`Agent "${agentName}" not found in genie directory`);let entry=resolved.entry,tmuxSession=agentName,chatName=await lookupChatName(chatId,env.OMNI_INSTANCE??""),windowName=sanitizeWindowName(chatId,chatName??void 0),{paneId,created}=await ensureTeamWindow(tmuxSession,windowName,entry.dir);if(created){let omniEnv={...env,GENIE_OMNI_CHAT_ID:chatId,GENIE_OMNI_AGENT:agentName},params=buildOmniSpawnParams(agentName,chatId,entry,omniEnv,initialMessage),launch=buildLaunchCommand(params),allEnv={...omniEnv,...launch.env},envPrefix=Object.entries(allEnv).map(([k,v])=>`${k}=${shellQuote(v)}`).join(" "),cmd=envPrefix?`${envPrefix} ${launch.command}`:launch.command;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(cmd)} Enter`)}let sessionKey=`${agentName}:${chatId}`,registration=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"",tmuxSession,windowName,paneId,entry.dir);if(this.sessions.set(sessionKey,{executorId:registration?.executorId??null,agentId:registration?.agentId??null,repoPath:entry.dir}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionKey,agentName,chatId,executorType:"tmux",createdAt:now,lastActivityAt:now,tmux:{session:tmuxSession,window:windowName,paneId}}}async registerInWorldA(agentName,chatId,instanceId,tmuxSession,tmuxWindow,tmuxPaneId,repoPath){if(!this.safePgCall)return null;let agent=await this.safePgCall("tmux-find-or-create-agent",()=>findOrCreateAgent(`${agentName}:${chatId}`,"omni","omni"),null,{chatId});if(!agent)return null;await this.safePgCall("tmux-update-agent-pane",async()=>{await(await Promise.resolve().then(() => (init_db(),exports_db)).then((m)=>m.getConnection()))`
|
|
624
624
|
UPDATE agents
|
|
625
625
|
SET pane_id = ${tmuxPaneId},
|
|
626
626
|
session = ${tmuxSession},
|
|
@@ -713,10 +713,10 @@ ${queryContent}`;let{messages:queryMessages}=state.provider.runQuery({agentId:se
|
|
|
713
713
|
UPDATE omni_requests
|
|
714
714
|
SET status = 'pending', started_at = NULL, next_retry_at = ${nextRetry}
|
|
715
715
|
WHERE id = ${id}
|
|
716
|
-
`}}class TurnTracker{turns=new Map;open(sessionKey,turnId,messageId){this.turns.set(sessionKey,{turnId,sessionKey,messageId,startedAt:Date.now(),closed:!1})}close(sessionKey,action){let turn=this.turns.get(sessionKey);if(turn&&!turn.closed)turn.closed=!0,turn.closedAction=action}isOpen(sessionKey){let turn=this.turns.get(sessionKey);return turn!==void 0&&!turn.closed}getTurnId(sessionKey){return this.turns.get(sessionKey)?.turnId}getByTurnId(turnId){for(let turn of this.turns.values())if(turn.turnId===turnId)return turn;return}delete(sessionKey){this.turns.delete(sessionKey)}}var exports_omni_bridge={};__export(exports_omni_bridge,{getBridge:()=>getBridge,OmniBridge:()=>OmniBridge});function getBridge(){return bridgeInstance}function withTimeout(p,ms,label){return new Promise((resolve4,reject)=>{let timer2=setTimeout(()=>reject(Error(`${label} timed out after ${ms}ms`)),ms);timer2.unref?.(),p.then((v)=>{clearTimeout(timer2),resolve4(v)},(err)=>{clearTimeout(timer2),reject(err)})})}function isPgConnectionError(err){if(!err||typeof err!=="object")return!1;let e=err,code=e.code??"";if(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EPIPE","EHOSTUNREACH"].includes(code))return!0;let msg=e.message??String(err);return/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EPIPE|connection terminated|connection closed|server closed the connection|the database system is shutting down/i.test(msg)}class OmniBridge{nc=null;sub=null;executor;turnTracker=new TurnTracker;sessions=new Map;messageQueue=[];idleCheckTimer=null;sc=import_nats.StringCodec();sql=null;pgAvailable=!1;pgProvider;natsConnectFn;queueConfig;queue=null;sessionStore=null;natsUrl;idleTimeoutMs;maxConcurrent;executorType;constructor(config={}){if(this.natsUrl=config.natsUrl??process.env.GENIE_NATS_URL??DEFAULT_NATS_URL,this.idleTimeoutMs=config.idleTimeoutMs??(process.env.GENIE_IDLE_TIMEOUT_MS?Number(process.env.GENIE_IDLE_TIMEOUT_MS):DEFAULT_IDLE_TIMEOUT_MS),this.maxConcurrent=config.maxConcurrent??(process.env.GENIE_MAX_CONCURRENT?Number(process.env.GENIE_MAX_CONCURRENT):DEFAULT_MAX_CONCURRENT),this.pgProvider=config.pgProvider??(async()=>{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return await getConnection2()}),this.natsConnectFn=config.natsConnectFn??import_nats.connect,this.queueConfig=config.queue??{},this.executorType=resolveExecutorType(config.executorType),this.executorType==="sdk")this.executor=new ClaudeSdkOmniExecutor;else this.executor=new ClaudeCodeOmniExecutor}async start(){if(this.nc){console.log("[omni-bridge] Already running");return}if(console.log(`[omni-bridge] Connecting to NATS at ${this.natsUrl}...`),this.nc=await this.natsConnectFn({servers:this.natsUrl,name:"genie-omni-bridge",reconnect:!0,maxReconnectAttempts:-1,reconnectTimeWait:2000}),console.log("[omni-bridge] Connected to NATS"),await this.probePg(),this.pgAvailable&&this.sql)this.sessionStore=new BridgeSessionStore(this.sql),await this.recoverSessions();if(this.executorType==="sdk"&&this.pgAvailable&&this.sql)this.queue=new OmniQueue(this.sql,(_req,msg)=>this.routeMessage(msg),this.queueConfig),await this.queue.recoverStale(),this.queue.start();this.executor.setSafePgCall(this.safePgCall.bind(this));let sc=this.sc,nc=this.nc;this.executor.setNatsPublish((topic,payload)=>{nc.publish(topic,sc.encode(payload))}),this.sub=this.nc.subscribe("omni.message.>"),this.processSubscription();let turnSubs=["omni.turn.open.>","omni.turn.done.>","omni.turn.nudge.>","omni.turn.timeout.>"];for(let topic of turnSubs){let sub=this.nc.subscribe(topic);this.processTurnEvents(sub)}let sessionResetSub=this.nc.subscribe("omni.session.reset.>");this.processSessionResetEvents(sessionResetSub),this.idleCheckTimer=setInterval(()=>this.checkIdleSessions(),IDLE_CHECK_INTERVAL_MS),bridgeInstance=this,console.log(`[omni-bridge] Listening on omni.message.> (max_concurrent=${this.maxConcurrent}, idle_timeout=${this.idleTimeoutMs}ms)`)}async stop(){if(!this.nc){console.log("[omni-bridge] Not running");return}if(console.log("[omni-bridge] Shutting down..."),this.queue)this.queue.stop(),this.queue=null;if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null;for(let[key,entry]of this.sessions){if(entry.idleTimer)clearTimeout(entry.idleTimer);if(!entry.spawning&&entry.session)if(entry.session.executorType==="tmux")console.log(`[omni-bridge] Detaching from tmux session ${key} (pane stays alive)`);else{try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down session ${key}:`,err)}let closeId=entry.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close_sdk",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0)}}if(this.sessions.clear(),this.sub)this.sub.unsubscribe(),this.sub=null;try{await this.nc.drain()}catch{}this.nc=null,this.sql=null,this.pgAvailable=!1,this.sessionStore=null,bridgeInstance=null,console.log("[omni-bridge] Stopped")}async status(){let now=Date.now(),activeFromPg=null,executorIds=[];if(this.pgAvailable&&this.sql){let rows=await this.safePgCall("status_active_count",async(sql)=>sql`
|
|
716
|
+
`}}class TurnTracker{turns=new Map;open(sessionKey,turnId,messageId){this.turns.set(sessionKey,{turnId,sessionKey,messageId,startedAt:Date.now(),closed:!1})}close(sessionKey,action){let turn=this.turns.get(sessionKey);if(turn&&!turn.closed)turn.closed=!0,turn.closedAction=action}isOpen(sessionKey){let turn=this.turns.get(sessionKey);return turn!==void 0&&!turn.closed}getTurnId(sessionKey){return this.turns.get(sessionKey)?.turnId}getByTurnId(turnId){for(let turn of this.turns.values())if(turn.turnId===turnId)return turn;return}delete(sessionKey){this.turns.delete(sessionKey)}}var exports_omni_bridge={};__export(exports_omni_bridge,{getBridge:()=>getBridge,OmniBridge:()=>OmniBridge});function getBridge(){return bridgeInstance}function withTimeout(p,ms,label){return new Promise((resolve4,reject)=>{let timer2=setTimeout(()=>reject(Error(`${label} timed out after ${ms}ms`)),ms);timer2.unref?.(),p.then((v)=>{clearTimeout(timer2),resolve4(v)},(err)=>{clearTimeout(timer2),reject(err)})})}function isPgConnectionError(err){if(!err||typeof err!=="object")return!1;let e=err,code=e.code??"";if(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EPIPE","EHOSTUNREACH"].includes(code))return!0;let msg=e.message??String(err);return/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EPIPE|connection terminated|connection closed|server closed the connection|the database system is shutting down/i.test(msg)}class OmniBridge{nc=null;sub=null;executor;turnTracker=new TurnTracker;sessions=new Map;messageQueue=[];recentMessageIds=new Map;idleCheckTimer=null;sc=import_nats.StringCodec();sql=null;pgAvailable=!1;pgProvider;natsConnectFn;queueConfig;queue=null;sessionStore=null;natsUrl;idleTimeoutMs;maxConcurrent;executorType;constructor(config={}){if(this.natsUrl=config.natsUrl??process.env.GENIE_NATS_URL??DEFAULT_NATS_URL,this.idleTimeoutMs=config.idleTimeoutMs??(process.env.GENIE_IDLE_TIMEOUT_MS?Number(process.env.GENIE_IDLE_TIMEOUT_MS):DEFAULT_IDLE_TIMEOUT_MS),this.maxConcurrent=config.maxConcurrent??(process.env.GENIE_MAX_CONCURRENT?Number(process.env.GENIE_MAX_CONCURRENT):DEFAULT_MAX_CONCURRENT),this.pgProvider=config.pgProvider??(async()=>{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return await getConnection2()}),this.natsConnectFn=config.natsConnectFn??import_nats.connect,this.queueConfig=config.queue??{},this.executorType=resolveExecutorType(config.executorType),this.executorType==="sdk")this.executor=new ClaudeSdkOmniExecutor;else this.executor=new ClaudeCodeOmniExecutor}async start(){if(this.nc){console.log("[omni-bridge] Already running");return}if(console.log(`[omni-bridge] Connecting to NATS at ${this.natsUrl}...`),this.nc=await this.natsConnectFn({servers:this.natsUrl,name:"genie-omni-bridge",reconnect:!0,maxReconnectAttempts:-1,reconnectTimeWait:2000}),console.log("[omni-bridge] Connected to NATS"),await this.probePg(),this.pgAvailable&&this.sql)this.sessionStore=new BridgeSessionStore(this.sql),await this.recoverSessions();if(this.executorType==="sdk"&&this.pgAvailable&&this.sql)this.queue=new OmniQueue(this.sql,(_req,msg)=>this.routeMessage(msg),this.queueConfig),await this.queue.recoverStale(),this.queue.start();this.executor.setSafePgCall(this.safePgCall.bind(this));let sc=this.sc,nc=this.nc;this.executor.setNatsPublish((topic,payload)=>{nc.publish(topic,sc.encode(payload))}),this.sub=this.nc.subscribe("omni.message.>",{queue:"genie-bridge"}),this.processSubscription();let turnSubs=["omni.turn.open.>","omni.turn.done.>","omni.turn.nudge.>","omni.turn.timeout.>"];for(let topic of turnSubs){let sub=this.nc.subscribe(topic,{queue:"genie-bridge"});this.processTurnEvents(sub)}let sessionResetSub=this.nc.subscribe("omni.session.reset.>",{queue:"genie-bridge"});this.processSessionResetEvents(sessionResetSub),this.idleCheckTimer=setInterval(()=>this.checkIdleSessions(),IDLE_CHECK_INTERVAL_MS),bridgeInstance=this,console.log(`[omni-bridge] Listening on omni.message.> (max_concurrent=${this.maxConcurrent}, idle_timeout=${this.idleTimeoutMs}ms)`)}async stop(){if(!this.nc){console.log("[omni-bridge] Not running");return}if(console.log("[omni-bridge] Shutting down..."),this.queue)this.queue.stop(),this.queue=null;if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null;for(let[key,entry]of this.sessions){if(entry.idleTimer)clearTimeout(entry.idleTimer);if(!entry.spawning&&entry.session)if(entry.session.executorType==="tmux")console.log(`[omni-bridge] Detaching from tmux session ${key} (pane stays alive)`);else{try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down session ${key}:`,err)}let closeId=entry.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close_sdk",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0)}}if(this.sessions.clear(),this.sub)this.sub.unsubscribe(),this.sub=null;try{await this.nc.drain()}catch{}this.nc=null,this.sql=null,this.pgAvailable=!1,this.sessionStore=null,bridgeInstance=null,console.log("[omni-bridge] Stopped")}async status(){let now=Date.now(),activeFromPg=null,executorIds=[];if(this.pgAvailable&&this.sql){let rows=await this.safePgCall("status_active_count",async(sql)=>sql`
|
|
717
717
|
SELECT id FROM executors
|
|
718
718
|
WHERE ended_at IS NULL AND metadata->>'source' = 'omni'
|
|
719
|
-
`,null);if(rows)activeFromPg=rows.length,executorIds=rows.map((r)=>r.id)}let pgQueue=null;if(this.queue)pgQueue=await this.safePgCall("status_queue_stats",(_sql)=>this.queue?.stats()??Promise.resolve(null),null);return{connected:this.nc!==null,natsUrl:this.natsUrl,pgAvailable:this.pgAvailable,activeSessions:activeFromPg??this.sessions.size,maxConcurrent:this.maxConcurrent,idleTimeoutMs:this.idleTimeoutMs,queueDepth:pgQueue?pgQueue.pending+pgQueue.processing:this.messageQueue.length,executorType:this.executorType,executorIds,pgQueue,sessions:Array.from(this.sessions.entries()).map(([key,entry])=>({id:key,agentName:entry.session.agentName,chatId:entry.session.chatId,instanceId:entry.instanceId,executorType:entry.session.executorType,spawning:entry.spawning,idleMs:now-entry.session.lastActivityAt,bufferSize:entry.buffer.length}))}}async probePg(){try{let sql=await withTimeout(this.pgProvider(),PG_STARTUP_PROBE_TIMEOUT_MS,"PG provider startup");await withTimeout(Promise.resolve(sql`SELECT 1`),PG_STARTUP_PROBE_TIMEOUT_MS,"PG SELECT 1 probe"),this.sql=sql,this.pgAvailable=!0,console.log("[omni-bridge] PG reachable \u2014 session recovery enabled")}catch(err){this.sql=null,this.pgAvailable=!1;let msg=err instanceof Error?err.message:String(err);if(isPgConnectionError(err)){console.warn(`[omni-bridge] PG unavailable \u2014 session recovery disabled (${msg})`);return}throw Error(`[omni-bridge] PG schema mismatch or setup error: ${msg}. ${"Run `bun run migrate` (or the equivalent migration command) and retry."}`)}}async recoverSessions(){if(!this.sessionStore)return;let activeSessions=await this.safePgCall("recover_list_active",(sql)=>new BridgeSessionStore(sql).list("active"),[]);if(activeSessions.length===0)return;console.log(`[omni-bridge] Found ${activeSessions.length} active session(s) from previous run, recovering...`);let orphanIds=[];for(let row of activeSessions){let key=`${row.agent_name}:${row.chat_id}`;if(!row.tmux_pane_id){orphanIds.push(row.id);continue}if(this.sessions.has(key)){orphanIds.push(row.id);continue}let alive=!1;try{alive=await isPaneAlive(row.tmux_pane_id)}catch{}if(!alive){orphanIds.push(row.id);continue}let entry={session:{id:row.executor_id??row.id,agentName:row.agent_name,chatId:row.chat_id,executorType:"tmux",createdAt:new Date(row.started_at).getTime(),lastActivityAt:new Date(row.last_activity_at).getTime(),tmux:{session:"",window:"",paneId:row.tmux_pane_id}},instanceId:row.instance_id,spawning:!1,buffer:[],idleTimer:null,pgBridgeSessionId:row.id};this.sessions.set(key,entry),this.resetIdleTimer(key),console.log(`[omni-bridge] Recovered session ${key} (pane=${row.tmux_pane_id})`)}if(orphanIds.length>0)await this.safePgCall("recover_mark_orphaned",(sql)=>new BridgeSessionStore(sql).markOrphaned(orphanIds),void 0),console.log(`[omni-bridge] Marked ${orphanIds.length} stale session(s) as orphaned`);if(this.sessions.size>0)console.log(`[omni-bridge] Recovered ${this.sessions.size} live session(s)`)}async safePgCall(op,fn,fallback,ctx){if(!this.pgAvailable||!this.sql)return fallback;let sql=this.sql;try{return await withTimeout(fn(sql),PG_RUNTIME_QUERY_TIMEOUT_MS,`safePgCall(${op})`)}catch(err){let msg=err instanceof Error?err.message:String(err),execPart=ctx?.executorId?` executor_id=${ctx.executorId}`:"",chatPart=ctx?.chatId?` chat_id=${ctx.chatId}`:"";if(console.warn(`[omni-bridge] safePgCall(${op}) failed${execPart}${chatPart}: ${msg}`),isPgConnectionError(err))this.pgAvailable=!1,this.sql=null,console.warn("[omni-bridge] PG connection lost \u2014 switching to degraded mode");return fallback}}async processSubscription(){if(!this.sub)return;for await(let msg of this.sub)try{let data=this.sc.decode(msg.data),parsed=JSON.parse(data),parts=msg.subject.split(".");if(parts.length>=4)parsed.instanceId=parsed.instanceId||parts[2],parsed.chatId=parsed.chatId||parts[3];if(console.log(`[omni-bridge] NATS message received: ${msg.subject} agent=${parsed.agent} chat=${parsed.chatId}`),!parsed.chatId||!parsed.agent){console.warn("[omni-bridge] Dropping message: missing chatId or agent",msg.subject);continue}if(this.queue){let env=parsed.env??{};await this.queue.enqueue(parsed,env)}else{let key=`${parsed.agent}:${parsed.chatId}`,hasSession=this.sessions.has(key);console.log(`[omni-bridge] Routing message for ${key} (hasSession=${hasSession}, queue=${!!this.queue})`),await this.routeMessage(parsed),console.log(`[omni-bridge] routeMessage done for ${key}`)}}catch(err){console.error("[omni-bridge] Error processing message:",err)}}async processTurnEvents(sub){for await(let msg of sub)try{let payload=JSON.parse(this.sc.decode(msg.data)),parts=msg.subject.split("."),eventType=parts[2],instanceId=parts[3],chatId=parts.slice(4).join(".");console.log(`[omni-bridge] Turn event: ${eventType} instance=${instanceId} chat=${chatId}`);let sessionKey=this.findSessionKey(instanceId,chatId);if(!sessionKey&&payload.turnId){if(sessionKey=this.findSessionKeyByTurnId(payload.turnId),sessionKey)console.log(`[omni-bridge] Matched session via turnId fallback: ${sessionKey}`)}if(sessionKey)await this.routeTurnEvent(eventType,sessionKey,payload);else console.log(`[omni-bridge] No session found for turn.${eventType} (instance=${instanceId}, chat=${chatId})`)}catch(err){console.warn("[omni-bridge] Error processing turn event:",err)}}async routeTurnEvent(eventType,sessionKey,payload){switch(eventType){case"open":this.turnTracker.open(sessionKey,payload.turnId,payload.messageId);break;case"done":this.turnTracker.close(sessionKey,payload.action),await this.handleTurnDone(sessionKey);break;case"nudge":await this.handleTurnNudge(sessionKey,payload.message);break;case"timeout":await this.handleTurnTimeout(sessionKey);break}}findSessionKeyByTurnId(turnId){for(let[key]of this.sessions)if(this.turnTracker.getTurnId(key)===turnId)return key;return}chatIdMap=new Map;findSessionKey(instanceId,chatId){let resolvedChatId=this.chatIdMap.get(chatId);for(let[key,entry]of this.sessions){if(entry.instanceId!==instanceId)continue;if(entry.session?.chatId===chatId)return key;if(resolvedChatId&&entry.session?.chatId===resolvedChatId)return key;if(entry.spawning&&key.endsWith(`:${chatId}`))return key;if(resolvedChatId&&entry.spawning&&key.endsWith(`:${resolvedChatId}`))return key}return}async handleTurnNudge(sessionKey,nudgeText){let entry=this.sessions.get(sessionKey);if(!entry?.session)return;try{await this.executor.injectNudge(entry.session,nudgeText)}catch(err){console.warn(`[omni-bridge] Failed to inject nudge for ${sessionKey}:`,err)}}async processSessionResetEvents(sub){for await(let msg of sub)try{let parts=msg.subject.split(".");if(parts.length<5){console.warn(`[omni-bridge] Malformed session-reset subject: ${msg.subject}`);continue}let instanceId=parts[3],chatId=parts.slice(4).join("."),action;try{action=JSON.parse(this.sc.decode(msg.data)).action}catch{}await this.handleSessionReset(instanceId,chatId,action)}catch(err){console.warn("[omni-bridge] Error processing session reset event:",err)}}async handleSessionReset(instanceId,chatId,action){let sessionKey=this.findSessionKey(instanceId,chatId);if(!sessionKey){console.log(`[omni-bridge] Session reset for cold chat ${instanceId}/${chatId} \u2014 no-op`);return}let entry=this.sessions.get(sessionKey);if(!entry)return;let actionTag=action?` (action=${action})`:"";if(entry.spawning){console.log(`[omni-bridge] Session reset for spawning ${sessionKey}${actionTag}, marking cancelled`),entry.cancelled=!0,entry.buffer=[],this.turnTracker.close(sessionKey,"reset"),await this.removeSession(sessionKey),await this.drainQueue();return}if(!entry.session)return;console.log(`[omni-bridge] Session reset for ${sessionKey}${actionTag}, evicting`),this.turnTracker.close(sessionKey,"reset");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down reset session ${sessionKey}:`,err)}await this.removeSession(sessionKey),await this.drainQueue()}async handleTurnDone(sessionKey){if(!this.sessions.get(sessionKey)?.session)return;console.log(`[omni-bridge] Turn done for ${sessionKey}, session stays alive for next message`),this.resetIdleTimer(sessionKey)}async handleTurnTimeout(sessionKey){let entry=this.sessions.get(sessionKey);if(!entry?.session)return;console.warn(`[omni-bridge] Turn timed out for ${sessionKey}, evicting session`),this.turnTracker.close(sessionKey,"timeout");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down timed-out session ${sessionKey}:`,err)}this.sessions.delete(sessionKey)}async routeMessage(message){let key=`${message.agent}:${message.chatId}`,entry=this.sessions.get(key);if(entry){if(entry.spawning){if(entry.buffer.length<MAX_BUFFER_PER_CHAT)entry.buffer.push(message);else console.warn(`[omni-bridge] Buffer full (${MAX_BUFFER_PER_CHAT}) for ${key}, dropping message from ${message.sender}`),await this.publishBufferFullReply(message);return}if(await this.executor.isAlive(entry.session)){await this.executor.deliver(entry.session,message),this.resetIdleTimer(key);let bsId=entry.pgBridgeSessionId;if(bsId&&this.sessionStore)this.safePgCall("session_activity",(sql)=>new BridgeSessionStore(sql).recordActivity(bsId),void 0,{chatId:message.chatId});return}await this.removeSession(key)}await this.spawnSession(message)}async spawnSession(message){let key=`${message.agent}:${message.chatId}`,existing=this.sessions.get(key);if(existing){if(existing.buffer.length<MAX_BUFFER_PER_CHAT)existing.buffer.push(message),console.log(`[omni-bridge] Buffered message for existing session ${key} (buffer=${existing.buffer.length})`);return}if(this.sessions.size>=this.maxConcurrent){this.messageQueue.push(message),await this.publishAutoReply(message),console.log(`[omni-bridge] Max concurrent (${this.maxConcurrent}) reached, queued message for ${key}`);return}let placeholder={session:null,instanceId:message.instanceId,spawning:!0,buffer:[message],idleTimer:null};this.sessions.set(key,placeholder);try{let raw=message,payloadEnv=raw.env,spawnEnv={OMNI_API_KEY:payloadEnv?.OMNI_API_KEY??process.env.OMNI_API_KEY??"",OMNI_INSTANCE:payloadEnv?.OMNI_INSTANCE??message.instanceId,OMNI_CHAT:payloadEnv?.OMNI_CHAT??message.chatId,OMNI_MESSAGE:payloadEnv?.OMNI_MESSAGE??raw.messageId??"",OMNI_TURN_ID:payloadEnv?.OMNI_TURN_ID??"",OMNI_SENDER_NAME:payloadEnv?.OMNI_SENDER_NAME??message.sender??""};console.log(`[omni-bridge] Spawning session for ${key}...`);let session=await this.executor.spawn(message.agent,message.chatId,spawnEnv,message.content);if(placeholder.cancelled){console.log(`[omni-bridge] Spawn for ${key} completed but was cancelled by reset, shutting down`);try{await this.executor.shutdown(session)}catch(err){console.warn(`[omni-bridge] Error shutting down cancelled spawn for ${key}:`,err)}return}if(placeholder.session=session,placeholder.spawning=!1,this.sessionStore){let pgId=await this.safePgCall("session_create",(sql)=>new BridgeSessionStore(sql).create({instanceId:message.instanceId,chatId:message.chatId,agentName:message.agent,executorId:session.sdk?.executorId,tmuxPaneId:session.tmux?.paneId,claudeSessionId:session.sdk?.claudeSessionId}),void 0,{chatId:message.chatId});if(pgId)placeholder.pgBridgeSessionId=pgId}for(let buffered of placeholder.buffer)await this.executor.deliver(session,buffered);placeholder.buffer=[],this.resetIdleTimer(key);let sessionTag=session.executorType==="tmux"?`(tmux pane=${session.tmux?.paneId})`:"(executor=sdk)";console.log(`[omni-bridge] Session active: ${key} ${sessionTag}`)}catch(err){console.error(`[omni-bridge] Failed to spawn session for ${key}:`,err);let lostMessages=placeholder.buffer;if(lostMessages.length>0)console.warn(`[omni-bridge] Re-queuing ${lostMessages.length} buffered message(s) from failed spawn for ${key}`),this.messageQueue.push(...lostMessages);this.sessions.delete(key)}}resetIdleTimer(key){let entry=this.sessions.get(key);if(!entry)return;if(entry.idleTimer)clearTimeout(entry.idleTimer);entry.idleTimer=setTimeout(async()=>{console.log(`[omni-bridge] Idle timeout for ${key}, shutting down...`);try{await this.executor.shutdown(entry.session)}catch{}await this.removeSession(key),await this.drainQueue()},this.idleTimeoutMs)}async checkIdleSessions(){let now=Date.now();for(let[key,entry]of this.sessions){if(entry.spawning)continue;if(!await this.executor.isAlive(entry.session)){console.log(`[omni-bridge] Dead session detected: ${key}`),await this.removeSession(key);continue}let idleMs=now-entry.session.lastActivityAt;if(idleMs>this.idleTimeoutMs){console.log(`[omni-bridge] Forcing idle shutdown: ${key} (idle ${Math.round(idleMs/1000)}s)`);try{await this.executor.shutdown(entry.session)}catch{}await this.removeSession(key)}}}async removeSession(key){let entry=this.sessions.get(key);if(entry?.idleTimer)clearTimeout(entry.idleTimer);let closeId=entry?.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0);this.sessions.delete(key)}async drainQueue(){while(this.messageQueue.length>0){if(this.sessions.size>=this.maxConcurrent)break;let message=this.messageQueue.shift();if(message)await this.spawnSession(message)}}async publishBufferFullReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Fila de mensagens cheia, por favor aguarde e tente novamente.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}async publishAutoReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Aguarde um momento, estou atendendo outros clientes.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}}var import_nats,DEFAULT_NATS_URL="localhost:4222",DEFAULT_IDLE_TIMEOUT_MS=900000,DEFAULT_MAX_CONCURRENT=20,MAX_BUFFER_PER_CHAT=50,IDLE_CHECK_INTERVAL_MS=30000,PG_STARTUP_PROBE_TIMEOUT_MS=5000,PG_RUNTIME_QUERY_TIMEOUT_MS=2000,bridgeInstance=null;var init_omni_bridge=__esm(()=>{init_executor_config();init_tmux();init_claude_code();init_claude_sdk2();import_nats=__toESM(require_mod4(),1)});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",isSpaceKey=(key)=>key.name==="space",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_errors3=__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_errors3();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,i2)=>!Object.is(dep,oldDeps[i2])))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=(open2,close)=>{if(!hasColors)return(input)=>input;let openCode=`\x1B[${open2}m`,closeCode=`\x1B[${close}m`;return(input)=>{let string=input+"",index=string.indexOf(closeCode);if(index===-1)return openCode+string+closeCode;let result2=openCode,lastIndex=0,replaceCode=(close===22?closeCode:"")+openCode;while(index!==-1)result2+=string.slice(lastIndex,index)+replaceCode,lastIndex=index+closeCode.length,index=string.indexOf(closeCode,lastIndex);return result2+=string.slice(lastIndex)+closeCode,result2}},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 common2,specialMainSymbols,specialFallbackSymbols,mainSymbols,fallbackSymbols,shouldUseMain,figures,esm_default,replacements;var init_esm2=__esm(()=>{common2={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={...common2,...specialMainSymbols},fallbackSymbols={...common2,...specialFallbackSymbols},shouldUseMain=isUnicodeSupported(),figures=shouldUseMain?mainSymbols:fallbackSymbols,esm_default=figures,replacements=Object.entries(specialMainSymbols)});var import_yoctocolors_cjs,defaultTheme;var init_theme=__esm(()=>{init_esm2();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,i2)=>dep!==dependencies[i2])){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 i2=0;i2<string.length;i2++){let code=string.codePointAt(i2);if(code<=31||code>=127&&code<=159)continue;if(code>=768&&code<=879)continue;if(code>65535)i2++;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,b2=rgb[2]/255,min=Math.min(r,g,b2),max=Math.max(r,g,b2),delta=max-min,h,s;if(max===min)h=0;else if(r===max)h=(g-b2)/delta;else if(g===max)h=2+(b2-r)/delta;else if(b2===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,b2=rgb[2]/255,v=Math.max(r,g,b2),diff=v-Math.min(r,g,b2),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(b2),r===v)h=bdif-gdif;else if(g===v)h=0.3333333333333333+rdif-bdif;else if(b2===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],b2=rgb[2],h=convert.rgb.hsl(rgb)[0],w=0.00392156862745098*Math.min(r,Math.min(g,b2));return b2=1-0.00392156862745098*Math.max(r,Math.max(g,b2)),[h,w*100,b2*100]};convert.rgb.cmyk=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b2=rgb[2]/255,k=Math.min(1-r,1-g,1-b2),c=(1-r-k)/(1-k)||0,m=(1-g-k)/(1-k)||0,y=(1-b2-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,b2=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,b2=b2>0.04045?((b2+0.055)/1.055)**2.4:b2/12.92;let x=r*0.4124+g*0.3576+b2*0.1805,y=r*0.2126+g*0.7152+b2*0.0722,z=r*0.0193+g*0.1192+b2*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),b2=200*(y-z);return[l,a,b2]};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 i2=0;i2<3;i2++){if(t3=h+0.3333333333333333*-(i2-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[i2]=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 i2=Math.floor(6*h),v=1-bl;if(f=6*h-i2,(i2&1)!==0)f=1-f;let n=wh+f*(v-wh),r,g,b2;switch(i2){default:case 6:case 0:r=v,g=n,b2=wh;break;case 1:r=n,g=v,b2=wh;break;case 2:r=wh,g=v,b2=n;break;case 3:r=wh,g=n,b2=v;break;case 4:r=n,g=wh,b2=v;break;case 5:r=v,g=wh,b2=n;break}return[r*255,g*255,b2*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),b2=1-Math.min(1,y*(1-k)+k);return[r*255,g*255,b2*255]};convert.xyz.rgb=function(xyz){let x=xyz[0]/100,y=xyz[1]/100,z=xyz[2]/100,r,g,b2;return r=x*3.2406+y*-1.5372+z*-0.4986,g=x*-0.9689+y*1.8758+z*0.0415,b2=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,b2=b2>0.0031308?1.055*b2**0.4166666666666667-0.055:b2*12.92,r=Math.min(Math.max(0,r),1),g=Math.min(Math.max(0,g),1),b2=Math.min(Math.max(0,b2),1),[r*255,g*255,b2*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),b2=200*(y-z);return[l,a,b2]};convert.lab.xyz=function(lab){let l=lab[0],a=lab[1],b2=lab[2],x,y,z;y=(l+16)/116,x=a/500+y,z=y-b2/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],b2=lab[2],h;if(h=Math.atan2(b2,a)*360/2/Math.PI,h<0)h+=360;let c=Math.sqrt(a*a+b2*b2);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),b2=c*Math.sin(hr);return[l,a,b2]};convert.rgb.ansi16=function(args,saturation=null){let[r,g,b2]=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(b2/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],b2=args[2];if(r===g&&g===b2){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(b2/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,b2=(color>>2&1)*mult*255;return[r,g,b2]};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,b2=rem%6/5*255;return[r,g,b2]};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,b2=integer&255;return[r,g,b2]};convert.rgb.hcg=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b2=rgb[2]/255,max=Math.max(Math.max(r,g),b2),min=Math.min(Math.min(r,g),b2),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-b2)/chroma%6;else if(max===g)hue=2+(b2-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,i2=0;i2<len;i2++)graph[models[i2]]={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,i2=0;i2<len;i2++){let adjacent=adjacents[i2],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 path2=[graph[toModel].parent,toModel],fn=conversions[graph[toModel].parent][toModel],cur=graph[toModel].parent;while(graph[cur].parent)path2.unshift(graph[cur].parent),fn=link(conversions[graph[cur].parent][cur],fn),cur=graph[cur].parent;return fn.conversion=path2,fn}module.exports=function(fromModel){let graph=deriveBFS(fromModel),conversion={},models=Object.keys(graph);for(let len=models.length,i2=0;i2<len;i2++){let toModel=models[i2];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 result2=fn(args);if(typeof result2==="object")for(let len=result2.length,i2=0;i2<len;i2++)result2[i2]=Math.round(result2[i2]);return result2};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,b2)=>[r,g,b2],setLazyProperty=(object,property,get3)=>{Object.defineProperty(object,property,{get:()=>{let value=get3();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=(str2)=>{let words=str2.split(" "),last=words.length;while(last>0){if(stringWidth(words[last-1])>0)break;last--}if(last===words.length)return str2;return words.slice(0,last).join(" ")+words.slice(last).join("")},exec2=(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(`
|
|
719
|
+
`,null);if(rows)activeFromPg=rows.length,executorIds=rows.map((r)=>r.id)}let pgQueue=null;if(this.queue)pgQueue=await this.safePgCall("status_queue_stats",(_sql)=>this.queue?.stats()??Promise.resolve(null),null);return{connected:this.nc!==null,natsUrl:this.natsUrl,pgAvailable:this.pgAvailable,activeSessions:activeFromPg??this.sessions.size,maxConcurrent:this.maxConcurrent,idleTimeoutMs:this.idleTimeoutMs,queueDepth:pgQueue?pgQueue.pending+pgQueue.processing:this.messageQueue.length,executorType:this.executorType,executorIds,pgQueue,sessions:Array.from(this.sessions.entries()).map(([key,entry])=>({id:key,agentName:entry.session.agentName,chatId:entry.session.chatId,instanceId:entry.instanceId,executorType:entry.session.executorType,spawning:entry.spawning,idleMs:now-entry.session.lastActivityAt,bufferSize:entry.buffer.length}))}}async probePg(){try{let sql=await withTimeout(this.pgProvider(),PG_STARTUP_PROBE_TIMEOUT_MS,"PG provider startup");await withTimeout(Promise.resolve(sql`SELECT 1`),PG_STARTUP_PROBE_TIMEOUT_MS,"PG SELECT 1 probe"),this.sql=sql,this.pgAvailable=!0,console.log("[omni-bridge] PG reachable \u2014 session recovery enabled")}catch(err){this.sql=null,this.pgAvailable=!1;let msg=err instanceof Error?err.message:String(err);if(isPgConnectionError(err)){console.warn(`[omni-bridge] PG unavailable \u2014 session recovery disabled (${msg})`);return}throw Error(`[omni-bridge] PG schema mismatch or setup error: ${msg}. ${"Run `bun run migrate` (or the equivalent migration command) and retry."}`)}}async recoverSessions(){if(!this.sessionStore)return;let orphanedCount=await this.safePgCall("recover_orphan_all",(sql)=>new BridgeSessionStore(sql).markAllOrphaned(),0);if(orphanedCount>0)console.log(`[omni-bridge] Startup cleanup: orphaned ${orphanedCount} stale session(s) from previous run`)}async safePgCall(op,fn,fallback,ctx){if(!this.pgAvailable||!this.sql)return fallback;let sql=this.sql;try{return await withTimeout(fn(sql),PG_RUNTIME_QUERY_TIMEOUT_MS,`safePgCall(${op})`)}catch(err){let msg=err instanceof Error?err.message:String(err),execPart=ctx?.executorId?` executor_id=${ctx.executorId}`:"",chatPart=ctx?.chatId?` chat_id=${ctx.chatId}`:"";if(console.warn(`[omni-bridge] safePgCall(${op}) failed${execPart}${chatPart}: ${msg}`),isPgConnectionError(err))this.pgAvailable=!1,this.sql=null,console.warn("[omni-bridge] PG connection lost \u2014 switching to degraded mode");return fallback}}async processSubscription(){if(!this.sub)return;for await(let msg of this.sub)try{let data=this.sc.decode(msg.data),parsed=JSON.parse(data),parts=msg.subject.split(".");if(parts.length>=4)parsed.instanceId=parsed.instanceId||parts[2],parsed.chatId=parsed.chatId||parts[3];console.log(`[omni-bridge] NATS message received: ${msg.subject} agent=${parsed.agent} chat=${parsed.chatId}`);let messageId=parsed.messageId;if(messageId&&this.recentMessageIds.has(messageId)){console.log(`[omni-bridge] Dedup: skipping duplicate messageId=${messageId}`);continue}if(messageId){if(this.recentMessageIds.set(messageId,Date.now()),this.recentMessageIds.size>1000){let cutoff=Date.now()-60000;for(let[id,ts3]of this.recentMessageIds)if(ts3<cutoff)this.recentMessageIds.delete(id)}}if(!parsed.chatId||!parsed.agent){console.warn("[omni-bridge] Dropping message: missing chatId or agent",msg.subject);continue}if(this.queue){let env=parsed.env??{};await this.queue.enqueue(parsed,env)}else{let key=`${parsed.agent}:${parsed.chatId}`,hasSession=this.sessions.has(key);console.log(`[omni-bridge] Routing message for ${key} (hasSession=${hasSession}, queue=${!!this.queue})`),await this.routeMessage(parsed),console.log(`[omni-bridge] routeMessage done for ${key}`)}}catch(err){console.error("[omni-bridge] Error processing message:",err)}}async processTurnEvents(sub){for await(let msg of sub)try{let payload=JSON.parse(this.sc.decode(msg.data)),parts=msg.subject.split("."),eventType=parts[2],instanceId=parts[3],chatId=parts.slice(4).join(".");console.log(`[omni-bridge] Turn event: ${eventType} instance=${instanceId} chat=${chatId}`);let sessionKey=this.findSessionKey(instanceId,chatId);if(!sessionKey&&payload.turnId){if(sessionKey=this.findSessionKeyByTurnId(payload.turnId),sessionKey)console.log(`[omni-bridge] Matched session via turnId fallback: ${sessionKey}`)}if(sessionKey)await this.routeTurnEvent(eventType,sessionKey,payload);else console.log(`[omni-bridge] No session found for turn.${eventType} (instance=${instanceId}, chat=${chatId})`)}catch(err){console.warn("[omni-bridge] Error processing turn event:",err)}}async routeTurnEvent(eventType,sessionKey,payload){switch(eventType){case"open":this.turnTracker.open(sessionKey,payload.turnId,payload.messageId);break;case"done":this.turnTracker.close(sessionKey,payload.action),await this.handleTurnDone(sessionKey);break;case"nudge":await this.handleTurnNudge(sessionKey,payload.message);break;case"timeout":await this.handleTurnTimeout(sessionKey);break}}findSessionKeyByTurnId(turnId){for(let[key]of this.sessions)if(this.turnTracker.getTurnId(key)===turnId)return key;return}chatIdMap=new Map;findSessionKey(instanceId,chatId){let resolvedChatId=this.chatIdMap.get(chatId);for(let[key,entry]of this.sessions){if(entry.instanceId!==instanceId)continue;if(entry.session?.chatId===chatId)return key;if(resolvedChatId&&entry.session?.chatId===resolvedChatId)return key;if(entry.spawning&&key.endsWith(`:${chatId}`))return key;if(resolvedChatId&&entry.spawning&&key.endsWith(`:${resolvedChatId}`))return key}return}async handleTurnNudge(sessionKey,nudgeText){let entry=this.sessions.get(sessionKey);if(!entry?.session)return;try{await this.executor.injectNudge(entry.session,nudgeText)}catch(err){console.warn(`[omni-bridge] Failed to inject nudge for ${sessionKey}:`,err)}}async processSessionResetEvents(sub){for await(let msg of sub)try{let parts=msg.subject.split(".");if(parts.length<5){console.warn(`[omni-bridge] Malformed session-reset subject: ${msg.subject}`);continue}let instanceId=parts[3],chatId=parts.slice(4).join("."),action;try{action=JSON.parse(this.sc.decode(msg.data)).action}catch{}await this.handleSessionReset(instanceId,chatId,action)}catch(err){console.warn("[omni-bridge] Error processing session reset event:",err)}}async handleSessionReset(instanceId,chatId,action){let sessionKey=this.findSessionKey(instanceId,chatId);if(!sessionKey){console.log(`[omni-bridge] Session reset for cold chat ${instanceId}/${chatId} \u2014 no-op`);return}let entry=this.sessions.get(sessionKey);if(!entry)return;let actionTag=action?` (action=${action})`:"";if(entry.spawning){console.log(`[omni-bridge] Session reset for spawning ${sessionKey}${actionTag}, marking cancelled`),entry.cancelled=!0,entry.buffer=[],this.turnTracker.close(sessionKey,"reset"),await this.removeSession(sessionKey),await this.drainQueue();return}if(!entry.session)return;console.log(`[omni-bridge] Session reset for ${sessionKey}${actionTag}, evicting`),this.turnTracker.close(sessionKey,"reset");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down reset session ${sessionKey}:`,err)}await this.removeSession(sessionKey),await this.drainQueue()}async handleTurnDone(sessionKey){if(!this.sessions.get(sessionKey)?.session)return;console.log(`[omni-bridge] Turn done for ${sessionKey}, session stays alive for next message`),this.resetIdleTimer(sessionKey)}async handleTurnTimeout(sessionKey){let entry=this.sessions.get(sessionKey);if(!entry?.session)return;console.warn(`[omni-bridge] Turn timed out for ${sessionKey}, evicting session`),this.turnTracker.close(sessionKey,"timeout");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down timed-out session ${sessionKey}:`,err)}this.sessions.delete(sessionKey)}async routeMessage(message){let key=`${message.agent}:${message.chatId}`,entry=this.sessions.get(key);if(entry){if(entry.spawning){if(entry.buffer.length<MAX_BUFFER_PER_CHAT)entry.buffer.push(message);else console.warn(`[omni-bridge] Buffer full (${MAX_BUFFER_PER_CHAT}) for ${key}, dropping message from ${message.sender}`),await this.publishBufferFullReply(message);return}if(await this.executor.isAlive(entry.session)){await this.executor.deliver(entry.session,message),this.resetIdleTimer(key);let bsId=entry.pgBridgeSessionId;if(bsId&&this.sessionStore)this.safePgCall("session_activity",(sql)=>new BridgeSessionStore(sql).recordActivity(bsId),void 0,{chatId:message.chatId});return}await this.removeSession(key)}await this.spawnSession(message)}async spawnSession(message){let key=`${message.agent}:${message.chatId}`,existing=this.sessions.get(key);if(existing){if(existing.buffer.length<MAX_BUFFER_PER_CHAT)existing.buffer.push(message),console.log(`[omni-bridge] Buffered message for existing session ${key} (buffer=${existing.buffer.length})`);return}if(this.sessions.size>=this.maxConcurrent){this.messageQueue.push(message),await this.publishAutoReply(message),console.log(`[omni-bridge] Max concurrent (${this.maxConcurrent}) reached, queued message for ${key}`);return}let placeholder={session:null,instanceId:message.instanceId,spawning:!0,buffer:[message],idleTimer:null};this.sessions.set(key,placeholder);try{let raw=message,payloadEnv=raw.env,spawnEnv={OMNI_API_KEY:payloadEnv?.OMNI_API_KEY??process.env.OMNI_API_KEY??"",OMNI_INSTANCE:payloadEnv?.OMNI_INSTANCE??message.instanceId,OMNI_CHAT:payloadEnv?.OMNI_CHAT??message.chatId,OMNI_MESSAGE:payloadEnv?.OMNI_MESSAGE??raw.messageId??"",OMNI_TURN_ID:payloadEnv?.OMNI_TURN_ID||"",OMNI_SENDER_NAME:payloadEnv?.OMNI_SENDER_NAME??message.sender??""};console.log(`[omni-bridge] Spawning session for ${key}...`);let session=await this.executor.spawn(message.agent,message.chatId,spawnEnv,message.content);if(placeholder.cancelled){console.log(`[omni-bridge] Spawn for ${key} completed but was cancelled by reset, shutting down`);try{await this.executor.shutdown(session)}catch(err){console.warn(`[omni-bridge] Error shutting down cancelled spawn for ${key}:`,err)}return}if(placeholder.session=session,placeholder.spawning=!1,this.sessionStore){let pgId=await this.safePgCall("session_create",(sql)=>new BridgeSessionStore(sql).create({instanceId:message.instanceId,chatId:message.chatId,agentName:message.agent,executorId:session.sdk?.executorId,tmuxPaneId:session.tmux?.paneId,claudeSessionId:session.sdk?.claudeSessionId}),void 0,{chatId:message.chatId});if(pgId)placeholder.pgBridgeSessionId=pgId}for(let buffered of placeholder.buffer)await this.executor.deliver(session,buffered);placeholder.buffer=[],this.resetIdleTimer(key);let sessionTag=session.executorType==="tmux"?`(tmux pane=${session.tmux?.paneId})`:"(executor=sdk)";console.log(`[omni-bridge] Session active: ${key} ${sessionTag}`)}catch(err){console.error(`[omni-bridge] Failed to spawn session for ${key}:`,err);let lostMessages=placeholder.buffer;if(lostMessages.length>0)console.warn(`[omni-bridge] Re-queuing ${lostMessages.length} buffered message(s) from failed spawn for ${key}`),this.messageQueue.push(...lostMessages);this.sessions.delete(key)}}resetIdleTimer(key){let entry=this.sessions.get(key);if(!entry)return;if(entry.idleTimer)clearTimeout(entry.idleTimer);entry.idleTimer=setTimeout(async()=>{console.log(`[omni-bridge] Idle timeout for ${key}, shutting down...`);try{await this.executor.shutdown(entry.session)}catch{}await this.removeSession(key),await this.drainQueue()},this.idleTimeoutMs)}async checkIdleSessions(){let now=Date.now();for(let[key,entry]of this.sessions){if(entry.spawning)continue;if(!await this.executor.isAlive(entry.session)){console.log(`[omni-bridge] Dead session detected: ${key}`),await this.removeSession(key);continue}let idleMs=now-entry.session.lastActivityAt;if(idleMs>this.idleTimeoutMs){console.log(`[omni-bridge] Forcing idle shutdown: ${key} (idle ${Math.round(idleMs/1000)}s)`);try{await this.executor.shutdown(entry.session)}catch{}await this.removeSession(key)}}}async removeSession(key){let entry=this.sessions.get(key);if(entry?.idleTimer)clearTimeout(entry.idleTimer);let closeId=entry?.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0);this.sessions.delete(key)}async drainQueue(){while(this.messageQueue.length>0){if(this.sessions.size>=this.maxConcurrent)break;let message=this.messageQueue.shift();if(message)await this.spawnSession(message)}}async publishBufferFullReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Fila de mensagens cheia, por favor aguarde e tente novamente.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}async publishAutoReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Aguarde um momento, estou atendendo outros clientes.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}}var import_nats,DEFAULT_NATS_URL="localhost:4222",DEFAULT_IDLE_TIMEOUT_MS=900000,DEFAULT_MAX_CONCURRENT=20,MAX_BUFFER_PER_CHAT=50,IDLE_CHECK_INTERVAL_MS=30000,PG_STARTUP_PROBE_TIMEOUT_MS=5000,PG_RUNTIME_QUERY_TIMEOUT_MS=2000,bridgeInstance=null;var init_omni_bridge=__esm(()=>{init_executor_config();init_claude_code();init_claude_sdk2();import_nats=__toESM(require_mod4(),1)});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",isSpaceKey=(key)=>key.name==="space",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_errors3=__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_errors3();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,i2)=>!Object.is(dep,oldDeps[i2])))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=(open2,close)=>{if(!hasColors)return(input)=>input;let openCode=`\x1B[${open2}m`,closeCode=`\x1B[${close}m`;return(input)=>{let string=input+"",index=string.indexOf(closeCode);if(index===-1)return openCode+string+closeCode;let result2=openCode,lastIndex=0,replaceCode=(close===22?closeCode:"")+openCode;while(index!==-1)result2+=string.slice(lastIndex,index)+replaceCode,lastIndex=index+closeCode.length,index=string.indexOf(closeCode,lastIndex);return result2+=string.slice(lastIndex)+closeCode,result2}},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 common2,specialMainSymbols,specialFallbackSymbols,mainSymbols,fallbackSymbols,shouldUseMain,figures,esm_default,replacements;var init_esm2=__esm(()=>{common2={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={...common2,...specialMainSymbols},fallbackSymbols={...common2,...specialFallbackSymbols},shouldUseMain=isUnicodeSupported(),figures=shouldUseMain?mainSymbols:fallbackSymbols,esm_default=figures,replacements=Object.entries(specialMainSymbols)});var import_yoctocolors_cjs,defaultTheme;var init_theme=__esm(()=>{init_esm2();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,i2)=>dep!==dependencies[i2])){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 i2=0;i2<string.length;i2++){let code=string.codePointAt(i2);if(code<=31||code>=127&&code<=159)continue;if(code>=768&&code<=879)continue;if(code>65535)i2++;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,b2=rgb[2]/255,min=Math.min(r,g,b2),max=Math.max(r,g,b2),delta=max-min,h,s;if(max===min)h=0;else if(r===max)h=(g-b2)/delta;else if(g===max)h=2+(b2-r)/delta;else if(b2===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,b2=rgb[2]/255,v=Math.max(r,g,b2),diff=v-Math.min(r,g,b2),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(b2),r===v)h=bdif-gdif;else if(g===v)h=0.3333333333333333+rdif-bdif;else if(b2===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],b2=rgb[2],h=convert.rgb.hsl(rgb)[0],w=0.00392156862745098*Math.min(r,Math.min(g,b2));return b2=1-0.00392156862745098*Math.max(r,Math.max(g,b2)),[h,w*100,b2*100]};convert.rgb.cmyk=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b2=rgb[2]/255,k=Math.min(1-r,1-g,1-b2),c=(1-r-k)/(1-k)||0,m=(1-g-k)/(1-k)||0,y=(1-b2-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,b2=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,b2=b2>0.04045?((b2+0.055)/1.055)**2.4:b2/12.92;let x=r*0.4124+g*0.3576+b2*0.1805,y=r*0.2126+g*0.7152+b2*0.0722,z=r*0.0193+g*0.1192+b2*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),b2=200*(y-z);return[l,a,b2]};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 i2=0;i2<3;i2++){if(t3=h+0.3333333333333333*-(i2-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[i2]=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 i2=Math.floor(6*h),v=1-bl;if(f=6*h-i2,(i2&1)!==0)f=1-f;let n=wh+f*(v-wh),r,g,b2;switch(i2){default:case 6:case 0:r=v,g=n,b2=wh;break;case 1:r=n,g=v,b2=wh;break;case 2:r=wh,g=v,b2=n;break;case 3:r=wh,g=n,b2=v;break;case 4:r=n,g=wh,b2=v;break;case 5:r=v,g=wh,b2=n;break}return[r*255,g*255,b2*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),b2=1-Math.min(1,y*(1-k)+k);return[r*255,g*255,b2*255]};convert.xyz.rgb=function(xyz){let x=xyz[0]/100,y=xyz[1]/100,z=xyz[2]/100,r,g,b2;return r=x*3.2406+y*-1.5372+z*-0.4986,g=x*-0.9689+y*1.8758+z*0.0415,b2=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,b2=b2>0.0031308?1.055*b2**0.4166666666666667-0.055:b2*12.92,r=Math.min(Math.max(0,r),1),g=Math.min(Math.max(0,g),1),b2=Math.min(Math.max(0,b2),1),[r*255,g*255,b2*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),b2=200*(y-z);return[l,a,b2]};convert.lab.xyz=function(lab){let l=lab[0],a=lab[1],b2=lab[2],x,y,z;y=(l+16)/116,x=a/500+y,z=y-b2/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],b2=lab[2],h;if(h=Math.atan2(b2,a)*360/2/Math.PI,h<0)h+=360;let c=Math.sqrt(a*a+b2*b2);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),b2=c*Math.sin(hr);return[l,a,b2]};convert.rgb.ansi16=function(args,saturation=null){let[r,g,b2]=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(b2/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],b2=args[2];if(r===g&&g===b2){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(b2/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,b2=(color>>2&1)*mult*255;return[r,g,b2]};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,b2=rem%6/5*255;return[r,g,b2]};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,b2=integer&255;return[r,g,b2]};convert.rgb.hcg=function(rgb){let r=rgb[0]/255,g=rgb[1]/255,b2=rgb[2]/255,max=Math.max(Math.max(r,g),b2),min=Math.min(Math.min(r,g),b2),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-b2)/chroma%6;else if(max===g)hue=2+(b2-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,i2=0;i2<len;i2++)graph[models[i2]]={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,i2=0;i2<len;i2++){let adjacent=adjacents[i2],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 path2=[graph[toModel].parent,toModel],fn=conversions[graph[toModel].parent][toModel],cur=graph[toModel].parent;while(graph[cur].parent)path2.unshift(graph[cur].parent),fn=link(conversions[graph[cur].parent][cur],fn),cur=graph[cur].parent;return fn.conversion=path2,fn}module.exports=function(fromModel){let graph=deriveBFS(fromModel),conversion={},models=Object.keys(graph);for(let len=models.length,i2=0;i2<len;i2++){let toModel=models[i2];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 result2=fn(args);if(typeof result2==="object")for(let len=result2.length,i2=0;i2<len;i2++)result2[i2]=Math.round(result2[i2]);return result2};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,b2)=>[r,g,b2],setLazyProperty=(object,property,get3)=>{Object.defineProperty(object,property,{get:()=>{let value=get3();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=(str2)=>{let words=str2.split(" "),last=words.length;while(last>0){if(stringWidth(words[last-1])>0)break;last--}if(last===words.length)return str2;return words.slice(0,last).join(" ")+words.slice(last).join("")},exec2=(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(`
|
|
720
720
|
`);for(let[index,character]of[...pre].entries()){if(ret+=character,ESCAPES.has(character)){let code2=parseFloat(/\d[^m]*/.exec(pre.slice(index,index+4)));escapeCode=code2===39?null:code2}let code=ansiStyles.codes.get(Number(escapeCode));if(escapeCode&&code){if(pre[index+1]===`
|
|
721
721
|
`)ret+=wrapAnsi(code);else if(character===`
|
|
722
722
|
`)ret+=wrapAnsi(escapeCode)}}return ret};module.exports=(string,columns,options)=>{return String(string).normalize().replace(/\r\n/g,`
|
|
@@ -896,7 +896,7 @@ Run 'genie agent list' to list agents.`)}async function resolveTarget(target,opt
|
|
|
896
896
|
LIMIT 100
|
|
897
897
|
`).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 truncate2(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}**: ${truncate2(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}] ${truncate2(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}: ${truncate2(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}: ${truncate2(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(`
|
|
898
898
|
`)}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,healAgentFile:()=>healAgentFile});import{execSync as execSync6}from"child_process";import{existsSync as existsSync22,watch as fsWatch,readFileSync as readFileSync15,readdirSync as readdirSync6,realpathSync as realpathSync3,writeFileSync as writeFileSync11}from"fs";import{join as join25}from"path";function getGitRemoteUrl(dir){try{return execSync6(`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=join25(agentDir,"repos");try{if(!existsSync22(reposLink))return null;let target=realpathSync3(reposLink);if(!existsSync22(target))return null;return target}catch{return null}}function discoverAgents(workspaceRoot){let agentsDir=join25(workspaceRoot,"agents");if(!existsSync22(agentsDir))return[];let agents=[];try{let entries=readdirSync6(agentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let agentDir=join25(agentsDir,entry.name);if(!existsSync22(join25(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=join25(parentDir,".genie","agents");if(!existsSync22(subAgentsDir))return;try{let entries=readdirSync6(subAgentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let subDir=join25(subAgentsDir,entry.name);if(!existsSync22(join25(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=join25(workspaceRoot,"agents",agentName);if(!existsSync22(join25(agentDir,"AGENTS.md")))return null;return{name:agentName,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)}}function healAgentFile(agentsMdPath,agentName,healResult){let content=readFileSync15(agentsMdPath,"utf-8"),fmMatch=content.match(/^(---\n)([\s\S]*?)(\n---)/);if(!fmMatch)return!1;let prefix=fmMatch[1],fmBlock=fmMatch[2],suffix=fmMatch[3],rest=content.slice(fmMatch[0].length),modified=!1,healedBlock=fmBlock;for(let{field,value}of INVALID_LITERALS)if(new RegExp(`^${field}:\\s*${value}\\s*$`,"m").test(healedBlock))healedBlock=healedBlock.replace(new RegExp(`${field}:\\s*${value}\\s*\\n?`,"m"),""),healResult.healed.push({agent:agentName,field,value}),modified=!0;if(!modified)return!1;let newContent=prefix+healedBlock+suffix+rest,tmpPath=`${agentsMdPath}.tmp.${Date.now()}`;writeFileSync11(tmpPath,newContent,"utf-8");let{renameSync:renameSync2}=__require("fs");return renameSync2(tmpPath,agentsMdPath),!0}function buildResolveContext(workspaceRoot,agentName){let workspaceDefaults;try{workspaceDefaults=getWorkspaceConfig(workspaceRoot).agents?.defaults}catch{}let parent;if(agentName.includes("/")){let parentName=agentName.split("/")[0],parentAgentsMd=join25(workspaceRoot,"agents",parentName,"AGENTS.md");if(existsSync22(parentAgentsMd)){let parentContent=readFileSync15(parentAgentsMd,"utf-8"),parentFm=parseFrontmatter(parentContent);parent={name:parentName,fields:parentFm}}}return{workspaceDefaults,parent}}function computeResolvedMetadata(fm,ctx){let declared={},resolved={};for(let field of Object.keys(BUILTIN_DEFAULTS)){let fmValue=fm[field];if(fmValue!==void 0&&fmValue!==null&&fmValue!==""&&fmValue!=="inherit")declared[field]=fmValue;let result2=resolveFieldWithSource(fm,field,ctx);resolved[field]={value:result2.value,source:result2.source}}return{declared,resolved}}async function syncAgentDirectory(workspaceRoot){let result2={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],healed:[],errors:[]},agents=discoverAgents(workspaceRoot),discoveredNames=new Set(agents.map((a)=>a.name)),healResult={healed:[]};for(let agent of agents){let agentsMdPath=join25(agent.dir,"AGENTS.md");try{healAgentFile(agentsMdPath,agent.name,healResult)}catch{}}result2.healed=healResult.healed;for(let h of healResult.healed)console.log(`[sync] healed ${h.agent}/AGENTS.md: removed invalid '${h.field}: ${h.value}' line`);for(let agent of agents)try{await syncSingleAgent(agent,result2,workspaceRoot)}catch(err){result2.errors.push({name:agent.name,error:err instanceof Error?err.message:String(err)})}return await removeMissingAgents(discoveredNames,result2),result2}function printSyncResult(result2){if(result2.healed.length>0)console.log(` Healed: ${result2.healed.length} invalid literal(s) removed`);if(result2.registered.length>0)console.log(` Registered: ${result2.registered.join(", ")}`);if(result2.updated.length>0)console.log(` Updated: ${result2.updated.join(", ")}`);if(result2.reactivated.length>0)console.log(` Reactivated: ${result2.reactivated.join(", ")}`);if(result2.archived.length>0)console.log(` Removed: ${result2.archived.join(", ")}`);if(result2.unchanged.length>0)console.log(` Unchanged: ${result2.unchanged.join(", ")}`);for(let err of result2.errors)console.error(` Error (${err.name}): ${err.error}`);let total=result2.registered.length+result2.updated.length+result2.unchanged.length+result2.reactivated.length;console.log(`
|
|
899
|
-
Sync complete: ${total} active agent(s), ${result2.archived.length} removed.`)}async function removeMissingAgents(discoveredNames,result2){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 rm2(entry.name))result2.archived.push(entry.name)}}catch{}}async function syncSingleAgent(agent,result2,workspaceRoot){let repoPath=(agent.repoUrl?extractOrgRepo(agent.repoUrl):null)??agent.repoUrl??agent.dir,agentsMdPath=join25(agent.dir,"AGENTS.md"),content=readFileSync15(agentsMdPath,"utf-8"),fm=parseFrontmatter(content),_resolvedMeta;if(workspaceRoot){let ctx=buildResolveContext(workspaceRoot,agent.name);_resolvedMeta=computeResolvedMetadata(fm,ctx)}let resolved=await resolve2(agent.name),existing=resolved&&!resolved.builtin?resolved.entry:null,sdkConfig=fm.sdk,permissions=fm.permissions,disallowedTools=fm.disallowedTools,omniScopes=fm.omniScopes,hooks=fm.hooks;if(!existing){await add({name:agent.name,dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,permissions,disallowedTools,omniScopes,hooks,sdk:sdkConfig}),result2.registered.push(agent.name);return}let identityUpdate={dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,permissions,disallowedTools,omniScopes,hooks,sdk:sdkConfig},sdkChanged=JSON.stringify(existing.sdk)!==JSON.stringify(sdkConfig),permissionsChanged=JSON.stringify(existing.permissions)!==JSON.stringify(permissions),disallowedToolsChanged=JSON.stringify(existing.disallowedTools)!==JSON.stringify(disallowedTools),omniScopesChanged=JSON.stringify(existing.omniScopes)!==JSON.stringify(omniScopes),hooksChanged=JSON.stringify(existing.hooks)!==JSON.stringify(hooks);if(sdkChanged||permissionsChanged||disallowedToolsChanged||omniScopesChanged||hooksChanged||existing.repo!==repoPath||existing.dir!==agent.dir||existing.promptMode!==(fm.promptMode??"append")||existing.model!==fm.model||existing.description!==fm.description||existing.color!==fm.color||existing.provider!==fm.provider)await edit(agent.name,identityUpdate),result2.updated.push(agent.name);else result2.unchanged.push(agent.name)}async function syncSingleAgentByName(workspaceRoot,agentName){let agent=discoverSingleAgent(workspaceRoot,agentName);if(!agent)return"not-found";let result2={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],healed:[],errors:[]};if(await syncSingleAgent(agent,result2,workspaceRoot),result2.registered.length>0)return"registered";if(result2.updated.length>0)return"updated";return"unchanged"}function watchAgentDirectory(workspaceRoot,options){let agentsDir=join25(workspaceRoot,"agents");if(!existsSync22(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=join25(agentsDir,name);if(existsSync22(agentDir)&&existsSync22(join25(agentDir,"AGENTS.md"))){let action=await syncSingleAgentByName(workspaceRoot,name);return action!=="unchanged"&&action!=="not-found"?action:null}if(!existsSync22(agentDir)){if(await rm2(name))return"removed"}return null}var INVALID_LITERALS;var init_agent_sync=__esm(()=>{init_agent_directory();init_defaults();init_frontmatter();init_workspace();INVALID_LITERALS=[{field:"model",value:"inherit"}]});var exports_term_format={};__export(exports_term_format,{truncate:()=>truncate3,stripAnsi:()=>stripAnsi2,padRight:()=>padRight,formatTimestamp:()=>formatTimestamp,formatTime:()=>formatTime,formatRelativeTimestamp:()=>formatRelativeTimestamp,formatDate:()=>formatDate,color:()=>color});function padRight(str2,len){return str2.length>=len?str2:str2+" ".repeat(len-str2.length)}function truncate3(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??"??:??"}}function color(name,text){return isTTY?`${ANSI[name]}${text}${ANSI.reset}`:text}function stripAnsi2(str2){return str2.replace(ANSI_REGEX,"")}var ANSI,isTTY,ANSI_REGEX;var init_term_format=__esm(()=>{ANSI={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightCyan:"\x1B[96m"},isTTY=process.stdout.isTTY&&!process.env.NO_COLOR;ANSI_REGEX=/\x1b\[[0-9;]*m/g});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 execSync7}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 execSync7("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`
|
|
899
|
+
Sync complete: ${total} active agent(s), ${result2.archived.length} removed.`)}async function removeMissingAgents(discoveredNames,result2){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 rm(entry.name))result2.archived.push(entry.name)}}catch{}}async function syncSingleAgent(agent,result2,workspaceRoot){let repoPath=(agent.repoUrl?extractOrgRepo(agent.repoUrl):null)??agent.repoUrl??agent.dir,agentsMdPath=join25(agent.dir,"AGENTS.md"),content=readFileSync15(agentsMdPath,"utf-8"),fm=parseFrontmatter(content),_resolvedMeta;if(workspaceRoot){let ctx=buildResolveContext(workspaceRoot,agent.name);_resolvedMeta=computeResolvedMetadata(fm,ctx)}let resolved=await resolve2(agent.name),existing=resolved&&!resolved.builtin?resolved.entry:null,sdkConfig=fm.sdk,permissions=fm.permissions,disallowedTools=fm.disallowedTools,omniScopes=fm.omniScopes,hooks=fm.hooks;if(!existing){await add({name:agent.name,dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,permissions,disallowedTools,omniScopes,hooks,sdk:sdkConfig}),result2.registered.push(agent.name);return}let identityUpdate={dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,permissions,disallowedTools,omniScopes,hooks,sdk:sdkConfig},sdkChanged=JSON.stringify(existing.sdk)!==JSON.stringify(sdkConfig),permissionsChanged=JSON.stringify(existing.permissions)!==JSON.stringify(permissions),disallowedToolsChanged=JSON.stringify(existing.disallowedTools)!==JSON.stringify(disallowedTools),omniScopesChanged=JSON.stringify(existing.omniScopes)!==JSON.stringify(omniScopes),hooksChanged=JSON.stringify(existing.hooks)!==JSON.stringify(hooks);if(sdkChanged||permissionsChanged||disallowedToolsChanged||omniScopesChanged||hooksChanged||existing.repo!==repoPath||existing.dir!==agent.dir||existing.promptMode!==(fm.promptMode??"append")||existing.model!==fm.model||existing.description!==fm.description||existing.color!==fm.color||existing.provider!==fm.provider)await edit(agent.name,identityUpdate),result2.updated.push(agent.name);else result2.unchanged.push(agent.name)}async function syncSingleAgentByName(workspaceRoot,agentName){let agent=discoverSingleAgent(workspaceRoot,agentName);if(!agent)return"not-found";let result2={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],healed:[],errors:[]};if(await syncSingleAgent(agent,result2,workspaceRoot),result2.registered.length>0)return"registered";if(result2.updated.length>0)return"updated";return"unchanged"}function watchAgentDirectory(workspaceRoot,options){let agentsDir=join25(workspaceRoot,"agents");if(!existsSync22(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=join25(agentsDir,name);if(existsSync22(agentDir)&&existsSync22(join25(agentDir,"AGENTS.md"))){let action=await syncSingleAgentByName(workspaceRoot,name);return action!=="unchanged"&&action!=="not-found"?action:null}if(!existsSync22(agentDir)){if(await rm(name))return"removed"}return null}var INVALID_LITERALS;var init_agent_sync=__esm(()=>{init_agent_directory();init_defaults();init_frontmatter();init_workspace();INVALID_LITERALS=[{field:"model",value:"inherit"}]});var exports_term_format={};__export(exports_term_format,{truncate:()=>truncate3,stripAnsi:()=>stripAnsi2,padRight:()=>padRight,formatTimestamp:()=>formatTimestamp,formatTime:()=>formatTime,formatRelativeTimestamp:()=>formatRelativeTimestamp,formatDate:()=>formatDate,color:()=>color});function padRight(str2,len){return str2.length>=len?str2:str2+" ".repeat(len-str2.length)}function truncate3(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??"??:??"}}function color(name,text){return isTTY?`${ANSI[name]}${text}${ANSI.reset}`:text}function stripAnsi2(str2){return str2.replace(ANSI_REGEX,"")}var ANSI,isTTY,ANSI_REGEX;var init_term_format=__esm(()=>{ANSI={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightCyan:"\x1B[96m"},isTTY=process.stdout.isTTY&&!process.env.NO_COLOR;ANSI_REGEX=/\x1b\[[0-9;]*m/g});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 execSync7}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 execSync7("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`
|
|
900
900
|
SELECT t.id FROM tasks t
|
|
901
901
|
JOIN projects p ON t.project_id = p.id
|
|
902
902
|
WHERE p.name = ${projectName} AND t.seq = ${seq2}
|
|
@@ -3112,7 +3112,7 @@ ${context}`}}}catch{return}}var DENY_PATTERNS=[{test:(cmd)=>/git\s+push\b/i.test
|
|
|
3112
3112
|
`+" genie agent send --to <a> \u2014 communicate directly"},{test:/sleep\s+\d+\s*&&\s*.*(?:capture-pane|tmux\s+list)/,message:`Consider using genie primitives instead of terminal polling:
|
|
3113
3113
|
genie task status <slug>
|
|
3114
3114
|
genie events list --since 5m`}];async function orchestrationGuard(payload){let command=payload.tool_input?.command;if(typeof command!=="string")return;for(let{test,message}of NUDGE_PATTERNS)if(test.test(command))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:`[orchestration-guard] ${message}`}};return}import{existsSync as existsSync21,readFileSync as readFileSync14}from"fs";import{basename as basename4,join as join24}from"path";function readAgentNameFromSettings(cwd){let localSettings=join24(cwd,".claude","settings.local.json");if(!existsSync21(localSettings))return;try{return JSON.parse(readFileSync14(localSettings,"utf-8")).agentName||void 0}catch{return}}function nameFromCwd(cwd){let name=basename4(cwd);return name&&name!=="/"&&name!=="."?name:void 0}function resolveAgentName(payload){let cwd=payload.cwd;return process.env.GENIE_AGENT_NAME||payload.teammate_name||cwd&&readAgentNameFromSettings(cwd)||cwd&&nameFromCwd(cwd)||payload.session_id&&`session-${payload.session_id.slice(0,8)}`||"unknown"}function resolveTeamName(payload){return payload.team_name??process.env.GENIE_TEAM??void 0}async function emit(subject,event){try{let{publishSubjectEvent:publishSubjectEvent2}=await Promise.resolve().then(() => (init_runtime_events(),exports_runtime_events));await publishSubjectEvent2(process.cwd(),subject,event)}catch(error2){let msg=error2 instanceof Error?error2.message:String(error2);console.warn(`[runtime-emit] event log unavailable: ${msg}`)}}async function emitToolCallEvent(payload){let{tool_name:toolName,tool_input:input}=payload;if(!toolName||!input)return;let agent=resolveAgentName(payload);await emit(`genie.tool.${agent}.call`,{timestamp:new Date().toISOString(),kind:"tool_call",agent,team:resolveTeamName(payload),text:summarizeToolCall(toolName,input),data:{toolCall:{name:toolName,input}},source:"hook"});return}async function emitMessageEvent(payload){let input=payload.tool_input;if(!input)return;let msgType=input.type;if(msgType&&msgType!=="message"&&msgType!=="broadcast")return;let to=input.to,content=input.content??input.message;if(!to||!content)return;let agent=resolveAgentName(payload),subject=msgType==="broadcast"?"genie.msg.broadcast":`genie.msg.${to}`;await emit(subject,{timestamp:new Date().toISOString(),kind:"message",agent,team:resolveTeamName(payload),peer:to,direction:"out",text:content,source:"hook"});return}async function emitUserPromptEvent(payload){let prompt2=payload.prompt;if(!prompt2)return;let agent=resolveAgentName(payload);await emit(`genie.user.${agent}.prompt`,{timestamp:new Date().toISOString(),kind:"user",agent,team:resolveTeamName(payload),text:prompt2,source:"hook"});return}async function emitAssistantResponseEvent(payload){let lastMessage=payload.last_assistant_message;if(!lastMessage)return;let agent=resolveAgentName(payload);await emit(`genie.agent.${agent}.response`,{timestamp:new Date().toISOString(),kind:"assistant",agent,team:resolveTeamName(payload),text:lastMessage,source:"hook"});return}function summarizeToolCall(name,input){switch(name){case"Read":case"Edit":case"Write":return`${name} ${input.file_path??""}`;case"Bash":return`$ ${String(input.command??"").split(`
|
|
3115
|
-
`)[0]}`;case"Grep":return`Grep "${input.pattern}" ${input.path??""}`;case"Glob":return`Glob ${input.pattern}`;case"Agent":return`Agent: ${input.description??""}`;case"SendMessage":return`SendMessage \u2192 ${input.to}: ${String(input.message??"").slice(0,80)}`;default:return name}}
|
|
3115
|
+
`)[0]}`;case"Grep":return`Grep "${input.pattern}" ${input.path??""}`;case"Glob":return`Glob ${input.pattern}`;case"Agent":return`Agent: ${input.description??""}`;case"SendMessage":return`SendMessage \u2192 ${input.to}: ${String(input.message??"").slice(0,80)}`;default:return name}}init_types3();var handlers=[{name:"branch-guard",event:"PreToolUse",matcher:/^Bash$/,priority:1,fn:branchGuard},{name:"orchestration-guard",event:"PreToolUse",matcher:/^Bash$/,priority:2,fn:orchestrationGuard},{name:"brain-inject",event:"PreToolUse",matcher:/.*/,priority:5,fn:brainInject},{name:"freshness",event:"PreToolUse",matcher:/^Read$/,priority:8,fn:freshness},{name:"audit-context",event:"PreToolUse",matcher:/^(Write|Edit)$/,priority:8,fn:auditContext},{name:"identity-inject",event:"PreToolUse",matcher:/^SendMessage$/,priority:10,fn:identityInject},{name:"auto-spawn",event:"PreToolUse",matcher:/^SendMessage$/,priority:20,fn:autoSpawn},{name:"runtime-emit-tool",event:"PreToolUse",matcher:/.*/,priority:30,fn:emitToolCallEvent},{name:"runtime-emit-msg",event:"PostToolUse",matcher:/^SendMessage$/,priority:30,fn:emitMessageEvent},{name:"runtime-emit-user-prompt",event:"UserPromptSubmit",priority:30,fn:emitUserPromptEvent},{name:"runtime-emit-assistant-response",event:"Stop",priority:30,fn:emitAssistantResponseEvent}];function resolveHandlers(event,toolName){return handlers.filter((h)=>{if(h.event!==event)return!1;if(h.matcher&&toolName&&!h.matcher.test(toolName))return!1;if(h.matcher&&!toolName)return!1;return!0}).sort((a,b2)=>a.priority-b2.priority)}function hookDebug(handlerName,decision,elapsedMs){if(process.env.GENIE_HOOK_DEBUG==="1")console.error(`[hook-debug] ${handlerName} \u2192 ${decision} (${elapsedMs}ms)`)}async function runHandler(handler,payload,currentInput,isBlocking){let handlerPayload={...payload};if(currentInput)handlerPayload.tool_input=currentInput;let start=Date.now();try{let result2=await handler.fn(handlerPayload);return hookDebug(handler.name,result2?.decision??result2?.hookSpecificOutput?.permissionDecision??"allow",Date.now()-start),result2}catch(err){let msg=err instanceof Error?err.message:String(err);if(console.error(`[genie-hook] Handler "${handler.name}" threw: ${msg}`),isBlocking)return hookDebug(handler.name,"deny (crash)",Date.now()-start),{decision:"deny",reason:`handler crashed: ${msg}`};hookDebug(handler.name,"allow (crash, non-blocking)",Date.now()-start);return}}function buildDenyResponse(handler,reason,hookEventName){if(hookEventName==="PreToolUse")return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:reason??`Denied by handler: ${handler.name}`}};return{decision:"block",reason:reason??`Denied by handler: ${handler.name}`}}function buildBlockingResponse(hookEventName,contextMessages,currentInput,originalInput){let response={},hasContext=contextMessages.length>0,hasInputChange=currentInput&&originalInput&&JSON.stringify(currentInput)!==JSON.stringify(originalInput);if(hasInputChange)response.updatedInput=currentInput;if(hookEventName==="PreToolUse"&&(hasContext||hasInputChange)){let output={hookEventName:"PreToolUse"};if(hasContext)output.additionalContext=contextMessages.join(`
|
|
3116
3116
|
`);if(hasInputChange)output.permissionDecision="allow",output.updatedInput=currentInput;response.hookSpecificOutput=output}return response}async function executeBlockingChain(matched,payload){let currentInput=payload.tool_input?{...payload.tool_input}:void 0,contextMessages=[],hookEventName=payload.hook_event_name;for(let handler of matched){let result2=await runHandler(handler,payload,currentInput,!0);if(!result2)continue;if(result2.decision==="deny")return buildDenyResponse(handler,result2.reason,hookEventName);if(result2.hookSpecificOutput?.additionalContext)contextMessages.push(result2.hookSpecificOutput.additionalContext);let inputUpdate=result2.hookSpecificOutput?.updatedInput??result2.updatedInput;if(inputUpdate)currentInput={...currentInput,...inputUpdate}}return buildBlockingResponse(hookEventName,contextMessages,currentInput,payload.tool_input)}async function executeNonBlockingHandlers(matched,payload){await Promise.allSettled(matched.map((h)=>h.fn(payload).catch((err)=>{let msg=err instanceof Error?err.message:String(err);console.error(`[genie-hook] Handler "${h.name}" threw: ${msg}`)})))}async function dispatch(stdin){let payload;try{payload=JSON.parse(stdin)}catch{return console.error("[genie-hook] Invalid JSON on stdin"),""}let event=payload.hook_event_name;if(!event)return console.error("[genie-hook] Missing hook_event_name in payload"),"";let toolName=payload.tool_name,matched=resolveHandlers(event,toolName);if(matched.length===0)return"";if(isBlockingEvent(event)){let result2=await executeBlockingChain(matched,payload);if(Object.keys(result2).length>0)return JSON.stringify(result2);return""}return await executeNonBlockingHandlers(matched,payload),""}async function readStdin(){let chunks=[];for await(let chunk of Bun.stdin.stream())chunks.push(Buffer.from(chunk));return Buffer.concat(chunks).toString("utf-8")}async function dispatchAction(){let stdin=await readStdin();if(!stdin.trim())process.exit(0);let result2=await dispatch(stdin);if(result2)process.stdout.write(result2)}function registerHookNamespace(program2){program2.command("hook").description("Hook middleware for Claude Code integration").command("dispatch").description("Dispatch a CC hook event (reads JSON from stdin, writes decision to stdout)").action(dispatchAction)}init_audit();init_db();init_interactivity();init_otel_receiver();init_target_resolver();init_tmux();init_orchestrator();async function resolveOrcTarget(target){let resolved=await resolveTarget(target);return{paneId:resolved.paneId,session:resolved.session||target,label:formatResolvedLabel(resolved,target)}}async function sendTextChoice(paneId,text){await executeTmux2(`send-keys -t '${paneId}' End`),await sleep(100),await executeTmux2(`send-keys -t '${paneId}' Enter`),await sleep(100),await executeTmux2(`send-keys -t '${paneId}' ${shellEscape(text)}`),await sleep(100),await executeTmux2(`send-keys -t '${paneId}' Enter`)}function findCurrentOption(output){let lines=stripAnsi(output).split(`
|
|
3117
3117
|
`);for(let line of lines){let match=line.match(/^\s*\u276F\s*(\d+)\./);if(match)return Number.parseInt(match[1],10)}return 1}async function navigateToOption(paneId,targetOption,currentOption){let diff=targetOption-currentOption,key=diff>0?"Down":"Up";for(let i2=0;i2<Math.abs(diff);i2++)await executeTmux2(`send-keys -t '${paneId}' ${key}`),await sleep(50);await sleep(100),await executeTmux2(`send-keys -t '${paneId}' Enter`)}async function answerQuestion(target,choice){try{let{paneId,label}=await resolveOrcTarget(target),output=await capturePaneContent(paneId,50),state=detectState(output);if(state.type!=="question"){console.log(`No question pending (state: ${state.type})`);return}if(choice.startsWith("text:")){let text=choice.slice(5);await sendTextChoice(paneId,text),console.log(`Sent feedback: "${text.substring(0,50)}${text.length>50?"...":""}"`)}else if(/^\d+$/.test(choice)){let targetOption=Number.parseInt(choice,10);await navigateToOption(paneId,targetOption,findCurrentOption(output)),console.log(`Selected option ${targetOption} for ${label}`)}else await executeTmux2(`send-keys -t '${paneId}' '${choice}'`),console.log(`Sent '${choice}' to ${label}`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}function shellEscape(str2){return`"${str2.replace(/"/g,"\\\"").replace(/\$/g,"\\$")}"`}function sleep(ms){return new Promise((resolve5)=>setTimeout(resolve5,ms))}function registerAgentAnswer(parent){parent.command("answer <name> <choice>").description('Answer a question for an agent (use "text:..." for text input)').action(async(name,choice)=>{try{await answerQuestion(name,choice)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}})}var _brief;async function getBrief(){if(!_brief)_brief=await Promise.resolve().then(() => (init_brief(),exports_brief));return _brief}async function handleBrief(options){let team=options.team??process.env.GENIE_TEAM;if(!team)console.error("Error: --team is required (or set GENIE_TEAM)"),process.exit(1);let agent=options.agent??process.env.GENIE_AGENT_NAME,briefService=await getBrief(),brief=await briefService.generateBrief({team,agent,since:options.since,repoPath:process.cwd()});console.log(briefService.formatBrief(brief))}function registerAgentBrief(parent){parent.command("brief").description("Show startup brief \u2014 aggregated context since last session").option("--team <name>","Team name (default: GENIE_TEAM)").option("--agent <name>","Agent name (default: GENIE_AGENT_NAME)").option("--since <iso>","Start timestamp (default: last executor end)").action(async(options)=>{try{await handleBrief(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_agent_directory();init_agent_sync();init_builtin_agents();init_genie_config2();async function showEntry(name,json2){let resolved=await resolve2(name);if(!resolved)console.error(`Agent "${name}" not found in directory or built-ins.`),process.exit(1);if(json2){console.log(JSON.stringify({...resolved.entry,builtin:resolved.builtin},null,2));return}if(resolved.builtin)console.log(`
|
|
3118
3118
|
(built-in agent)`);if(console.log(""),console.log(` Name: ${resolved.entry.name}`),console.log(` Dir: ${contractPath(resolved.entry.dir)}`),resolved.entry.repo)console.log(` Repo: ${contractPath(resolved.entry.repo)}`);if(console.log(` Prompt mode: ${resolved.entry.promptMode}`),resolved.entry.model)console.log(` Model: ${resolved.entry.model}`);if(resolved.entry.roles?.length)console.log(` Roles: ${resolved.entry.roles.join(", ")}`);console.log(` Registered: ${resolved.entry.registeredAt}`),console.log("")}function printRegisteredAgentsTable(entries){let termW=process.stdout.columns||120,repoValues=entries.map((e)=>e.repo?contractPath(e.repo):contractPath(e.dir)),maxRepoLen=Math.max(4,...repoValues.map((v)=>v.length)),fixedW=42,repoW=Math.min(maxRepoLen+2,Math.max(30,termW-42-20));console.log(""),console.log("REGISTERED AGENTS"),console.log("-".repeat(Math.max(90,42+repoW+20))),console.log(` ${"NAME".padEnd(22)}${"SCOPE".padEnd(10)}${"REPO".padEnd(repoW)}${"MODEL".padEnd(8)}ROLES`);for(let i2=0;i2<entries.length;i2++){let entry=entries[i2],repo=repoValues[i2],roles=entry.roles?.join(", ")||"-";console.log(` ${entry.name.padEnd(22)}${entry.scope.padEnd(10)}${repo.padEnd(repoW)}${(entry.model||"-").padEnd(8)}${roles}`)}console.log("")}function printBuiltinAgentsTable(){console.log("BUILT-IN AGENTS"),console.log("-".repeat(80)),console.log(` ${"NAME".padEnd(22)}${"TYPE".padEnd(10)}${"MODEL".padEnd(8)}DESCRIPTION`);for(let agent of ALL_BUILTINS)console.log(` ${agent.name.padEnd(22)}${agent.category.padEnd(10)}${(agent.model||"-").padEnd(8)}${agent.description}`);console.log("")}async function listEntries(json2,includeBuiltins,_includeArchived){let entries=await ls();if(json2){let result2=entries.map((e)=>({...e,builtin:!1}));if(includeBuiltins)for(let b2 of ALL_BUILTINS)result2.push({name:b2.name,description:b2.description,model:b2.model,category:b2.category,scope:"built-in",builtin:!0});console.log(JSON.stringify(result2,null,2));return}if(entries.length===0&&!includeBuiltins){console.log(`
|
|
@@ -3158,7 +3158,7 @@ ${indented}`}function formatHumanOutput(events,label){let lines=[];if(lines.push
|
|
|
3158
3158
|
WHERE c.content ILIKE ${`%${query2}%`}
|
|
3159
3159
|
ORDER BY c.timestamp DESC
|
|
3160
3160
|
LIMIT ${limit}
|
|
3161
|
-
`;if(options.json){console.log(JSON.stringify(rows,null,2));return}if(rows.length===0){console.log(`No results for "${query2}".`);return}console.log(""),console.log(`Search: "${query2}" (${rows.length} results)`),console.log("\u2500".repeat(60));for(let r of rows){let preview=String(r.content).replace(/\n/g," ").slice(0,100),agent=r.agent_id??"(unknown)",time=r.timestamp?new Date(r.timestamp).toLocaleTimeString():"??:??";console.log(` [${time}] ${agent} (${r.role}): ${preview}`)}console.log("")}init_agent_directory();init_genie_config2();import{resolve as resolvePath2}from"path";init_audit();init_genie_config2();async function resolveOmniApiUrl(){let envUrl=process.env.OMNI_API_URL;if(envUrl)return envUrl;return(await loadGenieConfig()).omni?.apiUrl??null}async function resolveOmniApiKey(){let envKey=process.env.OMNI_API_KEY;if(envKey)return envKey;return(await loadGenieConfig()).omni?.apiKey}async function registerAgentInOmni(agentName,options){let apiUrl=await resolveOmniApiUrl();if(!apiUrl)return null;let apiKey=await resolveOmniApiKey(),body={name:agentName,provider:"claude",model:options?.model,agentType:"assistant",capabilities:options?.roles??[],metadata:{source:"genie",sessionIsolation:{perPerson:!0,perChannel:!0},registeredAt:new Date().toISOString()}},traceId=generateTraceId();try{let headers={"Content-Type":"application/json","X-Trace-Id":traceId};if(apiKey)headers.Authorization=`Bearer ${apiKey}`;let response=await fetch(`${apiUrl}/api/v2/agents`,{method:"POST",headers,body:JSON.stringify(body),signal:AbortSignal.timeout(1e4)});if(!response.ok){let text=await response.text().catch(()=>"");return console.warn(`Warning: Omni registration failed (HTTP ${response.status}): ${text}`),recordAuditEvent("omni",agentName,"registration_error",getActor(),{traceId,status:response.status,error:text.slice(0,200)}).catch(()=>{}),null}let result2=await response.json();return recordAuditEvent("omni",agentName,"registration_success",getActor(),{traceId,omniAgentId:result2.data.id}).catch(()=>{}),result2.data.id}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);return console.warn(`Warning: Omni registration failed: ${message}`),recordAuditEvent("omni",agentName,"registration_error",getActor(),{traceId,error:message.slice(0,200)}).catch(()=>{}),null}}async function findOmniAgent(agentName){let apiUrl=await resolveOmniApiUrl();if(!apiUrl)return null;let apiKey=await resolveOmniApiKey(),traceId=generateTraceId();try{let headers={"X-Trace-Id":traceId};if(apiKey)headers.Authorization=`Bearer ${apiKey}`;let response=await fetch(`${apiUrl}/api/v2/agents?name=${encodeURIComponent(agentName)}`,{method:"GET",headers,signal:AbortSignal.timeout(1e4)});if(!response.ok)return null;return(await response.json()).data?.find((a)=>a.name===agentName&&a.isActive)?.id??null}catch{return null}}init_agent_directory();init_agent_sync();init_audit();init_builtin_agents();init_defaults();init_frontmatter();init_genie_config2();init_workspace();import{resolve as resolvePath}from"path";function registerDirNamespace(program2){let dir=program2.command("dir").description("Agent directory management"),addCmd=dir.command("add <name>").description("Register an agent in the directory").requiredOption("--dir <path>","Agent folder (CWD + AGENTS.md)").option("--repo <path>","Default git repo (overridden by team)").option("--prompt-mode <mode>","Prompt mode: append or system","append").option("--model <model>","Default model (sonnet, opus, codex)").option("--roles <roles...>","Built-in roles this agent can orchestrate").option("--permission-preset <preset>","Permission preset: full, read-only, chat-only").option("--allow <tools>",'Comma-separated tool allow list (e.g. "Read,Glob,Grep,Bash")').option("--bash-allow <patterns>","Comma-separated regex patterns for allowed bash commands").option("--global","Write to global directory instead of project");registerSdkFlags(addCmd),addCmd.action(async(name,options)=>{try{await handleDirAdd(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("rm <name>").description("Remove an agent from the directory").option("--global","Remove from global directory instead of project").action(async(name,options)=>{try{let removed=await rm2(name,{global:options.global});if(recordAuditEvent("item",name,"item_removed",getActor(),{type:"agent",source:"dir_rm"}).catch(()=>{}),removed){let scope=options.global?"global":"project";console.log(`Agent "${name}" removed from ${scope} directory.`)}else console.error(`Agent "${name}" not found in directory.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("ls [name]").description("List all agents or show single entry details").option("--json","Output as JSON").option("--builtins","Include built-in roles and council members").option("--all","Include archived agents").action(async(name,options)=>{try{if(name)await showEntry2(name,options.json);else await listEntries2(options.json,options.builtins,options.all)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});let editCmd=dir.command("edit <name>").description("Update an agent directory entry").option("--dir <path>","Agent folder (CWD + AGENTS.md)").option("--repo <path>","Default git repo").option("--prompt-mode <mode>","Prompt mode: append or system").option("--model <model>","Default model").option("--provider <provider>","AI provider: claude or codex").option("--color <color>","Display color for TUI").option("--description <desc>","Agent description").option("--roles <roles...>","Built-in roles this agent can orchestrate").option("--permission-preset <preset>","Permission preset: full, read-only, chat-only").option("--allow <tools>",'Comma-separated tool allow list (e.g. "Read,Glob,Grep,Bash")').option("--bash-allow <patterns>","Comma-separated regex patterns for allowed bash commands").option("--global","Edit in global directory instead of project");registerSdkFlags(editCmd),editCmd.action(async(name,options)=>{try{await handleEdit(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("sync").description("Sync agents from workspace agents/ directory").action(async()=>{try{await handleDirSync()}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("export <name>").description("Print full AGENTS.md frontmatter for an agent from PG state").option("--stdout","Print to stdout as raw YAML (default)").option("--json","Print resolved fields as nested JSON with declared/resolved/source").action(async(name,options)=>{try{await handleDirExport(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}})}async function handleDirAdd(name,options){let promptMode=validatePromptMode(options.promptMode),resolvedDir=resolvePath(options.dir);if(options.repo)validateRepoPath(options.repo);let permissions=buildPermissions(options.permissionPreset,options.allow,options.bashAllow),sdk=buildSdkConfig(options),entry=await add({name,dir:resolvedDir,repo:options.repo?resolvePath(options.repo):void 0,promptMode,model:options.model,roles:normalizeRoles(options.roles),...permissions&&{permissions},...sdk&&{sdk}},{global:options.global});recordAuditEvent("item",name,"item_registered",getActor(),{type:"agent",source:"dir_add"}).catch(()=>{});let scope=options.global?"global":"project";console.log(`Agent "${entry.name}" registered (${scope}).`),printEntry(entry)}async function handleEdit(name,options){let updates={};if(options.dir)updates.dir=resolvePath(options.dir);if(options.repo)updates.repo=resolvePath(options.repo);if(options.promptMode)updates.promptMode=validatePromptMode(options.promptMode);if(options.model)updates.model=options.model;if(options.provider)updates.provider=options.provider;if(options.color)updates.color=options.color;if(options.description)updates.description=options.description;if(options.roles)updates.roles=normalizeRoles(options.roles);let permissions=buildPermissions(options.permissionPreset,options.allow,options.bashAllow);if(permissions)updates.permissions=permissions;let sdk=buildSdkConfig(options);if(sdk)updates.sdk=sdk;if(Object.keys(updates).length===0)console.error("No fields to update. Provide at least one of: --dir, --repo, --prompt-mode, --model, --provider, --color, --description, --roles, --permission-preset, --allow, --bash-allow, --sdk-*"),process.exit(1);let entry=await edit(name,updates,{global:options.global});syncFrontmatterToDisk(entry,updates),recordAuditEvent("item",name,"item_updated",getActor(),{type:"agent",source:"dir_edit"}).catch(()=>{});let scope=options.global?"global":"project";console.log(`Agent "${name}" updated (${scope}).`),printEntry(entry)}async function handleDirSync(){let{findWorkspace:findWorkspace2}=await Promise.resolve().then(() => (init_workspace(),exports_workspace)),ws=findWorkspace2();if(!ws)console.error("Not in a genie workspace. Run `genie init` first."),process.exit(1);console.log(`Syncing agents from ${ws.root}/agents/...`);let result2=await syncAgentDirectory(ws.root);printSyncResult(result2)}async function handleDirExport(name,options){let entry=await get(name);if(!entry)console.error(`Agent "${name}" not found in directory.`),process.exit(1);if(options.json){let ctx=buildDirResolveContext(name),output={name:entry.name};for(let field of RESOLVED_FIELDS){let declared=entry[field]??null,result2=resolveFieldWithSource(entry,field,ctx);output[field]={declared:declared??null,resolved:result2.value,source:result2.source}}console.log(JSON.stringify(output,null,2));return}let fm={};if(entry.name)fm.name=entry.name;if(entry.description)fm.description=entry.description;if(entry.model)fm.model=entry.model;if(entry.color)fm.color=entry.color;if(entry.promptMode)fm.promptMode=entry.promptMode;if(entry.provider)fm.provider=entry.provider;if(entry.sdk&&Object.keys(entry.sdk).length>0){let{serializeSdkConfig:serializeSdkConfig2}=await Promise.resolve().then(() => (init_frontmatter_writer(),exports_frontmatter_writer));fm.sdk=serializeSdkConfig2(entry.sdk)}let yamlStr=(await Promise.resolve().then(() => (init_js_yaml(),exports_js_yaml))).dump(fm,{lineWidth:-1,noRefs:!0,sortKeys:!1,quotingType:'"'});console.log(`---
|
|
3161
|
+
`;if(options.json){console.log(JSON.stringify(rows,null,2));return}if(rows.length===0){console.log(`No results for "${query2}".`);return}console.log(""),console.log(`Search: "${query2}" (${rows.length} results)`),console.log("\u2500".repeat(60));for(let r of rows){let preview=String(r.content).replace(/\n/g," ").slice(0,100),agent=r.agent_id??"(unknown)",time=r.timestamp?new Date(r.timestamp).toLocaleTimeString():"??:??";console.log(` [${time}] ${agent} (${r.role}): ${preview}`)}console.log("")}init_agent_directory();init_genie_config2();import{resolve as resolvePath2}from"path";init_audit();init_genie_config2();async function resolveOmniApiUrl(){let envUrl=process.env.OMNI_API_URL;if(envUrl)return envUrl;return(await loadGenieConfig()).omni?.apiUrl??null}async function resolveOmniApiKey(){let envKey=process.env.OMNI_API_KEY;if(envKey)return envKey;return(await loadGenieConfig()).omni?.apiKey}async function registerAgentInOmni(agentName,options){let apiUrl=await resolveOmniApiUrl();if(!apiUrl)return null;let apiKey=await resolveOmniApiKey(),body={name:agentName,provider:"claude",model:options?.model,agentType:"assistant",capabilities:options?.roles??[],metadata:{source:"genie",sessionIsolation:{perPerson:!0,perChannel:!0},registeredAt:new Date().toISOString()}},traceId=generateTraceId();try{let headers={"Content-Type":"application/json","X-Trace-Id":traceId};if(apiKey)headers.Authorization=`Bearer ${apiKey}`;let response=await fetch(`${apiUrl}/api/v2/agents`,{method:"POST",headers,body:JSON.stringify(body),signal:AbortSignal.timeout(1e4)});if(!response.ok){let text=await response.text().catch(()=>"");return console.warn(`Warning: Omni registration failed (HTTP ${response.status}): ${text}`),recordAuditEvent("omni",agentName,"registration_error",getActor(),{traceId,status:response.status,error:text.slice(0,200)}).catch(()=>{}),null}let result2=await response.json();return recordAuditEvent("omni",agentName,"registration_success",getActor(),{traceId,omniAgentId:result2.data.id}).catch(()=>{}),result2.data.id}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);return console.warn(`Warning: Omni registration failed: ${message}`),recordAuditEvent("omni",agentName,"registration_error",getActor(),{traceId,error:message.slice(0,200)}).catch(()=>{}),null}}async function findOmniAgent(agentName){let apiUrl=await resolveOmniApiUrl();if(!apiUrl)return null;let apiKey=await resolveOmniApiKey(),traceId=generateTraceId();try{let headers={"X-Trace-Id":traceId};if(apiKey)headers.Authorization=`Bearer ${apiKey}`;let response=await fetch(`${apiUrl}/api/v2/agents?name=${encodeURIComponent(agentName)}`,{method:"GET",headers,signal:AbortSignal.timeout(1e4)});if(!response.ok)return null;return(await response.json()).data?.find((a)=>a.name===agentName&&a.isActive)?.id??null}catch{return null}}init_agent_directory();init_agent_sync();init_audit();init_builtin_agents();init_defaults();init_frontmatter();init_genie_config2();init_workspace();import{resolve as resolvePath}from"path";function registerDirNamespace(program2){let dir=program2.command("dir").description("Agent directory management"),addCmd=dir.command("add <name>").description("Register an agent in the directory").requiredOption("--dir <path>","Agent folder (CWD + AGENTS.md)").option("--repo <path>","Default git repo (overridden by team)").option("--prompt-mode <mode>","Prompt mode: append or system","append").option("--model <model>","Default model (sonnet, opus, codex)").option("--roles <roles...>","Built-in roles this agent can orchestrate").option("--permission-preset <preset>","Permission preset: full, read-only, chat-only").option("--allow <tools>",'Comma-separated tool allow list (e.g. "Read,Glob,Grep,Bash")').option("--bash-allow <patterns>","Comma-separated regex patterns for allowed bash commands").option("--global","Write to global directory instead of project");registerSdkFlags(addCmd),addCmd.action(async(name,options)=>{try{await handleDirAdd(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("rm <name>").description("Remove an agent from the directory").option("--global","Remove from global directory instead of project").action(async(name,options)=>{try{let removed=await rm(name,{global:options.global});if(recordAuditEvent("item",name,"item_removed",getActor(),{type:"agent",source:"dir_rm"}).catch(()=>{}),removed){let scope=options.global?"global":"project";console.log(`Agent "${name}" removed from ${scope} directory.`)}else console.error(`Agent "${name}" not found in directory.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("ls [name]").description("List all agents or show single entry details").option("--json","Output as JSON").option("--builtins","Include built-in roles and council members").option("--all","Include archived agents").action(async(name,options)=>{try{if(name)await showEntry2(name,options.json);else await listEntries2(options.json,options.builtins,options.all)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});let editCmd=dir.command("edit <name>").description("Update an agent directory entry").option("--dir <path>","Agent folder (CWD + AGENTS.md)").option("--repo <path>","Default git repo").option("--prompt-mode <mode>","Prompt mode: append or system").option("--model <model>","Default model").option("--provider <provider>","AI provider: claude or codex").option("--color <color>","Display color for TUI").option("--description <desc>","Agent description").option("--roles <roles...>","Built-in roles this agent can orchestrate").option("--permission-preset <preset>","Permission preset: full, read-only, chat-only").option("--allow <tools>",'Comma-separated tool allow list (e.g. "Read,Glob,Grep,Bash")').option("--bash-allow <patterns>","Comma-separated regex patterns for allowed bash commands").option("--global","Edit in global directory instead of project");registerSdkFlags(editCmd),editCmd.action(async(name,options)=>{try{await handleEdit(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("sync").description("Sync agents from workspace agents/ directory").action(async()=>{try{await handleDirSync()}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),dir.command("export <name>").description("Print full AGENTS.md frontmatter for an agent from PG state").option("--stdout","Print to stdout as raw YAML (default)").option("--json","Print resolved fields as nested JSON with declared/resolved/source").action(async(name,options)=>{try{await handleDirExport(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}})}async function handleDirAdd(name,options){let promptMode=validatePromptMode(options.promptMode),resolvedDir=resolvePath(options.dir);if(options.repo)validateRepoPath(options.repo);let permissions=buildPermissions(options.permissionPreset,options.allow,options.bashAllow),sdk=buildSdkConfig(options),entry=await add({name,dir:resolvedDir,repo:options.repo?resolvePath(options.repo):void 0,promptMode,model:options.model,roles:normalizeRoles(options.roles),...permissions&&{permissions},...sdk&&{sdk}},{global:options.global});recordAuditEvent("item",name,"item_registered",getActor(),{type:"agent",source:"dir_add"}).catch(()=>{});let scope=options.global?"global":"project";console.log(`Agent "${entry.name}" registered (${scope}).`),printEntry(entry)}async function handleEdit(name,options){let updates={};if(options.dir)updates.dir=resolvePath(options.dir);if(options.repo)updates.repo=resolvePath(options.repo);if(options.promptMode)updates.promptMode=validatePromptMode(options.promptMode);if(options.model)updates.model=options.model;if(options.provider)updates.provider=options.provider;if(options.color)updates.color=options.color;if(options.description)updates.description=options.description;if(options.roles)updates.roles=normalizeRoles(options.roles);let permissions=buildPermissions(options.permissionPreset,options.allow,options.bashAllow);if(permissions)updates.permissions=permissions;let sdk=buildSdkConfig(options);if(sdk)updates.sdk=sdk;if(Object.keys(updates).length===0)console.error("No fields to update. Provide at least one of: --dir, --repo, --prompt-mode, --model, --provider, --color, --description, --roles, --permission-preset, --allow, --bash-allow, --sdk-*"),process.exit(1);let entry=await edit(name,updates,{global:options.global});syncFrontmatterToDisk(entry,updates),recordAuditEvent("item",name,"item_updated",getActor(),{type:"agent",source:"dir_edit"}).catch(()=>{});let scope=options.global?"global":"project";console.log(`Agent "${name}" updated (${scope}).`),printEntry(entry)}async function handleDirSync(){let{findWorkspace:findWorkspace2}=await Promise.resolve().then(() => (init_workspace(),exports_workspace)),ws=findWorkspace2();if(!ws)console.error("Not in a genie workspace. Run `genie init` first."),process.exit(1);console.log(`Syncing agents from ${ws.root}/agents/...`);let result2=await syncAgentDirectory(ws.root);printSyncResult(result2)}async function handleDirExport(name,options){let entry=await get(name);if(!entry)console.error(`Agent "${name}" not found in directory.`),process.exit(1);if(options.json){let ctx=buildDirResolveContext(name),output={name:entry.name};for(let field of RESOLVED_FIELDS){let declared=entry[field]??null,result2=resolveFieldWithSource(entry,field,ctx);output[field]={declared:declared??null,resolved:result2.value,source:result2.source}}console.log(JSON.stringify(output,null,2));return}let fm={};if(entry.name)fm.name=entry.name;if(entry.description)fm.description=entry.description;if(entry.model)fm.model=entry.model;if(entry.color)fm.color=entry.color;if(entry.promptMode)fm.promptMode=entry.promptMode;if(entry.provider)fm.provider=entry.provider;if(entry.sdk&&Object.keys(entry.sdk).length>0){let{serializeSdkConfig:serializeSdkConfig2}=await Promise.resolve().then(() => (init_frontmatter_writer(),exports_frontmatter_writer));fm.sdk=serializeSdkConfig2(entry.sdk)}let yamlStr=(await Promise.resolve().then(() => (init_js_yaml(),exports_js_yaml))).dump(fm,{lineWidth:-1,noRefs:!0,sortKeys:!1,quotingType:'"'});console.log(`---
|
|
3162
3162
|
${yamlStr}---`)}function buildDirResolveContext(agentName){let ctx={};try{let ws=findWorkspace();if(ws){let wsConfig=getWorkspaceConfig(ws.root);if(ctx.workspaceDefaults=wsConfig.agents?.defaults,agentName.includes("/")){let parentName=agentName.split("/")[0],{existsSync:existsSync26,readFileSync:readFileSync16}=__require("fs"),{join:join33}=__require("path"),parentAgentsMd=join33(ws.root,"agents",parentName,"AGENTS.md");if(existsSync26(parentAgentsMd)){let parentFm=parseFrontmatter(readFileSync16(parentAgentsMd,"utf-8"));ctx.parent={name:parentName,fields:parentFm}}}}}catch{}return ctx}function validateRepoPath(repo){if(repo.startsWith("/")||repo.startsWith("~/")||repo.startsWith("./")||repo.startsWith("../"))return;throw Error(`Invalid --repo value "${repo}". Must be a path (absolute "/...", home-relative "~/...", or dot-relative "./..." / "../..."). Got a bare word instead.`)}function validatePromptMode(mode){if(mode!=="system"&&mode!=="append")throw Error(`Invalid prompt mode "${mode}". Must be "append" or "system".`);return mode}function printEntry(entry){if(console.log(` Name: ${entry.name}`),console.log(` Dir: ${contractPath(entry.dir)}`),entry.repo)console.log(` Repo: ${contractPath(entry.repo)}`);if(console.log(` PromptMode: ${entry.promptMode}`),entry.model)console.log(` Model: ${entry.model}`);if(entry.provider)console.log(` Provider: ${entry.provider}`);if(entry.color)console.log(` Color: ${entry.color}`);if(entry.description)console.log(` Description: ${entry.description}`);if(entry.roles?.length)console.log(` Roles: ${entry.roles.join(", ")}`);if(entry.permissions?.preset)console.log(` Permissions: preset=${entry.permissions.preset}`);else if(entry.permissions?.allow){if(console.log(` Permissions: allow=${entry.permissions.allow.join(",")}`),entry.permissions.bashAllowPatterns?.length)console.log(` Bash Allow: ${entry.permissions.bashAllowPatterns.join(", ")}`)}if(entry.sdk)printSdkConfig(entry.sdk);console.log(` Registered: ${entry.registeredAt}`)}async function showEntry2(name,json2){let resolved=await resolve2(name);if(!resolved)console.error(`Agent "${name}" not found in directory or built-ins.`),process.exit(1);if(json2){console.log(JSON.stringify({...resolved.entry,builtin:resolved.builtin},null,2));return}if(resolved.builtin)console.log(`
|
|
3163
3163
|
(built-in ${resolved.entry.registeredAt==="(built-in)"?"agent":"agent"})`);console.log(""),printEntry(resolved.entry),console.log("")}async function listEntries2(json2,includeBuiltins,_includeArchived){let entries=await ls();if(json2){listEntriesJson(entries,includeBuiltins);return}if(entries.length===0&&!includeBuiltins){console.log(`
|
|
3164
3164
|
No agents registered. Add one with: genie dir add <name> --dir <path>`),console.log(`Use --builtins to also see built-in roles and council members.
|